@deepseek-ai/dsh-subagent 0.2.3-alpha.1 → 0.2.3-alpha.3

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 (63) hide show
  1. package/README.i18n.yaml +15 -12
  2. package/README.md +19 -5
  3. package/README.zh.md +19 -5
  4. package/lib/index.js +480 -162
  5. package/lib/typert.host.js +90 -5
  6. package/lib/typert.remote-client.d.ts +4 -1
  7. package/lib/typert.remote-client.d.ts.map +1 -1
  8. package/lib/typert.remote-client.js +57 -2
  9. package/lib/types/activation.d.ts +31 -4
  10. package/lib/types/activation.d.ts.map +1 -1
  11. package/lib/types/activation.js +35 -6
  12. package/lib/types/activation.js.map +1 -1
  13. package/lib/types/assistant-output.d.ts +4 -2
  14. package/lib/types/assistant-output.d.ts.map +1 -1
  15. package/lib/types/assistant-output.js +8 -8
  16. package/lib/types/assistant-output.js.map +1 -1
  17. package/lib/types/child-agent.d.ts +3 -4
  18. package/lib/types/child-agent.d.ts.map +1 -1
  19. package/lib/types/child-agent.js +4 -12
  20. package/lib/types/child-agent.js.map +1 -1
  21. package/lib/types/control-types.d.ts +26 -2
  22. package/lib/types/control-types.d.ts.map +1 -1
  23. package/lib/types/control.d.ts +16 -2
  24. package/lib/types/control.d.ts.map +1 -1
  25. package/lib/types/control.js +49 -2
  26. package/lib/types/control.js.map +1 -1
  27. package/lib/types/descriptor.d.ts +19 -15
  28. package/lib/types/descriptor.d.ts.map +1 -1
  29. package/lib/types/descriptor.js +10 -21
  30. package/lib/types/descriptor.js.map +1 -1
  31. package/lib/types/error.d.ts +4 -0
  32. package/lib/types/error.d.ts.map +1 -1
  33. package/lib/types/error.js.map +1 -1
  34. package/lib/types/index.d.ts +30 -2
  35. package/lib/types/index.d.ts.map +1 -1
  36. package/lib/types/index.js +58 -2
  37. package/lib/types/index.js.map +1 -1
  38. package/lib/types/lifecycle.d.ts +4 -4
  39. package/lib/types/lifecycle.d.ts.map +1 -1
  40. package/lib/types/lifecycle.js +4 -5
  41. package/lib/types/lifecycle.js.map +1 -1
  42. package/lib/types/manager.d.ts +38 -3
  43. package/lib/types/manager.d.ts.map +1 -1
  44. package/lib/types/manager.js +247 -38
  45. package/lib/types/manager.js.map +1 -1
  46. package/lib/types/model-selection.d.ts +22 -0
  47. package/lib/types/model-selection.d.ts.map +1 -0
  48. package/lib/types/model-selection.js +39 -0
  49. package/lib/types/model-selection.js.map +1 -0
  50. package/lib/types/types.d.ts +3 -3
  51. package/package.json +54 -54
  52. package/src/activation.ts +48 -9
  53. package/src/assistant-output.ts +9 -8
  54. package/src/child-agent.ts +4 -11
  55. package/src/control-types.ts +22 -2
  56. package/src/control.ts +67 -2
  57. package/src/descriptor.ts +20 -27
  58. package/src/error.ts +4 -0
  59. package/src/index.ts +67 -4
  60. package/src/lifecycle.ts +5 -6
  61. package/src/manager.ts +238 -34
  62. package/src/model-selection.ts +52 -0
  63. package/src/types.ts +3 -3
package/src/manager.ts CHANGED
@@ -8,11 +8,12 @@
8
8
 
9
9
  import { randomUUID } from 'node:crypto'
10
10
  import { isAbsolute, resolve } from 'node:path'
11
+ import { isDeepStrictEqual } from 'node:util'
11
12
  import type {} from '@deepseek-ai/dsh-working-directory'
12
13
  import { FiberState, type Context } from '@deepseek-ai/cordis'
13
- import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent'
14
+ import type { Agent, AgentOptions, CreateAgentOptions, ModelSelection } from '@deepseek-ai/dsh-agent'
14
15
  import { brandString } from '@deepseek-ai/dsh-brand'
