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/CHANGELOG.md +49 -0
- package/LICENSE +21 -0
- package/README.md +118 -2
- package/SECURITY.md +36 -0
- package/SKILL.md +345 -0
- package/docs/configuration.md +238 -0
- package/docs/development.md +82 -0
- package/docs/installation.md +131 -0
- package/docs/limitations.md +155 -0
- package/docs/reference.md +398 -0
- package/docs/security-model.md +79 -0
- package/package.json +74 -4
- package/src/access.ts +236 -0
- package/src/background.ts +591 -0
- package/src/config.ts +143 -0
- package/src/cursor.ts +114 -0
- package/src/discovery.ts +159 -0
- package/src/errors.ts +18 -0
- package/src/events.ts +236 -0
- package/src/format.ts +34 -0
- package/src/index.ts +129 -0
- package/src/interrupt.ts +20 -0
- package/src/live-state.ts +113 -0
- package/src/messages.ts +246 -0
- package/src/permissions.ts +62 -0
- package/src/session-row.ts +116 -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 +660 -0
- package/src/tools/cancel.ts +271 -0
- package/src/tools/index.ts +41 -0
- package/src/tools/input.ts +75 -0
- package/src/tools/list.ts +608 -0
- package/src/tools/names.ts +11 -0
- package/src/tools/output.ts +169 -0
- package/src/tools/send.ts +369 -0
- package/src/tools/usage.ts +434 -0
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,114 @@
|
|
|
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(
|
|
36
|
+
Buffer.from(value, "base64url").toString("utf8"),
|
|
37
|
+
) as unknown;
|
|
38
|
+
if (!parsed || typeof parsed !== "object") return undefined;
|
|
39
|
+
const payload = parsed as Record<string, unknown>;
|
|
40
|
+
if (payload.v !== CURSOR_VERSION) return undefined;
|
|
41
|
+
if (!isCursorTool(payload.tool)) return undefined;
|
|
42
|
+
if (typeof payload.root !== "string" || payload.root.length === 0) return undefined;
|
|
43
|
+
if (payload.filter !== undefined && typeof payload.filter !== "string")
|
|
44
|
+
return undefined;
|
|
45
|
+
if (
|
|
46
|
+
typeof payload.launchedAt !== "number" ||
|
|
47
|
+
!Number.isFinite(payload.launchedAt) ||
|
|
48
|
+
payload.launchedAt < 0
|
|
49
|
+
) {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
if (typeof payload.id !== "string" || payload.id.length === 0) return undefined;
|
|
53
|
+
return {
|
|
54
|
+
v: CURSOR_VERSION,
|
|
55
|
+
tool: payload.tool,
|
|
56
|
+
root: payload.root,
|
|
57
|
+
filter: payload.filter as string | undefined,
|
|
58
|
+
launchedAt: payload.launchedAt,
|
|
59
|
+
id: payload.id,
|
|
60
|
+
};
|
|
61
|
+
} catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export const encodeCursor = (
|
|
67
|
+
row: Pick<SessionRow, "launchedAt" | "id">,
|
|
68
|
+
scope: CursorScope,
|
|
69
|
+
): string =>
|
|
70
|
+
encodePayload({
|
|
71
|
+
v: CURSOR_VERSION,
|
|
72
|
+
tool: scope.tool,
|
|
73
|
+
root: scope.root,
|
|
74
|
+
filter: scope.filter,
|
|
75
|
+
launchedAt: row.launchedAt,
|
|
76
|
+
id: row.id,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const invalidCursorMessage = (toolName: ToolName): string =>
|
|
80
|
+
`Invalid cursor. Re-run the previous ${toolName} call and use the cursor it reported.`;
|
|
81
|
+
|
|
82
|
+
export const readCursor = (
|
|
83
|
+
value: unknown,
|
|
84
|
+
scope: CursorScope,
|
|
85
|
+
): { cursor?: PageCursor; error?: string } => {
|
|
86
|
+
if (value === undefined) return {};
|
|
87
|
+
if (
|
|
88
|
+
typeof value !== "string" ||
|
|
89
|
+
value.length === 0 ||
|
|
90
|
+
value.length > MAX_CURSOR_LENGTH
|
|
91
|
+
) {
|
|
92
|
+
return { error: invalidCursorMessage(scope.tool) };
|
|
93
|
+
}
|
|
94
|
+
const payload = decodePayload(value);
|
|
95
|
+
if (
|
|
96
|
+
!payload ||
|
|
97
|
+
payload.tool !== scope.tool ||
|
|
98
|
+
payload.root !== scope.root ||
|
|
99
|
+
(payload.filter ?? "") !== (scope.filter ?? "")
|
|
100
|
+
) {
|
|
101
|
+
return { error: invalidCursorMessage(scope.tool) };
|
|
102
|
+
}
|
|
103
|
+
return { cursor: { launchedAt: payload.launchedAt, id: payload.id } };
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const compareIds = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
|
|
107
|
+
|
|
108
|
+
/** Newest launch first, then a deterministic ID tie-break for stable paging. */
|
|
109
|
+
export const compareRows = (a: SessionRow, b: SessionRow): number =>
|
|
110
|
+
(b.launchedAt ?? 0) - (a.launchedAt ?? 0) || compareIds(a.id, b.id);
|
|
111
|
+
|
|
112
|
+
export const isAfterCursor = (row: SessionRow, cursor: PageCursor): boolean =>
|
|
113
|
+
row.launchedAt < cursor.launchedAt ||
|
|
114
|
+
(row.launchedAt === cursor.launchedAt && compareIds(row.id, cursor.id) > 0);
|
package/src/discovery.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import type { BackgroundJobStore } from "./background";
|
|
2
|
+
import type { ResolvedLimits } from "./config";
|
|
3
|
+
import { compareRows } from "./cursor";
|
|
4
|
+
import type { LiveStore } from "./live-state";
|
|
5
|
+
import {
|
|
6
|
+
normalizeSessionID,
|
|
7
|
+
readSessionListPage,
|
|
8
|
+
type SessionInfoLike,
|
|
9
|
+
type SessionList,
|
|
10
|
+
type SessionListResult,
|
|
11
|
+
} from "./session";
|
|
12
|
+
import { applySubtreeActivity, rowFromInfo, type SessionRow } from "./session-row";
|
|
13
|
+
|
|
14
|
+
export const MAX_DISCOVERY_PAGE_SIZE = 100;
|
|
15
|
+
|
|
16
|
+
export interface DiscoveryResult {
|
|
17
|
+
items: SessionInfoLike[];
|
|
18
|
+
complete: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DiscoveryDeps {
|
|
22
|
+
sessionList: SessionList;
|
|
23
|
+
live: LiveStore;
|
|
24
|
+
background: BackgroundJobStore;
|
|
25
|
+
limits: Pick<
|
|
26
|
+
ResolvedLimits,
|
|
27
|
+
"maxDiscoveryNodes" | "maxDiscoveryDepth" | "maxDiscoveryPages"
|
|
28
|
+
>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const createDiscovery = ({
|
|
32
|
+
sessionList,
|
|
33
|
+
live,
|
|
34
|
+
background,
|
|
35
|
+
limits,
|
|
36
|
+
}: DiscoveryDeps) => {
|
|
37
|
+
const { maxDiscoveryNodes, maxDiscoveryDepth, maxDiscoveryPages } = limits;
|
|
38
|
+
|
|
39
|
+
const listChildren = async (
|
|
40
|
+
parentID: string,
|
|
41
|
+
signal?: AbortSignal,
|
|
42
|
+
): Promise<DiscoveryResult> => {
|
|
43
|
+
const items: SessionInfoLike[] = [];
|
|
44
|
+
let cursor: string | undefined;
|
|
45
|
+
let complete = true;
|
|
46
|
+
for (let pageIndex = 0; pageIndex < maxDiscoveryPages; pageIndex++) {
|
|
47
|
+
if (signal?.aborted) return { items, complete: false };
|
|
48
|
+
let result: SessionListResult | undefined;
|
|
49
|
+
try {
|
|
50
|
+
result = await sessionList(
|
|
51
|
+
{
|
|
52
|
+
parentID,
|
|
53
|
+
limit: MAX_DISCOVERY_PAGE_SIZE,
|
|
54
|
+
order: "desc",
|
|
55
|
+
archived: false,
|
|
56
|
+
...(cursor ? { cursor } : {}),
|
|
57
|
+
},
|
|
58
|
+
{ signal },
|
|
59
|
+
);
|
|
60
|
+
} catch {
|
|
61
|
+
return { items, complete: false };
|
|
62
|
+
}
|
|
63
|
+
if (signal?.aborted) return { items, complete: false };
|
|
64
|
+
const page = readSessionListPage(result);
|
|
65
|
+
if (!page.valid) complete = false;
|
|
66
|
+
items.push(...page.items);
|
|
67
|
+
const previousCursor = cursor;
|
|
68
|
+
cursor = page.cursor;
|
|
69
|
+
if (!cursor) {
|
|
70
|
+
// A full page without a cursor may still be truncated; a short page
|
|
71
|
+
// without a cursor is a clean end.
|
|
72
|
+
if (page.items.length >= MAX_DISCOVERY_PAGE_SIZE) complete = false;
|
|
73
|
+
return { items, complete };
|
|
74
|
+
}
|
|
75
|
+
// A cursor is the primary signal that more rows exist. Do not stop on a
|
|
76
|
+
// short page: a proxy or server may cap the page below the requested
|
|
77
|
+
// limit and still return a cursor.
|
|
78
|
+
if (cursor === previousCursor) {
|
|
79
|
+
// A repeated cursor cannot make progress.
|
|
80
|
+
complete = false;
|
|
81
|
+
return { items, complete };
|
|
82
|
+
}
|
|
83
|
+
if (pageIndex === maxDiscoveryPages - 1) complete = false;
|
|
84
|
+
}
|
|
85
|
+
return { items, complete };
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Refresh a subtree from the server. The parentID filter is applied
|
|
90
|
+
* server-side and checked again so an ignored filter cannot pull in
|
|
91
|
+
* unrelated sessions. `complete` reports whether a limit, failure, or
|
|
92
|
+
* cancellation may have truncated the walk.
|
|
93
|
+
*/
|
|
94
|
+
const discoverSubtree = async (
|
|
95
|
+
root: string,
|
|
96
|
+
signal?: AbortSignal,
|
|
97
|
+
): Promise<DiscoveryResult> => {
|
|
98
|
+
const seen = new Set<string>([root]);
|
|
99
|
+
const queue: Array<{ id: string; depth: number }> = [{ id: root, depth: 0 }];
|
|
100
|
+
const items: SessionInfoLike[] = [];
|
|
101
|
+
let complete = true;
|
|
102
|
+
let discovered = 0;
|
|
103
|
+
|
|
104
|
+
for (let index = 0; index < queue.length; index++) {
|
|
105
|
+
if (signal?.aborted) return { items, complete: false };
|
|
106
|
+
const current = queue[index];
|
|
107
|
+
if (current.depth >= maxDiscoveryDepth) {
|
|
108
|
+
// This node may have children we deliberately did not inspect.
|
|
109
|
+
complete = false;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const children = await listChildren(current.id, signal);
|
|
113
|
+
if (!children.complete) complete = false;
|
|
114
|
+
for (const info of children.items) {
|
|
115
|
+
if (discovered >= maxDiscoveryNodes) {
|
|
116
|
+
complete = false;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
const id = normalizeSessionID(info.id);
|
|
120
|
+
if (!id) {
|
|
121
|
+
complete = false;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (seen.has(id)) continue;
|
|
125
|
+
const parentID = normalizeSessionID(info.parentID);
|
|
126
|
+
if (parentID !== current.id) {
|
|
127
|
+
complete = false;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
seen.add(id);
|
|
131
|
+
items.push(info);
|
|
132
|
+
discovered++;
|
|
133
|
+
queue.push({ id, depth: current.depth + 1 });
|
|
134
|
+
}
|
|
135
|
+
if (discovered >= maxDiscoveryNodes) {
|
|
136
|
+
complete = false;
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return { items, complete };
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const discoverRows = async (
|
|
144
|
+
root: string,
|
|
145
|
+
signal?: AbortSignal,
|
|
146
|
+
): Promise<{ rows: SessionRow[]; complete: boolean }> => {
|
|
147
|
+
const discovery = await discoverSubtree(root, signal);
|
|
148
|
+
const rows = discovery.items
|
|
149
|
+
.map((info) => rowFromInfo(live, background, info))
|
|
150
|
+
.filter((row): row is SessionRow => row !== undefined)
|
|
151
|
+
.toSorted(compareRows);
|
|
152
|
+
applySubtreeActivity(rows);
|
|
153
|
+
return { rows, complete: discovery.complete };
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
return { listChildren, discoverSubtree, discoverRows };
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
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 OpenCode 2.3.0+ with ctx.session.list. See the README.";
|
|
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);
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import type { BackgroundJobStore } from "./background";
|
|
2
|
+
import type { LiveStore } from "./live-state";
|
|
3
|
+
import { normalizeSessionID } from "./session";
|
|
4
|
+
import {
|
|
5
|
+
BUSY_SESSION_STATUSES,
|
|
6
|
+
OPENCODE_SESSION_STATUS,
|
|
7
|
+
RUN_STATUS,
|
|
8
|
+
type RunStatus,
|
|
9
|
+
} from "./status";
|
|
10
|
+
|
|
11
|
+
export const EVENT = {
|
|
12
|
+
status: "session.status",
|
|
13
|
+
executionStarted: "session.execution.started",
|
|
14
|
+
executionSucceeded: "session.execution.succeeded",
|
|
15
|
+
executionFailed: "session.execution.failed",
|
|
16
|
+
executionInterrupted: "session.execution.interrupted",
|
|
17
|
+
deleted: "session.deleted",
|
|
18
|
+
idle: "session.idle",
|
|
19
|
+
shellStarted: "session.shell.started",
|
|
20
|
+
shellEnded: "session.shell.ended",
|
|
21
|
+
} as const;
|
|
22
|
+
|
|
23
|
+
export type EventType = (typeof EVENT)[keyof typeof EVENT];
|
|
24
|
+
|
|
25
|
+
export const SERVER_CONNECTED_EVENT = "server.connected";
|
|
26
|
+
|
|
27
|
+
const EVENT_KIND = {
|
|
28
|
+
status: "status",
|
|
29
|
+
started: "started",
|
|
30
|
+
terminal: "terminal",
|
|
31
|
+
background: "background",
|
|
32
|
+
deleted: "deleted",
|
|
33
|
+
} as const;
|
|
34
|
+
|
|
35
|
+
type EventMeta =
|
|
36
|
+
| { kind: typeof EVENT_KIND.status }
|
|
37
|
+
| { kind: typeof EVENT_KIND.started }
|
|
38
|
+
| { kind: typeof EVENT_KIND.terminal; status: RunStatus }
|
|
39
|
+
| { kind: typeof EVENT_KIND.background }
|
|
40
|
+
| { kind: typeof EVENT_KIND.deleted };
|
|
41
|
+
|
|
42
|
+
export const EVENT_META: Readonly<Record<EventType, EventMeta>> = {
|
|
43
|
+
[EVENT.status]: { kind: EVENT_KIND.status },
|
|
44
|
+
[EVENT.executionStarted]: { kind: EVENT_KIND.started },
|
|
45
|
+
[EVENT.executionSucceeded]: { kind: EVENT_KIND.terminal, status: RUN_STATUS.finished },
|
|
46
|
+
[EVENT.executionFailed]: { kind: EVENT_KIND.terminal, status: RUN_STATUS.failed },
|
|
47
|
+
[EVENT.executionInterrupted]: { kind: EVENT_KIND.terminal, status: RUN_STATUS.stopped },
|
|
48
|
+
[EVENT.deleted]: { kind: EVENT_KIND.deleted },
|
|
49
|
+
[EVENT.idle]: { kind: EVENT_KIND.terminal, status: RUN_STATUS.unknown },
|
|
50
|
+
[EVENT.shellStarted]: { kind: EVENT_KIND.background },
|
|
51
|
+
[EVENT.shellEnded]: { kind: EVENT_KIND.background },
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const EVENT_META_MAP: ReadonlyMap<string, EventMeta> = new Map(
|
|
55
|
+
Object.entries(EVENT_META) as Array<[string, EventMeta]>,
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
export const EVENT_TYPES: readonly EventType[] = Object.keys(EVENT_META) as EventType[];
|
|
59
|
+
|
|
60
|
+
export const TERMINAL_EVENT_STATUS: ReadonlyMap<string, RunStatus> = new Map(
|
|
61
|
+
Object.entries(EVENT_META)
|
|
62
|
+
.filter(
|
|
63
|
+
(entry): entry is [string, Extract<EventMeta, { kind: "terminal" }>] =>
|
|
64
|
+
entry[1].kind === EVENT_KIND.terminal,
|
|
65
|
+
)
|
|
66
|
+
.map(([type, meta]) => [type, meta.status]),
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
export const EVENT_RETRY_BASE_MS = 500;
|
|
70
|
+
export const EVENT_RETRY_MAX_MS = 30_000;
|
|
71
|
+
|
|
72
|
+
export interface EventLike {
|
|
73
|
+
type?: string;
|
|
74
|
+
created?: number;
|
|
75
|
+
data?: {
|
|
76
|
+
sessionID?: unknown;
|
|
77
|
+
status?: { type?: unknown };
|
|
78
|
+
shell?: { id?: unknown; status?: unknown };
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface EventSubscriptionOptions {
|
|
83
|
+
signal: AbortSignal;
|
|
84
|
+
types?: readonly EventType[];
|
|
85
|
+
onActivity?: () => void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface EventApi {
|
|
89
|
+
subscribe?: (options: EventSubscriptionOptions) => AsyncIterable<EventLike>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
|
|
93
|
+
new Promise((resolve) => {
|
|
94
|
+
if (signal.aborted) return resolve();
|
|
95
|
+
let onAbort: () => void;
|
|
96
|
+
const timer = setTimeout(() => {
|
|
97
|
+
signal.removeEventListener("abort", onAbort);
|
|
98
|
+
resolve();
|
|
99
|
+
}, ms);
|
|
100
|
+
onAbort = () => {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
resolve();
|
|
103
|
+
};
|
|
104
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
105
|
+
// Abort may have fired between the initial check and addEventListener.
|
|
106
|
+
if (signal.aborted) onAbort();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
export interface EventDeps {
|
|
110
|
+
live: LiveStore;
|
|
111
|
+
background: BackgroundJobStore;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export const handleEvent = async ({ live, background }: EventDeps, event: EventLike) => {
|
|
115
|
+
const type = event?.type;
|
|
116
|
+
const data = event?.data ?? {};
|
|
117
|
+
const id = normalizeSessionID(data.sessionID);
|
|
118
|
+
if (!id) return;
|
|
119
|
+
const meta = type ? EVENT_META_MAP.get(type) : undefined;
|
|
120
|
+
if (!meta) return;
|
|
121
|
+
const eventAt =
|
|
122
|
+
typeof event?.created === "number" &&
|
|
123
|
+
Number.isFinite(event.created) &&
|
|
124
|
+
event.created > 0
|
|
125
|
+
? event.created
|
|
126
|
+
: Date.now();
|
|
127
|
+
|
|
128
|
+
if (meta.kind === EVENT_KIND.deleted) {
|
|
129
|
+
live.forget(id);
|
|
130
|
+
background.recordDeleted(id, eventAt);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (meta.kind === EVENT_KIND.background) {
|
|
135
|
+
if (type === EVENT.shellStarted) {
|
|
136
|
+
background.recordShellStarted(id, data.shell?.id, eventAt);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (type === EVENT.shellEnded) {
|
|
140
|
+
if (data.shell?.status === "running") return;
|
|
141
|
+
background.recordShellEnded(id, data.shell?.id, eventAt);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const previous = live.live.get(id);
|
|
148
|
+
|
|
149
|
+
if (meta.kind === EVENT_KIND.status) {
|
|
150
|
+
const kind = data.status?.type;
|
|
151
|
+
if (typeof kind !== "string") return;
|
|
152
|
+
if (BUSY_SESSION_STATUSES.has(kind)) {
|
|
153
|
+
if (eventAt <= live.lastTransitionAt(id)) return;
|
|
154
|
+
live.rememberStarted(id, eventAt);
|
|
155
|
+
} else if (kind === OPENCODE_SESSION_STATUS.idle) {
|
|
156
|
+
if (eventAt < live.lastTransitionAt(id)) return;
|
|
157
|
+
if ((previous?.activeAt ?? 0) > 0 || previous?.status === RUN_STATUS.running) {
|
|
158
|
+
live.rememberTerminal(id, RUN_STATUS.unknown, eventAt);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (meta.kind === EVENT_KIND.started) {
|
|
165
|
+
if (eventAt <= live.lastTransitionAt(id)) return;
|
|
166
|
+
live.rememberStarted(id, eventAt);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (eventAt < live.lastTransitionAt(id)) return;
|
|
171
|
+
if (
|
|
172
|
+
meta.status === RUN_STATUS.unknown &&
|
|
173
|
+
(previous?.activeAt ?? 0) === 0 &&
|
|
174
|
+
previous?.status !== RUN_STATUS.running
|
|
175
|
+
)
|
|
176
|
+
return;
|
|
177
|
+
live.rememberTerminal(id, meta.status, eventAt);
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
export interface EventStreamDeps {
|
|
181
|
+
event: EventApi | undefined;
|
|
182
|
+
live: LiveStore;
|
|
183
|
+
background: BackgroundJobStore;
|
|
184
|
+
signal: AbortSignal;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Start the event stream only after tool registration succeeded, so a setup
|
|
189
|
+
* failure cannot leave a background subscriber behind. OpenCode's shared
|
|
190
|
+
* event stream does not reconnect after a failure, so recreate it here;
|
|
191
|
+
* `onActivity` also covers keepalive frames.
|
|
192
|
+
*/
|
|
193
|
+
export const startEventStream = ({
|
|
194
|
+
event,
|
|
195
|
+
live,
|
|
196
|
+
background,
|
|
197
|
+
signal,
|
|
198
|
+
}: EventStreamDeps) => {
|
|
199
|
+
const subscribe = event?.subscribe;
|
|
200
|
+
if (typeof subscribe !== "function") return;
|
|
201
|
+
|
|
202
|
+
const subscribeBound = subscribe.bind(event);
|
|
203
|
+
void (async () => {
|
|
204
|
+
let attempt = 0;
|
|
205
|
+
while (!signal.aborted) {
|
|
206
|
+
let healthy = false;
|
|
207
|
+
const connectedAt = Date.now();
|
|
208
|
+
try {
|
|
209
|
+
const stream = subscribeBound({
|
|
210
|
+
signal,
|
|
211
|
+
types: EVENT_TYPES,
|
|
212
|
+
onActivity: () => {
|
|
213
|
+
// Ignore the initial server.connected frame; only transport
|
|
214
|
+
// activity after a short grace period proves the stream is live.
|
|
215
|
+
if (Date.now() - connectedAt < EVENT_RETRY_BASE_MS) return;
|
|
216
|
+
healthy = true;
|
|
217
|
+
attempt = 0;
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
for await (const incoming of stream) {
|
|
221
|
+
if (incoming.type === SERVER_CONNECTED_EVENT) continue;
|
|
222
|
+
healthy = true;
|
|
223
|
+
attempt = 0;
|
|
224
|
+
await handleEvent({ live, background }, incoming);
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (signal.aborted) return;
|
|
228
|
+
console.error("subagent-tools: event stream stopped", error);
|
|
229
|
+
}
|
|
230
|
+
if (signal.aborted) return;
|
|
231
|
+
const delay = Math.min(EVENT_RETRY_MAX_MS, EVENT_RETRY_BASE_MS * 2 ** attempt);
|
|
232
|
+
if (!healthy) attempt++;
|
|
233
|
+
await sleep(delay, signal);
|
|
234
|
+
}
|
|
235
|
+
})();
|
|
236
|
+
};
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const MILLISECONDS_PER_SECOND = 1000;
|
|
2
|
+
const SECONDS_PER_MINUTE = 60;
|
|
3
|
+
const SECONDS_PER_HOUR = 3600;
|
|
4
|
+
|
|
5
|
+
export const compactNumber = (value: number): string => {
|
|
6
|
+
if (!Number.isFinite(value)) return "0";
|
|
7
|
+
if (Math.abs(value) >= 1_000_000) {
|
|
8
|
+
const millions = value / 1_000_000;
|
|
9
|
+
return `${Math.round(millions * 10) / 10}m`;
|
|
10
|
+
}
|
|
11
|
+
if (Math.abs(value) >= 1_000) {
|
|
12
|
+
const thousands = Math.round(value / 1_000);
|
|
13
|
+
if (Math.abs(thousands) >= 1_000) {
|
|
14
|
+
const millions = value / 1_000_000;
|
|
15
|
+
return `${Math.round(millions * 10) / 10}m`;
|
|
16
|
+
}
|
|
17
|
+
return `${thousands}k`;
|
|
18
|
+
}
|
|
19
|
+
return String(Math.round(value));
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const formatCost = (value: number): string =>
|
|
23
|
+
value > 0 && value < 0.01 ? `$${value.toFixed(4)}` : `$${value.toFixed(2)}`;
|
|
24
|
+
|
|
25
|
+
export const age = (from: number): string => {
|
|
26
|
+
const total = Math.max(0, Math.floor((Date.now() - from) / MILLISECONDS_PER_SECOND));
|
|
27
|
+
if (total < SECONDS_PER_MINUTE) return `${total}s`;
|
|
28
|
+
const minutes = Math.floor(total / SECONDS_PER_MINUTE);
|
|
29
|
+
if (minutes < SECONDS_PER_HOUR) return `${minutes}m`;
|
|
30
|
+
return `${Math.floor(minutes / SECONDS_PER_MINUTE)}h`;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const ageSeconds = (from: number): number =>
|
|
34
|
+
Math.max(0, Math.floor((Date.now() - from) / MILLISECONDS_PER_SECOND));
|