@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/lib/index.js CHANGED
@@ -6,15 +6,16 @@ import { ToolArgsError, assertObjectJsonSchema, validateJsonSchemaValue } from "
6
6
  import { canonicalClientTimeZone } from "@deepseek-ai/dsh-util-time";
7
7
  import { Remote, RemoteError, TypertRemoteService, principalOf } from "@deepseek-ai/dsh-typert-protocol";
8
8
  import { AttachmentError } from "@deepseek-ai/dsh-attachment";
9
+ import { HarnessError, LlmError, boundContextSummary, contentHasImage, createUserMessage, errorChain, joinAssistantStreamText } from "@deepseek-ai/dsh-llm";
9
10
  import { z as z$1 } from "zod";
10
- import { HarnessError, boundContextSummary, contentHasImage, createUserMessage, errorChain, joinAssistantStreamText } from "@deepseek-ai/dsh-llm";
11
- import { foldConsumedWork } from "@deepseek-ai/dsh-agent";
12
11
  import { randomUUID } from "node:crypto";
13
12
  import { isAbsolute, resolve } from "node:path";
13
+ import { isDeepStrictEqual } from "node:util";
14
14
  import { SessionLogOffset, SessionSeq } from "@deepseek-ai/dsh-session";
15
15
  import { PERSONA_PREFIX_SECTION } from "@deepseek-ai/dsh-system-prompt";
16
- import { assertNever, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
17
16
  import { appendChunkedList, chunkedListSchema, iterateChunkedList } from "@deepseek-ai/dsh-chunked-list";
17
+ import { foldConsumedWorkForEvent } from "@deepseek-ai/dsh-agent";
18
+ import { assertNever } from "@deepseek-ai/dsh-util-values";
18
19
  import { accessSync, constants, statSync } from "node:fs";
19
20
  //#region lib/types/error.js
20
21
  /**
@@ -39,8 +40,7 @@ var SubagentError = class extends HarnessError {
39
40
  //#endregion
40
41
  //#region lib/types/control.js
41
42
  /**
42
- * Browser-facing subagent prompt and interrupt request validation plus the
43
- * stable prompt failure codes returned by the Remote surface.
43
+ * Browser-facing subagent request validation and stable control failures.
44
44
  *
45
45
  * @module @deepseek-ai/dsh-subagent
46
46
  */
@@ -50,7 +50,13 @@ const CONTROL_ID_SCHEMAS = {
50
50
  childSessionId: SESSION_ID_SCHEMA,
51
51
  delivery: z$1.enum(["queue", "steer"])
52
52
  }),
53
- "subagent.interrupt": z$1.object({ childSessionId: SESSION_ID_SCHEMA })
53
+ "subagent.interrupt": z$1.object({ childSessionId: SESSION_ID_SCHEMA }),
54
+ "subagent.selectModel": z$1.object({
55
+ childSessionId: SESSION_ID_SCHEMA,
56
+ provider: z$1.string().min(1),
57
+ model: z$1.string().min(1),
58
+ reasoningEffort: z$1.string().min(1).optional()
59
+ })
54
60
  };
55
61
  /**
56
62
  * Apply the subagent payload checks that are stricter than generated
@@ -92,6 +98,32 @@ function rejectPrompt(error, childSessionId, signal) {
92
98
  function isCancellation(error, signal) {
93
99
  return signal.aborted || error instanceof SubagentError && error.code === "CANCELLED";
94
100
  }
101
+ /**
102
+ * Report selection failures while preserving an uncertain persistence outcome.
103
+ * @param error - failure from model selection or its durability barrier.
104
+ * @param childSessionId - addressed child.
105
+ * @param signal - caller cancellation before recording.
106
+ * @returns Never — the refusal is thrown.
107
+ * @throws {RemoteError} always; persistence uncertainty takes precedence over cancellation.
108
+ */
109
+ function rejectModelSelection(error, childSessionId, signal) {
110
+ if (error instanceof SubagentError && error.code === "PERSISTENCE_UNCONFIRMED") throw new RemoteError("subagent/model-selection-unconfirmed", "the child model choice may have changed, but persistence is unconfirmed; reload its state before retrying", { childSessionId }, { cause: error });
111
+ if (isCancellation(error, signal)) throw new RemoteError("gateway/cancelled", "subagent model selection was cancelled", {}, { cause: error });
112
+ if (error instanceof LlmError) throw new RemoteError("subagent/model-unavailable", error.message, { childSessionId }, { cause: error });
113
+ if (error instanceof SubagentError) switch (error.code) {
114
+ case "MODEL_UNAVAILABLE": throw new RemoteError("subagent/model-unavailable", "the selected subagent model is unavailable; choose another model or retry", { childSessionId }, { cause: error });
115
+ case "UNAUTHORIZED": throw new RemoteError("subagent/unauthorized", "subagent model selection is not authorized", { childSessionId }, { cause: error });
116
+ case "NOT_RESUMABLE":
117
+ case "UNSUPPORTED_CAPABILITY":
118
+ case "NOT_CONTINUABLE": throw new RemoteError("subagent/not-resumable", "subagent does not support model selection", { childSessionId }, { cause: error });
119
+ case "DRAINING":
120
+ case "ACTIVATION_CLOSING":
121
+ case "CONTINUATION_UNAVAILABLE":
122
+ case "PERSISTENCE_UNAVAILABLE": throw new RemoteError("subagent/model-selection-unavailable", "subagent model selection is temporarily unavailable", { childSessionId }, { cause: error });
123
+ default: break;
124
+ }
125
+ throw new RemoteError("gateway/internal", "subagent model selection failed", {}, { cause: error });
126
+ }
95
127
  //#endregion
96
128
  //#region lib/types/depth.js
97
129
  /**
@@ -166,17 +198,17 @@ function createLifecycleEmitter(ctx, carrier) {
166
198
  * token ceiling, or was cancelled, so deriving the reason from disposal would
167
199
  * report failed work as completed.
168
200
  *
169
- * {@link foldConsumedWork} supplies both halves the raw turn sequence cannot:
201
+ * `foldConsumedWork` supplies both halves the raw turn sequence cannot:
170
202
  * which turn accounts for the work this epoch consumed, and whether accepted
171
203
  * work was cancelled after it without any turn opening over it. A recorded
172
204
  * failure still wins over a cancellation — stopping a child that had already
173
205
  * failed does not turn its failure into a cancellation.
174
- * @param events - this epoch's own event suffix.
206
+ * @param work - the consumed-work account of this epoch's own events.
175
207
  * @returns its terminal stop reason; `completed` only for an epoch that both
176
208
  * closed cleanly and had nothing left to run.
177
209
  */
