@deepseek-ai/dsh-subagent 0.1.2-alpha.3 → 0.1.2-alpha.4

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.
package/lib/index.js CHANGED
@@ -7,9 +7,9 @@ import { z } from "zod";
7
7
  import { HarnessError, ReasoningEffortId, boundContextSummary, contentHasImage, createUserMessage, errorChain } from "@deepseek-ai/dsh-llm";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import { foldConsumedWork } from "@deepseek-ai/dsh-agent";
10
+ import { Session, SessionLogOffset, SessionSeq } from "@deepseek-ai/dsh-session";
10
11
  import { brandString } from "@deepseek-ai/dsh-brand";
11
12
  import { snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
12
- import { Session } from "@deepseek-ai/dsh-session";
13
13
  import { accessSync, constants, statSync } from "node:fs";
14
14
  import { isAbsolute, resolve } from "node:path";
15
15
  //#region lib/types/error.js
@@ -327,16 +327,16 @@ function createActivationObserver(emit, provider, childId, parent) {
327
327
  id: childId,
328
328
  local: true
329
329
  };
330
- let boundary = 0;
330
+ let boundary = SessionLogOffset(0);
331
331
  let captured = { stopReason: "completed" };
332
332
  const terminal = (failure) => failure === void 0 ? captured : { stopReason: "error" };
333
333
  return {
334
334
  start: (child) => {
335
- boundary = child.session.events.length;
335
+ boundary = child.session.seq;
336
336
  emit("subagent/start", identity, parent);
337
337
  },
338
338
  capture: (child) => {
339
- const own = child.session.events.slice(boundary);
339
+ const own = child.session.snapshotEvents(boundary);
340
340
  const output = finalAssistantOutput(own);
341
341
  captured = {
342
342
  stopReason: epochStopReason(own),
@@ -653,19 +653,19 @@ function resolveChildAgentOptions(parent, requested, childDepth) {
653
653
  * child never had.
654
654
  * @param parent - the delegating parent agent.
655
655
  * @param childDepth - the resolved delegation depth to persist.
656
- * @param lineageSeedLength - how many leading events came from the parent's log.
656
+ * @param isSeeded - whether this child inherits a parent-log prefix, including an explicitly empty one.
657
657
  * @returns the `meta` for `ctx.agents.create()`.
658
658
  */
659
- function childSessionMeta(parent, childDepth, lineageSeedLength) {
659
+ function childSessionMeta(parent, childDepth, isSeeded) {
660
660
  const parentHeader = parent.session.header;
661
661
  const agentPreset = parent.ctx.get("agentPresets")?.composedPreset(parent.ctx);
662
662
  return {
663
663
  ...parentHeader.cwd !== void 0 ? { cwd: parentHeader.cwd } : {},
664
664
  ...agentPreset === void 0 ? {} : { agentPreset },
665
665
  parentSession: parentHeader.id,
666
+ isSeeded,
666
667
  origin: "subagent",
667
- delegationDepth: childDepth,
668
- ...lineageSeedLength > 0 ? { seedLength: lineageSeedLength } : {}
668
+ delegationDepth: childDepth
669
669
  };
670
670
  }
671
671
  /**
@@ -767,9 +767,32 @@ function appendDelegatedPolicyOverrides(childSession, overrides) {
767
767
  function seedDescriptorTurn(childId, seed, descriptor) {
768
768
  const staged = Session.create(childId, seed);
769
769
  staged.append("subagent/descriptor", descriptor);
770
- return [...staged.events];
770
+ return staged.snapshotEvents();
771
771
  }
772
772
  //#endregion
773
+ //#region lib/types/internal.js
774
+ /**
775
+ * Continuation integration markers and host adapters outside the public
776
+ * Service Definition and model-facing Agent messaging contract.
777
+ * @module @deepseek-ai/dsh-subagent/internal
778
+ */
779
+ /** Process-stable identity carried only by the standard adjacent-Agent messaging tool. */
780
+ const adjacentAgentSendMessageTool = Symbol.for("dsh.subagent.adjacentAgentSendMessageTool");
781
+ /**
782
+ * Test whether one visible definition is the standard adjacent-Agent messaging tool.
783
+ * @param definition - the scope-resolved `send_message` candidate.
784
+ * @returns whether the definition carries the internal standard-tool identity.
785
+ */
786
+ function isAdjacentAgentSendMessageTool(definition) {
787
+ return definition !== void 0 && definition[adjacentAgentSendMessageTool] === true;
788
+ }
789
+ /**
790
+ * Process-stable symbol-keyed Queue delivery shared by the bundled runtime
791
+ * entry and this unbundled internal subpath.
792
+ * @internal
793
+ */
794
+ const queueSubagentPrompt = Symbol.for("dsh.subagent.queuePrompt");
795
+ //#endregion
773
796
  //#region lib/types/continuation.js
774
797
  /**
775
798
  * Internal continuable-subagent manager: stable child ids, descriptor
@@ -861,6 +884,32 @@ var __disposeResources$1 = (function(SuppressedError) {
861
884
  function disposalOf(activation) {
862
885
  return activation.disposal;
863
886
  }
887
+ /** Build durable attribution for one adjacent-Agent message. */
888
+ function agentMessageSource(sender) {
889
+ return {
890
+ kind: "agent-message",
891
+ form: "relay",
892
+ senderSessionId: sender.id
893
+ };
894
+ }
895
+ /** Build the model-visible and durable representation of one adjacent-Agent message. */
896
+ function agentMessage(sender, content) {
897
+ return createUserMessage({
898
+ content: [{
899
+ type: "text",
900
+ text: `Agent ${sender.id} sent a message:`
901
+ }, ...content],
902
+ source: agentMessageSource(sender)
903
+ });
904
+ }
905
+ /** Append adjacent-Agent return guidance to a continuable child's initial task. */
906
+ function continuableInitialPrompt(parentId, prompt) {
907
+ const encodedParentId = JSON.stringify(parentId);
908
+ return [...prompt, {
909
+ type: "text",
910
+ text: `Your parent agent id is ${encodedParentId}. Before you finish, send your result to that agent with send_message({ agent_id: ${encodedParentId}, message: "<self-contained result>" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn.`
911
+ }];
912
+ }
864
913
  /**
865
914
  * One line telling a parent that a background child is finished and why, in
866
915
  * the parent's own task vocabulary.
@@ -910,7 +959,6 @@ var ChildLock = class {
910
959
  var SubagentContinuationManager = class {
911
960
  ctx;
912
961
  host;
913
- setupRegistry;
914
962
  /** Child session id → its live Activation. Process-local, never durable. */
915
963
  activations = /* @__PURE__ */ new Map();
916
964
  /** Materializations admitted before drain, tracked through publication or rollback. */
@@ -926,10 +974,9 @@ var SubagentContinuationManager = class {
926
974
  */
927
975
  closingScopes = /* @__PURE__ */ new Map();
928
976
  draining = false;
929
- constructor(ctx, host, setupRegistry) {
977
+ constructor(ctx, host) {
930
978
  this.ctx = ctx;
931
979
  this.host = host;
932
- this.setupRegistry = setupRegistry;
933
980
  const scope = ctx.plugin(function activationOwner() {});
934
981
  this.ownerCtx = scope.ctx;
935
982
  ctx.on("agent/disposed", ({ agent }) => {
@@ -986,7 +1033,7 @@ var SubagentContinuationManager = class {
986
1033
  });
987
1034
  spec.signal.throwIfAborted();
988
1035
  this.assertAdmitting(parent);
989
- const lineageSeedLength = prepared.seed?.length ?? 0;
1036
+ const inheritedEventCount = SessionLogOffset(prepared.seed?.length ?? 0);
990
1037
  const seed = seedDescriptorTurn(childId, prepared.seed, descriptor);
991
1038
  return {
992
1039
  childId,
@@ -1007,7 +1054,8 @@ var SubagentContinuationManager = class {
1007
1054
  parent,
1008
1055
  create: {
1009
1056
  seed,
1010
- meta: childSessionMeta(parent, childDepth, lineageSeedLength),
1057
+ meta: childSessionMeta(parent, childDepth, prepared.seed !== void 0),
1058
+ inheritedEventCount,
1011
1059
  delegatedPolicies
1012
1060
  },
1013
1061
  agentOptions,
@@ -1017,7 +1065,11 @@ var SubagentContinuationManager = class {
1017
1065
  },
1018
1066
  signal: spec.signal
1019
1067
  });
1020
- return this.submitMaterialized(activation, request.prompt, { kind: "user" }, parent, spec.signal);
1068
+ return this.submitMaterialized(activation, isAdjacentAgentSendMessageTool(this.ctx.get("tools")?.get("send_message", activation.handle.agent)) ? continuableInitialPrompt(parent.id, request.prompt) : request.prompt, {
1069
+ source: { kind: "user" },
1070
+ signal: spec.signal,
1071
+ delivery: "queue"
1072
+ }, parent);
1021
1073
  })
1022
1074
  };
1023
1075
  }
@@ -1026,23 +1078,50 @@ var SubagentContinuationManager = class {
1026
1078
  if (this.ctx.agents.get(childId) !== void 0 || this.ctx.get("sessions")?.get(childId) !== void 0) throw new SubagentError(`subagent "${childId}" already exists`, "DUPLICATE_CHILD");
1027
1079
  }
1028
1080
  /**
1029
- * Deliver one later message to a known continuable child as its next FIFO
1030
- * turn. Routing depends only on Activation residency: a `running` Activation
1031
- * enqueues, a `waiting` one wakes the same Agent, and an absent one
1032
- * cold-resumes a new Activation from the persisted Session. The Agent inbox
1033
- * is the only queue, so every accepted message has one observable order.
1034
- *
1035
- * The caller signal owns lookup, materialization, and admission only until
1036
- * inbox acceptance; afterwards the accepted turn cannot be cancelled through
1037
- * this service.
1038
- * @param parent - the exact live direct parent authorizing this delivery.
1039
- * @param childId - the durable child session id.
1040
- * @param content - the user-role content to deliver.
1041
- * @param options - the message source fields and caller cancellation.
1081
+ * Deliver one model-authored message to a direct continuable child or to the
1082
+ * sender's direct parent. Both directions use Steer: a running target admits
1083
+ * the message at its nearest step boundary, while an idle target starts a
1084
+ * turn. A missing direct child cold-resumes through the ordinary continuation
1085
+ * lifecycle. The caller signal owns the operation only until inbox acceptance.
1086
+ * @param sender - exact live Agent authorizing and originating the message.
1087
+ * @param targetId - durable direct-parent or direct-child session id.
1088
+ * @param content - model-authored content to deliver.
1089
+ * @param options - caller cancellation before acceptance.
1090
+ * @returns the accepted message's inbox id.
1091
+ * @throws when adjacency, availability, or admission rejects delivery.
1092
+ */
1093
+ async sendMessage(sender, targetId, content, options) {
1094
+ if (this.ctx.agents.get(sender.id) !== sender) throw new SubagentError("message delivery requires the exact live sender agent", "UNAUTHORIZED");
1095
+ this.assertAdmitting(sender);
1096
+ const senderActivation = this.activations.get(sender.id);
1097
+ if (senderActivation !== void 0 && senderActivation.handle.agent === sender && senderActivation.parentSession === targetId) {
1098
+ options.signal.throwIfAborted();
1099
+ return this.sendToParent(senderActivation, sender, content);
1100
+ }
1101
+ if (sender.session.header.parentSession === targetId) throw new SubagentError(`agent "${sender.id}" is not a resident continuable child and cannot send to parent "${targetId}"`, "UNAUTHORIZED");
1102
+ return this.deliverToChild(sender, targetId, content, {
1103
+ signal: options.signal,
1104
+ delivery: "steer"
1105
+ });
1106
+ }
1107
+ /**
1108
+ * Queue one human-authored prompt as a distinct direct-child turn.
1109
+ * @param parent - exact live direct parent authorizing delivery.
1110
+ * @param childId - durable direct-child session id.
1111
+ * @param content - human-authored content to deliver.
1112
+ * @param source - durable host-protocol provenance.
1113
+ * @param signal - caller cancellation before inbox acceptance.
1042
1114
  * @returns the accepted message's inbox id.
1043
- * @throws when parent authority, availability, or admission rejects the delivery.
1044
1115
  */
1045
- async followup(parent, childId, content, options) {
1116
+ async queuePrompt(parent, childId, content, source, signal) {
1117
+ return this.deliverToChild(parent, childId, content, {
1118
+ source,
1119
+ signal,
1120
+ delivery: "queue"
1121
+ });
1122
+ }
1123
+ /** Route one parent-originated delivery through residency and cold resume. */
1124
+ async deliverToChild(parent, childId, content, options) {
1046
1125
  this.assertAdmitting(parent);
1047
1126
  while (true) {
1048
1127
  const live = await this.locks.run(childId, async () => {
@@ -1061,7 +1140,7 @@ var SubagentContinuationManager = class {
1061
1140
  return;
1062
1141
  }
1063
1142
  }
1064
- return this.submitAdmitted(activation, content, options.source, parent, options.signal);
1143
+ return this.submitAdmitted(activation, content, options, parent);
1065
1144
  });
1066
1145
  /* v8 ignore start -- only the lost-cutoff arm above returns undefined, so only that
1067
1146
  * race reaches the retry below, which then cold-resumes a new Activation. */
@@ -1105,59 +1184,17 @@ var SubagentContinuationManager = class {
1105
1184
  if (activation.disposal !== void 0) return;
1106
1185
  activation.handle.agent.cancel(authority.kind === "user" ? { kind: "user" } : { kind: "parent" }, { keepInbox: true });
1107
1186
  }
1108
- /**
1109
- * Deliver explicitly selected content from one resident continuable child to
1110
- * its durable direct parent. Sender authorization, parent resolution, and
1111
- * send acceptance share one no-await span. Reporting neither concludes the
1112
- * child's turn nor changes its Activation lifetime.
1113
- * @param child - exact live reporting child; this is the authority credential.
1114
- * @param content - selected model-facing content.
1115
- * @param options - scheduling policy and pre-acceptance cancellation.
1116
- * @returns the stable identity of the message accepted by the parent.
1117
- * @throws {SubagentError} when the sender is unauthorized, the parent is not
1118
- * live, or continuation admission is closing.
1119
- */
1120
- async reportFrom(child, content, options) {
1121
- options.signal.throwIfAborted();
1122
- this.assertAdmitting(child);
1123
- const activation = this.authorizeReporter(child);
1124
- const parent = this.resolveReportParent(child);
1125
- return this.deliverReport(activation, parent, content, options.delivery);
1126
- }
1127
- /** Authorize only the exact Agent of one resident Activation. */
1128
- authorizeReporter(child) {
1129
- const activation = this.activations.get(child.id);
1130
- if (activation === void 0 || activation.handle.agent !== child) throw new SubagentError(`agent "${child.id}" is not a live continuable subagent and cannot report`, "UNAUTHORIZED");
1131
- /* v8 ignore next 6 -- only a synchronous re-entrant disposer can open this
1132
- * transaction between exact-agent authorization and this no-await cutoff. */
1133
- if (activation.disposal !== void 0) throw new SubagentError(`subagent "${child.id}" activation is being disposed; the report was not delivered`, "ACTIVATION_CLOSING");
1134
- return activation;
1135
- }
1136
- /** Resolve the reporting child's live direct parent from durable lineage. */
1137
- resolveReportParent(child) {
1138
- const parentId = child.session.header.parentSession;
1139
- /* v8 ignore next -- every continuation-managed child has direct-parent metadata. */
1140
- const parent = parentId === void 0 ? void 0 : this.ctx.agents.get(parentId);
1141
- if (parent === void 0) throw new SubagentError("direct parent is not live; report was not delivered", "PARENT_UNAVAILABLE");
1142
- return parent;
1143
- }
1144
- /** Deliver one framed report through the selected parent scheduling preset. */
1145
- deliverReport(activation, parent, content, delivery) {
1146
- const message = createUserMessage({
1147
- content: [{
1148
- type: "text",
1149
- text: `Background subagent ${activation.childId} reported:`
1150
- }, ...content],
1151
- source: {
1152
- kind: "subagent-report",
1153
- form: "relay",
1154
- senderSessionId: activation.childId
1155
- }
1156
- });
1157
- if (delivery === "next-step") this.sendWaking(parent, message, () => {
1158
- this.sendReport(parent, message, delivery);
1187
+ /** Deliver one resident continuable child's message to its live direct parent. */
1188
+ sendToParent(activation, sender, content) {
1189
+ /* v8 ignore next 6 -- only synchronous re-entrant teardown can open this
1190
+ * transaction between exact-agent authorization and this no-await span. */
1191
+ if (activation.disposal !== void 0) throw new SubagentError(`subagent "${sender.id}" activation is being disposed; the message was not delivered`, "ACTIVATION_CLOSING");
1192
+ const parent = this.ctx.agents.get(activation.parentSession);
1193
+ if (parent === void 0) throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE");
1194
+ const message = agentMessage(sender, content);
1195
+ this.sendWaking(parent, message, () => {
1196
+ this.sendAgentMessage(parent, message);
1159
1197
  });
1160
- else this.sendReport(parent, message, delivery);
1161
1198
  return message.id;
1162
1199
  }
1163
1200
  /**
@@ -1174,13 +1211,12 @@ var SubagentContinuationManager = class {
1174
1211
  if (parentActivation !== void 0 && parentActivation.handle.agent === parent) this.admitWaking(parentActivation, message.id, send);
1175
1212
  else send();
1176
1213
  }
1177
- /** Send one report while translating only the parent's own rejection. */
1178
- sendReport(parent, message, delivery) {
1214
+ /** Send one Agent message while translating only the target's own rejection. */
1215
+ sendAgentMessage(parent, message) {
1179
1216
  try {
1180
- if (delivery === "next-step") parent.steer(message);
1181
- else parent.inject(message);
1217
+ parent.steer(message);
1182
1218
  } catch (error) {
1183
- throw new SubagentError("direct parent is not live; report was not delivered", "PARENT_UNAVAILABLE", { cause: error });
1219
+ throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE", { cause: error });
1184
1220
  }
1185
1221
  }
1186
1222
  /**
@@ -1357,8 +1393,8 @@ var SubagentContinuationManager = class {
1357
1393
  const source = __addDisposableResource$1(env_1, observation, false);
1358
1394
  this.assertAdmitting(parent);
1359
1395
  this.authorizeLineage(parent, childId, source.header.parentSession);
1360
- const descriptor = foldSubagentDescriptor(source.events.slice(source.header.seedLength ?? 0));
1361
- if (descriptor === void 0 || descriptor.mode !== "continuable") throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; do not retry send_message with this id`, "NOT_RESUMABLE");
1396
+ const descriptor = foldSubagentDescriptor(source.events.slice(source.inheritedEventCount));
1397
+ 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");
1362
1398
  let activation;
1363
1399
  try {
1364
1400
  activation = await this.materialize({
@@ -1381,7 +1417,7 @@ var SubagentContinuationManager = class {
1381
1417
  if (error instanceof SubagentError) throw error;
1382
1418
  throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
1383
1419
  }
1384
- return await this.submitMaterialized(activation, content, options.source, parent, options.signal);
1420
+ return await this.submitMaterialized(activation, content, options, parent);
1385
1421
  } catch (e_1) {
1386
1422
  env_1.error = e_1;
1387
1423
  env_1.hasError = true;
@@ -1393,18 +1429,17 @@ var SubagentContinuationManager = class {
1393
1429
  * Submit to a freshly materialized Activation or roll it back completely.
1394
1430
  * @param activation - the just-published Activation to admit or release.
1395
1431
  * @param content - the initial or resumed message content.
1396
- * @param source - durable fields naming who supplied the accepted message.
1432
+ * @param options - durable source, scheduling, and pre-acceptance cancellation.
1397
1433
  * @param parent - the live direct parent authorizing admission.
1398
- * @param signal - caller cancellation owning admission until acceptance.
1399
1434
  * @returns the accepted inbox message id.
1400
1435
  */
1401
- async submitMaterialized(activation, content, source, parent, signal) {
1436
+ async submitMaterialized(activation, content, options, parent) {
1402
1437
  try {
1403
1438
  if (contentHasImage(content)) {
1404
- await this.assertImageCapable(activation.handle.agent, signal);
1439
+ await this.assertImageCapable(activation.handle.agent, options.signal);
1405
1440
  if (activation.disposal !== void 0) throw new SubagentError(`subagent "${activation.childId}" is closing`, "ACTIVATION_CLOSING");
1406
1441
  }
1407
- return this.submitAdmitted(activation, content, source, parent, signal);
1442
+ return this.submitAdmitted(activation, content, options, parent);
1408
1443
  } catch (error) {
1409
1444
  /* v8 ignore next -- rollback disposal failures must not mask the
1410
1445
  * pre-acceptance signal, drain, or lifecycle failure. */
@@ -1465,7 +1500,6 @@ var SubagentContinuationManager = class {
1465
1500
  const setup = (childCtx) => {
1466
1501
  if (create !== void 0) appendDelegatedPolicyOverrides(childCtx.agent.session, create.delegatedPolicies);
1467
1502
  applyChildComposition(childCtx, parent, inputs.composition);
1468
- return this.setupRegistry.apply(childCtx);
1469
1503
  };
1470
1504
  const observer = this.host.observeActivation(provider, childId, parent);
1471
1505
  const handle = create === void 0 ? await this.ownerCtx.agents.resume({
@@ -1477,6 +1511,7 @@ var SubagentContinuationManager = class {
1477
1511
  sessionId: childId,
1478
1512
  meta: create.meta,
1479
1513
  seed: create.seed,
1514
+ inheritedEventCount: create.inheritedEventCount,
1480
1515
  agentOptions: inputs.agentOptions,
1481
1516
  signal: inputs.signal,
1482
1517
  setup
@@ -1558,14 +1593,15 @@ var SubagentContinuationManager = class {
1558
1593
  * inbox id. Acceptance is the operation's success boundary; the manager owns
1559
1594
  * the Activation independently afterwards.
1560
1595
  */
1561
- submit(activation, content, source, parent) {
1596
+ submit(activation, content, options, parent) {
1562
1597
  this.acquireOwnership(parent, activation.childId);
1563
- const message = createUserMessage({
1598
+ const message = options.delivery === "steer" ? agentMessage(parent, content) : createUserMessage({
1564
1599
  content,
1565
- source
1600
+ source: options.source
1566
1601
  });
1567
1602
  const accepted = this.admitWaking(activation, message.id, () => {
1568
- activation.handle.agent.followup(message);
1603
+ if (options.delivery === "steer") activation.handle.agent.steer(message);
1604
+ else activation.handle.agent.followup(message);
1569
1605
  });
1570
1606
  activation.announced = true;
1571
1607
  return accepted;
@@ -1593,14 +1629,14 @@ var SubagentContinuationManager = class {
1593
1629
  * manager drain, or Activation disposal that wins before this synchronous
1594
1630
  * span rejects without inbox acceptance.
1595
1631
  */
1596
- submitAdmitted(activation, content, source, parent, signal) {
1597
- signal.throwIfAborted();
1632
+ submitAdmitted(activation, content, options, parent) {
1633
+ options.signal.throwIfAborted();
1598
1634
  this.assertAdmitting(parent);
1599
1635
  /* v8 ignore next 6 -- only a synchronous re-entrant disposer can change
1600
1636
  * this field between the caller's live check and this no-await boundary. */
1601
1637
  if (disposalOf(activation) !== void 0) throw new SubagentError(`subagent "${activation.childId}" activation is being disposed; the message was not accepted`, "ACTIVATION_CLOSING");
1602
1638
  this.authorizeLineage(parent, activation.childId, activation.handle.agent.session.header.parentSession);
1603
- return this.submit(activation, content, source, parent);
1639
+ return this.submit(activation, content, options, parent);
1604
1640
  }
1605
1641
  /**
1606
1642
  * Authorize one operation against the durable direct-parent lineage. Other
@@ -1786,134 +1822,6 @@ var SubagentContinuationManager = class {
1786
1822
  }
1787
1823
  };
1788
1824
  //#endregion
1789
- //#region lib/types/activation-setup-registry.js
1790
- /**
1791
- * Internal registry of deployment capabilities composed into every continuable
1792
- * child's unpublished creation context.
1793
- *
1794
- * A contribution grants a child-scoped capability without teaching the
1795
- * continuation manager which capabilities exist. The manager owns residency;
1796
- * this registry owns the join between plugin lifetime, unpublished setup, and
1797
- * Activation disposal, so no installation outlives either owner and no removed
1798
- * contribution can be installed after revocation reports completion.
1799
- *
1800
- * @module @deepseek-ai/dsh-subagent/activation-setup-registry
1801
- */
1802
- /** Re-read mutable removal state after a contribution may have revoked itself. */
1803
- function isRemoved(registration) {
1804
- return registration.removed;
1805
- }
1806
- /**
1807
- * Owns continuable-child setup registrations, installations, rollback, child
1808
- * cleanup, and immediate live revocation.
1809
- */
1810
- var SubagentActivationSetupRegistry = class {
1811
- /** Live contributions in installation order. */
1812
- registrations = /* @__PURE__ */ new Set();
1813
- /** Child context to its live installations. */
1814
- byChild = /* @__PURE__ */ new Map();
1815
- /**
1816
- * Register one contribution.
1817
- * @param contribution - synchronous child-scope installer.
1818
- * @returns an idempotent registration undo.
1819
- * @throws after attempting every installation when any disposer fails.
1820
- */
1821
- register(contribution) {
1822
- const registration = {
1823
- contribution,
1824
- removed: false,
1825
- installations: /* @__PURE__ */ new Set()
1826
- };
1827
- this.registrations.add(registration);
1828
- return () => {
1829
- if (registration.removed) return;
1830
- registration.removed = true;
1831
- this.registrations.delete(registration);
1832
- this.releaseAll([...registration.installations], "contribution removal");
1833
- };
1834
- }
1835
- /**
1836
- * Install every live contribution into one unpublished child context.
1837
- * @param childCtx - the child's unpublished scoped context.
1838
- * @returns the provisioning commit consumed at Agent publication.
1839
- */
1840
- apply(childCtx) {
1841
- const state = {
1842
- installations: [],
1843
- invalidated: false
1844
- };
1845
- try {
1846
- for (const registration of [...this.registrations]) {
1847
- /* v8 ignore next -- only a synchronous re-entrant revocation of an
1848
- * already-snapshotted registration reaches this guard. */
1849
- if (registration.removed) continue;
1850
- const installation = {
1851
- registration,
1852
- childCtx,
1853
- dispose: registration.contribution(childCtx),
1854
- released: false,
1855
- transaction: state
1856
- };
1857
- registration.installations.add(installation);
1858
- state.installations.push(installation);
1859
- let indexed = this.byChild.get(childCtx);
1860
- if (indexed === void 0) {
1861
- indexed = /* @__PURE__ */ new Set();
1862
- this.byChild.set(childCtx, indexed);
1863
- }
1864
- indexed.add(installation);
1865
- if (isRemoved(registration)) this.release(installation);
1866
- }
1867
- } catch (error) {
1868
- try {
1869
- this.releaseAll([...state.installations], "setup rollback");
1870
- } catch (releaseFailure) {}
1871
- throw error;
1872
- }
1873
- childCtx.effect(() => () => {
1874
- this.releaseChild(childCtx);
1875
- }, "subagents.activationSetup()");
1876
- return { commit: () => {
1877
- if (state.invalidated) throw new SubagentError("a continuable-subagent setup contribution was revoked while this child was being built; the child was not established", "ACTIVATION_SETUP_REVOKED");
1878
- for (const installation of state.installations) installation.transaction = void 0;
1879
- } };
1880
- }
1881
- /** Release every remaining installation owned by one disposed child scope. */
1882
- releaseChild(childCtx) {
1883
- const indexed = this.byChild.get(childCtx) ?? [];
1884
- this.releaseAll([...indexed], "child scope disposal");
1885
- }
1886
- /**
1887
- * Release a batch completely before reporting disposer failures.
1888
- * @param installations - records to release.
1889
- * @param during - operation name for diagnostics.
1890
- */
1891
- releaseAll(installations, during) {
1892
- const failures = [];
1893
- for (const installation of installations) try {
1894
- this.release(installation);
1895
- } catch (error) {
1896
- failures.push(error);
1897
- }
1898
- if (failures.length === 0) return;
1899
- throw new SubagentError(`continuable-subagent setup ${during} failed to release ${failures.length} installation(s): ` + failures.map((failure) => errorChain(failure)).join("; "), "ACTIVATION_SETUP_RELEASE_FAILED");
1900
- }
1901
- /** Drop one installation from both indices and dispose it exactly once. */
1902
- release(installation) {
1903
- if (installation.released) return;
1904
- installation.released = true;
1905
- installation.registration.installations.delete(installation);
1906
- const indexed = this.byChild.get(installation.childCtx);
1907
- /* v8 ignore next 4 -- every live installation is indexed until this method removes it. */
1908
- if (indexed !== void 0) {
1909
- indexed.delete(installation);
1910
- if (indexed.size === 0) this.byChild.delete(installation.childCtx);
1911
- }
1912
- if (installation.transaction !== void 0) installation.transaction.invalidated = true;
1913
- installation.dispose();
1914
- }
1915
- };
1916
- //#endregion
1917
1825
  //#region lib/types/list-children.js
1918
1826
  /**
1919
1827
  * Read-only enumeration of durable subagent children and descendant trees
@@ -1921,9 +1829,10 @@ var SubagentActivationSetupRegistry = class {
1921
1829
  * corpus; each child's mode/label is the registered `subagent` projection
1922
1830
  * unit's value, resolved
1923
1831
  * down a three-rung ladder: the registry's watermark cache for a live child,
1924
- * a durable projection-cache row when it serves an own-suffix identity (the
1925
- * seq gate), and one shared Session observation otherwise, validated against
1926
- * the enumerated lifecycle. The projection fold is the single classification
1832
+ * an unseeded durable projection-cache row, and one shared Session observation
1833
+ * otherwise. A seeded header deliberately lacks its exact inherited cut, so
1834
+ * it takes the body-bearing observation path before classifying an identity.
1835
+ * The projection fold is the single classification
1927
1836
  * authority — this module parses no descriptor
1928
1837
  * itself. Absent persistence, enumeration is live-only: a cold child is
1929
1838
  * unreachable for resume anyway, so its absence is capability absence, not an
@@ -2001,8 +1910,8 @@ const COLD_READ_CONCURRENCY = 4;
2001
1910
  * live-preferred merge of `ctx.sessions` and optional session persistence,
2002
1911
  * serving each identity from the `subagent` projection unit: the registry's
2003
1912
  * watermark snapshot for a live child; for a cold one, a durable
2004
- * projection-cache read when it serves an own-suffix identity (the seq gate),
2005
- * else one bounded-concurrency shared Session observation.
1913
+ * projection-cache read for an unseeded lifecycle, else one bounded-concurrency
1914
+ * shared Session observation carrying the exact inherited cut.
2006
1915
  * @see SubagentRuntime.listChildren for the public cancellation and failure contract.
2007
1916
  * @param ctx - context carrying the session store, the projection registry,
2008
1917
  * optional persistence, and the optional projection cache.
@@ -2105,7 +2014,7 @@ async function resolveCandidateRows(candidates, listing, signal) {
2105
2014
  };
2106
2015
  return;
2107
2016
  }
2108
- if (identity === void 0 || identity === null || identity.seq < (candidate.header.seedLength ?? 0)) return;
2017
+ if (identity === void 0 || identity === null || !candidate.live.isOwnSeq(identity.seq)) return;
2109
2018
  rows[index] = childRow(childId, identity, "running", subagentParents.has(childId));
2110
2019
  });
2111
2020
  if (coldReads.length > 0) {
@@ -2155,9 +2064,8 @@ function compareCorpusRecords(a, b) {
2155
2064
  return a.header.createdAt - b.header.createdAt || a.header.id.localeCompare(b.header.id);
2156
2065
  }
2157
2066
  /**
2158
- * Resolve one cold candidate down the remaining ladder: a durable
2159
- * projection-cache row when it serves an own-suffix identity (the seq gate),
2160
- * otherwise one shared Session observation. An absent or transiently failed
2067
+ * Resolve one cold candidate down the remaining ladder: an unseeded durable
2068
+ * projection-cache row, otherwise one shared Session observation. An absent or transiently failed
2161
2069
  * observation is one `unavailable` row retried on the next listing; an observation
2162
2070
  * source naming another lifecycle, and a
2163
2071
  * settled log the fold cannot identify — or that makes any registered unit
@@ -2171,14 +2079,14 @@ async function resolveColdIdentity(query, cache, header, hasChildren, signal) {
2171
2079
  };
2172
2080
  try {
2173
2081
  const childId = header.id;
2174
- if (cache !== void 0) {
2082
+ if (cache !== void 0 && !header.isSeeded) {
2175
2083
  let cached;
2176
2084
  try {
2177
- cached = cache.cachedSnapshot(header, ["subagent"])?.values.subagent;
2085
+ cached = cache.cachedSnapshot(header, SessionLogOffset(0), ["subagent"])?.values.subagent;
2178
2086
  } catch {
2179
2087
  cached = void 0;
2180
2088
  }
2181
- if (cached !== void 0 && cached !== null && cached.seq >= (header.seedLength ?? 0)) return childRow(childId, cached, "inactive", hasChildren);
2089
+ if (cached !== void 0 && cached !== null) return childRow(childId, cached, "inactive", hasChildren);
2182
2090
  }
2183
2091
  assertListingNotCancelled(signal);
2184
2092
  let observation;
@@ -2200,7 +2108,7 @@ async function resolveColdIdentity(query, cache, header, hasChildren, signal) {
2200
2108
  reason: "corrupt"
2201
2109
  };
2202
2110
  const identity = ownedObservation.projections?.values.subagent;
2203
- if (identity === void 0 || identity === null || identity.seq < (header.seedLength ?? 0)) return {
2111
+ if (identity === void 0 || identity === null || identity.seq < ownedObservation.inheritedEventCount) return {
2204
2112
  kind: "diagnostic",
2205
2113
  id: childId,
2206
2114
  reason: "corrupt"
@@ -2238,7 +2146,7 @@ const LIFECYCLE_WITNESS_KEYS = [
2238
2146
  "createdAt",
2239
2147
  "cwd",
2240
2148
  "parentSession",
2241
- "seedLength",
2149
+ "isSeeded",
2242
2150
  "delegationDepth",
2243
2151
  "origin",
2244
2152
  "agentPreset"
@@ -2349,11 +2257,11 @@ const subagentTimingProjectionDefinition = {
2349
2257
  const identityValueSchema = z.discriminatedUnion("mode", [z.object({
2350
2258
  mode: z.literal("one-shot"),
2351
2259
  label: z.string().optional(),
2352
- seq: z.number().int().nonnegative()
2260
+ seq: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
2353
2261
  }).strict(), z.object({
2354
2262
  mode: z.literal("continuable"),
2355
2263
  label: z.string(),
2356
- seq: z.number().int().nonnegative()
2264
+ seq: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
2357
2265
  }).strict()]);
2358
2266
  const identitySchema = identityValueSchema.nullable();
2359
2267
  const identityStateSchema = z.object({ identity: identityValueSchema.optional() }).strict();
@@ -2680,8 +2588,8 @@ async function settleRun(run) {
2680
2588
  *
2681
2589
  * Public operations express caller intent: `start` returns one published owned
2682
2590
  * one-shot run, `startContinuable` establishes a durable continuable child, and
2683
- * `followup` delivers later content without exposing whether the child is
2684
- * resident. Continuable children never become a {@link SubagentRun}: the
2591
+ * `sendMessage` steers between adjacent Agents without exposing whether a child
2592
+ * is resident. Continuable children never become a {@link SubagentRun}: the
2685
2593
  * continuation manager holds their `AgentHandle` directly and orders every turn
2686
2594
  * through the child's own inbox, so providers contribute only the detached
2687
2595
  * creation spec and see no handle, turn, or teardown. Child and descendant
@@ -2788,8 +2696,6 @@ let SubagentRuntime = (() => {
2788
2696
  }
2789
2697
  providers = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map());
2790
2698
  continuations;
2791
- /** Deployment contributions composed into unpublished continuable children. */
2792
- setupRegistry = new SubagentActivationSetupRegistry();
2793
2699
  /**
2794
2700
  * The contained lifecycle-edge publisher. Built here because scoped dispatch
2795
2701
  * keys its carrier by this exact service instance, whose own context filter
@@ -2803,7 +2709,7 @@ let SubagentRuntime = (() => {
2803
2709
  const manager = new SubagentContinuationManager(childCtx, {
2804
2710
  prepareContinuable: (name, request) => this.prepareContinuable(name, request),
2805
2711
  observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent)
2806
- }, this.setupRegistry);
2712
+ });
2807
2713
  this.continuations = manager;
2808
2714
  childCtx.effect(() => () => {
2809
2715
  /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
@@ -2828,22 +2734,35 @@ let SubagentRuntime = (() => {
2828
2734
  return this.requireContinuations().startContinuable(spec);
2829
2735
  }
2830
2736
  /**
2831
- * Deliver one later message to a continuable child as its next FIFO turn. A
2832
- * resident child's Agent inbox accepts it directly (waking a `waiting`
2833
- * Activation), while an absent one is cold-resumed from its persisted
2834
- * Session. The Agent inbox is the only queue, so every accepted message has
2835
- * one observable order.
2836
- * @param parent - the exact live direct parent authorizing this delivery.
2837
- * @param childId - durable child session id.
2838
- * @param content - user-role content to deliver.
2839
- * @param options - the message source fields and caller cancellation, which stops the
2840
- * operation only before inbox acceptance.
2737
+ * Steer one model-authored message to the sender's direct parent or direct
2738
+ * continuable child. A running target admits it at the nearest step boundary;
2739
+ * an idle target starts a turn, and an absent direct child cold-resumes from
2740
+ * persistence. The service derives durable sender attribution from the exact
2741
+ * live sender. Caller cancellation stops only pre-acceptance work.
2742
+ * @param sender - exact live Agent authorizing and originating the message.
2743
+ * @param targetId - durable direct-parent or direct-child session id.
2744
+ * @param content - model-authored content to deliver.
2745
+ * @param options - caller cancellation before inbox acceptance.
2841
2746
  * @returns the accepted message's inbox id.
2842
- * @throws when continuation services are unavailable, parent authority is
2843
- * rejected, or the message was not admitted.
2747
+ * @throws when continuation services are unavailable, adjacency is rejected,
2748
+ * or the message was not admitted.
2844
2749
  */
2845
- async followup(parent, childId, content, options) {
2846
- return this.requireContinuations().followup(parent, childId, content, options);
2750
+ async sendMessage(sender, targetId, content, options) {
2751
+ return this.requireContinuations().sendMessage(sender, targetId, content, options);
2752
+ }
2753
+ /**
2754
+ * Queue one host-protocol message as a distinct direct-child turn.
2755
+ * Symbol-keyed so host adapters can preserve their own provenance without
2756
+ * widening the public Service Definition or impersonating an Agent sender.
2757
+ * @param parent - exact live direct parent authorizing delivery.
2758
+ * @param childId - durable direct-child session id.
2759
+ * @param content - host-authored content to deliver.
2760
+ * @param source - durable host-protocol provenance.
2761
+ * @param signal - caller cancellation before inbox acceptance.
2762
+ * @returns the accepted message's inbox id.
2763
+ */
2764
+ [queueSubagentPrompt](parent, childId, content, source, signal) {
2765
+ return this.requireContinuations().queuePrompt(parent, childId, content, source, signal);
2847
2766
  }
2848
2767
  /**
2849
2768
  * Interrupt one live continuable child's current turn under a human parent
@@ -2864,31 +2783,6 @@ let SubagentRuntime = (() => {
2864
2783
  this.continuations?.interrupt(targetSessionId, authority);
2865
2784
  }
2866
2785
  /**
2867
- * Deliver selected content from one live continuable child to its durable
2868
- * direct parent. The child is the authority credential; callers cannot name a
2869
- * recipient. Reporting does not conclude the child's turn or Activation.
2870
- * @param child - exact live reporting child.
2871
- * @param content - selected model-facing content.
2872
- * @param options - parent scheduling and pre-acceptance cancellation.
2873
- * @returns the stable identity of the parent-accepted message.
2874
- * @throws when continuation services are unavailable, sender authorization
2875
- * fails, or the direct parent is not live.
2876
- */
2877
- async reportFrom(child, content, options) {
2878
- return this.requireContinuations().reportFrom(child, content, options);
2879
- }
2880
- /**
2881
- * Compose one deployment capability into every continuable child's
2882
- * unpublished creation context on fresh creation and cold resume. Grants wait
2883
- * for the next Activation; removing the contribution revokes every resident
2884
- * installation immediately.
2885
- * @param contribution - synchronous child-scope installer.
2886
- * @returns the exact Cordis effect disposer.
2887
- */
2888
- registerContinuableSetup(contribution) {
2889
- return this.ctx.effect(() => this.setupRegistry.register(contribution), "subagents.registerContinuableSetup()");
2890
- }
2891
- /**
2892
2786
  * Close continuable admission below exact live parent Agents, stop only their
2893
2787
  * visible descendant Activations synchronously, then await admitted scoped
2894
2788
  * materializations and release those forests child-first. The scoped cutoff
@@ -3016,10 +2910,7 @@ let SubagentRuntime = (() => {
3016
2910
  if (attachments === void 0) throw new Error("subagent image prompt requires an attachment store");
3017
2911
  content = await admitPromptContent(attachments, request.content);
3018
2912
  }
3019
- return { messageId: await this.followup(parent, childSessionId, content, {
3020
- source,
3021
- signal
3022
- }) };
2913
+ return { messageId: await this[queueSubagentPrompt](parent, childSessionId, content, source, signal) };
3023
2914
  } catch (error) {
3024
2915
  return rejectPrompt(error, childSessionId, signal);
3025
2916
  }