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.
package/src/events.ts CHANGED
@@ -1,6 +1,12 @@
1
- import type { LiveStore } from "./live-state"
2
- import { normalizeSessionID } from "./session"
3
- import { BUSY_SESSION_STATUSES, SESSION_STATUS, STATUS, type ChildStatus } from "./status"
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";
4
10
 
5
11
  export const EVENT = {
6
12
  status: "session.status",
@@ -10,137 +16,172 @@ export const EVENT = {
10
16
  executionInterrupted: "session.execution.interrupted",
11
17
  deleted: "session.deleted",
12
18
  idle: "session.idle",
13
- } as const
19
+ shellStarted: "session.shell.started",
20
+ shellEnded: "session.shell.ended",
21
+ } as const;
14
22
 
15
- export type EventType = (typeof EVENT)[keyof typeof EVENT]
23
+ export type EventType = (typeof EVENT)[keyof typeof EVENT];
16
24
 
17
- export const SERVER_CONNECTED_EVENT = "server.connected"
25
+ export const SERVER_CONNECTED_EVENT = "server.connected";
18
26
 
19
27
  const EVENT_KIND = {
20
28
  status: "status",
21
29
  started: "started",
22
30
  terminal: "terminal",
23
- } as const
31
+ background: "background",
32
+ deleted: "deleted",
33
+ } as const;
24
34
 
25
35
  type EventMeta =
26
36
  | { kind: typeof EVENT_KIND.status }
27
37
  | { kind: typeof EVENT_KIND.started }
28
- | { kind: typeof EVENT_KIND.terminal; status: ChildStatus }
38
+ | { kind: typeof EVENT_KIND.terminal; status: RunStatus }
39
+ | { kind: typeof EVENT_KIND.background }
40
+ | { kind: typeof EVENT_KIND.deleted };
29
41
 
30
42
  export const EVENT_META: Readonly<Record<EventType, EventMeta>> = {
31
43
  [EVENT.status]: { kind: EVENT_KIND.status },
32
44
  [EVENT.executionStarted]: { kind: EVENT_KIND.started },
33
- [EVENT.executionSucceeded]: { kind: EVENT_KIND.terminal, status: STATUS.finished },
34
- [EVENT.executionFailed]: { kind: EVENT_KIND.terminal, status: STATUS.failed },
35
- [EVENT.executionInterrupted]: { kind: EVENT_KIND.terminal, status: STATUS.stopped },
36
- [EVENT.deleted]: { kind: EVENT_KIND.terminal, status: STATUS.stopped },
37
- [EVENT.idle]: { kind: EVENT_KIND.terminal, status: STATUS.unknown },
38
- }
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
+ };
39
53
 
40
54
  const EVENT_META_MAP: ReadonlyMap<string, EventMeta> = new Map(
41
55
  Object.entries(EVENT_META) as Array<[string, EventMeta]>,
42
- )
56
+ );
43
57
 
44
- export const EVENT_TYPES: readonly EventType[] = Object.keys(EVENT_META) as EventType[]
58
+ export const EVENT_TYPES: readonly EventType[] = Object.keys(EVENT_META) as EventType[];
45
59
 
46
- export const TERMINAL_EVENT_STATUS: ReadonlyMap<string, ChildStatus> = new Map(
60
+ export const TERMINAL_EVENT_STATUS: ReadonlyMap<string, RunStatus> = new Map(
47
61
  Object.entries(EVENT_META)
48
62
  .filter(
49
63
  (entry): entry is [string, Extract<EventMeta, { kind: "terminal" }>] =>
50
64
  entry[1].kind === EVENT_KIND.terminal,
51
65
  )
52
66
  .map(([type, meta]) => [type, meta.status]),
53
- )
67
+ );
54
68
 
55
- export const EVENT_RETRY_BASE_MS = 500
56
- export const EVENT_RETRY_MAX_MS = 30_000
69
+ export const EVENT_RETRY_BASE_MS = 500;
70
+ export const EVENT_RETRY_MAX_MS = 30_000;
57
71
 
