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/index.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
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 OpenCode 2.3.0+.
|
|
32
|
+
*/
|
|
33
|
+
|
|
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";
|
|
47
|
+
|
|
48
|
+
export default Plugin.define({
|
|
49
|
+
id: "subagent-tools",
|
|
50
|
+
|
|
51
|
+
async setup(ctx) {
|
|
52
|
+
const config = resolveConfig(ctx.options);
|
|
53
|
+
|
|
54
|
+
const rawSessionList = (ctx.session as { list?: unknown }).list;
|
|
55
|
+
const sessionList =
|
|
56
|
+
typeof rawSessionList === "function"
|
|
57
|
+
? (rawSessionList.bind(ctx.session) as SessionList)
|
|
58
|
+
: undefined;
|
|
59
|
+
if (!sessionList) throw new Error(OPENCODE_REQUIREMENT);
|
|
60
|
+
|
|
61
|
+
const live = createLiveState();
|
|
62
|
+
const access = createAccess({
|
|
63
|
+
session: ctx.session,
|
|
64
|
+
limits: config.limits,
|
|
65
|
+
policy: config.sessionControlPolicy,
|
|
66
|
+
namespace: config.namespace,
|
|
67
|
+
});
|
|
68
|
+
const background = createBackgroundJobStore();
|
|
69
|
+
const discovery = createDiscovery({
|
|
70
|
+
sessionList,
|
|
71
|
+
live,
|
|
72
|
+
background,
|
|
73
|
+
limits: config.limits,
|
|
74
|
+
});
|
|
75
|
+
const guard = createGuard({
|
|
76
|
+
permission: ctx.permission,
|
|
77
|
+
enabled: config.enforcePermissions,
|
|
78
|
+
});
|
|
79
|
+
const sendMessage = createSendMessage({
|
|
80
|
+
session: ctx.session,
|
|
81
|
+
access,
|
|
82
|
+
guard,
|
|
83
|
+
live,
|
|
84
|
+
background,
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const toolsRegistration = await ctx.tool.transform((editor) => {
|
|
88
|
+
registerTools(editor, {
|
|
89
|
+
config,
|
|
90
|
+
access,
|
|
91
|
+
discovery,
|
|
92
|
+
live,
|
|
93
|
+
background,
|
|
94
|
+
guard,
|
|
95
|
+
sendMessage,
|
|
96
|
+
session: ctx.session,
|
|
97
|
+
model: ctx.model,
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const skillRegistration = config.registerSkill
|
|
102
|
+
? await registerSkill(ctx.skill)
|
|
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);
|
|
108
|
+
|
|
109
|
+
// Start the event stream only after tool registration succeeded, so a setup
|
|
110
|
+
// failure cannot leave a background subscriber behind.
|
|
111
|
+
const eventsAbort = new AbortController();
|
|
112
|
+
startEventStream({
|
|
113
|
+
event: ctx.event as unknown as EventApi | undefined,
|
|
114
|
+
live,
|
|
115
|
+
background,
|
|
116
|
+
signal: eventsAbort.signal,
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// Stop the event stream when the plugin unloads or its config reloads.
|
|
120
|
+
return async () => {
|
|
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
|
+
};
|
|
128
|
+
},
|
|
129
|
+
});
|
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,113 @@
|
|
|
1
|
+
import type { SessionInfoLike } from "./session";
|
|
2
|
+
import {
|
|
3
|
+
RUN_STATUS,
|
|
4
|
+
TERMINAL_RUN_STATUSES,
|
|
5
|
+
runStatusFromSession,
|
|
6
|
+
type RunStatus,
|
|
7
|
+
} from "./status";
|
|
8
|
+
|
|
9
|
+
export const MAX_LIVE_SESSIONS = 500;
|
|
10
|
+
|
|
11
|
+
/** Process-local live evidence for a session. Never persisted. */
|
|
12
|
+
export interface LiveState {
|
|
13
|
+
/** Last live start timestamp; 0 when the last observed transition was terminal. */
|
|
14
|
+
activeAt: number;
|
|
15
|
+
status?: RunStatus;
|
|
16
|
+
/** Last live start/terminal timestamp, used to drop out-of-order events. */
|
|
17
|
+
lastStartedAt: number;
|
|
18
|
+
lastTerminalAt: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const lastTransitionAt = (state: LiveState | undefined): number =>
|
|
22
|
+
Math.max(state?.lastStartedAt ?? 0, state?.lastTerminalAt ?? 0);
|
|
23
|
+
|
|
24
|
+
export const createLiveState = () => {
|
|
25
|
+
const live = new Map<string, LiveState>();
|
|
26
|
+
|
|
27
|
+
const rememberLive = (id: string, patch: Partial<LiveState>) => {
|
|
28
|
+
const previous = live.get(id);
|
|
29
|
+
// Re-insert so Map iteration order stays least-recently-used first.
|
|
30
|
+
if (previous) live.delete(id);
|
|
31
|
+
live.set(id, {
|
|
32
|
+
activeAt: patch.activeAt ?? previous?.activeAt ?? 0,
|
|
33
|
+
status: patch.status ?? previous?.status,
|
|
34
|
+
lastStartedAt: patch.lastStartedAt ?? previous?.lastStartedAt ?? 0,
|
|
35
|
+
lastTerminalAt: patch.lastTerminalAt ?? previous?.lastTerminalAt ?? 0,
|
|
36
|
+
});
|
|
37
|
+
while (live.size > MAX_LIVE_SESSIONS) {
|
|
38
|
+
const oldest = live.keys().next().value;
|
|
39
|
+
if (oldest === undefined) break;
|
|
40
|
+
live.delete(oldest);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const rememberStarted = (id: string, at: number) => {
|
|
45
|
+
rememberLive(id, { activeAt: at, status: RUN_STATUS.running, lastStartedAt: at });
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const rememberTerminal = (id: string, status: RunStatus, at: number) => {
|
|
49
|
+
rememberLive(id, { activeAt: 0, status, lastTerminalAt: at });
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const forget = (id: string) => {
|
|
53
|
+
live.delete(id);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const liveStatusFor = (id: string): RunStatus | undefined => {
|
|
57
|
+
const state = live.get(id);
|
|
58
|
+
if (!state) return undefined;
|
|
59
|
+
if (state.activeAt > 0) return RUN_STATUS.running;
|
|
60
|
+
return state.status;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Prefer a live start newer than the session marker (a resumed child with a
|
|
65
|
+
* stale outcome), then a live terminal or idle event at least as new as the
|
|
66
|
+
* marker. Everything else falls back to the session record.
|
|
67
|
+
*/
|
|
68
|
+
const statusFor = (info: SessionInfoLike, id: string): RunStatus => {
|
|
69
|
+
const state = live.get(id);
|
|
70
|
+
// `time.idle` is the canonical terminal marker. When it is absent, use
|
|
71
|
+
// `time.updated` as a conservative marker so a stale live event cannot
|
|
72
|
+
// override a newer session record.
|
|
73
|
+
const marker = info.time?.idle ?? info.time?.updated ?? 0;
|
|
74
|
+
const activeAt = state?.activeAt ?? 0;
|
|
75
|
+
if (activeAt > 0 && (marker === 0 || activeAt > marker)) return RUN_STATUS.running;
|
|
76
|
+
|
|
77
|
+
const sessionStatus = runStatusFromSession(info);
|
|
78
|
+
const liveStatus = state?.status;
|
|
79
|
+
const liveAt = state?.lastTerminalAt ?? 0;
|
|
80
|
+
if (liveStatus !== undefined) {
|
|
81
|
+
const terminal =
|
|
82
|
+
TERMINAL_RUN_STATUSES.has(liveStatus) ||
|
|
83
|
+
(liveStatus === RUN_STATUS.unknown && liveAt > 0);
|
|
84
|
+
if (terminal && (marker === 0 || liveAt >= marker)) {
|
|
85
|
+
// An idle-derived `unknown` must not hide a terminal outcome that the
|
|
86
|
+
// session record already knows. Other live evidence keeps precedence.
|
|
87
|
+
if (
|
|
88
|
+
liveStatus === RUN_STATUS.unknown &&
|
|
89
|
+
sessionStatus !== undefined &&
|
|
90
|
+
TERMINAL_RUN_STATUSES.has(sessionStatus)
|
|
91
|
+
) {
|
|
92
|
+
return sessionStatus;
|
|
93
|
+
}
|
|
94
|
+
return liveStatus;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return sessionStatus ?? RUN_STATUS.unknown;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
live,
|
|
103
|
+
rememberLive,
|
|
104
|
+
rememberStarted,
|
|
105
|
+
rememberTerminal,
|
|
106
|
+
forget,
|
|
107
|
+
liveStatusFor,
|
|
108
|
+
statusFor,
|
|
109
|
+
lastTransitionAt: (id: string) => lastTransitionAt(live.get(id)),
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
export type LiveStore = ReturnType<typeof createLiveState>;
|
package/src/messages.ts
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin";
|
|
2
|
+
import type { Access } from "./access";
|
|
3
|
+
import {
|
|
4
|
+
isSessionActive,
|
|
5
|
+
type BackgroundJobInfo,
|
|
6
|
+
type BackgroundJobStore,
|
|
7
|
+
} from "./background";
|
|
8
|
+
import { errorMessage } from "./errors";
|
|
9
|
+
import type { LiveStore } from "./live-state";
|
|
10
|
+
import type { Guard } from "./permissions";
|
|
11
|
+
import { guardTarget } from "./permissions";
|
|
12
|
+
import { RUN_STATUS, runStatusIsIdle, type RunStatus } from "./status";
|
|
13
|
+
import type { ToolCtx } from "./tools/input";
|
|
14
|
+
|
|
15
|
+
export const DELIVERY = {
|
|
16
|
+
steer: "steer",
|
|
17
|
+
queue: "queue",
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export type Delivery = (typeof DELIVERY)[keyof typeof DELIVERY];
|
|
21
|
+
|
|
22
|
+
export const DELIVERIES: readonly Delivery[] = Object.values(DELIVERY);
|
|
23
|
+
const DELIVERY_SET: ReadonlySet<string> = new Set(DELIVERIES);
|
|
24
|
+
|
|
25
|
+
export const isDelivery = (value: unknown): value is Delivery =>
|
|
26
|
+
typeof value === "string" && DELIVERY_SET.has(value);
|
|
27
|
+
|
|
28
|
+
export const SEND_KIND = {
|
|
29
|
+
prompt: "prompt",
|
|
30
|
+
synthetic: "synthetic",
|
|
31
|
+
} as const;
|
|
32
|
+
|
|
33
|
+
export type SendKind = (typeof SEND_KIND)[keyof typeof SEND_KIND];
|
|
34
|
+
|
|
35
|
+
export const SEND_KINDS: readonly SendKind[] = Object.values(SEND_KIND);
|
|
36
|
+
const SEND_KIND_SET: ReadonlySet<string> = new Set(SEND_KINDS);
|
|
37
|
+
|
|
38
|
+
export const isSendKind = (value: unknown): value is SendKind =>
|
|
39
|
+
typeof value === "string" && SEND_KIND_SET.has(value);
|
|
40
|
+
|
|
41
|
+
export const CONTEXT_DELIVERY = "next-step" as const;
|
|
42
|
+
|
|
43
|
+
/** Metadata source for context notes injected by this plugin. Never `subagent`. */
|
|
44
|
+
export const CONTEXT_METADATA_SOURCE = "subagent-tools" as const;
|
|
45
|
+
|
|
46
|
+
export type MessageMetadata = Record<string, string | number | boolean | null>;
|
|
47
|
+
|
|
48
|
+
export interface SendResultFields {
|
|
49
|
+
messageID?: string;
|
|
50
|
+
status?: RunStatus;
|
|
51
|
+
active?: boolean;
|
|
52
|
+
backgroundJob?: BackgroundJobInfo;
|
|
53
|
+
queued?: boolean;
|
|
54
|
+
pending?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface SendRequestBase {
|
|
58
|
+
sessionID: string;
|
|
59
|
+
text: string;
|
|
60
|
+
resume: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type SendRequest =
|
|
64
|
+
| (SendRequestBase & { kind: typeof SEND_KIND.prompt; delivery: Delivery })
|
|
65
|
+
| (SendRequestBase & {
|
|
66
|
+
kind: typeof SEND_KIND.synthetic;
|
|
67
|
+
delivery?: never;
|
|
68
|
+
description?: string;
|
|
69
|
+
metadata?: MessageMetadata;
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
export class SendAdmissionError extends Error {
|
|
73
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
74
|
+
super(message, options);
|
|
75
|
+
this.name = "SendAdmissionError";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface AdmittedMessage {
|
|
80
|
+
id?: string;
|
|
81
|
+
delivery?: Delivery;
|
|
82
|
+
text?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface SendResult {
|
|
86
|
+
admitted?: AdmittedMessage;
|
|
87
|
+
status?: RunStatus;
|
|
88
|
+
active?: boolean;
|
|
89
|
+
backgroundJob?: BackgroundJobInfo;
|
|
90
|
+
queued?: boolean;
|
|
91
|
+
pending: boolean;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const admittedFrom = (value: unknown): AdmittedMessage | undefined => {
|
|
95
|
+
if (!value || typeof value !== "object") return undefined;
|
|
96
|
+
const item = value as {
|
|
97
|
+
id?: unknown;
|
|
98
|
+
delivery?: unknown;
|
|
99
|
+
payload?: { text?: unknown };
|
|
100
|
+
};
|
|
101
|
+
const admitted: AdmittedMessage = {};
|
|
102
|
+
if (typeof item.id === "string" && item.id.length > 0) admitted.id = item.id;
|
|
103
|
+
if (isDelivery(item.delivery)) admitted.delivery = item.delivery;
|
|
104
|
+
if (typeof item.payload?.text === "string") admitted.text = item.payload.text;
|
|
105
|
+
return Object.keys(admitted).length > 0 ? admitted : undefined;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export const applySendResult = <T extends SendResultFields>(
|
|
109
|
+
output: T,
|
|
110
|
+
result: SendResult,
|
|
111
|
+
): T => {
|
|
112
|
+
if (result.admitted?.id) output.messageID = result.admitted.id;
|
|
113
|
+
if (result.status) output.status = result.status;
|
|
114
|
+
if (result.active !== undefined) output.active = result.active;
|
|
115
|
+
if (result.backgroundJob) output.backgroundJob = result.backgroundJob;
|
|
116
|
+
if (result.queued !== undefined) output.queued = result.queued;
|
|
117
|
+
if (result.pending) output.pending = true;
|
|
118
|
+
return output;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export interface SendDeps {
|
|
122
|
+
session: Plugin.Context["session"];
|
|
123
|
+
access: Access;
|
|
124
|
+
guard: Guard;
|
|
125
|
+
live: LiveStore;
|
|
126
|
+
background: BackgroundJobStore;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
type SendHandler = (
|
|
130
|
+
request: SendRequest,
|
|
131
|
+
signal: AbortSignal | undefined,
|
|
132
|
+
) => Promise<unknown>;
|
|
133
|
+
|
|
134
|
+
const createSendHandlers = (
|
|
135
|
+
session: Plugin.Context["session"],
|
|
136
|
+
): ReadonlyMap<SendKind, SendHandler> => {
|
|
137
|
+
const handlers: Record<SendKind, SendHandler> = {
|
|
138
|
+
[SEND_KIND.prompt]: (request, signal) =>
|
|
139
|
+
session.prompt(
|
|
140
|
+
{
|
|
141
|
+
sessionID: request.sessionID,
|
|
142
|
+
text: request.text,
|
|
143
|
+
delivery: request.kind === SEND_KIND.prompt ? request.delivery : undefined,
|
|
144
|
+
resume: request.resume,
|
|
145
|
+
},
|
|
146
|
+
{ signal },
|
|
147
|
+
),
|
|
148
|
+
[SEND_KIND.synthetic]: (request, signal) =>
|
|
149
|
+
session.synthetic(
|
|
150
|
+
{
|
|
151
|
+
sessionID: request.sessionID,
|
|
152
|
+
text: request.text,
|
|
153
|
+
description:
|
|
154
|
+
request.kind === SEND_KIND.synthetic ? request.description : undefined,
|
|
155
|
+
metadata: request.kind === SEND_KIND.synthetic ? request.metadata : undefined,
|
|
156
|
+
resume: request.resume,
|
|
157
|
+
},
|
|
158
|
+
{ signal },
|
|
159
|
+
),
|
|
160
|
+
};
|
|
161
|
+
return new Map(Object.entries(handlers) as Array<[SendKind, SendHandler]>);
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Shared admission path for `steer`, `queue`, and `context`.
|
|
166
|
+
* `prompt` admits a user message; `synthetic` admits a context-only note.
|
|
167
|
+
*/
|
|
168
|
+
export const createSendMessage = ({
|
|
169
|
+
session,
|
|
170
|
+
access,
|
|
171
|
+
guard,
|
|
172
|
+
live,
|
|
173
|
+
background,
|
|
174
|
+
}: SendDeps) => {
|
|
175
|
+
const sendHandlers = createSendHandlers(session);
|
|
176
|
+
|
|
177
|
+
return async (
|
|
178
|
+
request: SendRequest,
|
|
179
|
+
context: ToolCtx,
|
|
180
|
+
failureLabel: string,
|
|
181
|
+
): Promise<SendResult> => {
|
|
182
|
+
const info = await access.authorize(request.sessionID, context);
|
|
183
|
+
if (context?.signal?.aborted) {
|
|
184
|
+
throw new SendAdmissionError("Aborted before the message was accepted.");
|
|
185
|
+
}
|
|
186
|
+
await guard([guardTarget(info, request.sessionID)], context);
|
|
187
|
+
if (context?.signal?.aborted) {
|
|
188
|
+
throw new SendAdmissionError("Aborted before the message was accepted.");
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const handler = sendHandlers.get(request.kind);
|
|
192
|
+
if (!handler) {
|
|
193
|
+
throw new SendAdmissionError(`Unsupported send kind: ${String(request.kind)}`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Snapshot the observed target before admission: waking a child can change
|
|
197
|
+
// its status immediately, while the output describes the state that led to
|
|
198
|
+
// the queued/pending decision.
|
|
199
|
+
const status = info
|
|
200
|
+
? live.statusFor(info, request.sessionID)
|
|
201
|
+
: live.liveStatusFor(request.sessionID);
|
|
202
|
+
const backgroundJob = background.backgroundJobFor(request.sessionID);
|
|
203
|
+
const active = isSessionActive(status, backgroundJob);
|
|
204
|
+
// `unknown` is not idle: the session may still be running, so a message
|
|
205
|
+
// without resume cannot be reported as pending.
|
|
206
|
+
const pending = runStatusIsIdle(status) && !request.resume;
|
|
207
|
+
// Queue waits for the current execution, not background jobs. It is queued
|
|
208
|
+
// when the target is not idle, or when an idle target was not woken.
|
|
209
|
+
const queued =
|
|
210
|
+
request.kind === SEND_KIND.prompt && request.delivery === DELIVERY.queue
|
|
211
|
+
? status === undefined ||
|
|
212
|
+
status === RUN_STATUS.running ||
|
|
213
|
+
status === RUN_STATUS.unknown ||
|
|
214
|
+
!request.resume
|
|
215
|
+
: undefined;
|
|
216
|
+
|
|
217
|
+
let admitted: unknown;
|
|
218
|
+
try {
|
|
219
|
+
admitted = await handler(request, context?.signal);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
if (context?.signal?.aborted) {
|
|
222
|
+
throw new SendAdmissionError(
|
|
223
|
+
"Aborted while accepting the message; it may or may not have been accepted.",
|
|
224
|
+
{
|
|
225
|
+
cause: error,
|
|
226
|
+
},
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
throw new SendAdmissionError(
|
|
230
|
+
`${failureLabel} failed for ${request.sessionID}: ${errorMessage(error)}`,
|
|
231
|
+
{ cause: error },
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
admitted: admittedFrom(admitted),
|
|
237
|
+
status,
|
|
238
|
+
active,
|
|
239
|
+
...(backgroundJob ? { backgroundJob } : {}),
|
|
240
|
+
...(queued !== undefined ? { queued } : {}),
|
|
241
|
+
pending,
|
|
242
|
+
};
|
|
243
|
+
};
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
export type SendMessage = ReturnType<typeof createSendMessage>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin";
|
|
2
|
+
import {
|
|
3
|
+
MAX_AGENT_NAME_LENGTH,
|
|
4
|
+
MAX_PROMPT_PREVIEW_LENGTH,
|
|
5
|
+
type SessionInfoLike,
|
|
6
|
+
} from "./session";
|
|
7
|
+
import { clip } from "./text";
|
|
8
|
+
import type { ToolCtx } from "./tools/input";
|
|
9
|
+
|
|
10
|
+
export const PERMISSION_ACTION = "subagent.control";
|
|
11
|
+
|
|
12
|
+
export interface GuardTarget {
|
|
13
|
+
id: string;
|
|
14
|
+
title?: string;
|
|
15
|
+
agent?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const guardTarget = (
|
|
19
|
+
info: SessionInfoLike | undefined,
|
|
20
|
+
sessionID: string,
|
|
21
|
+
): GuardTarget => ({
|
|
22
|
+
id: sessionID,
|
|
23
|
+
title: clip(info?.title, MAX_PROMPT_PREVIEW_LENGTH),
|
|
24
|
+
agent: clip(info?.agent, MAX_AGENT_NAME_LENGTH),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export interface GuardDeps {
|
|
28
|
+
permission: Plugin.Context["permission"];
|
|
29
|
+
enabled: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const createGuard = ({ permission, enabled }: GuardDeps) => {
|
|
33
|
+
return async (targets: GuardTarget[], context: ToolCtx) => {
|
|
34
|
+
if (!enabled || targets.length === 0) return;
|
|
35
|
+
const sessionID = context.sessionID;
|
|
36
|
+
if (!sessionID) {
|
|
37
|
+
throw new Error(
|
|
38
|
+
"Refusing: the calling session is unknown, so permissions cannot be checked.",
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
await permission.assert({
|
|
42
|
+
sessionID,
|
|
43
|
+
agent: context.agent,
|
|
44
|
+
source:
|
|
45
|
+
context.messageID && context.id
|
|
46
|
+
? { type: "tool" as const, messageID: context.messageID, id: context.id }
|
|
47
|
+
: undefined,
|
|
48
|
+
action: PERMISSION_ACTION,
|
|
49
|
+
resources: targets.map((target) => target.id),
|
|
50
|
+
metadata: {
|
|
51
|
+
count: targets.length,
|
|
52
|
+
targets: targets.map((target) => ({
|
|
53
|
+
id: target.id,
|
|
54
|
+
...(target.title ? { title: target.title } : {}),
|
|
55
|
+
...(target.agent ? { agent: target.agent } : {}),
|
|
56
|
+
})),
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type Guard = ReturnType<typeof createGuard>;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isSessionActive,
|
|
3
|
+
type BackgroundJobInfo,
|
|
4
|
+
type BackgroundJobStore,
|
|
5
|
+
} from "./background";
|
|
6
|
+
import type { LiveStore } from "./live-state";
|
|
7
|
+
import {
|
|
8
|
+
MAX_AGENT_NAME_LENGTH,
|
|
9
|
+
MAX_TITLE_LENGTH,
|
|
10
|
+
normalizeSessionID,
|
|
11
|
+
type SessionInfoLike,
|
|
12
|
+
} from "./session";
|
|
13
|
+
import type { RunStatus } from "./status";
|
|
14
|
+
import { clip, textLength } from "./text";
|
|
15
|
+
import { normalizeTokens, type TokenUsage } from "./tokens";
|
|
16
|
+
|
|
17
|
+
export interface SessionRow {
|
|
18
|
+
id: string;
|
|
19
|
+
parentID?: string;
|
|
20
|
+
agent?: string;
|
|
21
|
+
title?: string;
|
|
22
|
+
titleTruncated?: boolean;
|
|
23
|
+
launchedAt: number;
|
|
24
|
+
status: RunStatus;
|
|
25
|
+
/** The session's own execution or background work. Descendants are excluded. */
|
|
26
|
+
active: boolean;
|
|
27
|
+
/** The session or any discovered descendant is active. */
|
|
28
|
+
subtreeActive: boolean;
|
|
29
|
+
/** True only when at least one discovered child is active in its subtree. */
|
|
30
|
+
activeDescendants?: boolean;
|
|
31
|
+
backgroundJob?: BackgroundJobInfo;
|
|
32
|
+
cost?: number;
|
|
33
|
+
tokens?: TokenUsage;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const rowFromInfo = (
|
|
37
|
+
live: LiveStore,
|
|
38
|
+
background: BackgroundJobStore,
|
|
39
|
+
info: SessionInfoLike,
|
|
40
|
+
fallback?: SessionRow,
|
|
41
|
+
): SessionRow | undefined => {
|
|
42
|
+
const id = normalizeSessionID(info.id) ?? fallback?.id;
|
|
43
|
+
if (!id) return undefined;
|
|
44
|
+
const created = info.time?.created;
|
|
45
|
+
const updated = info.time?.updated;
|
|
46
|
+
const launchedAt =
|
|
47
|
+
typeof created === "number" && Number.isFinite(created)
|
|
48
|
+
? created
|
|
49
|
+
: (fallback?.launchedAt ??
|
|
50
|
+
(typeof updated === "number" && Number.isFinite(updated) ? updated : 0));
|
|
51
|
+
const status = live.statusFor(info, id);
|
|
52
|
+
const backgroundJob = background.backgroundJobFor(id);
|
|
53
|
+
const active = isSessionActive(status, backgroundJob);
|
|
54
|
+
return {
|
|
55
|
+
id,
|
|
56
|
+
parentID: normalizeSessionID(info.parentID) ?? fallback?.parentID,
|
|
57
|
+
agent: clip(info.agent, MAX_AGENT_NAME_LENGTH) ?? fallback?.agent,
|
|
58
|
+
title: clip(info.title, MAX_TITLE_LENGTH) ?? fallback?.title,
|
|
59
|
+
titleTruncated:
|
|
60
|
+
typeof info.title === "string"
|
|
61
|
+
? textLength(info.title) > MAX_TITLE_LENGTH
|
|
62
|
+
: fallback?.titleTruncated,
|
|
63
|
+
launchedAt,
|
|
64
|
+
status,
|
|
65
|
+
active,
|
|
66
|
+
subtreeActive: active,
|
|
67
|
+
...(backgroundJob ? { backgroundJob } : {}),
|
|
68
|
+
cost:
|
|
69
|
+
typeof info.cost === "number" && Number.isFinite(info.cost)
|
|
70
|
+
? info.cost
|
|
71
|
+
: fallback?.cost,
|
|
72
|
+
tokens: normalizeTokens(info.tokens) ?? fallback?.tokens,
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Fill `subtreeActive` and `activeDescendants` after discovery built the rows.
|
|
78
|
+
* Missing parents are treated as subtree roots; a malformed cycle stops at the
|
|
79
|
+
* repeated row instead of recursing forever.
|
|
80
|
+
*/
|
|
81
|
+
export const applySubtreeActivity = (rows: SessionRow[]): void => {
|
|
82
|
+
const children = new Map<string, SessionRow[]>();
|
|
83
|
+
for (const row of rows) {
|
|
84
|
+
if (!row.parentID) continue;
|
|
85
|
+
const siblings = children.get(row.parentID) ?? [];
|
|
86
|
+
siblings.push(row);
|
|
87
|
+
children.set(row.parentID, siblings);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const memo = new Map<string, boolean>();
|
|
91
|
+
const visiting = new Set<string>();
|
|
92
|
+
|
|
93
|
+
const subtreeActive = (row: SessionRow): boolean => {
|
|
94
|
+
const cached = memo.get(row.id);
|
|
95
|
+
if (cached !== undefined) return cached;
|
|
96
|
+
// A malformed cycle is treated as active and stops recursion. This is
|
|
97
|
+
// fail-closed and keeps the result independent of row order.
|
|
98
|
+
if (visiting.has(row.id)) return true;
|
|
99
|
+
visiting.add(row.id);
|
|
100
|
+
const descendants = children.get(row.id) ?? [];
|
|
101
|
+
const value = row.active || descendants.some((child) => subtreeActive(child));
|
|
102
|
+
visiting.delete(row.id);
|
|
103
|
+
memo.set(row.id, value);
|
|
104
|
+
return value;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
for (const row of rows) {
|
|
108
|
+
row.subtreeActive = subtreeActive(row);
|
|
109
|
+
const descendants = children.get(row.id) ?? [];
|
|
110
|
+
if (descendants.some((child) => subtreeActive(child))) {
|
|
111
|
+
row.activeDescendants = true;
|
|
112
|
+
} else {
|
|
113
|
+
delete row.activeDescendants;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|