@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
package/src/catalog.ts ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Parent-owned durable subagent catalog events and their chunked projection.
3
+ *
4
+ * @module @deepseek-ai/dsh-subagent/catalog
5
+ */
6
+
7
+ import { z } from 'zod'
8
+ import { appendChunkedList, chunkedListSchema, iterateChunkedList } from '@deepseek-ai/dsh-chunked-list'
9
+ import type { ChunkedList } from '@deepseek-ai/dsh-chunked-list'
10
+ import type {
11
+ Session,
12
+ SessionEvent,
13
+ SessionHeader,
14
+ SessionId,
15
+ SessionLogOffset,
16
+ } from '@deepseek-ai/dsh-session'
17
+ import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
18
+ import { isAgentName } from './names.ts'
19
+ import type { SubagentCatalogEntry } from './projection-types.ts'
20
+
21
+ /** Catalog payload version emitted by local and external child creation. */
22
+ export const SUBAGENT_CATALOG_VERSION = 3
23
+
24
+ type KnownCatalogMode =
25
+ | { readonly mode: 'one-shot'; readonly label?: string }
26
+ | { readonly mode: 'continuable'; readonly label: string }
27
+
28
+ /**
29
+ * Parent catalog v0 records local modes, v1 adds unknown children, v2 records
30
+ * external executions, and v3 adds each child's name, unique among its siblings.
31
+ */
32
+ export type SubagentCatalogEvent =
33
+ & {
34
+ readonly childId: SessionId
35
+ readonly childCreatedAt: number
36
+ } & (
37
+ | ({ readonly version: 0 } & KnownCatalogMode)
38
+ | ({ readonly version: 1 } & (KnownCatalogMode | { readonly mode: 'unknown'; readonly label?: string }))
39
+ | { readonly version: 2; readonly mode: 'external'; readonly label?: string }
40
+ | ({ readonly version: 3; readonly name: string } & (
41
+ | { readonly mode: 'continuable'; readonly label: string }
42
+ | { readonly mode: 'external'; readonly label?: string }
43
+ ))
44
+ )
45
+
46
+ declare module '@deepseek-ai/dsh-session/types' {
47
+ interface SessionEventMap {
48
+ /**
49
+ * A direct child's identity and available discovery fields.
50
+ * @param data - versioned parent-owned catalog entry.
51
+ */
52
+ 'subagent/catalog': SubagentCatalogEvent
53
+ }
54
+ }
55
+
56
+ /** Host fold state for one parent catalog. */
57
+ export interface SubagentCatalogState {
58
+ readonly inheritedEventCount: SessionLogOffset
59
+ readonly head?: ChunkedList<SubagentCatalogEvent> | undefined
60
+ }
61
+
62
+ const sessionIdSchema = z.string() as unknown as z.ZodType<SessionId>
63
+ const oneShotCatalogSchema = z.object({
64
+ version: z.union([z.literal(0), z.literal(1)]),
65
+ childId: sessionIdSchema,
66
+ childCreatedAt: z.number().int().nonnegative(),
67
+ mode: z.literal('one-shot'),
68
+ label: z.string().optional(),
69
+ }).strict()
70
+ const continuableCatalogSchema = z.object({
71
+ version: z.union([z.literal(0), z.literal(1)]),
72
+ childId: sessionIdSchema,
73
+ childCreatedAt: z.number().int().nonnegative(),
74
+ mode: z.literal('continuable'),
75
+ label: z.string(),
76
+ }).strict()
77
+ const externalCatalogSchema = oneShotCatalogSchema.extend({ version: z.literal(2), mode: z.literal('external') })
78
+ const unknownCatalogSchema = oneShotCatalogSchema.extend({ version: z.literal(1), mode: z.literal('unknown') })
79
+ const nameSchema = z.string().refine(isAgentName, 'invalid agent name')
80
+ const namedContinuableCatalogSchema = continuableCatalogSchema.extend({ version: z.literal(3), name: nameSchema })
81
+ const namedExternalCatalogSchema = externalCatalogSchema.extend({ version: z.literal(3), name: nameSchema })
82
+ const eventDataSchema = z.union([
83
+ oneShotCatalogSchema,
84
+ externalCatalogSchema,
85
+ continuableCatalogSchema,
86
+ unknownCatalogSchema,
87
+ namedContinuableCatalogSchema,
88
+ namedExternalCatalogSchema,
89
+ ]) as z.ZodType<SubagentCatalogEvent>
90
+ const viewSchema = z.array(z.union([
91
+ oneShotCatalogSchema.omit({ version: true, childId: true, childCreatedAt: true }).extend({
92
+ id: sessionIdSchema,
93
+ createdAt: oneShotCatalogSchema.shape.childCreatedAt,
94
+ }),
95
+ externalCatalogSchema.omit({ version: true, childId: true, childCreatedAt: true }).extend({
96
+ id: sessionIdSchema,
97
+ createdAt: externalCatalogSchema.shape.childCreatedAt,
98
+ name: nameSchema.optional(),
99
+ }),
100
+ continuableCatalogSchema.omit({ version: true, childId: true, childCreatedAt: true }).extend({
101
+ id: sessionIdSchema,
102
+ createdAt: continuableCatalogSchema.shape.childCreatedAt,
103
+ name: nameSchema.optional(),
104
+ }),
105
+ unknownCatalogSchema.omit({ version: true, childId: true, childCreatedAt: true }).extend({
106
+ id: sessionIdSchema,
107
+ createdAt: unknownCatalogSchema.shape.childCreatedAt,
108
+ }),
109
+ ])) as z.ZodType<SubagentCatalogEntry[]>
110
+ const stateSchema: z.ZodType<SubagentCatalogState> = z.object({
111
+ inheritedEventCount: z.number().int().nonnegative() as unknown as z.ZodType<SessionLogOffset>,
112
+ head: chunkedListSchema(eventDataSchema).optional(),
113
+ }).strict()
114
+
115
+ /**
116
+ * Materialize complete and unknown-mode child identities from parent catalog events.
117
+ * @param state - parent catalog fold state.
118
+ * @returns current direct-child rows in parent catalog event order.
119
+ */
120
+ function subagentCatalogEntries(state: SubagentCatalogState): SubagentCatalogEntry[] {
121
+ const entries: SubagentCatalogEntry[] = []
122
+ for (const data of iterateChunkedList(state.head)) {
123
+ const { version: _version, childId, childCreatedAt, ...descriptor } = data
124
+ entries.push({ id: childId, createdAt: childCreatedAt, ...descriptor })
125
+ }
126
+ return entries
127
+ }
128
+
129
+ /** Parent-owned catalog; version-6 checkpoints retain unnamed facts, and invalid own facts reject restoration. */
130
+ export const subagentCatalogProjectionDefinition = {
131
+ key: 'subagentCatalog',
132
+ stateSchema,
133
+ init: (_header: SessionHeader, inheritedEventCount: SessionLogOffset) => ({ inheritedEventCount }),
134
+ apply: (state, event: SessionEvent) => {
135
+ if (event.type !== 'subagent/catalog' || event.seq < state.inheritedEventCount) return state
136
+ return { ...state, head: appendChunkedList(state.head, eventDataSchema.parse(event.data)) }
137
+ },
138
+ stateVersion: 6,
139
+ wire: { viewSchema, view: subagentCatalogEntries },
140
+ } satisfies ProjectionDefinition<'subagentCatalog', SubagentCatalogState>
141
+
142
+ /**
143
+ * Append a complete direct-child discovery fact to its parent Session.
144
+ * @param parent - durable direct parent receiving the discovery fact.
145
+ * @param child - established child's immutable Session metadata.
146
+ * @param descriptor - mode-discriminated creation label frozen with the child.
147
+ * @param name - the child's name, reserved unique among the parent's children.
148
+ */
149
+ export function establishCatalogChild(
150
+ parent: Session,
151
+ child: SessionHeader,
152
+ descriptor: { readonly mode: 'continuable'; readonly label: string },
153
+ name: string,
154
+ ): void {
155
+ parent.append('subagent/catalog', {
156
+ version: SUBAGENT_CATALOG_VERSION,
157
+ childId: child.id,
158
+ childCreatedAt: child.createdAt,
159
+ mode: descriptor.mode,
160
+ label: descriptor.label,
161
+ name,
162
+ })
163
+ }
164
+
165
+ /**
166
+ * Record an external execution without a local child Session.
167
+ * @param parent - durable direct parent receiving the discovery fact.
168
+ * @param childId - identity returned by the external provider.
169
+ * @param label - display label assigned by the caller.
170
+ * @param name - the child's name, reserved unique among the parent's children.
171
+ */
172
+ export function establishExternalCatalogChild(parent: Session, childId: SessionId, label: string, name: string): void {
173
+ parent.append('subagent/catalog', {
174
+ version: SUBAGENT_CATALOG_VERSION,
175
+ childId,
176
+ childCreatedAt: Date.now(),
177
+ mode: 'external',
178
+ label,
179
+ name,
180
+ })
181
+ }
182
+
183
+ /**
184
+ * Collect the names recorded in one parent's catalog.
185
+ * @param entries - the parent's current catalog rows.
186
+ * @returns names of every named child; historical entries contribute none.
187
+ */
188
+ export function catalogNames(entries: readonly SubagentCatalogEntry[]): Set<string> {
189
+ const names = new Set<string>()
190
+ for (const entry of entries) {
191
+ if ('name' in entry) names.add(entry.name)
192
+ }
193
+ return names
194
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Shared in-process child composition: the delegation-depth budget, the
3
+ * durable session metadata, the resolved child `AgentOptions`, the delegated
4
+ * policy seed, and the scoped setup used by local activations.
5
+ *
6
+ * @module @deepseek-ai/dsh-subagent/child-agent
7
+ */
8
+
9
+ import type { Context } from '@deepseek-ai/cordis'
10
+ import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent'
11
+ import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
12
+ import type { Session } from '@deepseek-ai/dsh-session'
13
+ import type {} from '@deepseek-ai/dsh-system-prompt'
14
+ import type { ToolRestriction } from '@deepseek-ai/dsh-tools'
15
+ // Type-only: make `ctx.get('sandboxPolicy')`, `ctx.get('approval')`, and
16
+ // `ctx.get('permissionPresets')` resolve to their services when composed — delegation consumes them
17
+ // opportunistically (the documented `ctx.get` pattern), never as a hard dep —
18
+ // and merge the inherited permission session-event payloads.
19
+ import type {} from '@deepseek-ai/dsh-sandbox-policy'
20
+ import type {} from '@deepseek-ai/dsh-user-approval'
21
+ import type {} from '@deepseek-ai/dsh-permission-presets'
22
+ // Type-only: make `ctx.get('agentPresets')` resolve to the preset roster when
23
+ // composed — a child inherits its parent's composition opportunistically (the
24
+ // documented `ctx.get` pattern), never as a hard dep. A rosterless deployment
25
+ // keeps its model-facing rows on the host plane, where the child already sees
26
+ // them through the tool registry's global layer.
27
+ import type {} from '@deepseek-ai/dsh-agent-preset-registry'
28
+ import { delegationDepthOf } from './depth.ts'
29
+ import { SubagentError } from './error.ts'
30
+
31
+ /** Thrown when starting a child would exceed the requested depth cap. */
32
+ export class SubagentDepthError extends Error {
33
+ constructor(public readonly attemptedDepth: number, public readonly maxDepth: number) {
34
+ super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`)
35
+ this.name = 'SubagentDepthError'
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Resolve the child's delegation depth from its parent and enforce an optional
41
+ * cap. The persisted parent header is the monotone floor, so a resumed parent
42
+ * cannot delegate as if it were top-level.
43
+ * @param parent - the delegating parent agent.
44
+ * @param maxDepth - optional absolute cap the resolved depth must not exceed.
45
+ * @returns the child's non-negative safe-integer depth.
46
+ * @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`.
47
+ * @throws {RangeError} when the resolved depth leaves the safe-integer range.
48
+ */
49
+ export function resolveChildDepth(parent: Agent, maxDepth: number | undefined): number {
50
+ const childDepth = delegationDepthOf(parent) + 1
51
+ if (!Number.isSafeInteger(childDepth)) {
52
+ throw new RangeError('subagent child depth exceeds the safe-integer range')
53
+ }
54
+ if (maxDepth !== undefined && childDepth > maxDepth) {
55
+ throw new SubagentDepthError(childDepth, maxDepth)
56
+ }
57
+ return childDepth
58
+ }
59
+
60
+ /**
61
+ * Resolve the parent values inherited by a child. The latest request header
62
+ * owns provider, model, and reasoning effort after request-time selection;
63
+ * creation options remain the fallback before the first request and retain
64
+ * the configured output-token limit.
65
+ * @param parent - delegating parent Agent.
66
+ * @returns detached Agent options for child-option merging.
67
+ */
68
+ export function parentAgentOptionsForDelegation(parent: Agent): AgentOptions {
69
+ const requestConfig = parent.session.requestHeader()?.config
70
+ if (requestConfig === undefined) return { ...parent.options }
71
+ const {
72
+ provider: _createdProvider,
73
+ model: _createdModel,
74
+ reasoningEffort: _createdReasoningEffort,
75
+ ...createdOptions
76
+ } = parent.options
77
+ return {
78
+ ...createdOptions,
79
+ provider: requestConfig.provider,
80
+ model: requestConfig.model,
81
+ ...requestConfig.reasoningEffort === undefined
82
+ ? {}
83
+ : { reasoningEffort: requestConfig.reasoningEffort },
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Resolve the child's `AgentOptions`: the parent's provider/model,
89
+ * reasoning-effort, and maxTokens values unless the request overrides them,
90
+ * stamped with the child's own delegation depth. Changing the route without
91
+ * naming an effort clears the parent's route-owned effort so the selected
92
+ * model resolves its own default.
93
+ * @param parent - the delegating parent whose route the child inherits.
94
+ * @param requested - per-child overrides, if any.
95
+ * @param childDepth - the resolved delegation depth to stamp.
96
+ * @returns the resolved options for `ctx.agents.create()`.
97
+ */
98
+ export function resolveChildAgentOptions(
99
+ parent: Agent,
100
+ requested: AgentOptions | undefined,
101
+ childDepth: number,
102
+ ): AgentOptions {
103
+ const parentOptions = parentAgentOptionsForDelegation(parent)
104
+ const parentProvider = parentOptions.provider
105
+ const parentModel = parentOptions.model
106
+ const parentReasoningEffort = parentOptions.reasoningEffort
107
+ const parentMaxTokens = parentOptions.maxTokens
108
+ const resolved: AgentOptions = {
109
+ ...parentProvider !== undefined ? { provider: parentProvider } : {},
110
+ ...parentModel !== undefined ? { model: parentModel } : {},
111
+ ...parentReasoningEffort !== undefined ? { reasoningEffort: parentReasoningEffort } : {},
112
+ ...parentMaxTokens !== undefined ? { maxTokens: parentMaxTokens } : {},
113
+ ...requested,
114
+ subagentDepth: childDepth,
115
+ }
116
+ const routeChanged = resolved.provider !== parentProvider || resolved.model !== parentModel
117
+ if (routeChanged && requested?.reasoningEffort === undefined) delete resolved.reasoningEffort
118
+ return resolved
119
+ }
120
+
121
+ /**
122
+ * Build the child session's durable creation metadata: the parent's workspace,
123
+ * its direct lineage, coarse product origin, the recursion budget that must
124
+ * survive persistence, the seed boundary that separates inherited parent
125
+ * history from child work, and the composition the child runs under.
126
+ *
127
+ * Omitted selection uses the parent's live composition, including any switch
128
+ * made while the parent was blank.
129
+ * @param parent - the delegating parent agent.
130
+ * @param childDepth - the resolved delegation depth to persist.
131
+ * @param isSeeded - whether this child inherits a parent-log prefix, including an explicitly empty one.
132
+ * @param selectedPreset - independent selection, or omission to inherit the parent.
133
+ * @returns the `meta` for `ctx.agents.create()`.
134
+ */
135
+ export function childSessionMeta(
136
+ parent: Agent,
137
+ childDepth: number,
138
+ isSeeded: boolean,
139
+ selectedPreset?: string,
140
+ ): NonNullable<CreateAgentOptions['meta']> {
141
+ const parentHeader = parent.session.header
142
+ const agentPreset = selectedPreset ?? parent.ctx.get('agentPresets')?.composedPreset(parent.ctx)
143
+ return {
144
+ ...parentHeader.cwd !== undefined ? { cwd: parentHeader.cwd } : {},
145
+ ...agentPreset === undefined ? {} : { agentPreset },
146
+ parentSession: parentHeader.id,
147
+ isSeeded,
148
+ // Navigation classification only; the descriptor remains the authority
149
+ // for mode and continuation capability.
150
+ origin: 'subagent',
151
+ // Durable: the recursion budget must survive persistence and resume.
152
+ delegationDepth: childDepth,
153
+ }
154
+ }
155
+
156
+ /** The scoped composition a child agent's creation window applies. */
157
+ export interface ChildComposition {
158
+ /** Preset to mount; omission shares a supplied creator or uses host composition. */
159
+ readonly agentPreset?: string | undefined
160
+ /** Historical descriptor persona reapplied only during cold resume. */
161
+ readonly persona?: string | undefined
162
+ /** Historical descriptor tool restriction reapplied only during cold resume. */
163
+ readonly toolFilter?: ToolRestriction | undefined
164
+ }
165
+
166
+ /**
167
+ * Model-facing delegation-scope statement for every in-process child. A
168
+ * runtime-context contribution rather than a system-prompt section, so the
169
+ * deployment's system prompt stays uniform across parents and children.
170
+ */
171
+ export const SUBAGENT_DELEGATION_CONTEXT
172
+ = 'You are a delegated subagent: your permission scope was fixed when you were started and cannot be '
173
+ + 'widened from inside this session — operations that require approval are rejected automatically. '
174
+ + 'When the task needs access beyond that scope, do not retry the denied operation; state the '
175
+ + 'limitation in your reply so the delegating agent can handle it.'
176
+
177
+ /**
178
+ * Compose a child before publication and restore historical descriptor overrides.
179
+ * Explicit selection mounts the named preset. Omission joins a supplied creator's
180
+ * current generation; a restored child without a saved preset uses host composition.
181
+ * Registrations belong to the child's scope.
182
+ * @param childCtx - the child agent's scoped creation context.
183
+ * @param parent - creator for fresh delegation; absent during target-only restoration.
184
+ * @param composition - independent preset and any overrides read from a historical descriptor.
185
+ * @returns A promise when mounting an independent preset; otherwise completes synchronously.
186
+ */
187
+ export function applyChildComposition(
188
+ childCtx: Context,
189
+ parent: Agent | undefined,
190
+ composition: ChildComposition,
191
+ ): void | Promise<void> {
192
+ if (composition.agentPreset !== undefined) {
193
+ const presets = childCtx.get('agentPresets')
194
+ if (presets === undefined) {
195
+ throw new SubagentError('selecting a child agent preset requires the agent-presets service', 'PRESET_UNAVAILABLE')
196
+ }
197
+ return presets.mount(childCtx, composition.agentPreset).then(() => {
198
+ applyChildOverrides(childCtx, composition)
199
+ })
200
+ }
201
+ if (parent !== undefined) childCtx.get('agentPresets')?.composeFrom(childCtx, parent.ctx)
202
+ applyChildOverrides(childCtx, composition)
203
+ }
204
+
205
+ function applyChildOverrides(childCtx: Context, composition: ChildComposition): void {
206
+ childCtx.systemPrompt.context({
207
+ name: 'subagent:delegation',
208
+ order: childCtx.systemPrompt.getContextOrder('SUBAGENT_DELEGATION'),
209
+ text: SUBAGENT_DELEGATION_CONTEXT,
210
+ })
211
+ if (composition.persona !== undefined) {
212
+ childCtx.systemPrompt.section({
213
+ name: 'deployment:persona-prefix',
214
+ order: childCtx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX'),
215
+ text: composition.persona,
216
+ })
217
+ }
218
+ if (composition.toolFilter !== undefined) childCtx.tools.restrict(composition.toolFilter)
219
+ }
220
+
221
+ /** Policy seeded onto a child session's log at the delegation boundary. */
222
+ export interface DelegatedPolicyOverrides {
223
+ /**
224
+ * The parent's current preset identity when it runs in Auto or Full access;
225
+ * the child keeps it under the pinned `never` approval policy.
226
+ */
227
+ readonly permissionPreset: 'auto' | 'danger-full-access' | undefined
228
+ /** The parent session's explicit sandbox-mode override, or `undefined` without one. */
229
+ readonly sandboxMode: SandboxMode | undefined
230
+ /**
231
+ * `'never'` whenever the approval capability is composed, `undefined`
232
+ * otherwise: a delegated child acts only within the sandbox scope fixed at
233
+ * delegation, so its asks are rejected deterministically.
234
+ */
235
+ readonly approvalPolicy: 'never' | undefined
236
+ }
237
+
238
+ /**
239
+ * Capture the permission state to seed into one delegation. Call synchronously before
240
+ * the child start's first await: a later parent switch belongs to the
241
+ * parent's future, not to this child. Auto and Full access identities are
242
+ * inherited only through the in-process DSH path so either can replace a stale
243
+ * same-bundle fork value. Only the parent session's explicit sandbox override
244
+ * is captured — never deployment defaults or one-shot grants — and the approval
245
+ * policy is pinned to `'never'` regardless of the parent's own policy.
246
+ * @param parent - the delegating parent agent.
247
+ * @returns the sandbox override (or `undefined` without one) and the approval pin.
248
+ */
249
+ export function captureDelegatedPolicyOverrides(parent: Agent): DelegatedPolicyOverrides {
250
+ const preset = parent.ctx.get('permissionPresets')?.current(parent.session)
251
+ return {
252
+ permissionPreset: preset === 'auto' || preset === 'danger-full-access' ? preset : undefined,
253
+ sandboxMode: parent.ctx.get('sandboxPolicy')?.overrideOf(parent.session),
254
+ approvalPolicy: parent.ctx.get('approval') === undefined ? undefined : 'never',
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Append the captured delegation policy onto the child's own log as
260
+ * `source: 'delegation'` events after Session announcement and before Agent registration, so the
261
+ * child's effective policy is reconstructable from its log alone. Appends land
262
+ * after any fork seed, so fresh policy wins stale seed state; later child
263
+ * switches still win over these events.
264
+ * @param childSession - the child's announced, writable Session.
265
+ * @param overrides - the policy captured at delegation.
266
+ */
267
+ export function appendDelegatedPolicyOverrides(
268
+ childSession: Session,
269
+ overrides: DelegatedPolicyOverrides,
270
+ ): void {
271
+ if (overrides.sandboxMode !== undefined) {
272
+ childSession.append('sandbox/mode', { mode: overrides.sandboxMode, source: 'delegation' })
273
+ }
274
+ if (overrides.approvalPolicy !== undefined) {
275
+ childSession.append('approval/policy', { policy: overrides.approvalPolicy, source: 'delegation' })
276
+ }
277
+ if (overrides.permissionPreset !== undefined) {
278
+ childSession.append('permission/preset', { preset: overrides.permissionPreset })
279
+ }
280
+ }
package/src/client.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Browser-safe subagent projection and control vocabulary.
3
+ *
4
+ * @module @deepseek-ai/dsh-subagent/client
5
+ */
6
+
7
+ export type * from './control-types.ts'
8
+ export type { SubagentCatalogEntry, SubagentIdentityProjection, SubagentTimingProjection } from './projection-types.ts'
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Model-visible messages owned by continuable-subagent orchestration.
3
+ *
4
+ * @module @deepseek-ai/dsh-subagent/continuation-messages
5
+ */
6
+
7
+ import type { Agent } from '@deepseek-ai/dsh-agent'
8
+ import { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm'
9
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
10
+ import type { SessionId } from '@deepseek-ai/dsh-session'
11
+ import type { SubagentResult } from './types.ts'
12
+
13
+ /** Durable attribution for one model-authored message between Agents. */
14
+ export interface AgentMessageSource {
15
+ readonly kind: 'agent-message'
16
+ /** A message another agent addressed to this one (`relay` context form). */
17
+ readonly form: 'relay'
18
+ /** Session id of the Agent whose tool call produced the message. */
19
+ readonly senderSessionId: SessionId
20
+ }
21
+
22
+ /**
23
+ * Durable attribution for the runtime's own account of a continuable child
24
+ * settling. Deliberately a different kind from
25
+ * {@link AgentMessageSource}: an Agent message is content the sender chose,
26
+ * while this message is the manager stating what became of the child, and a
27
+ * transcript that merged them would credit the child with words it never wrote.
28
+ */
29
+ export interface SubagentSettledMessageSource {
30
+ readonly kind: 'subagent-settled'
31
+ /** A runtime account shown without expanding the row (`notice` context form). */
32
+ readonly form: 'notice'
33
+ /** One-line account of how the child ended. */
34
+ readonly summary: string
35
+ /** Exact execution stop reason; absent on historical notices. Writers always include it. */
36
+ readonly stopReason?: SubagentResult['stopReason']
37
+ /** Session id of the child that settled. */
38
+ readonly senderSessionId: SessionId
39
+ }
40
+
41
+ declare module '@deepseek-ai/dsh-llm' {
42
+ interface MessageSourceMap {
43
+ 'agent-message': AgentMessageSource
44
+ 'subagent-settled': SubagentSettledMessageSource
45
+ }
46
+ }
47
+
48
+ /** Build durable attribution for one Agent message. */
49
+ function agentMessageSource(sender: Agent): AgentMessageSource {
50
+ return {
51
+ kind: 'agent-message',
52
+ form: 'relay',
53
+ senderSessionId: sender.id,
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Build the model-visible and durable representation of one Agent message.
59
+ * @param sender - exact live Agent that authored the message.
60
+ * @param senderName - the sender's model-facing name in its subagent tree.
61
+ * @param content - model-visible message blocks supplied by the sender.
62
+ * @returns the durable user-message representation delivered to the recipient.
63
+ */
64
+ export function createAgentMessage(
65
+ sender: Agent,
66
+ senderName: string,
67
+ content: ContentBlock[],
68
+ ): ReturnType<typeof createUserMessage> {
69
+ return createUserMessage({
70
+ content: [
71
+ { type: 'text' as const, text: `Agent ${senderName} sent a message: ` },
72
+ ...content,
73
+ ],
74
+ source: agentMessageSource(sender),
75
+ })
76
+ }
77
+
78
+ /**
79
+ * Append automatic result-delivery guidance to a parent-delivered child's initial task.
80
+ * @param prompt - initial model-visible task blocks.
81
+ * @returns task blocks followed by the result-delivery guidance.
82
+ */
83
+ export function withResultDeliveryGuidance(
84
+ prompt: ContentBlock[],
85
+ ): ContentBlock[] {
86
+ return [
87
+ ...prompt,
88
+ {
89
+ type: 'text',
90
+ text: 'Your final answer is delivered automatically if your '
91
+ + 'parent is still online. Include the result and relevant evidence in that answer; the parent does not '
92
+ + 'receive your full transcript, tool output, or reasoning. If your last action is a message to your '
93
+ + 'parent, the completion notice omits your final answer; include the result and relevant evidence in that message.',
94
+ },
95
+ ]
96
+ }
97
+
98
+ /**
99
+ * One line telling a parent that a background child is finished and why, in
100
+ * the parent's own task vocabulary.
101
+ * @param childName - the model-facing name the parent knows the child by.
102
+ * @param stopReason - how the child's last ordinary turn ended.
103
+ * @param continuable - whether the child accepts a later message.
104
+ * @returns the model-facing opening line of the settlement notice.
105
+ */
106
+ function settlementSummary(childName: string, stopReason: SubagentResult['stopReason'], continuable: boolean): string {
107
+ const subject = `Background subagent ${childName}`
108
+ switch (stopReason) {
109
+ case 'completed':
110
+ return continuable
111
+ ? `${subject} finished and will do no further work unless you send it more.`
112
+ : `${subject} finished. It cannot receive follow-up messages.`
113
+ case 'aborted':
114
+ return `${subject} was stopped before it finished.`
115
+ case 'max-tokens':
116
+ return `${subject} ran out of room before it finished.`
117
+ // A pre-step rejection — a hook deny, a policy plugin — discarded input
118
+ // the child had claimed, so the parent must not treat the task as done.
119
+ case 'refusal':
120
+ return `${subject} declined the task.`
121
+ case 'error':
122
+ return `${subject} failed before it finished.`
123
+ /* v8 ignore next 4 -- `SubagentResult['stopReason']` is merge-extensible, so this arm
124
+ * needs a backend that adds a variant; an unnameable ending is reported as unfinished
125
+ * rather than silently as success. */
126
+ default:
127
+ return `${subject} ended abnormally (${String(stopReason)}) before it finished.`
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Build the runtime-owned settlement notice from the child's nonempty closing text.
133
+ * @param childId - durable child session id recorded as the sender.
134
+ * @param childName - model-facing child name used in the notice text.
135
+ * @param terminal - recorded terminal state for the settled Activation.
136
+ * @param continuable - whether the child can accept another task.
137
+ * @param omitClosingText - replace the closing text when the child's last action
138
+ * was a message to its direct parent.
139
+ * @returns the durable user-message representation delivered to the parent.
140
+ */
141
+ export function createSettlementMessage(
142
+ childId: SessionId,
143
+ childName: string,
144
+ terminal: SubagentResult,
145
+ continuable = true,
146
+ omitClosingText = false,
147
+ ): ReturnType<typeof createUserMessage> {
148
+ const summary = settlementSummary(childName, terminal.stopReason, continuable)
149
+ // Parent providers receive this notice as a user message and may reject
150
+ // nontext assistant blocks. Keep this conversion local so SDK/UI consumers
151
+ // retain the complete child output.
152
+ const closingText = terminal.output.flatMap(block =>
153
+ block.type === 'text' && block.text.length > 0 ? [block] : [],
154
+ )
155
+ return createUserMessage({
156
+ content: [
157
+ { type: 'text' as const, text: summary },
158
+ ...omitClosingText
159
+ ? [{ type: 'text' as const, text: 'It sent you a message just before finishing, so its closing message is omitted.' }]
160
+ : closingText.length === 0
161
+ ? [{ type: 'text' as const, text: 'It left no closing message.' }]
162
+ : [{ type: 'text' as const, text: 'Its closing message:' }, ...closingText],
163
+ ...terminal.structured !== undefined
164
+ ? [{ type: 'text' as const, text: `Structured result: ${JSON.stringify(terminal.structured)}` }] : [],
165
+ ...terminal.diagnostic !== undefined
166
+ ? [{ type: 'text' as const, text: terminal.diagnostic }] : [],
167
+ ],
168
+ source: {
169
+ kind: 'subagent-settled' as const,
170
+ form: 'notice' as const,
171
+ summary: boundContextSummary(summary),
172
+ stopReason: terminal.stopReason,
173
+ senderSessionId: childId,
174
+ },
175
+ })
176
+ }