opencode-subagent-tools 0.0.0-stage → 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.
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>;