15
- import { type ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm'
16
+ import { contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm'
16
17
  import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm'
17
18
  import { SessionLogOffset } from '@deepseek-ai/dsh-session'
18
19
  import type { Session, SessionId, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session'
@@ -32,6 +33,7 @@ import { foldSubagentDescriptor, snapshotSubagentDescriptor } from './descriptor
32
33
  import type { SubagentDescriptorData } from './descriptor.ts'
33
34
  import { catalogNames, establishCatalogChild, establishExternalCatalogChild } from './catalog.ts'
34
35
  import { SubagentError } from './error.ts'
36
+ import { requireInitialModel, restorationOptions } from './model-selection.ts'
35
37
  import type { LifecycleEmitter } from './lifecycle.ts'
36
38
  import { ROOT_AGENT_NAME, SiblingNameReservations, agentAddress, joinAgentPath, parentAgentPath } from './names.ts'
37
39
  import type { SiblingNameReservation } from './names.ts'
@@ -45,7 +47,8 @@ import type {
45
47
  import { attachStructuredRuntime } from './structured.ts'
46
48
  import type { StructuredAttachment } from './structured.ts'
47
49
  import type { SubagentDelivery } from './control-types.ts'
48
- import { ActivationPool, ChildLock, activationAgent, captureLocalResult, observeLocalFailure, requireLocalActivation } from './activation.ts'
50
+ import { ActivationPool, ChildLock, activationAgent, captureLocalResult, foldLocalResult, observeLocalFailure, requireLocalActivation } from './activation.ts'
51
+ import { AssistantOutputFold } from './assistant-output.ts'
49
52
  import type { Activation, ActivationResource, LocalActivation } from './activation.ts'
50
53
 
51
54
  /** Inputs shared by model steering and human prompt delivery. */
@@ -103,10 +106,14 @@ type MaterializeInputs = MaterializeBase & (
103
106
  delegatedPolicies: DelegatedPolicyOverrides
104
107
  /** Child-owned composition record appended after the inherited marker. */
105
108
  descriptor: SubagentDescriptorData
109
+ /** Complete model choice captured before provider preparation. */
110
+ initialModel: ModelSelection
106
111
  }
107
112
  agentOptions: AgentOptions
108
113
  composition: ChildComposition
109
114
  outputSchema?: ObjectJsonSchema | undefined
115
+ /** Restore only to record durable state; see {@link Activation.maintenance}. */
116
+ maintenance?: boolean
110
117
  }
111
118
  | { kind: 'external'; start: (signal: AbortSignal) => Promise<SubagentRun> }
112
119
  )
@@ -167,6 +174,13 @@ export class SubagentManager {
167
174
  // Drain managed instances before Cordis releases their owning scope.
168
175
  const scope = ctx.plugin(function activationOwner() {})
169
176
  this.ownerCtx = scope.ctx
177
+ // This scope outlives every activation, including one whose child was
178
+ // disposed by another owner and has already released its own listeners.
179
+ // Global, because a child may run under a scope this manager is not in.
180
+ scope.ctx.on('session/event', (session, event) => {
181
+ const activation = this.resident.get(session.id)
182
+ if (activation?.kind === 'local' && activation.handle.agent.session === session) foldLocalResult(activation, event)
183
+ }, { global: true })
170
184
  installSubagentArchiveAdmission(ctx, (agent) => {
171
185
  const activation = this.resident.get(agent.id)
172
186
  return activation !== undefined && activationAgent(activation) === agent ? activation.ancestors : undefined
@@ -182,7 +196,15 @@ export class SubagentManager {
182
196
  })
183
197
  ctx.effect(function* (this: SubagentManager) {
184
198
  yield scope.dispose
185
- yield () => this.drain()
199
+ // A rejected drain skips the disposers yielded before it, which would
200
+ // leave the scope's global listener on the session/event dispatch.
201
+ yield async () => {
202
+ try {
203
+ await this.drain()
204
+ } finally {
205
+ await scope.dispose()
206
+ }
207
+ }
186
208
  }.bind(this), 'subagents.manager()')
187
209
  }
188
210
 
@@ -335,24 +357,21 @@ export class SubagentManager {
335
357
  const childId = spec.childId ?? brandString<SessionId>(randomUUID())
336
358
  this.assertChildIdAvailable(childId)
337
359
  const childDepth = resolveChildDepth(parent, spec.maxDepth)
338
- // Snapshot before any await: invalid descriptor JSON rejects the call
339
- // before a child exists, and the detached value is what reaches the log.
340
360
  const agentOptions = resolveChildAgentOptions(parent, spec.agentOptions, childDepth)
341
- const agentProvider = agentOptions.provider
342
- const agentModel = agentOptions.model
343
- const agentReasoningEffort = agentOptions.reasoningEffort
361
+ const initialModel = requireInitialModel(agentOptions)
344
362
  const descriptor = snapshotSubagentDescriptor({
345
363
  mode: 'continuable',
346
364
  provider: spec.provider,
347
365
  label: spec.label,
348
- ...agentProvider !== undefined ? { agentProvider } : {},
349
- ...agentModel !== undefined ? { agentModel } : {},
350
- ...agentReasoningEffort !== undefined ? { agentReasoningEffort } : {},
351
366
  })
352
367
  // Capture before the first await: a later parent switch belongs to the
353
368
  // parent's future, not to this child.
354
369
  const delegatedPolicies = captureDelegatedPolicyOverrides(parent)
355
370
 
371
+ if (spec.agentOptions?.provider !== undefined || spec.agentOptions?.model !== undefined
372
+ || spec.agentOptions?.reasoningEffort !== undefined) {
373
+ await this.validateModelSelection(parent.ctx, initialModel, signal)
374
+ }
356
375
  const cwd = await this.resolveDirectory(spec, signal)
357
376
  const prepared = await prepare({
358
377
  sessionId: childId,
@@ -393,6 +412,7 @@ export class SubagentManager {
393
412
  inheritedEventCount,
394
413
  delegatedPolicies,
395
414
  descriptor,
415
+ initialModel,
396
416
  },
397
417
  agentOptions,
398
418
  composition: { agentPreset: spec.agentPreset },
@@ -641,9 +661,168 @@ export class SubagentManager {
641
661
  return this.deliverToMember(root, childId, content, options)
642
662
  }
643
663
 
664
+ /**
665
+ * Record a child's next selection without running it or changing user defaults.
666
+ * A cold child is restored for maintenance only: it holds no capacity slot,
667
+ * publishes no lifecycle events, admits no input, and closes before return.
668
+ * @param childId - durable continuable child Session id.
669
+ * @param selection - complete selection; omitted effort follows adapter defaults.
670
+ * @param authority - trusted user operation or exact live creation ancestor.
671
+ * @param signal - cancellation before selection is recorded.
672
+ * @returns the recorded selection after its durability barrier completes.
673
+ */
674
+ async selectModel(
675
+ childId: SessionId,
676
+ selection: Readonly<ModelSelection>,
677
+ authority: SubagentInterruptAuthority,
678
+ signal: AbortSignal,
679
+ ): Promise<ModelSelection> {
680
+ signal.throwIfAborted()
681
+ const selected = { ...selection }
682
+ const ancestry = this.resident.get(childId)
683
+ let root: Agent
684
+ let ancestors: readonly SessionId[]
685
+ if (ancestry !== undefined) {
686
+ ;({ root, ancestors } = ancestry)
687
+ } else {
688
+ using source = await this.observeContinuation(childId, signal)
689
+ ;({ root, ancestors } = await this.resolveCreationAncestry(source, signal))
690
+ }
691
+ this.authorizeSelection(childId, root, ancestors, authority)
692
+ return this.trackStartup(root, signal, async (signal) => {
693
+ while (true) {
694
+ const result = await this.locks.run(childId, async () => {
695
+ signal.throwIfAborted()
696
+ this.authorizeSelection(childId, root, ancestors, authority)
697
+ const activation = this.resident.get(childId)
698
+ if (activation === undefined) {
699
+ await this.validateModelSelection(this.ctx, selected, signal)
700
+ const restored = await this.restoreTarget(root, childId, signal, selected)
701
+ await this.selectWhileMaintained(restored, selected, root, authority)
702
+ return { selected }
703
+ }
704
+ if (activation.root !== root) throw new SubagentError('target belongs to another subagent tree', 'UNAUTHORIZED')
705
+ const { handle } = requireLocalActivation(activation)
706
+ await this.validateModelSelection(this.ctx, selected, signal)
707
+ signal.throwIfAborted()
708
+ this.authorizeSelection(childId, root, activation.ancestors, authority)
709
+ if (activation.closing !== undefined) return { closing: activation.closing }
710
+ await this.recordSelection(handle.agent, selected)
711
+ return { selected }
712
+ })
713
+ if ('selected' in result) return result.selected
714
+ await Promise.allSettled([result.closing])
715
+ }
716
+ })
717
+ }
718
+
719
+ /** Recheck exact caller identities after asynchronous validation and storage work. */
720
+ private authorizeSelection(
721
+ childId: SessionId, root: Agent, ancestors: readonly SessionId[], authority: SubagentInterruptAuthority,
722
+ ): void {
723
+ this.assertAdmitting(root)
724
+ if (authority.kind === 'user') return
725
+ const caller = authority.agent
726
+ if (caller.id === childId || this.rootOf(caller) !== root || !ancestors.includes(caller.id)) {
727
+ throw new SubagentError(`subagent "${childId}" is not a descendant of the selecting agent`, 'UNAUTHORIZED')
728
+ }
729
+ this.assertAdmitting(caller)
730
+ }
731
+
732
+ /** Validate a choice without persisting adapter-defaulted controls; LLM failures keep their class and code. */
733
+ private async validateModelSelection(ctx: Context, selection: ModelSelection, signal: AbortSignal): Promise<void> {
734
+ const llm = ctx.get('llm')
735
+ if (llm === undefined) {
736
+ throw new SubagentError('cannot validate the selected subagent model because the LLM service is unavailable', 'MODEL_UNAVAILABLE')
737
+ }
738
+ try {
739
+ await llm.resolveCallConfig(selection, signal)
740
+ } catch (error: unknown) {
741
+ signal.throwIfAborted()
742
+ throw error
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Record a choice through a maintenance restoration and begin its release
748
+ * from the idle phase it owns. Input that reaches the Agent meanwhile cannot
749
+ * start a turn, and the release cancels it. A restored Agent that an
750
+ * `agent/created` listener already woke rejects the choice with
751
+ * `CONTINUATION_UNAVAILABLE`, and the release cancels the started turn.
752
+ */
753
+ private async selectWhileMaintained(
754
+ activation: Activation, selection: ModelSelection, root: Agent, authority: SubagentInterruptAuthority,
755
+ ): Promise<void> {
756
+ let closed: Promise<void> | undefined
757
+ const close = (): Promise<void> => closed ??= this.close(activation, () => this.finishDisposal(activation, false))
758
+ try {
759
+ const { agent } = requireLocalActivation(activation).handle
760
+ let maintained: Promise<void>
761
+ try {
762
+ maintained = agent.runMaintenance(async () => {
763
+ try {
764
+ this.authorizeSelection(activation.childId, root, activation.ancestors, authority)
765
+ await this.recordSelection(agent, selection)
766
+ } finally {
767
+ // Begin release while this task owns the idle phase; the outer finally observes its outcome.
768
+ void close().catch(() => undefined)
769
+ }
770
+ })
771
+ } catch (error: unknown) {
772
+ // Restoration ends its own maintenance first, so a wake requested during `agent/created` starts a turn.
773
+ throw new SubagentError(
774
+ `subagent "${activation.childId}" received input while restored for model selection; continue it before changing its model`,
775
+ 'CONTINUATION_UNAVAILABLE',
776
+ { cause: error },
777
+ )
778
+ }
779
+ await maintained
780
+ } finally {
781
+ try {
782
+ await close()
783
+ } catch (error: unknown) {
784
+ // The selection outcome is already settled; release failure is reported separately.
785
+ this.reportTeardownFailure(activation, error)
786
+ }
787
+ }
788
+ }
789
+
790
+ /** Append a choice through the child's live Session and confirm it in the durable log. */
791
+ private async recordSelection(agent: Agent, selection: ModelSelection): Promise<void> {
792
+ const persistence = this.requirePersistence()
793
+ const session = agent.session
794
+ const before = session.seq
795
+ try {
796
+ agent.model.select(selection)
797
+ const appended = session.seq > before
798
+ const recordedSeq = appended ? before : session.seq - 1
799
+ if (!await agent.ctx.sessions.flush(session)) {
800
+ throw new Error('no Session durability listener participated')
801
+ }
802
+ await using stored = await persistence.open(agent.id, 'read')
803
+ const { events } = await stored.read(recordedSeq, 1)
804
+ const event = events[0]
805
+ if (!isDeepStrictEqual(stored.header, session.header) || event?.seq !== recordedSeq
806
+ || (appended && (event.type !== 'model/selection' || !isDeepStrictEqual(event.data, selection)))) {
807
+ throw new Error('the recorded selection is not present in the durable child log')
808
+ }
809
+ } catch (error: unknown) {
810
+ throw this.selectionPersistenceFailure(agent.id, error)
811
+ }
812
+ }
813
+
814
+ /** Preserve an uncertain durable outcome instead of reporting that no change occurred. */
815
+ private selectionPersistenceFailure(childId: SessionId, error: unknown): SubagentError {
816
+ return new SubagentError(
817
+ `model selection for subagent "${childId}" may have changed, but persistence could not be confirmed; reload its state before retrying`,
818
+ 'PERSISTENCE_UNCONFIRMED',
819
+ { cause: error },
820
+ )
821
+ }
822
+
644
823
  /** Admit local input synchronously before any teardown can begin. */
645
824
  private deliver(activation: Activation, message: UserMessage, delivery: SubagentDelivery): void {
646
- if (activation.closing !== undefined) {
825
+ if (activation.closing !== undefined || activation.maintenance) {
647
826
  throw new SubagentError(
648
827
  'subagent activation is being disposed; the message was not accepted',
649
828
  'ACTIVATION_CLOSING',
@@ -715,8 +894,10 @@ export class SubagentManager {
715
894
  private materialize(inputs: MaterializeInputs): Promise<Activation> {
716
895
  this.assertAdmitting(inputs.root)
717
896
  inputs.signal.throwIfAborted()
718
- const pool = this.rootPool(inputs.root)
719
- const releaseSlot = pool.reserve(this.maxActiveSubagents())
897
+ // Maintenance runs no work, so it does not compete for execution capacity.
898
+ const releaseSlot = inputs.kind === 'local' && inputs.maintenance === true
899
+ ? () => {}
900
+ : this.rootPool(inputs.root).reserve(this.maxActiveSubagents())
720
901
  return this.materializeTracked(inputs, releaseSlot).catch((error: unknown) => {
721
902
  releaseSlot()
722
903
  throw error
@@ -847,6 +1028,7 @@ export class SubagentManager {
847
1028
  child.session.append('agent-preset/selected', { agentPreset: inputs.composition.agentPreset })
848
1029
  }
849
1030
  child.session.append('subagent/descriptor', create.descriptor)
1031
+ child.session.append('model/selection', create.initialModel)
850
1032
  appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies)
851
1033
  const workingDirectory = childCtx.get('workingDirectory')
852
1034
  if (workingDirectory === undefined) {
@@ -884,7 +1066,10 @@ export class SubagentManager {
884
1066
  resource = {
885
1067
  kind: 'local',
886
1068
  handle,
887
- outputStart: handle.agent.session.seq,
1069
+ output: new AssistantOutputFold(),
1070
+ work: undefined,
1071
+ outputFailure: undefined,
1072
+ workFailure: undefined,
888
1073
  structured,
889
1074
  failureAt: undefined,
890
1075
  poke: Promise.withResolvers<void>(),
@@ -905,6 +1090,7 @@ export class SubagentManager {
905
1090
  result: Promise.withResolvers<SubagentResult>(),
906
1091
  closing: undefined,
907
1092
  accepted: false,
1093
+ maintenance: inputs.kind === 'local' && inputs.maintenance === true,
908
1094
  }
909
1095
  void activation.result.promise.catch(() => undefined)
910
1096
  this.resident.set(childId, activation)
@@ -931,7 +1117,7 @@ export class SubagentManager {
931
1117
  }
932
1118
  // Listeners may read the resident Agent or drain it immediately. Publish
933
1119
  // after residency and inbox listeners, as the last rollback-protected step.
934
- this.host.emitLifecycle('subagent/start', this.runInfo(activation), root)
1120
+ if (!activation.maintenance) this.host.emitLifecycle('subagent/start', this.runInfo(activation), root)
935
1121
  } catch (error: unknown) {
936
1122
  /* v8 ignore next -- rollback failure must not mask the admission failure
937
1123
  * that prevented this operation from returning an accepted message id. */
@@ -1122,11 +1308,13 @@ export class SubagentManager {
1122
1308
  this.notifySettlement(activation, result)
1123
1309
  // The sole end publication follows resource release and parent notification,
1124
1310
  // before result delivery.
1125
- this.host.emitLifecycle('subagent/end', {
1126
- ...this.runInfo(activation),
1127
- stopReason: terminal.stopReason,
1128
- ...terminal.output.length === 0 ? {} : { lastAssistantMessage: terminal.output },
1129
- }, activation.root)
1311
+ if (!activation.maintenance) {
1312
+ this.host.emitLifecycle('subagent/end', {
1313
+ ...this.runInfo(activation),
1314
+ stopReason: terminal.stopReason,
1315
+ ...terminal.output.length === 0 ? {} : { lastAssistantMessage: terminal.output },
1316
+ }, activation.root)
1317
+ }
1130
1318
  if (resultFailure === undefined) activation.result.resolve(result)
1131
1319
  else activation.result.reject(resultFailure.error)
1132
1320
  if (failure !== undefined) throw failure
@@ -1227,8 +1415,18 @@ export class SubagentManager {
1227
1415
  }
1228
1416
  }
1229
1417
 
1230
- /** Reconstruct only the target under its subagent tree root; the caller owns acceptance or rollback. */
1231
- private async restoreTarget(root: Agent, childId: SessionId, signal: AbortSignal): Promise<Activation> {
1418
+ /**
1419
+ * Reconstruct only the target under its subagent tree root; the caller owns
1420
+ * acceptance or rollback. A selection restores it for maintenance instead.
1421
+ * @param root - exact live subagent tree root that owns the child.
1422
+ * @param childId - durable continuable child Session id.
1423
+ * @param signal - cancellation through publication.
1424
+ * @param maintenanceSelection - choice being recorded; it also supplies the route of a child that has none.
1425
+ * @returns the published Activation.
1426
+ */
1427
+ private async restoreTarget(
1428
+ root: Agent, childId: SessionId, signal: AbortSignal, maintenanceSelection?: ModelSelection,
1429
+ ): Promise<Activation> {
1232
1430
  return this.trackStartup(root, signal, async (signal) => {
1233
1431
  using source = await this.observeContinuation(childId, signal)
1234
1432
  this.assertAdmitting(root)
@@ -1250,6 +1448,16 @@ export class SubagentManager {
1250
1448
  )
1251
1449
  }
1252
1450
  const { ancestors, path } = await this.resolveCreationAncestry(source, signal, root)
1451
+ // Releasing a maintenance restoration cancels queued input, so leave pending input to an execution.
1452
+ const pending = source.projections?.values.inbox
1453
+ if (maintenanceSelection !== undefined && pending !== undefined
1454
+ && pending['next-turn'].length + pending['next-step'].length > 0) {
1455
+ throw new SubagentError(
1456
+ `subagent "${childId}" has pending input; continue it before changing its model`,
1457
+ 'CONTINUATION_UNAVAILABLE',
1458
+ )
1459
+ }
1460
+ const agentOptions = restorationOptions(descriptor, source.projections?.values.modelSelection?.next, maintenanceSelection)
1253
1461
  let activation: Activation
1254
1462
  try {
1255
1463
  const projectedPreset = source.projections?.values.agentPreset
@@ -1264,19 +1472,14 @@ export class SubagentManager {
1264
1472
  root,
1265
1473
  ancestors,
1266
1474
  path,
1267
- agentOptions: {
1268
- ...descriptor.agentProvider !== undefined ? { provider: descriptor.agentProvider } : {},
1269
- ...descriptor.agentModel !== undefined ? { model: descriptor.agentModel } : {},
1270
- ...descriptor.agentReasoningEffort !== undefined
1271
- ? { reasoningEffort: brandString<ReasoningEffortId>(descriptor.agentReasoningEffort) }
1272
- : {},
1273
- },
1475
+ agentOptions,
1274
1476
  composition: {
1275
1477
  agentPreset: agentPreset ?? undefined,
1276
1478
  persona: descriptor.persona,
1277
1479
  toolFilter: descriptor.toolFilter,
1278
1480
  },
1279
1481
  signal,
1482
+ maintenance: maintenanceSelection !== undefined,
1280
1483
  })
1281
1484
  } catch (error: unknown) {
1282
1485
  signal.throwIfAborted()
@@ -1338,13 +1541,14 @@ export class SubagentManager {
1338
1541
  return message.id
1339
1542
  }
1340
1543
 
1341
- /** Refuse image content for a child whose fixed model accepts text only. */
1544
+ /** Refuse image content for the selection held through inbox admission. */
1342
1545
  private async assertImageCapable(
1343
1546
  agent: Agent,
1344
1547
  signal: AbortSignal,
1345
1548
  ): Promise<void> {
1346
- const { provider, model } = agent.options
1347
- if (provider === undefined || model === undefined) return
1549
+ const selection = agent.model.current()
1550
+ if (selection === undefined) return
1551
+ const { provider, model } = selection
1348
1552
  const llm = this.ctx.get('llm')
1349
1553
  /* v8 ignore next -- without an LLM registry, delivery defers to projection. */
1350
1554
  if (llm === undefined) return
@@ -0,0 +1,52 @@
1
+ /** Model selection resolved before a local child is created or restored. */
2
+
3
+ import type { AgentOptions, ModelSelection } from '@deepseek-ai/dsh-agent'
4
+ import type { ContinuableSubagentDescriptorData } from './descriptor.ts'
5
+ import { SubagentError } from './error.ts'
6
+
7
+ /**
8
+ * Require the complete initial selection before publishing a child.
9
+ * @param options - resolved child options captured from its creator and explicit overrides.
10
+ * @returns the detached model selection, excluding activation controls.
11
+ * @throws {SubagentError} with MODEL_UNAVAILABLE when the provider or model is absent.
12
+ */
13
+ export function requireInitialModel(options: AgentOptions): ModelSelection {
14
+ const { provider, model, reasoningEffort } = options
15
+ if (!provider || !model) {
16
+ throw new SubagentError(
17
+ 'subagent startup requires a provider and model; select both before creating a child',
18
+ 'MODEL_UNAVAILABLE',
19
+ )
20
+ }
21
+ return { provider, model, ...reasoningEffort === undefined ? {} : { reasoningEffort } }
22
+ }
23
+
24
+ /**
25
+ * Build the Agent options for restoring a saved child. The restored Agent reads
26
+ * its recorded choice from the child's own log first; a historical descriptor
27
+ * route applies only when that log records neither a choice nor a request.
28
+ * @param descriptor - continuable descriptor from the child's own log.
29
+ * @param recorded - the observed log's next choice, or none.
30
+ * @param selecting - choice a maintenance restore is about to record; it supplies the route only when neither source has one.
31
+ * @returns Agent options carrying the descriptor's historical route or the selecting choice, if any.
32
+ * @throws {SubagentError} with NOT_RESUMABLE when no source supplies a complete model.
33
+ */
34
+ export function restorationOptions(
35
+ descriptor: ContinuableSubagentDescriptorData,
36
+ recorded: ModelSelection | null | undefined,
37
+ selecting?: ModelSelection,
38
+ ): AgentOptions {
39
+ const { agentProvider: provider, agentModel: model, agentReasoningEffort: reasoningEffort } = descriptor
40
+ if (recorded == null && (!provider || !model)) {
41
+ if (selecting !== undefined) return { ...selecting }
42
+ throw new SubagentError(
43
+ 'subagent has no complete saved model selection and cannot be resumed; select its model or create a new child',
44
+ 'NOT_RESUMABLE',
45
+ )
46
+ }
47
+ return {
48
+ ...provider === undefined ? {} : { provider },
49
+ ...model === undefined ? {} : { model },
50
+ ...reasoningEffort === undefined ? {} : { reasoningEffort },
51
+ }
52
+ }
package/src/types.ts CHANGED
@@ -82,7 +82,7 @@ export interface SubagentMemberNames {
82
82
  }
83
83
 
84
84
  /**
85
- * Authority under which one interrupt request is admitted. `user` is a trusted
85
+ * Authority under which a child control operation is admitted. `user` is a trusted
86
86
  * host operation; Remote callers need permission on the target Session before
87
87
  * invoking it. `ancestor` carries an exact live Agent in the target's creation ancestry.
88
88
  */
@@ -178,8 +178,8 @@ export interface SubagentStartRequest {
178
178
  /**
179
179
  * Optional host-Agent provider, model, reasoning-effort, and output-token
180
180
  * overrides. Requires {@link SubagentCapabilities.agentOptions}; in-process
181
- * providers merge them over the parent Agent's options when they create the
182
- * child, while the DSH SDK provider merges them over its instance defaults
181
+ * providers resolve them against the parent's current model choice and
182
+ * output-token limit, while the DSH SDK provider merges them over its instance defaults
183
183
  * before initializing the separate child runtime.
184
184
  */
185
185
  readonly agentOptions?: AgentOptions