@deepseek-ai/dsh-subagent 0.2.2-rc.1 → 0.2.2-rc.2

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.
Files changed (108) hide show
  1. package/README.i18n.yaml +46 -28
  2. package/README.md +52 -23
  3. package/README.zh.md +52 -23
  4. package/lib/index.js +845 -902
  5. package/lib/typert.host.js +91 -125
  6. package/lib/typert.remote-client.d.ts +3 -3
  7. package/lib/typert.remote-client.d.ts.map +1 -0
  8. package/lib/typert.remote-client.js +17 -63
  9. package/lib/types/activation.d.ts +17 -25
  10. package/lib/types/activation.d.ts.map +1 -0
  11. package/lib/types/activation.js +1 -1
  12. package/lib/types/activation.js.map +1 -0
  13. package/lib/types/archive-admission.d.ts +11 -4
  14. package/lib/types/archive-admission.d.ts.map +1 -0
  15. package/lib/types/archive-admission.js +39 -115
  16. package/lib/types/archive-admission.js.map +1 -0
  17. package/lib/types/assistant-output.d.ts.map +1 -0
  18. package/lib/types/assistant-output.js.map +1 -0
  19. package/lib/types/catalog.d.ts +27 -7
  20. package/lib/types/catalog.d.ts.map +1 -0
  21. package/lib/types/catalog.js +31 -8
  22. package/lib/types/catalog.js.map +1 -0
  23. package/lib/types/child-agent.d.ts +7 -17
  24. package/lib/types/child-agent.d.ts.map +1 -0
  25. package/lib/types/child-agent.js +6 -4
  26. package/lib/types/child-agent.js.map +1 -0
  27. package/lib/types/client.d.ts.map +1 -0
  28. package/lib/types/client.js.map +1 -0
  29. package/lib/types/continuation-messages.d.ts +13 -10
  30. package/lib/types/continuation-messages.d.ts.map +1 -0
  31. package/lib/types/continuation-messages.js +22 -22
  32. package/lib/types/continuation-messages.js.map +1 -0
  33. package/lib/types/control-types.d.ts +7 -28
  34. package/lib/types/control-types.d.ts.map +1 -0
  35. package/lib/types/control-types.js.map +1 -0
  36. package/lib/types/control.d.ts +0 -4
  37. package/lib/types/control.d.ts.map +1 -0
  38. package/lib/types/control.js +1 -5
  39. package/lib/types/control.js.map +1 -0
  40. package/lib/types/depth.d.ts.map +1 -0
  41. package/lib/types/depth.js.map +1 -0
  42. package/lib/types/descriptor.d.ts +1 -1
  43. package/lib/types/descriptor.d.ts.map +1 -0
  44. package/lib/types/descriptor.js +1 -1
  45. package/lib/types/descriptor.js.map +1 -0
  46. package/lib/types/error.d.ts.map +1 -0
  47. package/lib/types/error.js.map +1 -0
  48. package/lib/types/index.d.ts +74 -97
  49. package/lib/types/index.d.ts.map +1 -0
  50. package/lib/types/index.js +125 -146
  51. package/lib/types/index.js.map +1 -0
  52. package/lib/types/lifecycle.d.ts +9 -38
  53. package/lib/types/lifecycle.d.ts.map +1 -0
  54. package/lib/types/lifecycle.js +5 -31
  55. package/lib/types/lifecycle.js.map +1 -0
  56. package/lib/types/list-children.d.ts +12 -0
  57. package/lib/types/list-children.d.ts.map +1 -0
  58. package/lib/types/list-children.js +35 -6
  59. package/lib/types/list-children.js.map +1 -0
  60. package/lib/types/manager.d.ts +96 -112
  61. package/lib/types/manager.d.ts.map +1 -0
  62. package/lib/types/manager.js +471 -568
  63. package/lib/types/manager.js.map +1 -0
  64. package/lib/types/names.d.ts +56 -0
  65. package/lib/types/names.d.ts.map +1 -0
  66. package/lib/types/names.js +96 -0
  67. package/lib/types/names.js.map +1 -0
  68. package/lib/types/out-of-process.d.ts.map +1 -0
  69. package/lib/types/out-of-process.js.map +1 -0
  70. package/lib/types/projection-types.d.ts +18 -6
  71. package/lib/types/projection-types.d.ts.map +1 -0
  72. package/lib/types/projection-types.js.map +1 -0
  73. package/lib/types/projection.d.ts +2 -2
  74. package/lib/types/projection.d.ts.map +1 -0
  75. package/lib/types/projection.js.map +1 -0
  76. package/lib/types/structured.d.ts +1 -1
  77. package/lib/types/structured.d.ts.map +1 -0
  78. package/lib/types/structured.js +2 -2
  79. package/lib/types/structured.js.map +1 -0
  80. package/lib/types/types.d.ts +34 -28
  81. package/lib/types/types.d.ts.map +1 -0
  82. package/lib/types/types.js +2 -4
  83. package/lib/types/types.js.map +1 -0
  84. package/package.json +54 -54
  85. package/src/activation.ts +184 -0
  86. package/src/archive-admission.ts +84 -0
  87. package/src/assistant-output.ts +75 -0
  88. package/src/catalog.ts +194 -0
  89. package/src/child-agent.ts +280 -0
  90. package/src/client.ts +8 -0
  91. package/src/continuation-messages.ts +176 -0
  92. package/src/control-types.ts +127 -0
  93. package/src/control.ts +103 -0
  94. package/src/depth.ts +51 -0
  95. package/src/descriptor.ts +269 -0
  96. package/src/error.ts +15 -0
  97. package/src/index.ts +604 -0
  98. package/src/lifecycle.ts +116 -0
  99. package/src/list-children.ts +168 -0
  100. package/src/manager.ts +1359 -0
  101. package/src/names.ts +113 -0
  102. package/src/out-of-process.ts +217 -0
  103. package/src/projection-types.ts +109 -0
  104. package/src/projection.ts +184 -0
  105. package/src/structured.ts +155 -0
  106. package/src/types.ts +364 -0
  107. package/lib/types/internal.d.ts +0 -58
  108. package/lib/types/internal.js +0 -58
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Client-safe recursive catalog rows and browser continuation requests,
3
+ * receipts, and failures.
4
+ *
5
+ * @module @deepseek-ai/dsh-subagent/control-types
6
+ */
7
+
8
+ import type { PromptContentPart } from '@deepseek-ai/dsh-attachment/types'
9
+ import type { Branded } from '@deepseek-ai/dsh-brand'
10
+ import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
11
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
12
+ import type { KnownSubagentCatalogFields } from './projection-types.ts'
13
+ // Type-only: the Workspace registry's archive-admission family map this runtime merges `subagent` into.
14
+ import type {} from '@deepseek-ai/dsh-workspace/types'
15
+
16
+ /**
17
+ * Client-minted identity of one browser prompt, persisted on the exact accepted
18
+ * message. It carries the Session Controller's `session-request-id` brand so a
19
+ * subagent prompt and an ordinary Session prompt share one identity
20
+ * vocabulary; that package depends on this one, so the brand is spelled here
21
+ * rather than imported.
22
+ */
23
+ export type SubagentPromptRequestId = Branded<'session-request-id'>
24
+
25
+ /** Shared child fields for recursive catalog listing. */
26
+ export type SubagentCatalogRow =
27
+ & {
28
+ /** The durable child session id, stable across Activations. */
29
+ readonly id: SessionId
30
+ /**
31
+ * Whether recursive catalog listing observed a resident Session. This
32
+ * does not encode a durable outcome or guarantee continuation delivery.
33
+ */
34
+ readonly activity: 'running' | 'inactive'
35
+ }
36
+ & KnownSubagentCatalogFields
37
+
38
+ /**
39
+ * One recursive catalog row. Traversal may also return diagnostics for
40
+ * unknown catalog modes or unreadable child catalogs.
41
+ */
42
+ export type SubagentListEntry =
43
+ | SubagentCatalogRow & {
44
+ readonly kind: 'child'
45
+ /** Whether the child catalog contains a direct child. */
46
+ readonly hasChildren: boolean
47
+ }
48
+ | {
49
+ readonly kind: 'diagnostic'
50
+ /** The candidate's session id. */
51
+ readonly id: SessionId
52
+ /**
53
+ * `corrupt` means the child catalog read found invalid or conflicting
54
+ * Session data; `unavailable` means it could not be read. Either failure
55
+ * stops that branch. `unsupported` means the parent catalog records an
56
+ * unknown child mode; its readable catalog is still traversed.
57
+ */
58
+ readonly reason: 'corrupt' | 'unsupported' | 'unavailable'
59
+ }
60
+
61
+ /** Durable parent/child browsing address; unknown mode is resolved when child history is read. */
62
+ export type SubagentAddress =
63
+ & {
64
+ readonly parentSessionId: SessionId
65
+ readonly childSessionId: SessionId
66
+ }
67
+ & (
68
+ | { readonly mode: 'one-shot' }
69
+ | { readonly mode: 'continuable' }
70
+ | { readonly mode: 'unknown' }
71
+ )
72
+
73
+ /** One Agent inbox destination for a continuation message. */
74
+ export type SubagentDelivery = 'queue' | 'steer'
75
+
76
+ /** One human message addressed to a continuable subagent. */
77
+ export interface SubagentPromptRequest {
78
+ /** Identity persisted on the accepted message, minted before the call. */
79
+ readonly requestId: SubagentPromptRequestId
80
+ readonly childSessionId: SessionId
81
+ /** Whether this message queues a later turn or targets the nearest step. */
82
+ readonly delivery: SubagentDelivery
83
+ /**
84
+ * Browser prompt parts delivered as the child's user message. The Host
85
+ * admits and persists image parts before delivery, so the wire never
86
+ * carries a durable attachment reference the caller could fabricate.
87
+ */
88
+ readonly content: readonly PromptContentPart[]
89
+ /** Optional browser zone sampled for this exact human prompt. */
90
+ readonly clientTimeZone?: string
91
+ }
92
+
93
+ /** Inbox identity returned once the continuation accepts one human message. */
94
+ export interface SubagentPromptReceipt {
95
+ readonly messageId: MessageId
96
+ }
97
+
98
+ /** Uniform acknowledgement that one interrupt request was admitted. */
99
+ export interface SubagentInterruptReceipt {
100
+ readonly accepted: true
101
+ }
102
+
103
+ /**
104
+ * Failure details the control surface answers with. Prompts and interrupts
105
+ * share these failures with the Client Remote result.
106
+ */
107
+ declare module '@deepseek-ai/dsh-workspace/types' {
108
+ interface SessionActivityKindMap {
109
+ /** A subagent session delegated from this session (at any depth) is inside a turn. */
110
+ subagent: true
111
+ }
112
+ }
113
+
114
+ declare module '@deepseek-ai/dsh-typert-protocol' {
115
+ interface RemoteErrorDetailsMap {
116
+ /** A browser-supplied zone is neither UTC nor a canonical IANA name. */
117
+ 'subagent/invalid-time-zone': { readonly value: string }
118
+ /** The addressed child cannot take a continuation. */
119
+ 'subagent/not-resumable': { readonly childSessionId: SessionId }
120
+ /** The supplied address or live subagent-tree identity could not be verified. */
121
+ 'subagent/unauthorized': { readonly childSessionId: SessionId }
122
+ /** Image admission or model image-capability refusal. */
123
+ 'subagent/attachment-invalid': { readonly reason: string }
124
+ /** The child exists but its inbox cannot admit the message now. */
125
+ 'subagent/delivery-unavailable': { readonly childSessionId: SessionId }
126
+ }
127
+ }
package/src/control.ts ADDED
@@ -0,0 +1,103 @@
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
+ childSessionId: SESSION_ID_SCHEMA,
18
+ delivery: z.enum(['queue', 'steer']),
19
+ }),
20
+ 'subagent.interrupt': z.object({
21
+ childSessionId: SESSION_ID_SCHEMA,
22
+ }),
23
+ } as const
24
+
25
+ /**
26
+ * Apply the subagent payload checks that are stricter than generated
27
+ * branded-string codecs.
28
+ * @param method - method name carried in the failure message.
29
+ * @param payload - decoded control fields to validate.
30
+ * @throws {RemoteError} `gateway/bad-request` with the original Zod issues.
31
+ */
32
+ export function validateControlRequest(
33
+ method: keyof typeof CONTROL_ID_SCHEMAS,
34
+ payload: unknown,
35
+ ): void {
36
+ const parsed = CONTROL_ID_SCHEMAS[method].safeParse(payload)
37
+ if (!parsed.success) {
38
+ throw new RemoteError('gateway/bad-request', `invalid payload for ${method}`, { issues: parsed.error.issues })
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Refuse one continuation prompt without exposing provider detail: admission
44
+ * failures the caller can act on keep their own code, everything else is
45
+ * internal.
46
+ * @param error - the thrown value.
47
+ * @param childSessionId - the addressed child.
48
+ * @param signal - the caller's cancellation.
49
+ * @returns Never — the refusal is thrown.
50
+ * @throws {RemoteError} always.
51
+ */
52
+ export function rejectPrompt(error: unknown, childSessionId: SessionId, signal: AbortSignal): never {
53
+ if (isCancellation(error, signal)) {
54
+ throw new RemoteError('gateway/cancelled', 'subagent prompt was cancelled', {}, { cause: error })
55
+ }
56
+ if (error instanceof AttachmentError) {
57
+ throw new RemoteError('subagent/attachment-invalid', error.message, { reason: error.code }, { cause: error })
58
+ }
59
+ if (error instanceof SubagentError) {
60
+ switch (error.code) {
61
+ case 'MODEL_DOES_NOT_SUPPORT_IMAGES':
62
+ throw new RemoteError(
63
+ 'subagent/attachment-invalid',
64
+ error.message,
65
+ { reason: error.code },
66
+ { cause: error },
67
+ )
68
+ case 'NOT_RESUMABLE':
69
+ throw new RemoteError(
70
+ 'subagent/not-resumable',
71
+ 'subagent cannot be resumed',
72
+ { childSessionId },
73
+ { cause: error },
74
+ )
75
+ case 'UNAUTHORIZED':
76
+ throw new RemoteError(
77
+ 'subagent/unauthorized',
78
+ 'subagent membership in the active tree could not be verified',
79
+ { childSessionId },
80
+ { cause: error },
81
+ )
82
+ case 'DRAINING':
83
+ case 'ACTIVATION_CLOSING':
84
+ case 'ACTIVATION_LIMIT_REACHED':
85
+ case 'CONTINUATION_UNAVAILABLE':
86
+ case 'PERSISTENCE_UNAVAILABLE':
87
+ throw new RemoteError(
88
+ 'subagent/delivery-unavailable',
89
+ 'subagent follow-up is temporarily unavailable',
90
+ { childSessionId },
91
+ { cause: error },
92
+ )
93
+ // A code outside the admission vocabulary is not the caller's move to make.
94
+ default:
95
+ break
96
+ }
97
+ }
98
+ throw new RemoteError('gateway/internal', 'subagent prompt failed', {}, { cause: error })
99
+ }
100
+
101
+ function isCancellation(error: unknown, signal: AbortSignal): boolean {
102
+ return signal.aborted || (error instanceof SubagentError && error.code === 'CANCELLED')
103
+ }
package/src/depth.ts ADDED
@@ -0,0 +1,51 @@
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 (runtime !== undefined && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) {
31
+ throw new TypeError('agent subagentDepth must be a non-negative safe integer')
32
+ }
33
+ // The header value was validated at the session boundary (creation and
34
+ // persistence load both construct through the store).
35
+ return Math.max(agent.session.header.delegationDepth ?? 0, runtime ?? 0)
36
+ }
37
+
38
+ /**
39
+ * Reject a recursion cap that cannot represent an exact delegation depth.
40
+ * @param maxDepth - the optional runtime value to validate.
41
+ */
42
+ export function assertSubagentMaxDepth(maxDepth: unknown): void {
43
+ if (maxDepth !== undefined && (
44
+ typeof maxDepth !== 'number'
45
+ || !Number.isSafeInteger(maxDepth)
46
+ || maxDepth < 0
47
+ || Object.is(maxDepth, -0)
48
+ )) {
49
+ throw new TypeError('subagent maxDepth must be a non-negative safe integer')
50
+ }
51
+ }
@@ -0,0 +1,269 @@
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 subagent tree root 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 = [
97
+ 'version',
98
+ 'mode',
99
+ 'provider',
100
+ 'label',
101
+ ] as const
102
+ const ONE_SHOT_DESCRIPTOR_KEYS = new Set(DESCRIPTOR_BASE_KEYS)
103
+ const CONTINUABLE_DESCRIPTOR_KEYS = new Set([
104
+ ...DESCRIPTOR_BASE_KEYS,
105
+ 'agentProvider',
106
+ 'agentModel',
107
+ 'agentReasoningEffort',
108
+ 'persona',
109
+ 'toolFilter',
110
+ ])
111
+ const TOOL_FILTER_KEYS = new Set(['allow', 'deny'])
112
+
113
+ /** Whether a persisted JSON value is an object record. */
114
+ function isRecord(value: unknown): value is Record<string, unknown> {
115
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
116
+ }
117
+
118
+ /** Reject fields outside one versioned record's declared schema. */
119
+ function assertKnownKeys(value: Record<string, unknown>, keys: ReadonlySet<string>, path: string): void {
120
+ const unknown = Object.keys(value).find(key => !keys.has(key))
121
+ if (unknown !== undefined) {
122
+ throw new Error(`persisted subagent descriptor ${path} has unknown field "${unknown}"`)
123
+ }
124
+ }
125
+
126
+ /** Read one optional string field from a persisted descriptor record. */
127
+ function optionalString(value: Record<string, unknown>, key: string): string | undefined {
128
+ if (!Object.hasOwn(value, key)) return undefined
129
+ const field = value[key]
130
+ if (typeof field !== 'string') {
131
+ throw new Error(`persisted subagent descriptor ${key} must be a string`)
132
+ }
133
+ return field
134
+ }
135
+
136
+ /** Read one optional string-array field from a persisted tool restriction. */
137
+ function optionalStringArray(value: Record<string, unknown>, key: string): string[] | undefined {
138
+ if (!Object.hasOwn(value, key)) return undefined
139
+ const field = value[key]
140
+ if (!Array.isArray(field)) {
141
+ throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`)
142
+ }
143
+ const items: unknown[] = field
144
+ if (items.some(item => typeof item !== 'string')) {
145
+ throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`)
146
+ }
147
+ return items as string[]
148
+ }
149
+
150
+ /** Validate and reconstruct a persisted tool restriction. */
151
+ function parseToolFilter(value: unknown): ToolRestriction {
152
+ if (!isRecord(value)) {
153
+ throw new Error('persisted subagent descriptor toolFilter must be an object')
154
+ }
155
+ assertKnownKeys(value, TOOL_FILTER_KEYS, 'toolFilter')
156
+ const allow = optionalStringArray(value, 'allow')
157
+ const deny = optionalStringArray(value, 'deny')
158
+ if (allow === undefined && deny === undefined) {
159
+ throw new Error('persisted subagent descriptor toolFilter must declare allow and/or deny')
160
+ }
161
+ return {
162
+ ...allow !== undefined ? { allow } : {},
163
+ ...deny !== undefined ? { deny } : {},
164
+ }
165
+ }
166
+
167
+ /** Validate one persisted descriptor payload for the current runtime. */
168
+ function parseSubagentDescriptor(value: unknown): SubagentDescriptorData | undefined {
169
+ if (!isRecord(value)) {
170
+ throw new Error('persisted subagent descriptor payload must be an object')
171
+ }
172
+ const version = value['version']
173
+ if (typeof version !== 'number') {
174
+ throw new Error('persisted subagent descriptor version must be a number')
175
+ }
176
+ if (version !== SUBAGENT_DESCRIPTOR_VERSION) return undefined
177
+
178
+ const mode = value['mode']
179
+ if (mode !== 'one-shot' && mode !== 'continuable') {
180
+ throw new Error('persisted subagent descriptor mode must be "one-shot" or "continuable"')
181
+ }
182
+ assertKnownKeys(
183
+ value,
184
+ mode === 'one-shot' ? ONE_SHOT_DESCRIPTOR_KEYS : CONTINUABLE_DESCRIPTOR_KEYS,
185
+ 'payload',
186
+ )
187
+ const provider = value['provider']
188
+ if (typeof provider !== 'string') {
189
+ throw new Error('persisted subagent descriptor provider must be a string')
190
+ }
191
+ if (mode === 'one-shot') {
192
+ const label = optionalString(value, 'label')
193
+ return {
194
+ version: SUBAGENT_DESCRIPTOR_VERSION,
195
+ mode,
196
+ provider,
197
+ ...label !== undefined ? { label } : {},
198
+ }
199
+ }
200
+ const label = value['label']
201
+ if (typeof label !== 'string') {
202
+ throw new Error('persisted subagent descriptor label must be a string')
203
+ }
204
+ const agentProvider = optionalString(value, 'agentProvider')
205
+ const agentModel = optionalString(value, 'agentModel')
206
+ const agentReasoningEffort = optionalString(value, 'agentReasoningEffort') as ReasoningEffortId | undefined
207
+ const persona = optionalString(value, 'persona')
208
+ const toolFilter = Object.hasOwn(value, 'toolFilter')
209
+ ? parseToolFilter(value['toolFilter'])
210
+ : undefined
211
+ return {
212
+ version: SUBAGENT_DESCRIPTOR_VERSION,
213
+ mode,
214
+ provider,
215
+ label,
216
+ ...agentProvider !== undefined ? { agentProvider } : {},
217
+ ...agentModel !== undefined ? { agentModel } : {},
218
+ ...agentReasoningEffort !== undefined ? { agentReasoningEffort } : {},
219
+ ...persona !== undefined ? { persona } : {},
220
+ ...toolFilter !== undefined ? { toolFilter } : {},
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Validate and detach a continuable descriptor input.
226
+ * @param input - the caller-collected continuable composition fields.
227
+ * @returns the versioned, detached continuable descriptor payload.
228
+ * @throws when a field is not losslessly JSON-serializable.
229
+ */
230
+ export function snapshotSubagentDescriptor(
231
+ input: ContinuableSubagentDescriptorInput,
232
+ ): ContinuableSubagentDescriptorData {
233
+ const candidate: ContinuableSubagentDescriptorData = {
234
+ version: SUBAGENT_DESCRIPTOR_VERSION,
235
+ mode: input.mode,
236
+ provider: input.provider,
237
+ label: input.label,
238
+ ...input.agentProvider !== undefined ? { agentProvider: input.agentProvider } : {},
239
+ ...input.agentModel !== undefined ? { agentModel: input.agentModel } : {},
240
+ ...input.agentReasoningEffort !== undefined ? { agentReasoningEffort: input.agentReasoningEffort } : {},
241
+ ...input.persona !== undefined ? { persona: input.persona } : {},
242
+ ...input.toolFilter !== undefined ? { toolFilter: input.toolFilter } : {},
243
+ }
244
+ const snapshot = snapshotJsonValue(candidate)
245
+ if (snapshot === undefined) {
246
+ throw new Error('subagent descriptor is not losslessly JSON-serializable')
247
+ }
248
+ return snapshot
249
+ }
250
+
251
+ /**
252
+ * Fold a persisted child log to its supported descriptor. The first
253
+ * `subagent/descriptor` event is authoritative — the establishing provider
254
+ * appends exactly one, so a later same-type event cannot rewrite the declared
255
+ * composition.
256
+ * @param events - the loaded child session events.
257
+ * @returns the descriptor, or `undefined` when the log has none or its
258
+ * version is not {@link SUBAGENT_DESCRIPTOR_VERSION} (the child cannot be
259
+ * classified by this runtime).
260
+ * @throws when a current-version persisted payload does not match its complete
261
+ * declared schema.
262
+ */
263
+ export function foldSubagentDescriptor(events: readonly SessionEvent[]): SubagentDescriptorData | undefined {
264
+ const event = events.find(
265
+ (candidate): candidate is SessionEvent<'subagent/descriptor'> => candidate.type === 'subagent/descriptor',
266
+ )
267
+ if (event === undefined) return undefined
268
+ return parseSubagentDescriptor(event.data)
269
+ }
package/src/error.ts ADDED
@@ -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
+ }