178
- function epochStopReason(events) {
179
- const { end, droppedUnrun } = foldConsumedWork(events);
210
+ function epochStopReason(work) {
211
+ const { end, droppedUnrun } = work;
180
212
  switch (end?.data.reason.kind) {
181
213
  case "max-tokens": return "max-tokens";
182
214
  case "aborted":
@@ -237,22 +269,17 @@ function resolveChildDepth(parent, maxDepth) {
237
269
  return childDepth;
238
270
  }
239
271
  /**
240
- * Resolve the parent values inherited by a child. The latest request header
241
- * owns provider, model, and reasoning effort after request-time selection;
242
- * creation options remain the fallback before the first request and retain
243
- * the configured output-token limit.
272
+ * Capture the parent's current model choice and configured output controls.
273
+ * A recorded choice applies even before the parent uses it in a request;
274
+ * adapter-defaulted effort remains unselected.
244
275
  * @param parent - delegating parent Agent.
245
276
  * @returns detached Agent options for child-option merging.
246
277
  */
247
278
  function parentAgentOptionsForDelegation(parent) {
248
- const requestConfig = parent.session.requestHeader()?.config;
249
- if (requestConfig === void 0) return { ...parent.options };
250
279
  const { provider: _createdProvider, model: _createdModel, reasoningEffort: _createdReasoningEffort, ...createdOptions } = parent.options;
251
280
  return {
252
281
  ...createdOptions,
253
- provider: requestConfig.provider,
254
- model: requestConfig.model,
255
- ...requestConfig.reasoningEffort === void 0 ? {} : { reasoningEffort: requestConfig.reasoningEffort }
282
+ ...parent.model.current()
256
283
  };
257
284
  }
258
285
  /**
@@ -580,8 +607,10 @@ function describe(child, identity) {
580
607
  * The durable subagent-child descriptor: the versioned, model-hidden
581
608
  * `subagent/descriptor` session event that identifies every session-backed
582
609
  * subagent, including historical one-shot records. The manager appends each
583
- * continuable child's descriptor inside its initial turn, preserving the
584
- * declared composition required for cold resume.
610
+ * continuable child's descriptor during unpublished setup. Current records
611
+ * contain identity fields; model choices belong to the child's own
612
+ * `model/selection` events. Historical continuable records may also carry an
613
+ * initial route, persona, and tool restriction that cold resume reapplies.
585
614
  *
586
615
  * The descriptor deliberately snapshots explicit fields rather than the
587
616
  * merge-extensible `AgentOptions` object: an unrelated extension value cannot
@@ -592,9 +621,8 @@ function describe(child, identity) {
592
621
  * to one activation's result contract rather than durable child composition.
593
622
  * Per-activation knobs such as `maxTokens` are omitted for the same reason as
594
623
  * `outputSchema`: they budget one activation. Cold resume requires the exact
595
- * live subagent tree root for authorization but reconstructs child options only from the
596
- * durable descriptor, so it neither restores the prior budget nor inherits
597
- * the parent's current one; the resumed route's defaults apply instead.
624
+ * live subagent tree root for authorization. It neither restores the prior budget
625
+ * nor inherits the parent's current one; the resumed route's defaults apply instead.
598
626
  *
599
627
  * @module @deepseek-ai/dsh-subagent/descriptor
600
628
  */
@@ -698,25 +726,17 @@ function parseSubagentDescriptor(value) {
698
726
  };
699
727
  }
700
728
  /**
701
- * Validate and detach a continuable descriptor input.
702
- * @param input - the caller-collected continuable composition fields.
703
- * @returns the versioned, detached continuable descriptor payload.
704
- * @throws when a field is not losslessly JSON-serializable.
729
+ * Build the current continuable child identity record.
730
+ * @param input - the caller-collected continuable identity fields.
731
+ * @returns the versioned continuable descriptor payload.
705
732
  */
706
733
  function snapshotSubagentDescriptor(input) {
707
- const snapshot = snapshotJsonValue({
734
+ return {
708
735
  version: 3,
709
736
  mode: input.mode,
710
737
  provider: input.provider,
711
- label: input.label,
712
- ...input.agentProvider !== void 0 ? { agentProvider: input.agentProvider } : {},
713
- ...input.agentModel !== void 0 ? { agentModel: input.agentModel } : {},
714
- ...input.agentReasoningEffort !== void 0 ? { agentReasoningEffort: input.agentReasoningEffort } : {},
715
- ...input.persona !== void 0 ? { persona: input.persona } : {},
716
- ...input.toolFilter !== void 0 ? { toolFilter: input.toolFilter } : {}
717
- });
718
- if (snapshot === void 0) throw new Error("subagent descriptor is not losslessly JSON-serializable");
719
- return snapshot;
738
+ label: input.label
739
+ };
720
740
  }
721
741
  /**
722
742
  * Fold a persisted child log to its supported descriptor. The first
@@ -980,6 +1000,46 @@ function catalogNames(entries) {
980
1000
  return names;
981
1001
  }
982
1002
  //#endregion
1003
+ //#region lib/types/model-selection.js
1004
+ /** Model selection resolved before a local child is created or restored. */
1005
+ /**
1006
+ * Require the complete initial selection before publishing a child.
1007
+ * @param options - resolved child options captured from its creator and explicit overrides.
1008
+ * @returns the detached model selection, excluding activation controls.
1009
+ * @throws {SubagentError} with MODEL_UNAVAILABLE when the provider or model is absent.
1010
+ */
1011
+ function requireInitialModel(options) {
1012
+ const { provider, model, reasoningEffort } = options;
1013
+ if (!provider || !model) throw new SubagentError("subagent startup requires a provider and model; select both before creating a child", "MODEL_UNAVAILABLE");
1014
+ return {
1015
+ provider,
1016
+ model,
1017
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
1018
+ };
1019
+ }
1020
+ /**
1021
+ * Build the Agent options for restoring a saved child. The restored Agent reads
1022
+ * its recorded choice from the child's own log first; a historical descriptor
1023
+ * route applies only when that log records neither a choice nor a request.
1024
+ * @param descriptor - continuable descriptor from the child's own log.
1025
+ * @param recorded - the observed log's next choice, or none.
1026
+ * @param selecting - choice a maintenance restore is about to record; it supplies the route only when neither source has one.
1027
+ * @returns Agent options carrying the descriptor's historical route or the selecting choice, if any.
1028
+ * @throws {SubagentError} with NOT_RESUMABLE when no source supplies a complete model.
1029
+ */
1030
+ function restorationOptions(descriptor, recorded, selecting) {
1031
+ const { agentProvider: provider, agentModel: model, agentReasoningEffort: reasoningEffort } = descriptor;
1032
+ if (recorded == null && (!provider || !model)) {
1033
+ if (selecting !== void 0) return { ...selecting };
1034
+ throw new SubagentError("subagent has no complete saved model selection and cannot be resumed; select its model or create a new child", "NOT_RESUMABLE");
1035
+ }
1036
+ return {
1037
+ ...provider === void 0 ? {} : { provider },
1038
+ ...model === void 0 ? {} : { model },
1039
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
1040
+ };
1041
+ }
1042
+ //#endregion
983
1043
  //#region lib/types/structured.js
984
1044
  /**
985
1045
  * Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
@@ -1088,74 +1148,8 @@ function attachStructuredRuntime(childCtx, schema, canComplete) {
1088
1148
  };
1089
1149
  }
1090
1150
  //#endregion
1091
- //#region lib/types/assistant-output.js
1092
- /**
1093
- * Canonical selection of a child's final assistant output. Backend run results
1094
- * and `subagent/end.lastAssistantMessage` apply the same rule: select the last
1095
- * non-empty assistant message. An empty-content message records usage only
1096
- * when the loop appends it after a max-tokens step with no executable blocks,
1097
- * so it does not replace earlier output. If no non-empty message exists,
1098
- * select the accumulated assistant text. Selection is independent of the
1099
- * run's stop reason.
1100
- *
1101
- * @module @deepseek-ai/dsh-subagent/assistant-output
1102
- */
1103
- /**
1104
- * Incremental fold of the selection rule, for backends that observe a child's
1105
- * output as it streams: session-event backends {@link push} each event, and
1106
- * transports without session events (ACP content chunks) {@link pushText} raw
1107
- * text into the same streamed fallback.
1108
- */
1109
- var AssistantOutputFold = class {
1110
- message;
1111
- partial = [];
1112
- /**
1113
- * Fold one session event: a non-empty assistant message becomes the
1114
- * candidate final answer, while its embedded stream and any log-only attempt
1115
- * extend the streamed fallback; every other event contributes nothing.
1116
- * @param event - the next observed session event.
1117
- */
1118
- push(event) {
1119
- if (event.type === "assistant/message") {
1120
- const content = event.data.message.content;
1121
- if (content.length > 0) this.message = content;
1122
- }
1123
- if (event.type === "assistant/message" || event.type === "assistant/attempt") this.pushText(joinAssistantStreamText(event.data.stream));
1124
- }
1125
- /**
1126
- * Extend the streamed fallback with text observed outside session events.
1127
- * @param text - the next streamed text piece (an empty piece is a no-op).
1128
- */
1129
- pushText(text) {
1130
- if (text.length > 0) this.partial.push(text);
1131
- }
1132
- /**
1133
- * Select the final output folded so far.
1134
- * @returns the last non-empty assistant message, else the accumulated
1135
- * streamed text, or `undefined` when the child produced neither.
1136
- */
1137
- collect() {
1138
- if (this.message !== void 0) return this.message;
1139
- const text = this.partial.join("");
1140
- return text.length > 0 ? [{
1141
- type: "text",
1142
- text
1143
- }] : void 0;
1144
- }
1145
- };
1146
- /**
1147
- * Apply the selection rule to one complete child-owned event suffix.
1148
- * @param events - the child-owned events (after any seed or epoch boundary).
1149
- * @returns the selected output, or `undefined` when the child produced none.
1150
- */
1151
- function finalAssistantOutput(events) {
1152
- const fold = new AssistantOutputFold();
1153
- for (const event of events) fold.push(event);
1154
- return fold.collect();
1155
- }
1156
- //#endregion
1157
1151
  //#region lib/types/activation.js
1158
- /** Execution-period records, capacity slots, child serialization, and local output capture.
1152
+ /** Execution-period records, capacity slots, child serialization, and local result capture.
1159
1153
  * @module @deepseek-ai/dsh-subagent/activation
1160
1154
  */
1161
1155
  /** Process-local capacity shared by every member of a subagent tree. */
@@ -1218,14 +1212,36 @@ function observeLocalFailure(activation, wake) {
1218
1212
  });
1219
1213
  }
