@morlay/dsh-subagent 0.0.6 → 0.0.8

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.
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Browser-facing subagent prompt and interrupt request validation plus the
3
+ * stable prompt failure codes returned by the Remote surface.
4
+ *
5
+ * @module @deepseek-ai/dsh-subagent
6
+ */
7
+
8
+ import { AttachmentError } from "@deepseek-ai/dsh-attachment";
9
+ import type { SessionId } from "@deepseek-ai/dsh-session";
10
+ import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
11
+ import { z } from "zod";
12
+ import { SubagentError } from "./error.ts";
13
+
14
+ const SESSION_ID_SCHEMA = z.string().min(1);
15
+ const CONTROL_ID_SCHEMAS = {
16
+ "subagent.prompt": z.object({
17
+ parentSessionId: SESSION_ID_SCHEMA,
18
+ childSessionId: SESSION_ID_SCHEMA,
19
+ mode: z.literal("continuable"),
20
+ delivery: z.enum(["queue", "steer"]),
21
+ }),
22
+ "subagent.interrupt": z.object({
23
+ parentSessionId: SESSION_ID_SCHEMA,
24
+ childSessionId: SESSION_ID_SCHEMA,
25
+ mode: z.literal("continuable"),
26
+ }),
27
+ } as const;
28
+
29
+ /**
30
+ * Apply the subagent payload checks that are stricter than generated
31
+ * branded-string codecs.
32
+ * @param method - method name carried in the failure message.
33
+ * @param payload - decoded control fields to validate.
34
+ * @throws {RemoteError} `gateway/bad-request` with the original Zod issues.
35
+ */
36
+ export function validateControlRequest(
37
+ method: keyof typeof CONTROL_ID_SCHEMAS,
38
+ payload: unknown,
39
+ ): void {
40
+ const parsed = CONTROL_ID_SCHEMAS[method].safeParse(payload);
41
+ if (!parsed.success) {
42
+ throw new RemoteError("gateway/bad-request", `invalid payload for ${method}`, {
43
+ issues: parsed.error.issues,
44
+ });
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Refuse one continuation prompt without exposing provider detail: admission
50
+ * failures the caller can act on keep their own code, everything else is
51
+ * internal.
52
+ * @param error - the thrown value.
53
+ * @param childSessionId - the addressed child.
54
+ * @param signal - the caller's cancellation.
55
+ * @returns Never — the refusal is thrown.
56
+ * @throws {RemoteError} always.
57
+ */
58
+ export function rejectPrompt(
59
+ error: unknown,
60
+ childSessionId: SessionId,
61
+ signal: AbortSignal,
62
+ ): never {
63
+ if (isCancellation(error, signal)) {
64
+ throw new RemoteError(
65
+ "gateway/cancelled",
66
+ "subagent prompt was cancelled",
67
+ {},
68
+ { cause: error },
69
+ );
70
+ }
71
+ if (error instanceof AttachmentError) {
72
+ throw new RemoteError(
73
+ "subagent/attachment-invalid",
74
+ error.message,
75
+ { reason: error.code },
76
+ { cause: error },
77
+ );
78
+ }
79
+ if (error instanceof SubagentError) {
80
+ switch (error.code) {
81
+ case "MODEL_DOES_NOT_SUPPORT_IMAGES":
82
+ throw new RemoteError(
83
+ "subagent/attachment-invalid",
84
+ error.message,
85
+ { reason: error.code },
86
+ { cause: error },
87
+ );
88
+ case "NOT_RESUMABLE":
89
+ throw new RemoteError(
90
+ "subagent/not-resumable",
91
+ "subagent cannot be resumed",
92
+ { childSessionId },
93
+ { cause: error },
94
+ );
95
+ case "UNAUTHORIZED":
96
+ throw new RemoteError(
97
+ "subagent/unauthorized",
98
+ "subagent does not belong to this parent",
99
+ { childSessionId },
100
+ { cause: error },
101
+ );
102
+ case "DRAINING":
103
+ case "ACTIVATION_CLOSING":
104
+ case "ACTIVATION_LIMIT_REACHED":
105
+ case "CONTINUATION_UNAVAILABLE":
106
+ case "PERSISTENCE_UNAVAILABLE":
107
+ throw new RemoteError(
108
+ "subagent/delivery-unavailable",
109
+ "subagent follow-up is temporarily unavailable",
110
+ { childSessionId },
111
+ { cause: error },
112
+ );
113
+ // A code outside the admission vocabulary is not the caller's move to make.
114
+ default:
115
+ break;
116
+ }
117
+ }
118
+ throw new RemoteError("gateway/internal", "subagent prompt failed", {}, { cause: error });
119
+ }
120
+
121
+ function isCancellation(error: unknown, signal: AbortSignal): boolean {
122
+ return signal.aborted || (error instanceof SubagentError && error.code === "CANCELLED");
123
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Delegation-depth accounting: the recursion budget a parent passes to its
3
+ * children. Kept apart from the service so composition helpers can read it
4
+ * without importing the registry.
5
+ *
6
+ * @module @deepseek-ai/dsh-subagent/depth
7
+ */
8
+
9
+ import type { Agent } from "@deepseek-ai/dsh-agent";
10
+
11
+ declare module "@deepseek-ai/dsh-agent" {
12
+ interface AgentOptions {
13
+ /** Delegation depth: zero for a top-level agent and parent depth + 1 for a child. */
14
+ subagentDepth?: number;
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Read an agent's delegation depth, treating absence as top-level depth zero.
20
+ * The persisted session header is authoritative and monotone: runtime
21
+ * `AgentOptions.subagentDepth` may DEEPEN the count but can never lower it —
22
+ * a resumed child arrives with fresh options, and counting it from zero would
23
+ * let it delegate as if it were top-level.
24
+ * @param agent - the agent whose header and options carry the depth.
25
+ * @returns its non-negative safe-integer depth.
26
+ * @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer.
27
+ */
28
+ export function delegationDepthOf(agent: Agent): number {
29
+ const runtime = agent.options.subagentDepth;
30
+ if (
31
+ runtime !== undefined &&
32
+ (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))
33
+ ) {
34
+ throw new TypeError("agent subagentDepth must be a non-negative safe integer");
35
+ }
36
+ // The header value was validated at the session boundary (creation and
37
+ // persistence load both construct through the store).
38
+ return Math.max(agent.session.header.delegationDepth ?? 0, runtime ?? 0);
39
+ }
40
+
41
+ /**
42
+ * Reject a recursion cap that cannot represent an exact delegation depth.
43
+ * @param maxDepth - the optional runtime value to validate.
44
+ */
45
+ export function assertSubagentMaxDepth(maxDepth: unknown): void {
46
+ if (
47
+ maxDepth !== undefined &&
48
+ (typeof maxDepth !== "number" ||
49
+ !Number.isSafeInteger(maxDepth) ||
50
+ maxDepth < 0 ||
51
+ Object.is(maxDepth, -0))
52
+ ) {
53
+ throw new TypeError("subagent maxDepth must be a non-negative safe integer");
54
+ }
55
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The durable subagent-child descriptor: the versioned, model-hidden
3
+ * `subagent/descriptor` session event that identifies every session-backed
4
+ * subagent, including historical one-shot records. The manager appends each
5
+ * continuable child's descriptor inside its initial turn, preserving the
6
+ * declared composition required for cold resume.
7
+ *
8
+ * The descriptor deliberately snapshots explicit fields rather than the
9
+ * merge-extensible `AgentOptions` object: an unrelated extension value cannot
10
+ * make continuation fail merely because it is not JSON, and later composition
11
+ * inputs require a deliberate {@link SUBAGENT_DESCRIPTOR_VERSION} change. It
12
+ * omits `subagentDepth` — cold resume trusts the persisted header's
13
+ * `delegationDepth` as the monotone floor — and `outputSchema`, which belongs
14
+ * to one activation's result contract rather than durable child composition.
15
+ * Per-activation knobs such as `maxTokens` are omitted for the same reason as
16
+ * `outputSchema`: they budget one activation. Cold resume requires the exact
17
+ * live parent for authorization but reconstructs child options only from the
18
+ * durable descriptor, so it neither restores the prior budget nor inherits
19
+ * the parent's current one; the resumed route's defaults apply instead.
20
+ *
21
+ * @module @deepseek-ai/dsh-subagent/descriptor
22
+ */
23
+
24
+ import { snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
25
+ import type { SessionEvent } from "@deepseek-ai/dsh-session";
26
+ import type { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
27
+ import type { ToolRestriction } from "@deepseek-ai/dsh-tools";
28
+
29
+ declare module "@deepseek-ai/dsh-session/types" {
30
+ interface SessionEventMap {
31
+ /**
32
+ * Durable identity and lifecycle mode of a session-backed subagent child,
33
+ * appended once inside the child's initial turn, before its first
34
+ * request. Continuable records also carry their
35
+ * resumable composition. Log-only: it carries no `surfaceOp`, never enters
36
+ * model history, and survives compaction.
37
+ */
38
+ "subagent/descriptor": SubagentDescriptorData;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * The current descriptor format version, stamped into every appended
44
+ * `subagent/descriptor` event and required verbatim by {@link foldSubagentDescriptor}.
45
+ * Supporting another composition input is a deliberate version change, never
46
+ * an implicit extra field.
47
+ */
48
+ export const SUBAGENT_DESCRIPTOR_VERSION = 3;
49
+
50
+ /** Fields shared by every supported `subagent/descriptor` payload. */
51
+ interface SubagentDescriptorBase {
52
+ /** Descriptor format version ({@link SUBAGENT_DESCRIPTOR_VERSION}). */
53
+ readonly version: number;
54
+ /** Whether the child is a terminal one-shot run or a resumable conversation. */
55
+ readonly mode: "one-shot" | "continuable";
56
+ /** The `ctx.subagents` provider name that established the child. */
57
+ readonly provider: string;
58
+ }
59
+
60
+ /** A session-backed subagent that cannot be cold-resumed after its run. */
61
+ export interface OneShotSubagentDescriptorData extends SubagentDescriptorBase {
62
+ readonly mode: "one-shot";
63
+ /**
64
+ * The initial delegation's short `description`, kept as the child's durable
65
+ * creation label so enumeration can identify the conversation without
66
+ * replaying parent tool results or exposing the child prompt.
67
+ */
68
+ readonly label?: string;
69
+ }
70
+
71
+ /** A session-backed subagent whose declared composition supports cold resume. */
72
+ export interface ContinuableSubagentDescriptorData extends SubagentDescriptorBase {
73
+ readonly mode: "continuable";
74
+ /** The initial delegation's short `description`, used for durable enumeration. */
75
+ readonly label: string;
76
+ /** Resolved child `agentOptions.provider`, when one was declared. */
77
+ readonly agentProvider?: string;
78
+ /** Resolved child `agentOptions.model`, when one was declared. */
79
+ readonly agentModel?: string;
80
+ /** Resolved child `agentOptions.reasoningEffort`, when one was declared. */
81
+ readonly agentReasoningEffort?: ReasoningEffortId;
82
+ /** Per-child persona that shadows the deployment persona on resume. */
83
+ readonly persona?: string;
84
+ /** Child tool scoping reapplied on resume. */
85
+ readonly toolFilter?: ToolRestriction;
86
+ }
87
+
88
+ /** The supported durable subagent identity and optional continuation composition. */
89
+ export type SubagentDescriptorData =
90
+ | OneShotSubagentDescriptorData
91
+ | ContinuableSubagentDescriptorData;
92
+
93
+ /** Continuable composition fields before the snapshot stamps their format version. */
94
+ export type ContinuableSubagentDescriptorInput = Omit<ContinuableSubagentDescriptorData, "version">;
95
+
96
+ const DESCRIPTOR_BASE_KEYS = ["version", "mode", "provider", "label"] as const;
97
+ const ONE_SHOT_DESCRIPTOR_KEYS = new Set(DESCRIPTOR_BASE_KEYS);
98
+ const CONTINUABLE_DESCRIPTOR_KEYS = new Set([
99
+ ...DESCRIPTOR_BASE_KEYS,
100
+ "agentProvider",
101
+ "agentModel",
102
+ "agentReasoningEffort",
103
+ "persona",
104
+ "toolFilter",
105
+ ]);
106
+ const TOOL_FILTER_KEYS = new Set(["allow", "deny"]);
107
+
108
+ /** Whether a persisted JSON value is an object record. */
109
+ function isRecord(value: unknown): value is Record<string, unknown> {
110
+ return typeof value === "object" && value !== null && !Array.isArray(value);
111
+ }
112
+
113
+ /** Reject fields outside one versioned record's declared schema. */
114
+ function assertKnownKeys(
115
+ value: Record<string, unknown>,
116
+ keys: ReadonlySet<string>,
117
+ path: string,
118
+ ): void {
119
+ const unknown = Object.keys(value).find((key) => !keys.has(key));
120
+ if (unknown !== undefined) {
121
+ throw new Error(`persisted subagent descriptor ${path} has unknown field "${unknown}"`);
122
+ }
123
+ }
124
+
125
+ /** Read one optional string field from a persisted descriptor record. */
126
+ function optionalString(value: Record<string, unknown>, key: string): string | undefined {
127
+ if (!Object.hasOwn(value, key)) return undefined;
128
+ const field = value[key];
129
+ if (typeof field !== "string") {
130
+ throw new Error(`persisted subagent descriptor ${key} must be a string`);
131
+ }
132
+ return field;
133
+ }
134
+
135
+ /** Read one optional string-array field from a persisted tool restriction. */
136
+ function optionalStringArray(value: Record<string, unknown>, key: string): string[] | undefined {
137
+ if (!Object.hasOwn(value, key)) return undefined;
138
+ const field = value[key];
139
+ if (!Array.isArray(field)) {
140
+ throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);
141
+ }
142
+ const items: unknown[] = field;
143
+ if (items.some((item) => typeof item !== "string")) {
144
+ throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);
145
+ }
146
+ return items as string[];
147
+ }
148
+
149
+ /** Validate and reconstruct a persisted tool restriction. */
150
+ function parseToolFilter(value: unknown): ToolRestriction {
151
+ if (!isRecord(value)) {
152
+ throw new Error("persisted subagent descriptor toolFilter must be an object");
153
+ }
154
+ assertKnownKeys(value, TOOL_FILTER_KEYS, "toolFilter");
155
+ const allow = optionalStringArray(value, "allow");
156
+ const deny = optionalStringArray(value, "deny");
157
+ if (allow === undefined && deny === undefined) {
158
+ throw new Error("persisted subagent descriptor toolFilter must declare allow and/or deny");
159
+ }
160
+ return {
161
+ ...(allow !== undefined ? { allow } : {}),
162
+ ...(deny !== undefined ? { deny } : {}),
163
+ };
164
+ }
165
+
166
+ /** Validate one persisted descriptor payload for the current runtime. */
167
+ function parseSubagentDescriptor(value: unknown): SubagentDescriptorData | undefined {
168
+ if (!isRecord(value)) {
169
+ throw new Error("persisted subagent descriptor payload must be an object");
170
+ }
171
+ const version = value["version"];
172
+ if (typeof version !== "number") {
173
+ throw new Error("persisted subagent descriptor version must be a number");
174
+ }
175
+ if (version !== SUBAGENT_DESCRIPTOR_VERSION) return undefined;
176
+
177
+ const mode = value["mode"];
178
+ if (mode !== "one-shot" && mode !== "continuable") {
179
+ throw new Error('persisted subagent descriptor mode must be "one-shot" or "continuable"');
180
+ }
181
+ assertKnownKeys(
182
+ value,
183
+ mode === "one-shot" ? ONE_SHOT_DESCRIPTOR_KEYS : CONTINUABLE_DESCRIPTOR_KEYS,
184
+ "payload",
185
+ );
186
+ const provider = value["provider"];
187
+ if (typeof provider !== "string") {
188
+ throw new Error("persisted subagent descriptor provider must be a string");
189
+ }
190
+ if (mode === "one-shot") {
191
+ const label = optionalString(value, "label");
192
+ return {
193
+ version: SUBAGENT_DESCRIPTOR_VERSION,
194
+ mode,
195
+ provider,
196
+ ...(label !== undefined ? { label } : {}),
197
+ };
198
+ }
199
+ const label = value["label"];
200
+ if (typeof label !== "string") {
201
+ throw new Error("persisted subagent descriptor label must be a string");
202
+ }
203
+ const agentProvider = optionalString(value, "agentProvider");
204
+ const agentModel = optionalString(value, "agentModel");
205
+ const agentReasoningEffort = optionalString(value, "agentReasoningEffort") as
206
+ | ReasoningEffortId
207
+ | undefined;
208
+ const persona = optionalString(value, "persona");
209
+ const toolFilter = Object.hasOwn(value, "toolFilter")
210
+ ? parseToolFilter(value["toolFilter"])
211
+ : undefined;
212
+ return {
213
+ version: SUBAGENT_DESCRIPTOR_VERSION,
214
+ mode,
215
+ provider,
216
+ label,
217
+ ...(agentProvider !== undefined ? { agentProvider } : {}),
218
+ ...(agentModel !== undefined ? { agentModel } : {}),
219
+ ...(agentReasoningEffort !== undefined ? { agentReasoningEffort } : {}),
220
+ ...(persona !== undefined ? { persona } : {}),
221
+ ...(toolFilter !== undefined ? { toolFilter } : {}),
222
+ };
223
+ }
224
+
225
+ /**
226
+ * Validate and detach a continuable descriptor input.
227
+ * @param input - the caller-collected continuable composition fields.
228
+ * @returns the versioned, detached continuable descriptor payload.
229
+ * @throws when a field is not losslessly JSON-serializable.
230
+ */
231
+ export function snapshotSubagentDescriptor(
232
+ input: ContinuableSubagentDescriptorInput,
233
+ ): ContinuableSubagentDescriptorData {
234
+ const candidate: ContinuableSubagentDescriptorData = {
235
+ version: SUBAGENT_DESCRIPTOR_VERSION,
236
+ mode: input.mode,
237
+ provider: input.provider,
238
+ label: input.label,
239
+ ...(input.agentProvider !== undefined ? { agentProvider: input.agentProvider } : {}),
240
+ ...(input.agentModel !== undefined ? { agentModel: input.agentModel } : {}),
241
+ ...(input.agentReasoningEffort !== undefined
242
+ ? { agentReasoningEffort: input.agentReasoningEffort }
243
+ : {}),
244
+ ...(input.persona !== undefined ? { persona: input.persona } : {}),
245
+ ...(input.toolFilter !== undefined ? { toolFilter: input.toolFilter } : {}),
246
+ };
247
+ const snapshot = snapshotJsonValue(candidate);
248
+ if (snapshot === undefined) {
249
+ throw new Error("subagent descriptor is not losslessly JSON-serializable");
250
+ }
251
+ return snapshot;
252
+ }
253
+
254
+ /**
255
+ * Fold a persisted child log to its supported descriptor. The first
256
+ * `subagent/descriptor` event is authoritative — the establishing provider
257
+ * appends exactly one, so a later same-type event cannot rewrite the declared
258
+ * composition.
259
+ * @param events - the loaded child session events.
260
+ * @returns the descriptor, or `undefined` when the log has none or its
261
+ * version is not {@link SUBAGENT_DESCRIPTOR_VERSION} (the child cannot be
262
+ * classified by this runtime).
263
+ * @throws when a current-version persisted payload does not match its complete
264
+ * declared schema.
265
+ */
266
+ export function foldSubagentDescriptor(
267
+ events: readonly SessionEvent[],
268
+ ): SubagentDescriptorData | undefined {
269
+ const event = events.find(
270
+ (candidate): candidate is SessionEvent<"subagent/descriptor"> =>
271
+ candidate.type === "subagent/descriptor",
272
+ );
273
+ if (event === undefined) return undefined;
274
+ return parseSubagentDescriptor(event.data);
275
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Typed failures shared by subagent service and provider operations.
3
+ *
4
+ * @module @deepseek-ai/dsh-subagent
5
+ */
6
+
7
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
8
+
9
+ /** Typed failure for the subagent seam. */
10
+ export class SubagentError extends HarnessError {
11
+ constructor(message: string, code: string, options?: ErrorOptions) {
12
+ super(message, code, options);
13
+ this.name = "SubagentError";
14
+ }
15
+ }