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/events.ts
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import type { LiveStore } from "./live-state"
|
|
2
|
+
import { normalizeSessionID } from "./session"
|
|
3
|
+
import { BUSY_SESSION_STATUSES, SESSION_STATUS, STATUS, type ChildStatus } from "./status"
|
|
4
|
+
|
|
5
|
+
export const EVENT = {
|
|
6
|
+
status: "session.status",
|
|
7
|
+
executionStarted: "session.execution.started",
|
|
8
|
+
executionSucceeded: "session.execution.succeeded",
|
|
9
|
+
executionFailed: "session.execution.failed",
|
|
10
|
+
executionInterrupted: "session.execution.interrupted",
|
|
11
|
+
deleted: "session.deleted",
|
|
12
|
+
idle: "session.idle",
|
|
13
|
+
} as const
|
|
14
|
+
|
|
15
|
+
export type EventType = (typeof EVENT)[keyof typeof EVENT]
|
|
16
|
+
|
|
17
|
+
export const SERVER_CONNECTED_EVENT = "server.connected"
|
|
18
|
+
|
|
19
|
+
const EVENT_KIND = {
|
|
20
|
+
status: "status",
|
|
21
|
+
started: "started",
|
|
22
|
+
terminal: "terminal",
|
|
23
|
+
} as const
|
|
24
|
+
|
|
25
|
+
type EventMeta =
|
|
26
|
+
| { kind: typeof EVENT_KIND.status }
|
|
27
|
+
| { kind: typeof EVENT_KIND.started }
|
|
28
|
+
| { kind: typeof EVENT_KIND.terminal; status: ChildStatus }
|
|
29
|
+
|
|
30
|
+
export const EVENT_META: Readonly<Record<EventType, EventMeta>> = {
|
|
31
|
+
[EVENT.status]: { kind: EVENT_KIND.status },
|
|
32
|
+
[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
|
+
}
|
|
39
|
+
|
|
40
|
+
const EVENT_META_MAP: ReadonlyMap<string, EventMeta> = new Map(
|
|
41
|
+
Object.entries(EVENT_META) as Array<[string, EventMeta]>,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
export const EVENT_TYPES: readonly EventType[] = Object.keys(EVENT_META) as EventType[]
|
|
45
|
+
|
|
46
|
+
export const TERMINAL_EVENT_STATUS: ReadonlyMap<string, ChildStatus> = new Map(
|
|
47
|
+
Object.entries(EVENT_META)
|
|
48
|
+
.filter(
|
|
49
|
+
(entry): entry is [string, Extract<EventMeta, { kind: "terminal" }>] =>
|
|
50
|
+
entry[1].kind === EVENT_KIND.terminal,
|
|
51
|
+
)
|
|
52
|
+
.map(([type, meta]) => [type, meta.status]),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
export const EVENT_RETRY_BASE_MS = 500
|
|
56
|
+
export const EVENT_RETRY_MAX_MS = 30_000
|
|
57
|
+
|
|
58
|
+
export interface EventLike {
|
|
59
|
+
type?: string
|
|
60
|
+
created?: number
|
|
61
|
+
data?: {
|
|
62
|
+
sessionID?: unknown
|
|
63
|
+
status?: { type?: unknown }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface EventSubscriptionOptions {
|
|
68
|
+
signal: AbortSignal
|
|
69
|
+
types?: readonly EventType[]
|
|
70
|
+
onActivity?: () => void
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface EventApi {
|
|
74
|
+
subscribe?: (options: EventSubscriptionOptions) => AsyncIterable<EventLike>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
|
|
78
|
+
new Promise((resolve) => {
|
|
79
|
+
if (signal.aborted) return resolve()
|
|
80
|
+
let onAbort: () => void
|
|
81
|
+
const timer = setTimeout(() => {
|
|
82
|
+
signal.removeEventListener("abort", onAbort)
|
|
83
|
+
resolve()
|
|
84
|
+
}, ms)
|
|
85
|
+
onAbort = () => {
|
|
86
|
+
clearTimeout(timer)
|
|
87
|
+
resolve()
|
|
88
|
+
}
|
|
89
|
+
signal.addEventListener("abort", onAbort, { once: true })
|
|
90
|
+
// 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
|
|
101
|
+
const eventAt =
|
|
102
|
+
typeof event?.created === "number" &&
|
|
103
|
+
Number.isFinite(event.created) &&
|
|
104
|
+
event.created > 0
|
|
105
|
+
? event.created
|
|
106
|
+
: Date.now()
|
|
107
|
+
const previous = live.live.get(id)
|
|
108
|
+
|
|
109
|
+
if (meta.kind === EVENT_KIND.status) {
|
|
110
|
+
const kind = data.status?.type
|
|
111
|
+
if (typeof kind !== "string") return
|
|
112
|
+
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)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (meta.kind === EVENT_KIND.started) {
|
|
125
|
+
if (eventAt <= live.lastTransitionAt(id)) return
|
|
126
|
+
live.rememberStarted(id, eventAt)
|
|
127
|
+
return
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (eventAt < live.lastTransitionAt(id)) return
|
|
131
|
+
if (
|
|
132
|
+
meta.status === STATUS.unknown &&
|
|
133
|
+
(previous?.activeAt ?? 0) === 0 &&
|
|
134
|
+
previous?.status !== STATUS.running
|
|
135
|
+
)
|
|
136
|
+
return
|
|
137
|
+
live.rememberTerminal(id, meta.status, eventAt)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface EventStreamDeps {
|
|
141
|
+
event: EventApi | undefined
|
|
142
|
+
live: LiveStore
|
|
143
|
+
signal: AbortSignal
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Start the event stream only after tool registration succeeded, so a setup
|
|
148
|
+
* failure cannot leave a background subscriber behind. OpenCode's shared
|
|
149
|
+
* event stream does not reconnect after a failure, so recreate it here;
|
|
150
|
+
* `onActivity` also covers keepalive frames.
|
|
151
|
+
*/
|
|
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)
|
|
157
|
+
void (async () => {
|
|
158
|
+
let attempt = 0
|
|
159
|
+
while (!signal.aborted) {
|
|
160
|
+
let healthy = false
|
|
161
|
+
const connectedAt = Date.now()
|
|
162
|
+
try {
|
|
163
|
+
const stream = subscribeBound({
|
|
164
|
+
signal,
|
|
165
|
+
types: EVENT_TYPES,
|
|
166
|
+
onActivity: () => {
|
|
167
|
+
// Ignore the initial server.connected frame; only transport
|
|
168
|
+
// 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
|
|
172
|
+
},
|
|
173
|
+
})
|
|
174
|
+
for await (const incoming of stream) {
|
|
175
|
+
if (incoming.type === SERVER_CONNECTED_EVENT) continue
|
|
176
|
+
healthy = true
|
|
177
|
+
attempt = 0
|
|
178
|
+
handleEvent(live, incoming)
|
|
179
|
+
}
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (signal.aborted) return
|
|
182
|
+
console.error("subagent-tools: event stream stopped", error)
|
|
183
|
+
}
|
|
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)
|
|
188
|
+
}
|
|
189
|
+
})()
|
|
190
|
+
}
|
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))
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* subagent-tools — discovery-first control for OpenCode subagents.
|
|
3
|
+
*
|
|
4
|
+
* OpenCode exposes `session.list`, `session.get`, `session.interrupt`, and
|
|
5
|
+
* `session.prompt { delivery: "steer" }` to plugins. This plugin adds the
|
|
6
|
+
* model-facing surface:
|
|
7
|
+
*
|
|
8
|
+
* subagent_list what is (or was) running, with observed state
|
|
9
|
+
* subagent_usage cost, cumulative tokens, and current context footprint
|
|
10
|
+
* subagent_cancel stop one session by its session ID
|
|
11
|
+
* subagent_cancel_descendants stop running descendants in the caller's subtree
|
|
12
|
+
* subagent_steer add a turn-level instruction to a running child
|
|
13
|
+
* subagent_queue add a follow-up turn after the current run settles
|
|
14
|
+
* subagent_context inject context into a child without requesting a turn
|
|
15
|
+
*
|
|
16
|
+
* Discovery is authoritative: every `list`/`cancel_descendants` walks the server's
|
|
17
|
+
* session tree with `ctx.session.list`. A small in-memory live map, fed by
|
|
18
|
+
* `session.status`, `session.execution.*`, `session.idle` and `session.deleted`
|
|
19
|
+
* events, adds freshness for the current process. Nothing is persisted: after a restart the server's session
|
|
20
|
+
* records are the source of truth.
|
|
21
|
+
*
|
|
22
|
+
* Single-target mutations follow `sessionControlPolicy`: the caller's subtree
|
|
23
|
+
* by default, any session except ancestors, or any session except the caller.
|
|
24
|
+
* `cancel_descendants` always stays inside the caller's subtree; read-only tools are
|
|
25
|
+
* intentionally unrestricted.
|
|
26
|
+
*
|
|
27
|
+
* Approval: `enforcePermissions` defaults to true, so every mutation is routed
|
|
28
|
+
* through `ctx.permission.assert` with the action `subagent.control`.
|
|
29
|
+
* `cancel_descendants` checks the whole batch in one permission request.
|
|
30
|
+
*
|
|
31
|
+
* Requires an OpenCode build with `ctx.session.list`.
|
|
32
|
+
*/
|
|
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"
|
|
46
|
+
|
|
47
|
+
export default Plugin.define({
|
|
48
|
+
id: "subagent-tools",
|
|
49
|
+
|
|
50
|
+
async setup(ctx) {
|
|
51
|
+
const config = resolveConfig(ctx.options)
|
|
52
|
+
|
|
53
|
+
const rawSessionList = (ctx.session as { list?: unknown }).list
|
|
54
|
+
const sessionList =
|
|
55
|
+
typeof rawSessionList === "function"
|
|
56
|
+
? (rawSessionList.bind(ctx.session) as SessionList)
|
|
57
|
+
: undefined
|
|
58
|
+
if (!sessionList) throw new Error(OPENCODE_REQUIREMENT)
|
|
59
|
+
|
|
60
|
+
const live = createLiveState()
|
|
61
|
+
const discovery = createDiscovery({
|
|
62
|
+
sessionList,
|
|
63
|
+
live,
|
|
64
|
+
limits: config.limits,
|
|
65
|
+
})
|
|
66
|
+
const access = createAccess({
|
|
67
|
+
session: ctx.session,
|
|
68
|
+
limits: config.limits,
|
|
69
|
+
policy: config.sessionControlPolicy,
|
|
70
|
+
namespace: config.namespace,
|
|
71
|
+
})
|
|
72
|
+
const guard = createGuard({
|
|
73
|
+
permission: ctx.permission,
|
|
74
|
+
enabled: config.enforcePermissions,
|
|
75
|
+
})
|
|
76
|
+
const sendMessage = createSendMessage({
|
|
77
|
+
session: ctx.session,
|
|
78
|
+
access,
|
|
79
|
+
guard,
|
|
80
|
+
live,
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
const toolsRegistration = await ctx.tool.transform((editor) => {
|
|
84
|
+
registerTools(editor, {
|
|
85
|
+
config,
|
|
86
|
+
access,
|
|
87
|
+
discovery,
|
|
88
|
+
live,
|
|
89
|
+
guard,
|
|
90
|
+
sendMessage,
|
|
91
|
+
session: ctx.session,
|
|
92
|
+
model: ctx.model,
|
|
93
|
+
})
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
const skillRegistration = config.registerSkill
|
|
97
|
+
? await registerSkill(ctx.skill)
|
|
98
|
+
: undefined
|
|
99
|
+
|
|
100
|
+
// Start the event stream only after tool registration succeeded, so a setup
|
|
101
|
+
// failure cannot leave a background subscriber behind.
|
|
102
|
+
const eventsAbort = new AbortController()
|
|
103
|
+
startEventStream({
|
|
104
|
+
event: ctx.event as unknown as EventApi | undefined,
|
|
105
|
+
live,
|
|
106
|
+
signal: eventsAbort.signal,
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
// Stop the event stream when the plugin unloads or its config reloads.
|
|
110
|
+
return async () => {
|
|
111
|
+
eventsAbort.abort()
|
|
112
|
+
if (skillRegistration) await skillRegistration.dispose().catch(() => undefined)
|
|
113
|
+
await toolsRegistration.dispose().catch(() => undefined)
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
})
|
package/src/interrupt.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export const INTERRUPT_OUTCOME = {
|
|
2
|
+
accepted: "accepted",
|
|
3
|
+
rejected: "rejected",
|
|
4
|
+
failed: "failed",
|
|
5
|
+
unknown: "unknown",
|
|
6
|
+
} as const
|
|
7
|
+
|
|
8
|
+
export type InterruptOutcome = (typeof INTERRUPT_OUTCOME)[keyof typeof INTERRUPT_OUTCOME]
|
|
9
|
+
|
|
10
|
+
export type InterruptResponse = { interrupted?: boolean } | undefined
|
|
11
|
+
|
|
12
|
+
/** Map the server's optional boolean to an outcome. `failed` is a thrown call. */
|
|
13
|
+
export const interruptOutcome = (
|
|
14
|
+
result: InterruptResponse,
|
|
15
|
+
): Exclude<InterruptOutcome, "failed"> =>
|
|
16
|
+
result?.interrupted === true
|
|
17
|
+
? INTERRUPT_OUTCOME.accepted
|
|
18
|
+
: result?.interrupted === false
|
|
19
|
+
? INTERRUPT_OUTCOME.rejected
|
|
20
|
+
: INTERRUPT_OUTCOME.unknown
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { SessionInfoLike } from "./session"
|
|
2
|
+
import { STATUS, TERMINAL_STATUSES, statusFromSession, type ChildStatus } from "./status"
|
|
3
|
+
|
|
4
|
+
export const MAX_LIVE_SESSIONS = 500
|
|
5
|
+
|
|
6
|
+
/** Process-local live evidence for a session. Never persisted. */
|
|
7
|
+
export interface LiveState {
|
|
8
|
+
/** Last live start timestamp; 0 when the last observed transition was terminal. */
|
|
9
|
+
activeAt: number
|
|
10
|
+
status?: ChildStatus
|
|
11
|
+
/** Last live start/terminal timestamp, used to drop out-of-order events. */
|
|
12
|
+
lastStartedAt: number
|
|
13
|
+
lastTerminalAt: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const lastTransitionAt = (state: LiveState | undefined): number =>
|
|
17
|
+
Math.max(state?.lastStartedAt ?? 0, state?.lastTerminalAt ?? 0)
|
|
18
|
+
|
|
19
|
+
export const createLiveState = () => {
|
|
20
|
+
const live = new Map<string, LiveState>()
|
|
21
|
+
|
|
22
|
+
const rememberLive = (id: string, patch: Partial<LiveState>) => {
|
|
23
|
+
const previous = live.get(id)
|
|
24
|
+
// Re-insert so Map iteration order stays least-recently-used first.
|
|
25
|
+
if (previous) live.delete(id)
|
|
26
|
+
live.set(id, {
|
|
27
|
+
activeAt: patch.activeAt ?? previous?.activeAt ?? 0,
|
|
28
|
+
status: patch.status ?? previous?.status,
|
|
29
|
+
lastStartedAt: patch.lastStartedAt ?? previous?.lastStartedAt ?? 0,
|
|
30
|
+
lastTerminalAt: patch.lastTerminalAt ?? previous?.lastTerminalAt ?? 0,
|
|
31
|
+
})
|
|
32
|
+
while (live.size > MAX_LIVE_SESSIONS) {
|
|
33
|
+
const oldest = live.keys().next().value
|
|
34
|
+
if (oldest === undefined) break
|
|
35
|
+
live.delete(oldest)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const rememberStarted = (id: string, at: number) => {
|
|
40
|
+
rememberLive(id, { activeAt: at, status: STATUS.running, lastStartedAt: at })
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const rememberTerminal = (id: string, status: ChildStatus, at: number) => {
|
|
44
|
+
rememberLive(id, { activeAt: 0, status, lastTerminalAt: at })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const liveStatusFor = (id: string): ChildStatus | undefined => {
|
|
48
|
+
const state = live.get(id)
|
|
49
|
+
if (!state) return undefined
|
|
50
|
+
if (state.activeAt > 0) return STATUS.running
|
|
51
|
+
return state.status
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Prefer a live start newer than the session marker (a resumed child with a
|
|
56
|
+
* stale outcome), then a live terminal or idle event at least as new as the
|
|
57
|
+
* marker. Everything else falls back to the session record.
|
|
58
|
+
*/
|
|
59
|
+
const statusFor = (info: SessionInfoLike, id: string): ChildStatus => {
|
|
60
|
+
const state = live.get(id)
|
|
61
|
+
// `time.idle` is the canonical terminal marker. When it is absent, use
|
|
62
|
+
// `time.updated` as a conservative marker so a stale live event cannot
|
|
63
|
+
// override a newer session record.
|
|
64
|
+
const marker = info.time?.idle ?? info.time?.updated ?? 0
|
|
65
|
+
const activeAt = state?.activeAt ?? 0
|
|
66
|
+
if (activeAt > 0 && (marker === 0 || activeAt > marker)) return STATUS.running
|
|
67
|
+
|
|
68
|
+
const liveStatus = state?.status
|
|
69
|
+
const liveAt = state?.lastTerminalAt ?? 0
|
|
70
|
+
if (liveStatus !== undefined) {
|
|
71
|
+
const terminal =
|
|
72
|
+
TERMINAL_STATUSES.has(liveStatus) || (liveStatus === STATUS.unknown && liveAt > 0)
|
|
73
|
+
if (terminal && (marker === 0 || liveAt >= marker)) return liveStatus
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return statusFromSession(info) ?? STATUS.unknown
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
live,
|
|
81
|
+
rememberLive,
|
|
82
|
+
rememberStarted,
|
|
83
|
+
rememberTerminal,
|
|
84
|
+
liveStatusFor,
|
|
85
|
+
statusFor,
|
|
86
|
+
lastTransitionAt: (id: string) => lastTransitionAt(live.get(id)),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export type LiveStore = ReturnType<typeof createLiveState>
|
package/src/messages.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import type { Access } from "./access"
|
|
3
|
+
import { errorMessage } from "./errors"
|
|
4
|
+
import type { LiveStore } from "./live-state"
|
|
5
|
+
import type { Guard } from "./permissions"
|
|
6
|
+
import { guardTarget } from "./permissions"
|
|
7
|
+
import { statusIsIdle, type ChildStatus } from "./status"
|
|
8
|
+
import type { ToolCtx } from "./tools/input"
|
|
9
|
+
|
|
10
|
+
export const DELIVERY = {
|
|
11
|
+
steer: "steer",
|
|
12
|
+
queue: "queue",
|
|
13
|
+
} as const
|
|
14
|
+
|
|
15
|
+
export type Delivery = (typeof DELIVERY)[keyof typeof DELIVERY]
|
|
16
|
+
|
|
17
|
+
export const DELIVERIES: readonly Delivery[] = Object.values(DELIVERY)
|
|
18
|
+
const DELIVERY_SET: ReadonlySet<string> = new Set(DELIVERIES)
|
|
19
|
+
|
|
20
|
+
export const isDelivery = (value: unknown): value is Delivery =>
|
|
21
|
+
typeof value === "string" && DELIVERY_SET.has(value)
|
|
22
|
+
|
|
23
|
+
export const SEND_KIND = {
|
|
24
|
+
prompt: "prompt",
|
|
25
|
+
synthetic: "synthetic",
|
|
26
|
+
} as const
|
|
27
|
+
|
|
28
|
+
export type SendKind = (typeof SEND_KIND)[keyof typeof SEND_KIND]
|
|
29
|
+
|
|
30
|
+
export const SEND_KINDS: readonly SendKind[] = Object.values(SEND_KIND)
|
|
31
|
+
const SEND_KIND_SET: ReadonlySet<string> = new Set(SEND_KINDS)
|
|
32
|
+
|
|
33
|
+
export const isSendKind = (value: unknown): value is SendKind =>
|
|
34
|
+
typeof value === "string" && SEND_KIND_SET.has(value)
|
|
35
|
+
|
|
36
|
+
export const CONTEXT_DELIVERY = "next-step" as const
|
|
37
|
+
|
|
38
|
+
export interface SendResultFields {
|
|
39
|
+
messageID?: string
|
|
40
|
+
status?: ChildStatus
|
|
41
|
+
pending?: boolean
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface SendRequestBase {
|
|
45
|
+
sessionID: string
|
|
46
|
+
text: string
|
|
47
|
+
resume: boolean
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type SendRequest =
|
|
51
|
+
| (SendRequestBase & { kind: typeof SEND_KIND.prompt; delivery: Delivery })
|
|
52
|
+
| (SendRequestBase & {
|
|
53
|
+
kind: typeof SEND_KIND.synthetic
|
|
54
|
+
delivery?: never
|
|
55
|
+
description?: string
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
export class SendAdmissionError extends Error {
|
|
59
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
60
|
+
super(message, options)
|
|
61
|
+
this.name = "SendAdmissionError"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface AdmittedMessage {
|
|
66
|
+
id?: string
|
|
67
|
+
delivery?: Delivery
|
|
68
|
+
text?: string
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface SendResult {
|
|
72
|
+
admitted?: AdmittedMessage
|
|
73
|
+
status?: ChildStatus
|
|
74
|
+
pending: boolean
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const admittedFrom = (value: unknown): AdmittedMessage | undefined => {
|
|
78
|
+
if (!value || typeof value !== "object") return undefined
|
|
79
|
+
const item = value as {
|
|
80
|
+
id?: unknown
|
|
81
|
+
delivery?: unknown
|
|
82
|
+
payload?: { text?: unknown }
|
|
83
|
+
}
|
|
84
|
+
const admitted: AdmittedMessage = {}
|
|
85
|
+
if (typeof item.id === "string" && item.id.length > 0) admitted.id = item.id
|
|
86
|
+
if (isDelivery(item.delivery)) admitted.delivery = item.delivery
|
|
87
|
+
if (typeof item.payload?.text === "string") admitted.text = item.payload.text
|
|
88
|
+
return Object.keys(admitted).length > 0 ? admitted : undefined
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const applySendResult = <T extends SendResultFields>(
|
|
92
|
+
output: T,
|
|
93
|
+
result: SendResult,
|
|
94
|
+
): T => {
|
|
95
|
+
if (result.admitted?.id) output.messageID = result.admitted.id
|
|
96
|
+
if (result.status) output.status = result.status
|
|
97
|
+
if (result.pending) output.pending = true
|
|
98
|
+
return output
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface SendDeps {
|
|
102
|
+
session: Plugin.Context["session"]
|
|
103
|
+
access: Access
|
|
104
|
+
guard: Guard
|
|
105
|
+
live: LiveStore
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
type SendHandler = (
|
|
109
|
+
request: SendRequest,
|
|
110
|
+
signal: AbortSignal | undefined,
|
|
111
|
+
) => Promise<unknown>
|
|
112
|
+
|
|
113
|
+
const createSendHandlers = (
|
|
114
|
+
session: Plugin.Context["session"],
|
|
115
|
+
): ReadonlyMap<SendKind, SendHandler> => {
|
|
116
|
+
const handlers: Record<SendKind, SendHandler> = {
|
|
117
|
+
[SEND_KIND.prompt]: (request, signal) =>
|
|
118
|
+
session.prompt(
|
|
119
|
+
{
|
|
120
|
+
sessionID: request.sessionID,
|
|
121
|
+
text: request.text,
|
|
122
|
+
delivery: request.kind === SEND_KIND.prompt ? request.delivery : undefined,
|
|
123
|
+
resume: request.resume,
|
|
124
|
+
},
|
|
125
|
+
{ signal },
|
|
126
|
+
),
|
|
127
|
+
[SEND_KIND.synthetic]: (request, signal) =>
|
|
128
|
+
session.synthetic(
|
|
129
|
+
{
|
|
130
|
+
sessionID: request.sessionID,
|
|
131
|
+
text: request.text,
|
|
132
|
+
description:
|
|
133
|
+
request.kind === SEND_KIND.synthetic ? request.description : undefined,
|
|
134
|
+
resume: request.resume,
|
|
135
|
+
},
|
|
136
|
+
{ signal },
|
|
137
|
+
),
|
|
138
|
+
}
|
|
139
|
+
return new Map(Object.entries(handlers) as Array<[SendKind, SendHandler]>)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Shared admission path for `steer`, `queue`, and `context`.
|
|
144
|
+
* `prompt` admits a user message; `synthetic` admits a context-only note.
|
|
145
|
+
*/
|
|
146
|
+
export const createSendMessage = ({ session, access, guard, live }: SendDeps) => {
|
|
147
|
+
const sendHandlers = createSendHandlers(session)
|
|
148
|
+
|
|
149
|
+
return async (
|
|
150
|
+
request: SendRequest,
|
|
151
|
+
context: ToolCtx,
|
|
152
|
+
failureLabel: string,
|
|
153
|
+
): Promise<SendResult> => {
|
|
154
|
+
const info = await access.authorize(request.sessionID, context)
|
|
155
|
+
if (context?.signal?.aborted) {
|
|
156
|
+
throw new SendAdmissionError("Aborted before the message was accepted.")
|
|
157
|
+
}
|
|
158
|
+
await guard([guardTarget(info, request.sessionID)], context)
|
|
159
|
+
if (context?.signal?.aborted) {
|
|
160
|
+
throw new SendAdmissionError("Aborted before the message was accepted.")
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const handler = sendHandlers.get(request.kind)
|
|
164
|
+
if (!handler) {
|
|
165
|
+
throw new SendAdmissionError(`Unsupported send kind: ${String(request.kind)}`)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
let admitted: unknown
|
|
169
|
+
try {
|
|
170
|
+
admitted = await handler(request, context?.signal)
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (context?.signal?.aborted) {
|
|
173
|
+
throw new SendAdmissionError(
|
|
174
|
+
"Aborted while accepting the message; it may or may not have been accepted.",
|
|
175
|
+
{
|
|
176
|
+
cause: error,
|
|
177
|
+
},
|
|
178
|
+
)
|
|
179
|
+
}
|
|
180
|
+
throw new SendAdmissionError(
|
|
181
|
+
`${failureLabel} failed for ${request.sessionID}: ${errorMessage(error)}`,
|
|
182
|
+
{ cause: error },
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const status = info
|
|
187
|
+
? live.statusFor(info, request.sessionID)
|
|
188
|
+
: live.liveStatusFor(request.sessionID)
|
|
189
|
+
// `unknown` is not idle: the session may still be running, so a message
|
|
190
|
+
// without resume cannot be reported as pending.
|
|
191
|
+
const pending = statusIsIdle(status) && !request.resume
|
|
192
|
+
return { admitted: admittedFrom(admitted), status, pending }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export type SendMessage = ReturnType<typeof createSendMessage>
|