1220
1214
  /**
1215
+ * Fold one committed child event into the result its epoch settles with.
1216
+ * `session/event` dispatch discards a listener exception, so each fold keeps
1217
+ * its first one and stops; {@link captureLocalResult} rethrows it.
1218
+ * @param activation - the resident local execution that owns the child.
1219
+ * @param event - the child Session event just committed.
1220
+ */
1221
+ function foldLocalResult(activation, event) {
1222
+ if (activation.outputFailure === void 0) try {
1223
+ activation.output.push(event);
1224
+ } catch (error) {
1225
+ activation.outputFailure = { error };
1226
+ }
1227
+ if (activation.workFailure === void 0) try {
1228
+ activation.work = foldConsumedWorkForEvent(activation.work, event);
1229
+ } catch (error) {
1230
+ activation.workFailure = { error };
1231
+ }
1232
+ }
1233
+ /**
1221
1234
  * Capture local output and retain failures without a later committed turn ending.
1222
1235
  * @param activation - the settled local execution and any structured result.
1223
1236
  * @returns final output, stop reason, and committed structured value.
1237
+ * @throws the first error a fold of this epoch's events threw; the stop-reason
1238
+ * fold is not consulted after a retained live failure.
1224
1239
  */
1225
1240
  function captureLocalResult(activation) {
1226
- const events = activation.handle.agent.session.snapshotEvents(activation.outputStart);
1227
- const output = finalAssistantOutput(events) ?? [];
1228
- const stopReason = activation.failureAt === void 0 ? epochStopReason(events) : "error";
1241
+ if (activation.outputFailure !== void 0) throw activation.outputFailure.error;
1242
+ if (activation.failureAt === void 0 && activation.workFailure !== void 0) throw activation.workFailure.error;
1243
+ const output = activation.output.collect() ?? [];
1244
+ const stopReason = activation.failureAt === void 0 ? epochStopReason(activation.work ?? { droppedUnrun: false }) : "error";
1229
1245
  const structured = activation.structured;
1230
1246
  if (structured !== void 0) {
1231
1247
  const captured = structured.captured();
@@ -1264,6 +1280,77 @@ var ChildLock = class {
1264
1280
  }
1265
1281
  };
1266
1282
  //#endregion
1283
+ //#region lib/types/assistant-output.js
1284
+ /**
1285
+ * Canonical selection of a child's final assistant output. Backend run results
1286
+ * and `subagent/end.lastAssistantMessage` apply the same rule: select the last
1287
+ * non-empty assistant message. An empty-content message records usage only
1288
+ * when the loop appends it after a max-tokens step with no executable blocks,
1289
+ * so it does not replace earlier output. If no non-empty message exists,
1290
+ * select the accumulated assistant text. Selection is independent of the
1291
+ * run's stop reason.
1292
+ *
1293
+ * @module @deepseek-ai/dsh-subagent/assistant-output
1294
+ */
1295
+ /**
1296
+ * Incremental fold of the selection rule, for backends that observe a child's
1297
+ * output as it streams: session-event backends {@link push} each event, and
1298
+ * transports without session events (ACP content chunks) {@link pushText} raw
1299
+ * text into the same streamed fallback.
1300
+ */
1301
+ var AssistantOutputFold = class {
1302
+ message;
1303
+ partial = [];
1304
+ /**
1305
+ * Fold one session event: a non-empty assistant message becomes the
1306
+ * candidate final answer and discards the streamed fallback. Before one
1307
+ * exists, the stream of an empty message or of a log-only attempt extends
1308
+ * that fallback. Every other event contributes nothing.
1309
+ * @param event - the next observed session event.
1310
+ */
1311
+ push(event) {
1312
+ if (event.type === "assistant/message") {
1313
+ const content = event.data.message.content;
1314
+ if (content.length > 0) {
1315
+ this.message = content;
1316
+ this.partial = [];
1317
+ }
1318
+ }
1319
+ if (event.type === "assistant/message" || event.type === "assistant/attempt") this.pushText(joinAssistantStreamText(event.data.stream));
1320
+ }
1321
+ /**
1322
+ * Extend the streamed fallback with text observed outside session events.
1323
+ * The fallback is discarded once a non-empty message exists.
1324
+ * @param text - the next streamed text piece (an empty piece is a no-op).
1325
+ */
1326
+ pushText(text) {
1327
+ if (this.message === void 0 && text.length > 0) this.partial.push(text);
1328
+ }
1329
+ /**
1330
+ * Select the final output folded so far.
1331
+ * @returns the last non-empty assistant message, else the accumulated
1332
+ * streamed text, or `undefined` when the child produced neither.
1333
+ */
1334
+ collect() {
1335
+ if (this.message !== void 0) return this.message;
1336
+ const text = this.partial.join("");
1337
+ return text.length > 0 ? [{
1338
+ type: "text",
1339
+ text
1340
+ }] : void 0;
1341
+ }
1342
+ };
1343
+ /**
1344
+ * Apply the selection rule to one complete child-owned event suffix.
1345
+ * @param events - the child-owned events (after any seed or epoch boundary).
1346
+ * @returns the selected output, or `undefined` when the child produced none.
1347
+ */
1348
+ function finalAssistantOutput(events) {
1349
+ const fold = new AssistantOutputFold();
1350
+ for (const event of events) fold.push(event);
1351
+ return fold.collect();
1352
+ }
1353
+ //#endregion
1267
1354
  //#region lib/types/manager.js
1268
1355
  /**
1269
1356
  * Owns subagent startup, message admission, cold resume, and execution lifetimes.
@@ -1366,6 +1453,10 @@ var SubagentManager = class {
1366
1453
  this.maxActiveSubagents = maxActiveSubagents;
1367
1454
  const scope = ctx.plugin(function activationOwner() {});
1368
1455
  this.ownerCtx = scope.ctx;
1456
+ scope.ctx.on("session/event", (session, event) => {
1457
+ const activation = this.resident.get(session.id);
1458
+ if (activation?.kind === "local" && activation.handle.agent.session === session) foldLocalResult(activation, event);
1459
+ }, { global: true });
1369
1460
  installSubagentArchiveAdmission(ctx, (agent) => {
1370
1461
  const activation = this.resident.get(agent.id);
1371
1462
  return activation !== void 0 && activationAgent(activation) === agent ? activation.ancestors : void 0;
@@ -1379,7 +1470,13 @@ var SubagentManager = class {
1379
1470
  });
1380
1471
  ctx.effect(function* () {
1381
1472
  yield scope.dispose;
1382
- yield () => this.drain();
1473
+ yield async () => {
1474
+ try {
1475
+ await this.drain();
1476
+ } finally {
1477
+ await scope.dispose();
1478
+ }
1479
+ };
1383
1480
  }.bind(this), "subagents.manager()");
1384
1481
  }
1385
1482
  /**
@@ -1493,18 +1590,14 @@ var SubagentManager = class {
1493
1590
  this.assertChildIdAvailable(childId);
1494
1591
  const childDepth = resolveChildDepth(parent, spec.maxDepth);
1495
1592
  const agentOptions = resolveChildAgentOptions(parent, spec.agentOptions, childDepth);
1496
- const agentProvider = agentOptions.provider;
1497
- const agentModel = agentOptions.model;
1498
- const agentReasoningEffort = agentOptions.reasoningEffort;
1593
+ const initialModel = requireInitialModel(agentOptions);
1499
1594
  const descriptor = snapshotSubagentDescriptor({
1500
1595
  mode: "continuable",
1501
1596
  provider: spec.provider,
1502
- label: spec.label,
1503
- ...agentProvider !== void 0 ? { agentProvider } : {},
1504
- ...agentModel !== void 0 ? { agentModel } : {},
1505
- ...agentReasoningEffort !== void 0 ? { agentReasoningEffort } : {}
1597
+ label: spec.label
1506
1598
  });
1507
1599
  const delegatedPolicies = captureDelegatedPolicyOverrides(parent);
1600
+ if (spec.agentOptions?.provider !== void 0 || spec.agentOptions?.model !== void 0 || spec.agentOptions?.reasoningEffort !== void 0) await this.validateModelSelection(parent.ctx, initialModel, signal);
1508
1601
  const cwd = await this.resolveDirectory(spec, signal);
1509
1602
  const prepared = await prepare({
1510
1603
  sessionId: childId,
@@ -1541,7 +1634,8 @@ var SubagentManager = class {
1541
1634
  meta: childSessionMeta(parent, childDepth, prepared.seed !== void 0, spec.agentPreset),
1542
1635
  inheritedEventCount,
1543
1636
  delegatedPolicies,
1544
- descriptor
1637
+ descriptor,
1638
+ initialModel
1545
1639
  },
1546
1640
  agentOptions,
1547
1641
  composition: { agentPreset: spec.agentPreset },
@@ -1784,9 +1878,157 @@ var SubagentManager = class {
1784
1878
  }
1785
1879
  return this.deliverToMember(root, childId, content, options);
1786
1880
  }
1881
+ /**
1882
+ * Record a child's next selection without running it or changing user defaults.
1883
+ * A cold child is restored for maintenance only: it holds no capacity slot,
1884
+ * publishes no lifecycle events, admits no input, and closes before return.
1885
+ * @param childId - durable continuable child Session id.
1886
+ * @param selection - complete selection; omitted effort follows adapter defaults.
1887
+ * @param authority - trusted user operation or exact live creation ancestor.
1888
+ * @param signal - cancellation before selection is recorded.
1889
+ * @returns the recorded selection after its durability barrier completes.
1890
+ */
1891
+ async selectModel(childId, selection, authority, signal) {
1892
+ signal.throwIfAborted();
1893
+ const selected = { ...selection };
1894
+ const ancestry = this.resident.get(childId);
1895
+ let root;
1896
+ let ancestors;
1897
+ if (ancestry !== void 0) ({root, ancestors} = ancestry);
1898
+ else {
1899
+ const env_3 = {
1900
+ stack: [],
1901
+ error: void 0,
1902
+ hasError: false
1903
+ };
1904
+ try {
1905
+ const source = __addDisposableResource$1(env_3, await this.observeContinuation(childId, signal), false);
1906
+ ({root, ancestors} = await this.resolveCreationAncestry(source, signal));
1907
+ } catch (e_3) {
1908
+ env_3.error = e_3;
1909
+ env_3.hasError = true;
1910
+ } finally {
1911
+ __disposeResources$1(env_3);
1912
+ }
1913
+ }
1914
+ this.authorizeSelection(childId, root, ancestors, authority);
1915
+ return this.trackStartup(root, signal, async (signal) => {
1916
+ while (true) {
1917
+ const result = await this.locks.run(childId, async () => {
1918
+ signal.throwIfAborted();
1919
+ this.authorizeSelection(childId, root, ancestors, authority);
1920
+ const activation = this.resident.get(childId);
1921
+ if (activation === void 0) {
1922
+ await this.validateModelSelection(this.ctx, selected, signal);
1923
+ const restored = await this.restoreTarget(root, childId, signal, selected);
1924
+ await this.selectWhileMaintained(restored, selected, root, authority);
1925
+ return { selected };
1926
+ }
1927
+ if (activation.root !== root) throw new SubagentError("target belongs to another subagent tree", "UNAUTHORIZED");
1928
+ const { handle } = requireLocalActivation(activation);
1929
+ await this.validateModelSelection(this.ctx, selected, signal);
1930
+ signal.throwIfAborted();
1931
+ this.authorizeSelection(childId, root, activation.ancestors, authority);
1932
+ if (activation.closing !== void 0) return { closing: activation.closing };
1933
+ await this.recordSelection(handle.agent, selected);
1934
+ return { selected };
1935
+ });
1936
+ if ("selected" in result) return result.selected;
1937
+ await Promise.allSettled([result.closing]);
1938
+ }
1939
+ });
1940
+ }
1941
+ /** Recheck exact caller identities after asynchronous validation and storage work. */
1942
+ authorizeSelection(childId, root, ancestors, authority) {
1943
+ this.assertAdmitting(root);
1944
+ if (authority.kind === "user") return;
1945
+ const caller = authority.agent;
1946
+ if (caller.id === childId || this.rootOf(caller) !== root || !ancestors.includes(caller.id)) throw new SubagentError(`subagent "${childId}" is not a descendant of the selecting agent`, "UNAUTHORIZED");
1947
+ this.assertAdmitting(caller);
1948
+ }
1949
+ /** Validate a choice without persisting adapter-defaulted controls; LLM failures keep their class and code. */
1950
+ async validateModelSelection(ctx, selection, signal) {
1951
+ const llm = ctx.get("llm");
1952
+ if (llm === void 0) throw new SubagentError("cannot validate the selected subagent model because the LLM service is unavailable", "MODEL_UNAVAILABLE");
1953
+ try {
1954
+ await llm.resolveCallConfig(selection, signal);
1955
+ } catch (error) {
1956
+ signal.throwIfAborted();
1957
+ throw error;
1958
+ }
1959
+ }
1960
+ /**
1961
+ * Record a choice through a maintenance restoration and begin its release
1962
+ * from the idle phase it owns. Input that reaches the Agent meanwhile cannot
1963
+ * start a turn, and the release cancels it. A restored Agent that an
1964
+ * `agent/created` listener already woke rejects the choice with
1965
+ * `CONTINUATION_UNAVAILABLE`, and the release cancels the started turn.
1966
+ */
1967
+ async selectWhileMaintained(activation, selection, root, authority) {
1968
+ let closed;
1969
+ const close = () => closed ??= this.close(activation, () => this.finishDisposal(activation, false));
1970
+ try {
1971
+ const { agent } = requireLocalActivation(activation).handle;
1972
+ let maintained;
1973
+ try {
1974
+ maintained = agent.runMaintenance(async () => {
1975
+ try {
1976
+ this.authorizeSelection(activation.childId, root, activation.ancestors, authority);
1977
+ await this.recordSelection(agent, selection);
1978
+ } finally {
1979
+ close().catch(() => void 0);
1980
+ }
1981
+ });
1982
+ } catch (error) {
1983
+ throw new SubagentError(`subagent "${activation.childId}" received input while restored for model selection; continue it before changing its model`, "CONTINUATION_UNAVAILABLE", { cause: error });
1984
+ }
1985
+ await maintained;
1986
+ } finally {
1987
+ try {
1988
+ await close();
1989
+ } catch (error) {
1990
+ this.reportTeardownFailure(activation, error);
1991
+ }
1992
+ }
1993
+ }
1994
+ /** Append a choice through the child's live Session and confirm it in the durable log. */
1995
+ async recordSelection(agent, selection) {
1996
+ const persistence = this.requirePersistence();
1997
+ const session = agent.session;
1998
+ const before = session.seq;
1999
+ try {
2000
+ const env_4 = {
2001
+ stack: [],
2002
+ error: void 0,
2003
+ hasError: false
2004
+ };
2005
+ try {
2006
+ agent.model.select(selection);
2007
+ const appended = session.seq > before;
2008
+ const recordedSeq = appended ? before : session.seq - 1;
2009
+ if (!await agent.ctx.sessions.flush(session)) throw new Error("no Session durability listener participated");
2010
+ const stored = __addDisposableResource$1(env_4, await persistence.open(agent.id, "read"), true);
2011
+ const { events } = await stored.read(recordedSeq, 1);
2012
+ const event = events[0];
2013
+ if (!isDeepStrictEqual(stored.header, session.header) || event?.seq !== recordedSeq || appended && (event.type !== "model/selection" || !isDeepStrictEqual(event.data, selection))) throw new Error("the recorded selection is not present in the durable child log");
2014
+ } catch (e_4) {
2015
+ env_4.error = e_4;
2016
+ env_4.hasError = true;
2017
+ } finally {
2018
+ const result_1 = __disposeResources$1(env_4);
2019
+ if (result_1) await result_1;
2020
+ }
2021
+ } catch (error) {
2022
+ throw this.selectionPersistenceFailure(agent.id, error);
2023
+ }
2024
+ }
2025
+ /** Preserve an uncertain durable outcome instead of reporting that no change occurred. */
2026
+ selectionPersistenceFailure(childId, error) {
2027
+ return new SubagentError(`model selection for subagent "${childId}" may have changed, but persistence could not be confirmed; reload its state before retrying`, "PERSISTENCE_UNCONFIRMED", { cause: error });
2028
+ }
1787
2029
  /** Admit local input synchronously before any teardown can begin. */
1788
2030
  deliver(activation, message, delivery) {
1789
- if (activation.closing !== void 0) throw new SubagentError("subagent activation is being disposed; the message was not accepted", "ACTIVATION_CLOSING");
2031
+ if (activation.closing !== void 0 || activation.maintenance) throw new SubagentError("subagent activation is being disposed; the message was not accepted", "ACTIVATION_CLOSING");
1790
2032
  const local = requireLocalActivation(activation);
1791
2033
  if (local.structured?.acceptsInput() === false) throw new SubagentError("subagent is submitting or has submitted its structured result; the message was not accepted", "INPUT_CLOSED");
1792
2034
  if (delivery === "steer") local.handle.agent.steer(message);
@@ -1838,7 +2080,7 @@ var SubagentManager = class {
1838
2080
  materialize(inputs) {
1839
2081
  this.assertAdmitting(inputs.root);
1840
2082
  inputs.signal.throwIfAborted();
1841
- const releaseSlot = this.rootPool(inputs.root).reserve(this.maxActiveSubagents());
2083
+ const releaseSlot = inputs.kind === "local" && inputs.maintenance === true ? () => {} : this.rootPool(inputs.root).reserve(this.maxActiveSubagents());
1842
2084
  return this.materializeTracked(inputs, releaseSlot).catch((error) => {
1843
2085
  releaseSlot();
1844
2086
  throw error;
@@ -1954,6 +2196,7 @@ var SubagentManager = class {
1954
2196
  if (create !== void 0) {
1955
2197
  if (inputs.composition.agentPreset !== void 0) child.session.append("agent-preset/selected", { agentPreset: inputs.composition.agentPreset });
1956
2198
  child.session.append("subagent/descriptor", create.descriptor);
2199
+ child.session.append("model/selection", create.initialModel);
1957
2200
  appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies);
1958
2201
  const workingDirectory = childCtx.get("workingDirectory");
1959
2202
  if (workingDirectory === void 0) throw new SubagentError("local subagents require the working-directory service", "WORKING_DIRECTORY_UNAVAILABLE");
@@ -1962,30 +2205,32 @@ var SubagentManager = class {
1962
2205
  if (inputs.composition.agentPreset === void 0) await applyChildComposition(childCtx, create?.parent, inputs.composition);
1963
2206
  if (inputs.outputSchema !== void 0) structured = attachStructuredRuntime(childCtx, inputs.outputSchema, () => child.inbox.nextStep.length === 0 && child.inbox.nextTurn.length === 0);
1964
2207
  };
1965
- const handle = create === void 0 ? await this.ownerCtx.agents.resume({
1966
- resumeSessionId: childId,
1967
- agentOptions: inputs.agentOptions,
1968
- signal: inputs.signal,
1969
- setup
1970
- }) : await this.ownerCtx.agents.create({
1971
- sessionId: childId,
1972
- meta: create.meta,
1973
- ...create.seed === void 0 ? {} : {
1974
- seed: create.seed,
1975
- parentSource: {
1976
- sessionId: create.parent.id,
1977
- endSeq: SessionLogOffset(create.seed.length)
1978
- }
1979
- },
1980
- inheritedEventCount: create.inheritedEventCount,
1981
- agentOptions: inputs.agentOptions,
1982
- signal: inputs.signal,
1983
- setup
1984
- });
1985
2208
  resource = {
1986
2209
  kind: "local",
1987
- handle,
1988
- outputStart: handle.agent.session.seq,
2210
+ handle: create === void 0 ? await this.ownerCtx.agents.resume({
2211
+ resumeSessionId: childId,
2212
+ agentOptions: inputs.agentOptions,
2213
+ signal: inputs.signal,
2214
+ setup
2215
+ }) : await this.ownerCtx.agents.create({
2216
+ sessionId: childId,
2217
+ meta: create.meta,
2218
+ ...create.seed === void 0 ? {} : {
2219
+ seed: create.seed,
2220
+ parentSource: {
2221
+ sessionId: create.parent.id,
2222
+ endSeq: SessionLogOffset(create.seed.length)
2223
+ }
2224
+ },
2225
+ inheritedEventCount: create.inheritedEventCount,
2226
+ agentOptions: inputs.agentOptions,
2227
+ signal: inputs.signal,
2228
+ setup
2229
+ }),
2230
+ output: new AssistantOutputFold(),
2231
+ work: void 0,
2232
+ outputFailure: void 0,
2233
+ workFailure: void 0,
1989
2234
  structured,
1990
2235
  failureAt: void 0,
1991
2236
  poke: Promise.withResolvers(),
@@ -2005,7 +2250,8 @@ var SubagentManager = class {
2005
2250
  delivery: inputs.delivery ?? "parent",
2006
2251
  result: Promise.withResolvers(),
2007
2252
  closing: void 0,
2008
- accepted: false
2253
+ accepted: false,
2254
+ maintenance: inputs.kind === "local" && inputs.maintenance === true
2009
2255
  };
2010
2256
  activation.result.promise.catch(() => void 0);
2011
2257
  this.resident.set(childId, activation);
@@ -2027,7 +2273,7 @@ var SubagentManager = class {
2027
2273
  if (event.type === "tool/call") activation.omitClosingText = false;
2028
2274
  });
2029
2275
  }
2030
- this.host.emitLifecycle("subagent/start", this.runInfo(activation), root);
2276
+ if (!activation.maintenance) this.host.emitLifecycle("subagent/start", this.runInfo(activation), root);
2031
2277
  } catch (error) {
2032
2278
  /* v8 ignore next -- rollback failure must not mask the admission failure
2033
2279
  * that prevented this operation from returning an accepted message id. */
@@ -2184,7 +2430,7 @@ var SubagentManager = class {
2184
2430
  stopReason: "error"
2185
2431
  };
2186
2432
  this.notifySettlement(activation, result);
2187
- this.host.emitLifecycle("subagent/end", {
2433
+ if (!activation.maintenance) this.host.emitLifecycle("subagent/end", {
2188
2434
  ...this.runInfo(activation),
2189
2435
  stopReason: terminal.stopReason,
2190
2436
  ...terminal.output.length === 0 ? {} : { lastAssistantMessage: terminal.output }
@@ -2271,16 +2517,24 @@ var SubagentManager = class {
2271
2517
  throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2272
2518
  }
2273
2519
  }
2274
- /** Reconstruct only the target under its subagent tree root; the caller owns acceptance or rollback. */
2275
- async restoreTarget(root, childId, signal) {
2520
+ /**
2521
+ * Reconstruct only the target under its subagent tree root; the caller owns
2522
+ * acceptance or rollback. A selection restores it for maintenance instead.
2523
+ * @param root - exact live subagent tree root that owns the child.
2524
+ * @param childId - durable continuable child Session id.
2525
+ * @param signal - cancellation through publication.
2526
+ * @param maintenanceSelection - choice being recorded; it also supplies the route of a child that has none.
2527
+ * @returns the published Activation.
2528
+ */
2529
+ async restoreTarget(root, childId, signal, maintenanceSelection) {
2276
2530
  return this.trackStartup(root, signal, async (signal) => {
2277
- const env_3 = {
2531
+ const env_5 = {
2278
2532
  stack: [],
2279
2533
  error: void 0,
2280
2534
  hasError: false
2281
2535
  };
2282
2536
  try {
2283
- const source = __addDisposableResource$1(env_3, await this.observeContinuation(childId, signal), false);
2537
+ const source = __addDisposableResource$1(env_5, await this.observeContinuation(childId, signal), false);
2284
2538
  this.assertAdmitting(root);
2285
2539
  const ownEvents = source.events.slice(source.inheritedEventCount);
2286
2540
  let descriptor;
@@ -2291,6 +2545,9 @@ var SubagentManager = class {
2291
2545
  }
2292
2546
  if (descriptor === void 0 || descriptor.mode !== "continuable") throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, "NOT_RESUMABLE");
2293
2547
  const { ancestors, path } = await this.resolveCreationAncestry(source, signal, root);
2548
+ const pending = source.projections?.values.inbox;
2549
+ if (maintenanceSelection !== void 0 && pending !== void 0 && pending["next-turn"].length + pending["next-step"].length > 0) throw new SubagentError(`subagent "${childId}" has pending input; continue it before changing its model`, "CONTINUATION_UNAVAILABLE");
2550
+ const agentOptions = restorationOptions(descriptor, source.projections?.values.modelSelection?.next, maintenanceSelection);
2294
2551
  let activation;
2295
2552
  try {
2296
2553
  const projectedPreset = source.projections?.values.agentPreset;
@@ -2303,17 +2560,14 @@ var SubagentManager = class {
2303
2560
  root,
2304
2561
  ancestors,
2305
2562
  path,
2306
- agentOptions: {
2307
- ...descriptor.agentProvider !== void 0 ? { provider: descriptor.agentProvider } : {},
2308
- ...descriptor.agentModel !== void 0 ? { model: descriptor.agentModel } : {},
2309
- ...descriptor.agentReasoningEffort !== void 0 ? { reasoningEffort: brandString(descriptor.agentReasoningEffort) } : {}
2310
- },
2563
+ agentOptions,
2311
2564
  composition: {
2312
2565
  agentPreset: agentPreset ?? void 0,
2313
2566
  persona: descriptor.persona,
2314
2567
  toolFilter: descriptor.toolFilter
2315
2568
  },
2316
- signal
2569
+ signal,
2570
+ maintenance: maintenanceSelection !== void 0
2317
2571
  });
2318
2572
  } catch (error) {
2319
2573
  signal.throwIfAborted();
@@ -2321,11 +2575,11 @@ var SubagentManager = class {
2321
2575
  throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2322
2576
  }
2323
2577
  return activation;
2324
- } catch (e_3) {
2325
- env_3.error = e_3;
2326
- env_3.hasError = true;
2578
+ } catch (e_5) {
2579
+ env_5.error = e_5;
2580
+ env_5.hasError = true;
2327
2581
  } finally {
2328
- __disposeResources$1(env_3);
2582
+ __disposeResources$1(env_5);
2329
2583
  }
2330
2584
  });
2331
2585
  }
@@ -2366,10 +2620,11 @@ var SubagentManager = class {
2366
2620
  options.onAccepted?.();
2367
2621
  return message.id;
2368
2622
  }
2369
- /** Refuse image content for a child whose fixed model accepts text only. */
2623
+ /** Refuse image content for the selection held through inbox admission. */
2370
2624
  async assertImageCapable(agent, signal) {
2371
- const { provider, model } = agent.options;
2372
- if (provider === void 0 || model === void 0) return;
2625
+ const selection = agent.model.current();
2626
+ if (selection === void 0) return;
2627
+ const { provider, model } = selection;
2373
2628
  const llm = this.ctx.get("llm");
2374
2629
  /* v8 ignore next -- without an LLM registry, delivery defers to projection. */
2375
2630
  if (llm === void 0) return;
@@ -2958,6 +3213,7 @@ let SubagentRuntime = (() => {
2958
3213
  let _instanceExtraInitializers = [];
2959
3214
  let _prompt_decorators;
2960
3215
  let _interruptByUser_decorators;
3216
+ let _selectModelByUser_decorators;
2961
3217
  return class SubagentRuntime extends _classSuper {
2962
3218
  static {
2963
3219
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
@@ -2969,6 +3225,10 @@ let SubagentRuntime = (() => {
2969
3225
  name: "interruptByUser",
2970
3226
  resources: { session: (childSessionId) => childSessionId }
2971
3227
  })];
3228
+ _selectModelByUser_decorators = [Remote({
3229
+ name: "selectModelByUser",
3230
+ resources: { session: (request) => request.childSessionId }
3231
+ })];
2972
3232
  __esDecorate(this, null, _prompt_decorators, {
2973
3233
  kind: "method",
2974
3234
  name: "prompt",
@@ -2991,6 +3251,17 @@ let SubagentRuntime = (() => {
2991
3251
  },
2992
3252
  metadata: _metadata
2993
3253
  }, null, _instanceExtraInitializers);
3254
+ __esDecorate(this, null, _selectModelByUser_decorators, {
3255
+ kind: "method",
3256
+ name: "selectModelByUser",
3257
+ static: false,
3258
+ private: false,
3259
+ access: {
3260
+ has: (obj) => "selectModelByUser" in obj,
3261
+ get: (obj) => obj.selectModelByUser
3262
+ },
3263
+ metadata: _metadata
3264
+ }, null, _instanceExtraInitializers);
2994
3265
  if (_metadata) Object.defineProperty(this, Symbol.metadata, {
2995
3266
  enumerable: true,
2996
3267
  configurable: true,
@@ -3173,6 +3444,22 @@ let SubagentRuntime = (() => {
3173
3444
  this.manager?.interrupt(targetSessionId, authority);
3174
3445
  }
3175
3446
  /**
3447
+ * Record a local child's complete model choice for future steps without
3448
+ * adding a message or changing user defaults. Selection and image admission
3449
+ * share the child's operation order; an already prepared step retains its model.
3450
+ * @param childId - durable continuable child Session id.
3451
+ * @param selection - complete choice; omitted effort follows adapter defaults.
3452
+ * @param authority - trusted user operation or exact live creation ancestor.
3453
+ * @param signal - cancellation before selection is recorded.
3454
+ * @returns the recorded choice after its durability barrier completes.
3455
+ * @throws {LlmError} when the LLM runtime rejects the selected route or effort.
3456
+ * @throws {SubagentError} when access or child availability fails;
3457
+ * PERSISTENCE_UNCONFIRMED means the choice may have changed but durability is unknown.
3458
+ */
3459
+ async selectModel(childId, selection, authority, signal) {
3460
+ return this.requireManager().selectModel(childId, selection, authority, signal);
3461
+ }
3462
+ /**
3176
3463
  * Close admission and stop all instances in the selected subagent trees, then await
3177
3464
  * pending startup and cleanup. Ordinary members are ignored. The cutoff lasts
3178
3465
  * until each exact root leaves the registry; unrelated subagent trees remain live.
@@ -3269,11 +3556,42 @@ let SubagentRuntime = (() => {
3269
3556
  try {
3270
3557
  this.interrupt(childSessionId, { kind: "user" });
3271
3558
  } catch (error) {
3272
- throw new RemoteError("gateway/internal", "subagent interrupt failed", {}, { cause: error });
3559
+ throw new RemoteError("gateway/internal", `subagent interrupt failed: ${String(error)}`, {}, { cause: error });
3273
3560
  }
3274
3561
  return { accepted: true };
3275
3562
  }
3276
3563
  /**
3564
+ * Select a local child's model under the caller's target-Session permission.
3565
+ * Like Session model selection, it accepts only a model its provider lists in the
3566
+ * current catalog. No message or global default is changed. A successful receipt
3567
+ * confirms the child's persistence barrier; an unconfirmed failure may follow a live change.
3568
+ * @param request - target and complete model choice; omitted effort uses adapter defaults.
3569
+ * @param signal - caller cancellation before selection is recorded.
3570
+ * @returns the recorded choice after confirmed persistence.
3571
+ * @throws {RemoteError} validation, authorization, availability, cancellation,
3572
+ * or subagent/model-selection-unconfirmed when the durable outcome is unknown.
3573
+ */
3574
+ async selectModelByUser(request, signal) {
3575
+ validateControlRequest("subagent.selectModel", request);
3576
+ const selection = {
3577
+ provider: request.provider,
3578
+ model: request.model,
3579
+ ...request.reasoningEffort === void 0 ? {} : { reasoningEffort: brandString(request.reasoningEffort) }
3580
+ };
3581
+ try {
3582
+ await this.assertListedModel(selection);
3583
+ return { selected: await this.selectModel(request.childSessionId, selection, { kind: "user" }, signal) };
3584
+ } catch (error) {
3585
+ return rejectModelSelection(error, request.childSessionId, signal);
3586
+ }
3587
+ }
3588
+ /** Refuse a user choice that the provider catalog does not list. */
3589
+ async assertListedModel(selection) {
3590
+ const llm = this.ctx.get("llm");
3591
+ if (llm === void 0) throw new SubagentError("cannot validate the selected subagent model because the LLM service is unavailable", "MODEL_UNAVAILABLE");
3592
+ if (!await llm.isModelInCatalog(selection.provider, selection.model)) throw new SubagentError(`provider "${selection.provider}" does not list model "${selection.model}"`, "MODEL_UNAVAILABLE");
3593
+ }
3594
+ /**
3277
3595
  * Register a provider under its name. Registration is effect-scoped and HMR
3278
3596
  * safe; removing a provider blocks new starts but does not revoke runs that
3279
3597
  * were already returned to their holders. Providers without either execution