58
72
  export interface EventLike {
59
- type?: string
60
- created?: number
73
+ type?: string;
74
+ created?: number;
61
75
  data?: {
62
- sessionID?: unknown
63
- status?: { type?: unknown }
64
- }
76
+ sessionID?: unknown;
77
+ status?: { type?: unknown };
78
+ shell?: { id?: unknown; status?: unknown };
79
+ };
65
80
  }
66
81
 
67
82
  export interface EventSubscriptionOptions {
68
- signal: AbortSignal
69
- types?: readonly EventType[]
70
- onActivity?: () => void
83
+ signal: AbortSignal;
84
+ types?: readonly EventType[];
85
+ onActivity?: () => void;
71
86
  }
72
87
 
73
88
  export interface EventApi {
74
- subscribe?: (options: EventSubscriptionOptions) => AsyncIterable<EventLike>
89
+ subscribe?: (options: EventSubscriptionOptions) => AsyncIterable<EventLike>;
75
90
  }
76
91
 
77
92
  export const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
78
93
  new Promise((resolve) => {
79
- if (signal.aborted) return resolve()
80
- let onAbort: () => void
94
+ if (signal.aborted) return resolve();
95
+ let onAbort: () => void;
81
96
  const timer = setTimeout(() => {
82
- signal.removeEventListener("abort", onAbort)
83
- resolve()
84
- }, ms)
97
+ signal.removeEventListener("abort", onAbort);
98
+ resolve();
99
+ }, ms);
85
100
  onAbort = () => {
86
- clearTimeout(timer)
87
- resolve()
88
- }
89
- signal.addEventListener("abort", onAbort, { once: true })
101
+ clearTimeout(timer);
102
+ resolve();
103
+ };
104
+ signal.addEventListener("abort", onAbort, { once: true });
90
105
  // Abort may have fired between the initial check and addEventListener.
91
- if (signal.aborted) onAbort()
92
- })
93
-
94
- export const handleEvent = (live: LiveStore, event: EventLike) => {
95
- const type = event?.type
96
- const data = event?.data ?? {}
97
- const id = normalizeSessionID(data.sessionID)
98
- if (!id) return
99
- const meta = type ? EVENT_META_MAP.get(type) : undefined
100
- if (!meta) return
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;
101
121
  const eventAt =
102
122
  typeof event?.created === "number" &&
103
123
  Number.isFinite(event.created) &&
104
124
  event.created > 0
105
125
  ? event.created
106
- : Date.now()
107
- const previous = live.live.get(id)
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);
108
148
 
109
149
  if (meta.kind === EVENT_KIND.status) {
110
- const kind = data.status?.type
111
- if (typeof kind !== "string") return
150
+ const kind = data.status?.type;
151
+ if (typeof kind !== "string") return;
112
152
  if (BUSY_SESSION_STATUSES.has(kind)) {
113
- if (eventAt <= live.lastTransitionAt(id)) return
114
- live.rememberStarted(id, eventAt)
115
- } else if (kind === SESSION_STATUS.idle) {
116
- if (eventAt < live.lastTransitionAt(id)) return
117
- if ((previous?.activeAt ?? 0) > 0 || previous?.status === STATUS.running) {
118
- live.rememberTerminal(id, STATUS.unknown, eventAt)
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);
119
159
  }
120
160
  }
121
- return
161
+ return;
122
162
  }
123
163
 
124
164
  if (meta.kind === EVENT_KIND.started) {
125
- if (eventAt <= live.lastTransitionAt(id)) return
126
- live.rememberStarted(id, eventAt)
127
- return
165
+ if (eventAt <= live.lastTransitionAt(id)) return;
166
+ live.rememberStarted(id, eventAt);
167
+ return;
128
168
  }
129
169
 
130
- if (eventAt < live.lastTransitionAt(id)) return
170
+ if (eventAt < live.lastTransitionAt(id)) return;
131
171
  if (
132
- meta.status === STATUS.unknown &&
172
+ meta.status === RUN_STATUS.unknown &&
133
173
  (previous?.activeAt ?? 0) === 0 &&
134
- previous?.status !== STATUS.running
174
+ previous?.status !== RUN_STATUS.running
135
175
  )
