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
package/src/access.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import {
|
|
3
|
+
SESSION_CONTROL_POLICY,
|
|
4
|
+
type ResolvedLimits,
|
|
5
|
+
type SessionControlPolicy,
|
|
6
|
+
} from "./config"
|
|
7
|
+
import { toolError } from "./errors"
|
|
8
|
+
import { normalizeSessionID, type SessionInfoLike } from "./session"
|
|
9
|
+
import type { ToolCtx } from "./tools/input"
|
|
10
|
+
import { TOOL } from "./tools/names"
|
|
11
|
+
|
|
12
|
+
export const OWNERSHIP = {
|
|
13
|
+
owned: "owned",
|
|
14
|
+
foreign: "foreign",
|
|
15
|
+
unknown: "unknown",
|
|
16
|
+
} as const
|
|
17
|
+
|
|
18
|
+
export type Ownership = (typeof OWNERSHIP)[keyof typeof OWNERSHIP]
|
|
19
|
+
|
|
20
|
+
export interface GetSessionResult {
|
|
21
|
+
info?: SessionInfoLike
|
|
22
|
+
ok: boolean
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface AccessDeps {
|
|
26
|
+
session: Plugin.Context["session"]
|
|
27
|
+
limits: Pick<ResolvedLimits, "maxDiscoveryDepth">
|
|
28
|
+
policy: SessionControlPolicy
|
|
29
|
+
namespace: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const PARENT_WALK = {
|
|
33
|
+
match: "match",
|
|
34
|
+
root: "root",
|
|
35
|
+
unknown: "unknown",
|
|
36
|
+
} as const
|
|
37
|
+
|
|
38
|
+
type ParentWalk = (typeof PARENT_WALK)[keyof typeof PARENT_WALK]
|
|
39
|
+
|
|
40
|
+
export const createAccess = ({ session, limits, policy, namespace }: AccessDeps) => {
|
|
41
|
+
const getSession = async (
|
|
42
|
+
sessionID: string,
|
|
43
|
+
signal?: AbortSignal,
|
|
44
|
+
): Promise<GetSessionResult> => {
|
|
45
|
+
try {
|
|
46
|
+
return {
|
|
47
|
+
info: (await session.get({ sessionID }, { signal })) as
|
|
48
|
+
| SessionInfoLike
|
|
49
|
+
| undefined,
|
|
50
|
+
ok: true,
|
|
51
|
+
}
|
|
52
|
+
} catch {
|
|
53
|
+
return { ok: false }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Walk a parent chain until `matches` accepts a parent ID or the chain ends.
|
|
59
|
+
* A chain that is deeper than `maxDiscoveryDepth` or malformed is reported as
|
|
60
|
+
* unknown, never as a clean end. `startInfo` is the record for the first ID.
|
|
61
|
+
*/
|
|
62
|
+
const walkParents = async (
|
|
63
|
+
start: string,
|
|
64
|
+
signal: AbortSignal | undefined,
|
|
65
|
+
matches: (parentID: string) => boolean,
|
|
66
|
+
): Promise<{ relation: ParentWalk; startInfo?: SessionInfoLike }> => {
|
|
67
|
+
const seen = new Set<string>()
|
|
68
|
+
let current = start
|
|
69
|
+
let startInfo: SessionInfoLike | undefined
|
|
70
|
+
|
|
71
|
+
for (let depth = 0; depth < limits.maxDiscoveryDepth; depth++) {
|
|
72
|
+
if (signal?.aborted) return { relation: PARENT_WALK.unknown, startInfo }
|
|
73
|
+
if (seen.has(current)) return { relation: PARENT_WALK.unknown, startInfo }
|
|
74
|
+
seen.add(current)
|
|
75
|
+
const { info, ok } = await getSession(current, signal)
|
|
76
|
+
if (!ok || !info) return { relation: PARENT_WALK.unknown, startInfo }
|
|
77
|
+
if (current === start) startInfo = info
|
|
78
|
+
const parentID = normalizeSessionID(info.parentID)
|
|
79
|
+
if (info.parentID !== undefined && parentID === undefined) {
|
|
80
|
+
return { relation: PARENT_WALK.unknown, startInfo }
|
|
81
|
+
}
|
|
82
|
+
if (!parentID) return { relation: PARENT_WALK.root, startInfo }
|
|
83
|
+
if (matches(parentID)) return { relation: PARENT_WALK.match, startInfo }
|
|
84
|
+
current = parentID
|
|
85
|
+
}
|
|
86
|
+
return { relation: PARENT_WALK.unknown, startInfo }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Confirm that the caller is an ancestor of `target`. A chain that is too
|
|
91
|
+
* deep or malformed is reported as unknown, never as foreign.
|
|
92
|
+
*/
|
|
93
|
+
const verifyDescendant = async (
|
|
94
|
+
target: string,
|
|
95
|
+
caller: string,
|
|
96
|
+
signal?: AbortSignal,
|
|
97
|
+
): Promise<{ ownership: Ownership; info?: SessionInfoLike }> => {
|
|
98
|
+
const result = await walkParents(target, signal, (parentID) => parentID === caller)
|
|
99
|
+
const ownership =
|
|
100
|
+
result.relation === PARENT_WALK.match
|
|
101
|
+
? OWNERSHIP.owned
|
|
102
|
+
: result.relation === PARENT_WALK.root
|
|
103
|
+
? OWNERSHIP.foreign
|
|
104
|
+
: OWNERSHIP.unknown
|
|
105
|
+
return { ownership, info: result.startInfo }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Report whether `target` is an ancestor of `caller`. The result is unknown
|
|
110
|
+
* when the chain is too deep, cyclic, or cannot be read.
|
|
111
|
+
*/
|
|
112
|
+
const findAncestor = async (
|
|
113
|
+
target: string,
|
|
114
|
+
caller: string,
|
|
115
|
+
signal?: AbortSignal,
|
|
116
|
+
): Promise<"ancestor" | "not-ancestor" | "unknown"> => {
|
|
117
|
+
const result = await walkParents(caller, signal, (parentID) => parentID === target)
|
|
118
|
+
return result.relation === PARENT_WALK.match
|
|
119
|
+
? "ancestor"
|
|
120
|
+
: result.relation === PARENT_WALK.root
|
|
121
|
+
? "not-ancestor"
|
|
122
|
+
: "unknown"
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const aborted = (): never => toolError("Aborted before the target could be verified.")
|
|
126
|
+
|
|
127
|
+
const readAuthorizedTarget = async (
|
|
128
|
+
target: string,
|
|
129
|
+
context: ToolCtx,
|
|
130
|
+
): Promise<SessionInfoLike> => {
|
|
131
|
+
const { info, ok } = await getSession(target, context.signal)
|
|
132
|
+
if (context?.signal?.aborted) return aborted()
|
|
133
|
+
if (!ok || !info) {
|
|
134
|
+
return toolError(`Refusing: ${target} could not be read from the server.`)
|
|
135
|
+
}
|
|
136
|
+
return info
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
type PolicyHandler = (
|
|
140
|
+
target: string,
|
|
141
|
+
caller: string,
|
|
142
|
+
context: ToolCtx,
|
|
143
|
+
) => Promise<SessionInfoLike | undefined>
|
|
144
|
+
|
|
145
|
+
const policyHandlers: Readonly<Record<SessionControlPolicy, PolicyHandler>> = {
|
|
146
|
+
[SESSION_CONTROL_POLICY.descendants]: async (target, caller, context) => {
|
|
147
|
+
const result = await verifyDescendant(target, caller, context.signal)
|
|
148
|
+
if (context?.signal?.aborted) return aborted()
|
|
149
|
+
if (result.ownership === OWNERSHIP.owned) return result.info
|
|
150
|
+
if (result.ownership === OWNERSHIP.foreign) {
|
|
151
|
+
return toolError(
|
|
152
|
+
`Refusing: ${target} is not a descendant of the calling session (${caller}).`,
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
return toolError(
|
|
156
|
+
`Refusing: ${target} could not be verified through the server's session tree. Run ${namespace}_${TOOL.list} and use an ID it reports.`,
|
|
157
|
+
)
|
|
158
|
+
},
|
|
159
|
+
[SESSION_CONTROL_POLICY.allExceptAncestors]: async (target, caller, context) => {
|
|
160
|
+
const info = await readAuthorizedTarget(target, context)
|
|
161
|
+
const relation = await findAncestor(target, caller, context.signal)
|
|
162
|
+
if (context?.signal?.aborted) return aborted()
|
|
163
|
+
if (relation === "ancestor") {
|
|
164
|
+
return toolError(
|
|
165
|
+
`Refusing: ${target} is an ancestor of the calling session (${caller}); sessionControlPolicy is all-except-ancestors.`,
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
if (relation === "unknown") {
|
|
169
|
+
return toolError(
|
|
170
|
+
`Refusing: ${target} could not be verified through the server's session tree. Run ${namespace}_${TOOL.list} and use an ID it reports.`,
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
return info
|
|
174
|
+
},
|
|
175
|
+
[SESSION_CONTROL_POLICY.all]: (target, _caller, context) =>
|
|
176
|
+
readAuthorizedTarget(target, context),
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const policyHandlerMap: ReadonlyMap<SessionControlPolicy, PolicyHandler> = new Map(
|
|
180
|
+
Object.entries(policyHandlers) as Array<[SessionControlPolicy, PolicyHandler]>,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
const authorize = async (
|
|
184
|
+
target: string,
|
|
185
|
+
context: ToolCtx,
|
|
186
|
+
): Promise<SessionInfoLike | undefined> => {
|
|
187
|
+
const caller = context?.sessionID
|
|
188
|
+
if (context?.signal?.aborted) return aborted()
|
|
189
|
+
if (caller && target === caller) {
|
|
190
|
+
return toolError("Refusing: a session cannot control itself.")
|
|
191
|
+
}
|
|
192
|
+
if (!caller) {
|
|
193
|
+
return toolError(
|
|
194
|
+
"Refusing: the calling session is unknown, so ownership of the target cannot be verified.",
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const handler = policyHandlerMap.get(policy)
|
|
199
|
+
if (!handler) {
|
|
200
|
+
return toolError(
|
|
201
|
+
`Refusing: unknown sessionControlPolicy "${String(policy)}"; the target was not authorized.`,
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
return handler(target, caller, context)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Read-only resolution for `usage`. Reading is intentionally unrestricted by
|
|
209
|
+
* `sessionControlPolicy`: the caller may read any session, including itself.
|
|
210
|
+
*/
|
|
211
|
+
const readUsageTarget = async (
|
|
212
|
+
target: string,
|
|
213
|
+
context: ToolCtx,
|
|
214
|
+
): Promise<SessionInfoLike | undefined> => {
|
|
215
|
+
if (context?.signal?.aborted) {
|
|
216
|
+
return toolError("Aborted before usage was read.")
|
|
217
|
+
}
|
|
218
|
+
const { info, ok } = await getSession(target, context.signal)
|
|
219
|
+
if (context?.signal?.aborted) {
|
|
220
|
+
return toolError("Aborted before usage was read.")
|
|
221
|
+
}
|
|
222
|
+
if (!ok || !info) {
|
|
223
|
+
return toolError(`Usage unavailable for ${target}: session could not be read.`)
|
|
224
|
+
}
|
|
225
|
+
return info
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
getSession,
|
|
230
|
+
verifyDescendant,
|
|
231
|
+
authorize,
|
|
232
|
+
readTarget: readUsageTarget,
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export type Access = ReturnType<typeof createAccess>
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { clipText } from "./text"
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_NAMESPACE = "subagent"
|
|
4
|
+
export const MAX_NAMESPACE_LENGTH = 64
|
|
5
|
+
|
|
6
|
+
export const SESSION_CONTROL_POLICY = {
|
|
7
|
+
/** Only the calling session's subtree. */
|
|
8
|
+
descendants: "descendants",
|
|
9
|
+
/** Any session except the calling session's ancestors. */
|
|
10
|
+
allExceptAncestors: "all-except-ancestors",
|
|
11
|
+
/** Any session except the calling session itself. */
|
|
12
|
+
all: "all",
|
|
13
|
+
} as const
|
|
14
|
+
|
|
15
|
+
export type SessionControlPolicy =
|
|
16
|
+
(typeof SESSION_CONTROL_POLICY)[keyof typeof SESSION_CONTROL_POLICY]
|
|
17
|
+
|
|
18
|
+
export const SESSION_CONTROL_POLICIES: readonly SessionControlPolicy[] =
|
|
19
|
+
Object.values(SESSION_CONTROL_POLICY)
|
|
20
|
+
|
|
21
|
+
export const isSessionControlPolicy = (value: unknown): value is SessionControlPolicy =>
|
|
22
|
+
typeof value === "string" &&
|
|
23
|
+
(SESSION_CONTROL_POLICIES as readonly string[]).includes(value)
|
|
24
|
+
|
|
25
|
+
export const OUTPUT_FORMAT = {
|
|
26
|
+
text: "text",
|
|
27
|
+
json: "json",
|
|
28
|
+
} as const
|
|
29
|
+
|
|
30
|
+
export type OutputFormat = (typeof OUTPUT_FORMAT)[keyof typeof OUTPUT_FORMAT]
|
|
31
|
+
|
|
32
|
+
export const OUTPUT_FORMATS: readonly OutputFormat[] = Object.values(OUTPUT_FORMAT)
|
|
33
|
+
|
|
34
|
+
export const isOutputFormat = (value: unknown): value is OutputFormat =>
|
|
35
|
+
typeof value === "string" && (OUTPUT_FORMATS as readonly string[]).includes(value)
|
|
36
|
+
|
|
37
|
+
export const DEFAULT_ALLOWED_OUTPUT_FORMATS: readonly OutputFormat[] = OUTPUT_FORMATS
|
|
38
|
+
|
|
39
|
+
export const normalizeOutputFormats = (value: unknown): readonly OutputFormat[] => {
|
|
40
|
+
if (!Array.isArray(value)) return DEFAULT_ALLOWED_OUTPUT_FORMATS
|
|
41
|
+
const allowed = new Set<OutputFormat>()
|
|
42
|
+
for (const item of value) {
|
|
43
|
+
if (isOutputFormat(item)) allowed.add(item)
|
|
44
|
+
}
|
|
45
|
+
if (allowed.size === 0) return DEFAULT_ALLOWED_OUTPUT_FORMATS
|
|
46
|
+
return OUTPUT_FORMATS.filter((format) => allowed.has(format))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const LIMIT_SPECS = {
|
|
50
|
+
/** Maximum nodes visited during one server discovery pass. */
|
|
51
|
+
maxDiscoveryNodes: { default: 200, min: 1, max: 5000 },
|
|
52
|
+
/** Maximum parent-chain depth walked during discovery and verification. */
|
|
53
|
+
maxDiscoveryDepth: { default: 8, min: 1, max: 32 },
|
|
54
|
+
/** Maximum session.list pages requested per parent. */
|
|
55
|
+
maxDiscoveryPages: { default: 5, min: 1, max: 50 },
|
|
56
|
+
/** Maximum rows returned by list per call. */
|
|
57
|
+
maxListRows: { default: 20, min: 1, max: 50 },
|
|
58
|
+
/** Maximum children interrupted by cancel_descendants per call. */
|
|
59
|
+
maxCancelBatch: { default: 20, min: 1, max: 50 },
|
|
60
|
+
/** Maximum characters accepted by steer, queue, and context. */
|
|
61
|
+
maxTextLength: { default: 16000, min: 1, max: 32000 },
|
|
62
|
+
} as const
|
|
63
|
+
|
|
64
|
+
export type LimitKey = keyof typeof LIMIT_SPECS
|
|
65
|
+
|
|
66
|
+
export const LIMIT_KEYS = Object.keys(LIMIT_SPECS) as readonly LimitKey[]
|
|
67
|
+
|
|
68
|
+
export type Limits = { [Key in LimitKey]?: number }
|
|
69
|
+
|
|
70
|
+
export type ResolvedLimits = { [Key in LimitKey]: number }
|
|
71
|
+
|
|
72
|
+
export interface Options {
|
|
73
|
+
/**
|
|
74
|
+
* Route mutations through `ctx.permission.assert` with action
|
|
75
|
+
* `subagent.control`. Defaults to true; set false to skip permission
|
|
76
|
+
* evaluation entirely.
|
|
77
|
+
*/
|
|
78
|
+
enforcePermissions?: boolean
|
|
79
|
+
/**
|
|
80
|
+
* Who mutating tools may target. Defaults to `"descendants"` (the calling
|
|
81
|
+
* session's subtree). `"all-except-ancestors"` allows foreign sessions but
|
|
82
|
+
* refuses the caller's parent chain. `"all"` allows any session except the
|
|
83
|
+
* caller itself. Read-only tools are not restricted by this option.
|
|
84
|
+
*/
|
|
85
|
+
sessionControlPolicy?: SessionControlPolicy | string
|
|
86
|
+
/** Tool namespace; tools become `<namespace>_list`, `<namespace>_cancel`, ... */
|
|
87
|
+
namespace?: string
|
|
88
|
+
/**
|
|
89
|
+
* Output formats the tools may return. `"text"` returns only the
|
|
90
|
+
* human-readable content; `"json"` also returns a structured output object.
|
|
91
|
+
* Include both to allow a per-call `format` choice. Defaults to
|
|
92
|
+
* ["text", "json"]. Unknown values are ignored; an empty or invalid list
|
|
93
|
+
* falls back to the default.
|
|
94
|
+
*/
|
|
95
|
+
allowedOutputFormats?: readonly string[]
|
|
96
|
+
/** Register the bundled SKILL.md as a model-facing skill. Defaults to true. */
|
|
97
|
+
registerSkill?: boolean
|
|
98
|
+
/** Optional tuning limits. See docs/configuration.md. */
|
|
99
|
+
limits?: Limits
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface Config {
|
|
103
|
+
namespace: string
|
|
104
|
+
enforcePermissions: boolean
|
|
105
|
+
sessionControlPolicy: SessionControlPolicy
|
|
106
|
+
allowedOutputFormats: readonly OutputFormat[]
|
|
107
|
+
registerSkill: boolean
|
|
108
|
+
limits: ResolvedLimits
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const limitInteger = (
|
|
112
|
+
value: unknown,
|
|
113
|
+
fallback: number,
|
|
114
|
+
min: number,
|
|
115
|
+
max: number,
|
|
116
|
+
): number => {
|
|
117
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return fallback
|
|
118
|
+
return Math.min(max, Math.max(min, Math.floor(value)))
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const resolveLimits = (value: unknown): ResolvedLimits => {
|
|
122
|
+
const raw = (value ?? {}) as Record<string, unknown>
|
|
123
|
+
const resolved = {} as ResolvedLimits
|
|
124
|
+
for (const key of LIMIT_KEYS) {
|
|
125
|
+
const spec = LIMIT_SPECS[key]
|
|
126
|
+
resolved[key] = limitInteger(raw[key], spec.default, spec.min, spec.max)
|
|
127
|
+
}
|
|
128
|
+
return resolved
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const resolveConfig = (raw: unknown): Config => {
|
|
132
|
+
const options = (raw ?? {}) as Options
|
|
133
|
+
return {
|
|
134
|
+
namespace: clipText(options.namespace, MAX_NAMESPACE_LENGTH) ?? DEFAULT_NAMESPACE,
|
|
135
|
+
enforcePermissions: options.enforcePermissions !== false,
|
|
136
|
+
sessionControlPolicy: isSessionControlPolicy(options.sessionControlPolicy)
|
|
137
|
+
? options.sessionControlPolicy
|
|
138
|
+
: SESSION_CONTROL_POLICY.descendants,
|
|
139
|
+
allowedOutputFormats: normalizeOutputFormats(options.allowedOutputFormats),
|
|
140
|
+
registerSkill: options.registerSkill !== false,
|
|
141
|
+
limits: resolveLimits(options.limits),
|
|
142
|
+
}
|
|
143
|
+
}
|
package/src/cursor.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { SessionRow } from "./session-row"
|
|
2
|
+
import { TOOL, type ToolName } from "./tools/names"
|
|
3
|
+
|
|
4
|
+
export const MAX_CURSOR_LENGTH = 512
|
|
5
|
+
export const CURSOR_VERSION = 1
|
|
6
|
+
|
|
7
|
+
const CURSOR_TOOLS: ReadonlySet<ToolName> = new Set([TOOL.list, TOOL.cancelDescendants])
|
|
8
|
+
|
|
9
|
+
const isCursorTool = (value: unknown): value is ToolName =>
|
|
10
|
+
typeof value === "string" && CURSOR_TOOLS.has(value as ToolName)
|
|
11
|
+
|
|
12
|
+
export interface CursorScope {
|
|
13
|
+
tool: ToolName
|
|
14
|
+
root: string
|
|
15
|
+
filter?: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface PageCursor {
|
|
19
|
+
launchedAt: number
|
|
20
|
+
id: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface CursorPayload extends PageCursor {
|
|
24
|
+
v: typeof CURSOR_VERSION
|
|
25
|
+
tool: ToolName
|
|
26
|
+
root: string
|
|
27
|
+
filter?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const encodePayload = (payload: CursorPayload): string =>
|
|
31
|
+
Buffer.from(JSON.stringify(payload), "utf8").toString("base64url")
|
|
32
|
+
|
|
33
|
+
const decodePayload = (value: string): CursorPayload | undefined => {
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8")) as unknown
|
|
36
|
+
if (!parsed || typeof parsed !== "object") return undefined
|
|
37
|
+
const payload = parsed as Record<string, unknown>
|
|
38
|
+
if (payload.v !== CURSOR_VERSION) return undefined
|
|
39
|
+
if (!isCursorTool(payload.tool)) return undefined
|
|
40
|
+
if (typeof payload.root !== "string" || payload.root.length === 0) return undefined
|
|
41
|
+
if (payload.filter !== undefined && typeof payload.filter !== "string")
|
|
42
|
+
return undefined
|
|
43
|
+
if (
|
|
44
|
+
typeof payload.launchedAt !== "number" ||
|
|
45
|
+
!Number.isFinite(payload.launchedAt) ||
|
|
46
|
+
payload.launchedAt < 0
|
|
47
|
+
) {
|
|
48
|
+
return undefined
|
|
49
|
+
}
|
|
50
|
+
if (typeof payload.id !== "string" || payload.id.length === 0) return undefined
|
|
51
|
+
return {
|
|
52
|
+
v: CURSOR_VERSION,
|
|
53
|
+
tool: payload.tool,
|
|
54
|
+
root: payload.root,
|
|
55
|
+
filter: payload.filter as string | undefined,
|
|
56
|
+
launchedAt: payload.launchedAt,
|
|
57
|
+
id: payload.id,
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
return undefined
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const encodeCursor = (
|
|
65
|
+
row: Pick<SessionRow, "launchedAt" | "id">,
|
|
66
|
+
scope: CursorScope,
|
|
67
|
+
): string =>
|
|
68
|
+
encodePayload({
|
|
69
|
+
v: CURSOR_VERSION,
|
|
70
|
+
tool: scope.tool,
|
|
71
|
+
root: scope.root,
|
|
72
|
+
filter: scope.filter,
|
|
73
|
+
launchedAt: row.launchedAt,
|
|
74
|
+
id: row.id,
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const invalidCursorMessage = (toolName: ToolName): string =>
|
|
78
|
+
`Invalid cursor. Re-run the previous ${toolName} call and use the cursor it reported.`
|
|
79
|
+
|
|
80
|
+
export const readCursor = (
|
|
81
|
+
value: unknown,
|
|
82
|
+
scope: CursorScope,
|
|
83
|
+
): { cursor?: PageCursor; error?: string } => {
|
|
84
|
+
if (value === undefined) return {}
|
|
85
|
+
if (
|
|
86
|
+
typeof value !== "string" ||
|
|
87
|
+
value.length === 0 ||
|
|
88
|
+
value.length > MAX_CURSOR_LENGTH
|
|
89
|
+
) {
|
|
90
|
+
return { error: invalidCursorMessage(scope.tool) }
|
|
91
|
+
}
|
|
92
|
+
const payload = decodePayload(value)
|
|
93
|
+
if (
|
|
94
|
+
!payload ||
|
|
95
|
+
payload.tool !== scope.tool ||
|
|
96
|
+
payload.root !== scope.root ||
|
|
97
|
+
(payload.filter ?? "") !== (scope.filter ?? "")
|
|
98
|
+
) {
|
|
99
|
+
return { error: invalidCursorMessage(scope.tool) }
|
|
100
|
+
}
|
|
101
|
+
return { cursor: { launchedAt: payload.launchedAt, id: payload.id } }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const compareIds = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)
|
|
105
|
+
|
|
106
|
+
/** Newest launch first, then a deterministic ID tie-break for stable paging. */
|
|
107
|
+
export const compareRows = (a: SessionRow, b: SessionRow): number =>
|
|
108
|
+
(b.launchedAt ?? 0) - (a.launchedAt ?? 0) || compareIds(a.id, b.id)
|
|
109
|
+
|
|
110
|
+
export const isAfterCursor = (row: SessionRow, cursor: PageCursor): boolean =>
|
|
111
|
+
row.launchedAt < cursor.launchedAt ||
|
|
112
|
+
(row.launchedAt === cursor.launchedAt && compareIds(row.id, cursor.id) > 0)
|
package/src/discovery.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import type { ResolvedLimits } from "./config"
|
|
2
|
+
import { compareRows } from "./cursor"
|
|
3
|
+
import type { LiveStore } from "./live-state"
|
|
4
|
+
import {
|
|
5
|
+
normalizeSessionID,
|
|
6
|
+
readSessionListPage,
|
|
7
|
+
type SessionInfoLike,
|
|
8
|
+
type SessionList,
|
|
9
|
+
type SessionListResult,
|
|
10
|
+
} from "./session"
|
|
11
|
+
import { rowFromInfo, type SessionRow } from "./session-row"
|
|
12
|
+
|
|
13
|
+
export const MAX_DISCOVERY_PAGE_SIZE = 100
|
|
14
|
+
|
|
15
|
+
export interface DiscoveryResult {
|
|
16
|
+
items: SessionInfoLike[]
|
|
17
|
+
complete: boolean
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface DiscoveryDeps {
|
|
21
|
+
sessionList: SessionList
|
|
22
|
+
live: LiveStore
|
|
23
|
+
limits: Pick<
|
|
24
|
+
ResolvedLimits,
|
|
25
|
+
"maxDiscoveryNodes" | "maxDiscoveryDepth" | "maxDiscoveryPages"
|
|
26
|
+
>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const createDiscovery = ({ sessionList, live, limits }: DiscoveryDeps) => {
|
|
30
|
+
const { maxDiscoveryNodes, maxDiscoveryDepth, maxDiscoveryPages } = limits
|
|
31
|
+
|
|
32
|
+
const listChildren = async (
|
|
33
|
+
parentID: string,
|
|
34
|
+
signal?: AbortSignal,
|
|
35
|
+
): Promise<DiscoveryResult> => {
|
|
36
|
+
const items: SessionInfoLike[] = []
|
|
37
|
+
let cursor: string | undefined
|
|
38
|
+
let complete = true
|
|
39
|
+
for (let pageIndex = 0; pageIndex < maxDiscoveryPages; pageIndex++) {
|
|
40
|
+
if (signal?.aborted) return { items, complete: false }
|
|
41
|
+
let result: SessionListResult | undefined
|
|
42
|
+
try {
|
|
43
|
+
result = await sessionList(
|
|
44
|
+
{
|
|
45
|
+
parentID,
|
|
46
|
+
limit: MAX_DISCOVERY_PAGE_SIZE,
|
|
47
|
+
order: "desc",
|
|
48
|
+
archived: false,
|
|
49
|
+
...(cursor ? { cursor } : {}),
|
|
50
|
+
},
|
|
51
|
+
{ signal },
|
|
52
|
+
)
|
|
53
|
+
} catch {
|
|
54
|
+
return { items, complete: false }
|
|
55
|
+
}
|
|
56
|
+
if (signal?.aborted) return { items, complete: false }
|
|
57
|
+
const page = readSessionListPage(result)
|
|
58
|
+
if (!page.valid) complete = false
|
|
59
|
+
items.push(...page.items)
|
|
60
|
+
const previousCursor = cursor
|
|
61
|
+
cursor = page.cursor
|
|
62
|
+
if (!cursor) {
|
|
63
|
+
// A full page without a cursor may still be truncated; a short page
|
|
64
|
+
// without a cursor is a clean end.
|
|
65
|
+
if (page.items.length >= MAX_DISCOVERY_PAGE_SIZE) complete = false
|
|
66
|
+
return { items, complete }
|
|
67
|
+
}
|
|
68
|
+
// A cursor is the primary signal that more rows exist. Do not stop on a
|
|
69
|
+
// short page: a proxy or server may cap the page below the requested
|
|
70
|
+
// limit and still return a cursor.
|
|
71
|
+
if (cursor === previousCursor) {
|
|
72
|
+
// A repeated cursor cannot make progress.
|
|
73
|
+
complete = false
|
|
74
|
+
return { items, complete }
|
|
75
|
+
}
|
|
76
|
+
if (pageIndex === maxDiscoveryPages - 1) complete = false
|
|
77
|
+
}
|
|
78
|
+
return { items, complete }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Refresh a subtree from the server. The parentID filter is applied
|
|
83
|
+
* server-side and checked again so an ignored filter cannot pull in
|
|
84
|
+
* unrelated sessions. `complete` reports whether a limit, failure, or
|
|
85
|
+
* cancellation may have truncated the walk.
|
|
86
|
+
*/
|
|
87
|
+
const discoverSubtree = async (
|
|
88
|
+
root: string,
|
|
89
|
+
signal?: AbortSignal,
|
|
90
|
+
): Promise<DiscoveryResult> => {
|
|
91
|
+
const seen = new Set<string>([root])
|
|
92
|
+
const queue: Array<{ id: string; depth: number }> = [{ id: root, depth: 0 }]
|
|
93
|
+
const items: SessionInfoLike[] = []
|
|
94
|
+
let complete = true
|
|
95
|
+
let discovered = 0
|
|
96
|
+
|
|
97
|
+
for (let index = 0; index < queue.length; index++) {
|
|
98
|
+
if (signal?.aborted) return { items, complete: false }
|
|
99
|
+
const current = queue[index]
|
|
100
|
+
if (current.depth >= maxDiscoveryDepth) {
|
|
101
|
+
// This node may have children we deliberately did not inspect.
|
|
102
|
+
complete = false
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
const children = await listChildren(current.id, signal)
|
|
106
|
+
if (!children.complete) complete = false
|
|
107
|
+
for (const info of children.items) {
|
|
108
|
+
if (discovered >= maxDiscoveryNodes) {
|
|
109
|
+
complete = false
|
|
110
|
+
break
|
|
111
|
+
}
|
|
112
|
+
const id = normalizeSessionID(info.id)
|
|
113
|
+
if (!id) {
|
|
114
|
+
complete = false
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
if (seen.has(id)) continue
|
|
118
|
+
const parentID = normalizeSessionID(info.parentID)
|
|
119
|
+
if (parentID !== current.id) {
|
|
120
|
+
complete = false
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
seen.add(id)
|
|
124
|
+
items.push(info)
|
|
125
|
+
discovered++
|
|
126
|
+
queue.push({ id, depth: current.depth + 1 })
|
|
127
|
+
}
|
|
128
|
+
if (discovered >= maxDiscoveryNodes) {
|
|
129
|
+
complete = false
|
|
130
|
+
break
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { items, complete }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const discoverRows = async (
|
|
137
|
+
root: string,
|
|
138
|
+
signal?: AbortSignal,
|
|
139
|
+
): Promise<{ rows: SessionRow[]; complete: boolean }> => {
|
|
140
|
+
const discovery = await discoverSubtree(root, signal)
|
|
141
|
+
const rows = discovery.items
|
|
142
|
+
.map((info) => rowFromInfo(live, info))
|
|
143
|
+
.filter((row): row is SessionRow => row !== undefined)
|
|
144
|
+
.toSorted(compareRows)
|
|
145
|
+
return { rows, complete: discovery.complete }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return { listChildren, discoverSubtree, discoverRows }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export type Discovery = ReturnType<typeof createDiscovery>
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Error as ToolError } from "@opencode/plugin/promise/tool"
|
|
2
|
+
|
|
3
|
+
export const REQUIRED_SESSION_ID = "sessionID is required."
|
|
4
|
+
export const REQUIRED_TEXT = "text is required."
|
|
5
|
+
export const OPENCODE_REQUIREMENT =
|
|
6
|
+
"subagent-tools requires an OpenCode build with ctx.session.list. See the README for the supported version."
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Refusals are tool errors, not successful results. OpenCode surfaces
|
|
10
|
+
* `Tool.Error` to the model with the reason, so the model can correct course
|
|
11
|
+
* instead of treating a refusal as normal output.
|
|
12
|
+
*/
|
|
13
|
+
export const toolError = (message: string): never => {
|
|
14
|
+
throw new ToolError({ message })
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const errorMessage = (error: unknown): string =>
|
|
18
|
+
error instanceof Error ? error.message : String(error)
|