136
- return
137
- live.rememberTerminal(id, meta.status, eventAt)
138
- }
176
+ return;
177
+ live.rememberTerminal(id, meta.status, eventAt);
178
+ };
139
179
 
140
180
  export interface EventStreamDeps {
141
- event: EventApi | undefined
142
- live: LiveStore
143
- signal: AbortSignal
181
+ event: EventApi | undefined;
182
+ live: LiveStore;
183
+ background: BackgroundJobStore;
184
+ signal: AbortSignal;
144
185
  }
145
186
 
146
187
  /**
@@ -149,16 +190,21 @@ export interface EventStreamDeps {
149
190
  * event stream does not reconnect after a failure, so recreate it here;
150
191
  * `onActivity` also covers keepalive frames.
151
192
  */
152
- export const startEventStream = ({ event, live, signal }: EventStreamDeps) => {
153
- const subscribe = event?.subscribe
154
- if (typeof subscribe !== "function") return
155
-
156
- const subscribeBound = subscribe.bind(event)
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);
157
203
  void (async () => {
158
- let attempt = 0
204
+ let attempt = 0;
159
205
  while (!signal.aborted) {
160
- let healthy = false
161
- const connectedAt = Date.now()
206
+ let healthy = false;
207
+ const connectedAt = Date.now();
162
208
  try {
163
209
  const stream = subscribeBound({
164
210
  signal,
@@ -166,25 +212,25 @@ export const startEventStream = ({ event, live, signal }: EventStreamDeps) => {
166
212
  onActivity: () => {
167
213
  // Ignore the initial server.connected frame; only transport
168
214
  // activity after a short grace period proves the stream is live.
169
- if (Date.now() - connectedAt < EVENT_RETRY_BASE_MS) return
170
- healthy = true
171
- attempt = 0
215
+ if (Date.now() - connectedAt < EVENT_RETRY_BASE_MS) return;
216
+ healthy = true;
217
+ attempt = 0;
172
218
  },
173
- })
219
+ });
174
220
  for await (const incoming of stream) {
175
- if (incoming.type === SERVER_CONNECTED_EVENT) continue
176
- healthy = true
177
- attempt = 0
178
- handleEvent(live, incoming)
221
+ if (incoming.type === SERVER_CONNECTED_EVENT) continue;
222
+ healthy = true;
223
+ attempt = 0;
224
+ await handleEvent({ live, background }, incoming);
179
225
  }
180
226
  } catch (error) {
181
- if (signal.aborted) return
182
- console.error("subagent-tools: event stream stopped", error)
227
+ if (signal.aborted) return;
228
+ console.error("subagent-tools: event stream stopped", error);
183
229
  }
184
- if (signal.aborted) return
185
- const delay = Math.min(EVENT_RETRY_MAX_MS, EVENT_RETRY_BASE_MS * 2 ** attempt)
186
- if (!healthy) attempt++
187
- await sleep(delay, signal)
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);
188
234
  }
189
- })()
190
- }
235
+ })();
236
+ };
package/src/format.ts CHANGED
@@ -1,34 +1,34 @@
1
- const MILLISECONDS_PER_SECOND = 1000
2
- const SECONDS_PER_MINUTE = 60
3
- const SECONDS_PER_HOUR = 3600
1
+ const MILLISECONDS_PER_SECOND = 1000;
2
+ const SECONDS_PER_MINUTE = 60;
3
+ const SECONDS_PER_HOUR = 3600;
4
4
 
5
5
  export const compactNumber = (value: number): string => {
6
- if (!Number.isFinite(value)) return "0"
6
+ if (!Number.isFinite(value)) return "0";
7
7
  if (Math.abs(value) >= 1_000_000) {
8
- const millions = value / 1_000_000
9
- return `${Math.round(millions * 10) / 10}m`
8
+ const millions = value / 1_000_000;
9
+ return `${Math.round(millions * 10) / 10}m`;
10
10
  }
11
11
  if (Math.abs(value) >= 1_000) {
12
- const thousands = Math.round(value / 1_000)
12
+ const thousands = Math.round(value / 1_000);
13
13
  if (Math.abs(thousands) >= 1_000) {
14
- const millions = value / 1_000_000
15
- return `${Math.round(millions * 10) / 10}m`
14
+ const millions = value / 1_000_000;
15
+ return `${Math.round(millions * 10) / 10}m`;
16
16
  }
17
- return `${thousands}k`
17
+ return `${thousands}k`;
18
18
  }
19
- return String(Math.round(value))
20
- }
19
+ return String(Math.round(value));
20
+ };
21
21
 
22
22
  export const formatCost = (value: number): string =>
23
- value > 0 && value < 0.01 ? `$${value.toFixed(4)}` : `$${value.toFixed(2)}`
23
+ value > 0 && value < 0.01 ? `$${value.toFixed(4)}` : `$${value.toFixed(2)}`;
24
24
 
25
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
- }
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
32
 
33
33
  export const ageSeconds = (from: number): number =>
34
- Math.max(0, Math.floor((Date.now() - from) / MILLISECONDS_PER_SECOND))
34
+ Math.max(0, Math.floor((Date.now() - from) / MILLISECONDS_PER_SECOND));
package/src/index.ts CHANGED
@@ -28,57 +28,61 @@
28
28
  * through `ctx.permission.assert` with the action `subagent.control`.
29
29
  * `cancel_descendants` checks the whole batch in one permission request.
30
30
  *
31
- * Requires an OpenCode build with `ctx.session.list`.
31
+ * Requires OpenCode 2.3.0+.
32
32
  */
33
33
 
34
- import { Plugin } from "@opencode/plugin"
35
- import { createAccess } from "./access"
36
- import { resolveConfig } from "./config"
37
- import { createDiscovery } from "./discovery"
38
- import { OPENCODE_REQUIREMENT } from "./errors"
39
- import { startEventStream, type EventApi } from "./events"
40
- import { createLiveState } from "./live-state"
41
- import { createSendMessage } from "./messages"
42
- import { createGuard } from "./permissions"
43
- import type { SessionList } from "./session"
44
- import { registerSkill } from "./skill"
45
- import { registerTools } from "./tools"
34
+ import { Plugin } from "@opencode/plugin";
35
+ import { createAccess } from "./access";
36
+ import { createBackgroundJobStore, registerIdleHook } from "./background";
37
+ import { resolveConfig } from "./config";
38
+ import { createDiscovery } from "./discovery";
39
+ import { OPENCODE_REQUIREMENT } from "./errors";
40
+ import { startEventStream, type EventApi } from "./events";
41
+ import { createLiveState } from "./live-state";
42
+ import { createSendMessage } from "./messages";
43
+ import { createGuard } from "./permissions";
44
+ import type { SessionList } from "./session";
45
+ import { registerSkill } from "./skill";
46
+ import { registerTools } from "./tools";
46
47
 
47
48
  export default Plugin.define({
48
49
  id: "subagent-tools",
49
50
 
50
51
  async setup(ctx) {
51
- const config = resolveConfig(ctx.options)
52
+ const config = resolveConfig(ctx.options);
52
53
 
53
- const rawSessionList = (ctx.session as { list?: unknown }).list
54
+ const rawSessionList = (ctx.session as { list?: unknown }).list;
54
55
  const sessionList =
55
56
  typeof rawSessionList === "function"
56
57
  ? (rawSessionList.bind(ctx.session) as SessionList)
57
- : undefined
58
- if (!sessionList) throw new Error(OPENCODE_REQUIREMENT)
58
+ : undefined;
59
+ if (!sessionList) throw new Error(OPENCODE_REQUIREMENT);
59
60
 
60
- const live = createLiveState()
61
- const discovery = createDiscovery({
62
- sessionList,
63
- live,
64
- limits: config.limits,
65
- })
61
+ const live = createLiveState();
66
62
  const access = createAccess({
67
63
  session: ctx.session,
68
64
  limits: config.limits,
69
65
  policy: config.sessionControlPolicy,
70
66
  namespace: config.namespace,
71
- })
67
+ });
68
+ const background = createBackgroundJobStore();
69
+ const discovery = createDiscovery({
70
+ sessionList,
71
+ live,
72
+ background,
73
+ limits: config.limits,
74
+ });
72
75
  const guard = createGuard({
73
76
  permission: ctx.permission,
74
77
  enabled: config.enforcePermissions,
75
- })
78
+ });
76
79
  const sendMessage = createSendMessage({
77
80
  session: ctx.session,
78
81
  access,
79
82
  guard,
80
83
  live,
81
- })
84
+ background,
85
+ });
82
86
 
83
87
  const toolsRegistration = await ctx.tool.transform((editor) => {
84
88
  registerTools(editor, {
@@ -86,31 +90,40 @@ export default Plugin.define({
86
90
  access,
87
91
  discovery,
88
92
  live,
93
+ background,
89
94
  guard,
90
95
  sendMessage,
91
96
  session: ctx.session,
92
97
  model: ctx.model,
93
- })
94
- })
98
+ });
99
+ });
95
100
 
96
101
  const skillRegistration = config.registerSkill
97
102
  ? await registerSkill(ctx.skill)
98
- : undefined
103
+ : undefined;
104
+
105
+ // The idle hook is experimental and optional. Register it only after the
106
+ // tools and skill succeeded, so a setup failure cannot leave it behind.
107
+ const idleHook = await registerIdleHook(ctx.session, background);
99
108
 
100
109
  // Start the event stream only after tool registration succeeded, so a setup
101
110
  // failure cannot leave a background subscriber behind.
102
- const eventsAbort = new AbortController()
111
+ const eventsAbort = new AbortController();
103
112
  startEventStream({
104
113
  event: ctx.event as unknown as EventApi | undefined,
105
114
  live,
115
+ background,
106
116
  signal: eventsAbort.signal,
107
- })
117
+ });
108
118
 
109
119
  // Stop the event stream when the plugin unloads or its config reloads.
110
120
  return async () => {
111
- eventsAbort.abort()
112
- if (skillRegistration) await skillRegistration.dispose().catch(() => undefined)
113
- await toolsRegistration.dispose().catch(() => undefined)
114
- }
121
+ eventsAbort.abort();
122
+ if (idleHook && typeof idleHook.dispose === "function") {
123
+ await idleHook.dispose().catch(() => undefined);
124
+ }
125
+ if (skillRegistration) await skillRegistration.dispose().catch(() => undefined);
126
+ await toolsRegistration.dispose().catch(() => undefined);
127
+ };
115
128
  },
116
- })
129
+ });
package/src/interrupt.ts CHANGED
@@ -3,11 +3,11 @@ export const INTERRUPT_OUTCOME = {
3
3
  rejected: "rejected",
4
4
  failed: "failed",
5
5
  unknown: "unknown",
6
- } as const
6
+ } as const;
7
7
 
8
- export type InterruptOutcome = (typeof INTERRUPT_OUTCOME)[keyof typeof INTERRUPT_OUTCOME]
8
+ export type InterruptOutcome = (typeof INTERRUPT_OUTCOME)[keyof typeof INTERRUPT_OUTCOME];
9
9
 
10
- export type InterruptResponse = { interrupted?: boolean } | undefined
10
+ export type InterruptResponse = { interrupted?: boolean } | undefined;
11
11
 
12
12
  /** Map the server's optional boolean to an outcome. `failed` is a thrown call. */
13
13
  export const interruptOutcome = (
@@ -17,4 +17,4 @@ export const interruptOutcome = (
17
17
  ? INTERRUPT_OUTCOME.accepted
18
18
  : result?.interrupted === false
19
19
  ? INTERRUPT_OUTCOME.rejected
20
- : INTERRUPT_OUTCOME.unknown
20
+ : INTERRUPT_OUTCOME.unknown;