@dsmm/dsmm 0.2.2 → 0.3.0

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 (61) hide show
  1. package/README.md +8 -10
  2. package/cordis.patch.yml +14 -0
  3. package/docs/agent-presets.md +4 -4
  4. package/docs/compatibility.md +19 -24
  5. package/docs/deferred-native-approval-risk.md +2 -2
  6. package/docs/model-routing.md +3 -3
  7. package/docs/profiles.md +1 -1
  8. package/docs/releasing.md +46 -6
  9. package/docs/settings-status.md +2 -2
  10. package/lib/agent-registry.d.ts +36 -0
  11. package/lib/agent-registry.js +75 -0
  12. package/lib/child-admission.d.ts +0 -2
  13. package/lib/child-admission.js +13 -24
  14. package/lib/child-capture.d.ts +5 -1
  15. package/lib/child-capture.js +7 -5
  16. package/lib/client/children-locales.d.ts +13 -13
  17. package/lib/client/deployment-controller.js +1 -1
  18. package/lib/client.js +3 -3
  19. package/lib/delivery-authority.d.ts +18 -3
  20. package/lib/delivery-authority.js +149 -12
  21. package/lib/index.d.ts +2 -2
  22. package/lib/index.js +13 -26
  23. package/lib/native-child-evidence.d.ts +1 -3
  24. package/lib/native-child-evidence.js +0 -29
  25. package/lib/permission-rpc.js +3 -3
  26. package/lib/profile-rpc.js +6 -4
  27. package/lib/profile-store.js +2 -2
  28. package/lib/role-control-rpc.js +12 -8
  29. package/lib/role-invocation.d.ts +1 -1
  30. package/lib/role-policy.d.ts +1 -4
  31. package/lib/role-policy.js +24 -41
  32. package/lib/role-providers.d.ts +1 -1
  33. package/lib/role-providers.js +15 -55
  34. package/lib/role-runs.d.ts +17 -14
  35. package/lib/role-runs.js +45 -14
  36. package/lib/role-subagents.js +16 -6
  37. package/lib/runtime-integration.d.ts +4 -35
  38. package/lib/runtime-integration.js +38 -120
  39. package/lib/session-persistence.d.ts +2 -1
  40. package/lib/session-persistence.js +1 -1
  41. package/lib/session-scope.js +4 -1
  42. package/lib/subagent-runtime.d.ts +19 -7
  43. package/lib/subagent-runtime.js +141 -15
  44. package/package.json +110 -100
  45. package/lib/legacy-child-policy.d.ts +0 -51
  46. package/lib/legacy-child-policy.js +0 -123
  47. package/lib/legacy-read-composition.d.ts +0 -20
  48. package/lib/legacy-read-composition.js +0 -144
  49. package/lib/legacy-read-contracts.d.ts +0 -157
  50. package/lib/legacy-read-contracts.js +0 -39
  51. package/lib/legacy-read-host.d.ts +0 -19
  52. package/lib/legacy-read-host.js +0 -67
  53. package/lib/legacy-read-integration.d.ts +0 -121
  54. package/lib/legacy-read-integration.js +0 -522
  55. package/lib/legacy-read-proxy.d.ts +0 -26
  56. package/lib/legacy-read-proxy.js +0 -237
  57. package/scripts/cold-profile-composition.mjs +0 -329
  58. package/scripts/cold-profile-sources.mjs +0 -238
  59. package/scripts/migrate-cold-profile.mjs +0 -315
  60. package/scripts/repair-session-log.mjs +0 -476
  61. package/scripts/session-repair-native-verifier.mjs +0 -367
@@ -38,7 +38,6 @@ import { foldSubagentDescriptor, SubagentError, SubagentRuntime } from "@deepsee
38
38
  import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
39
39
  import { createChildAdmissionBinding, projectChildAdmissionEvidence } from "./child-admission.js";
40
40
  import { scopeLifetime } from "./delivery-authority.js";
41
- import { createLegacyReadIntegration } from "./legacy-read-integration.js";
42
41
  import { NativeChildEvidenceReader } from "./native-child-evidence.js";
43
42
  import { DsmmProfileError } from "./profiles.js";
44
43
  import { capturedOriginalRoleInvocation, capturedRoleInvocation, currentRoleInvocation, duringRoleInvocation, invocationAgentOptions, resolveRoleInvocation } from "./role-invocation.js";
@@ -155,7 +154,7 @@ export function runtimeAdmissionView(ctx) {
155
154
  : { binding: "stock", deliveryFenceReady: false, restartRequired: true, reason: "explicit-composition-required" };
156
155
  }
157
156
  /** Capability projection only. Admission objects and A's CAS/maintenance methods remain untouched. */
158
- export function publicProfileRuntime(runtime, ctx, integration) {
157
+ export function publicProfileRuntime(runtime, ctx) {
159
158
  const getter = Object.assign(((agent) => runtime.getSettings(agent)), runtime.getSettings, { subagentRuntime: () => runtimeAdmissionView(ctx) });
160
159
  return new Proxy(runtime, { get(target, key) {
161
160
  if (key === "getSettings")
@@ -164,20 +163,19 @@ export function publicProfileRuntime(runtime, ctx, integration) {
164
163
  return async (...args) => {
165
164
  let result;
166
165
  const call = async () => { result = await Reflect.apply(Reflect.get(target, key), target, args); };
167
- if (key === "selectSession" && integration !== undefined)
168
- await integration.changeConfiguration("parent-profile-apply", call);
169
- else
170
- await call();
166
+ await call();
171
167
  return { ...result, subagentRuntime: runtimeAdmissionView(ctx) };
172
168
  };
173
169
  const value = Reflect.get(target, key);
174
170
  return typeof value === "function" ? value.bind(target) : value;
175
171
  } });
176
172
  }
177
- const hosts = new WeakMap();
178
- function unavailableLegacy() {
179
- throw new DsmmProfileError("unavailable", "Legacy execution requires the separately installed real Host operation/approval/audit adapter.");
173
+ export function assertSupportedHostStartup(startup) {
174
+ if (startup === null || typeof startup !== "object" || Array.isArray(startup) || Reflect.ownKeys(startup).length !== 0) {
175
+ throw new DsmmProfileError("unavailable", "Host compatibility startup options are unsupported; existing data is not migrated.");
176
+ }
180
177
  }
178
+ const hosts = new WeakMap();
181
179
  /** Exact live descendants are revoked synchronously before any native holder starts draining. */
182
180
  function revokeTree(registry, revoke, parent, reason) {
183
181
  const pending = [parent], seen = new Set();
@@ -194,6 +192,7 @@ function revokeTree(registry, revoke, parent, reason) {
194
192
  }
195
193
  const disabled = (reason) => ({ enabled: false, reason });
196
194
  export async function integrateSubagentRuntime(ctx, settings, policy, getRuntime, startup = {}) {
195
+ assertSupportedHostStartup(startup);
197
196
  const bound = ctx.get("subagents");
198
197
  if (bound === undefined || !(original(bound) instanceof DsmmSubagentRuntime) || !settings.modules.deepwork.enabled)
199
198
  return undefined;
@@ -206,7 +205,7 @@ export async function integrateSubagentRuntime(ctx, settings, policy, getRuntime
206
205
  try {
207
206
  if (retired)
208
207
  throw unavailable();
209
- const integration = await integrateManagedSubagentRuntime(scope, settings, policy, getRuntime, startup);
208
+ const integration = await integrateManagedSubagentRuntime(scope, settings, policy, getRuntime);
210
209
  if (retired)
211
210
  throw unavailable();
212
211
  resolve(integration);
@@ -226,7 +225,7 @@ export async function integrateSubagentRuntime(ctx, settings, policy, getRuntime
226
225
  retire(); }, reject);
227
226
  });
228
227
  }
229
- async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime, startup) {
228
+ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime) {
230
229
  const bound = ctx.get("subagents");
231
230
  const native = bound === undefined ? undefined : original(bound);
232
231
  if (!(native instanceof DsmmSubagentRuntime) || !settings.modules.deepwork.enabled)
@@ -236,6 +235,7 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
236
235
  throw new DsmmProfileError("unavailable", "Managed admission requires the explicit Host-owned startup entry, not a separately constructed runtime.");
237
236
  // Revocation outlives the entry's injection scope; this reference only enumerates exact native owners during teardown.
238
237
  const teardownAgents = original(ctx.agents);
238
+ const revokeResidency = native.authority.revokeParent.bind(native.authority);
239
239
  native.requireProviders(["spawn"]);
240
240
  const lifetime = new AbortController();
241
241
  scopeLifetime(ctx, "dsmm.integration: close startup preparation", () => lifetime.abort());
@@ -261,10 +261,8 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
261
261
  && state.policy.targets(parent).includes(invocation.capture.invocation.target);
262
262
  },
263
263
  teardown: {
264
- revokeParent: (agent, reason) => revokeTree(teardownAgents, (agent, why) => native.authority.revokeParent(agent, why), agent, reason),
264
+ revokeParent: (agent, reason) => revokeTree(teardownAgents, revokeResidency, agent, reason),
265
265
  async disposeRun(run) {
266
- if (run.localAgent !== undefined)
267
- revokeTree(teardownAgents, (agent, why) => native.authority.revokeParent(agent, why), run.localAgent, "run-disposed");
268
266
  await run.dispose();
269
267
  },
270
268
  },
@@ -284,58 +282,16 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
284
282
  },
285
283
  assertDelivery: policy.assertChildDelivery.bind(policy),
286
284
  };
287
- const legacyRead = startup.experimentalLegacyRead === undefined ? undefined : createLegacyReadIntegration({ ctx,
288
- authority: native.authority, authorityOwner: stable.owner, nativeHistory: history,
289
- trustedHostStartup: startup.experimentalLegacyRead.startup, classifyChildReport: startup.experimentalLegacyRead.classifyChildReport, coreAdmissions: originalAdmissions,
290
- admissions: {
291
- resolveOriginalChildEvidence: (ticket, id, signal) => bridge.policy.resolveChildEvidence(ticket, SessionId(id), signal),
292
- childAdmission: child => getRuntime().admission(child),
293
- assertCurrentParent(ticket, child, evidence) {
294
- native.authority.assertTicket(ticket);
295
- const borrowed = bridge.authority.acquireParentTicket(ticket.parent);
296
- if (borrowed.owner !== ticket.owner || borrowed.admission !== ticket.admission || borrowed.parentEpoch !== ticket.parentEpoch)
297
- throw new SubagentError("Legacy parent is not the exact current Host admission", "UNAUTHORIZED");
298
- policy.assertChildDelivery(borrowed, child.id, evidence);
299
- native.authority.assertTicket(ticket);
300
- },
301
- },
302
- proxyDefinitions: {
303
- admit(parent, child, definition) {
304
- const identity = policy.identity(child), tools = child.ctx.tools;
305
- if (identity.parent !== parent || !ctx.agents.isOwnedBy(child.id, parent) || tools.get(definition.name, child) !== definition)
306
- throw new SubagentError("Legacy proxy requires its exact registered child realm", "UNAUTHORIZED");
307
- policy.captureTools(child, tools, [definition.name]);
308
- },
309
- assertAdmitted(child, definition) {
310
- const tools = child.ctx.tools;
311
- if (tools.get(definition.name, child) !== definition || policy.toolDenial(child, definition.name, tools) !== undefined)
312
- throw new SubagentError("Legacy proxy definition is not admitted by the actual role guard", "UNAUTHORIZED");
313
- },
314
- },
315
- });
316
- const legacyCore = legacyRead?.core;
317
- if (legacyRead !== undefined && legacyCore === undefined)
318
- throw new DsmmProfileError("unavailable", "Legacy read requires an explicit trusted cold Host composition.");
319
285
  bridge = createChildAdmissionBinding({ ctx, owner: stable.owner, deliveryAuthority: native.authority,
320
286
  nativeSubstrate: settings, nativeHistory: history,
321
- get legacyCapabilities() { return legacyCore?.legacyCapabilities ?? unavailableLegacy(); },
322
287
  collaborators: {
323
288
  classifyParent: classifyDsmmAgent,
324
- resolveOriginalChildEvidence: (...args) => (legacyCore ?? originalAdmissions).resolveOriginalChildEvidence(...args),
289
+ resolveOriginalChildEvidence: originalAdmissions.resolveOriginalChildEvidence,
325
290
  childAdmission: { prepare: (...args) => completion.prepare(...args), validateRole: (...args) => completion.validateRole(...args) },
326
- assertDelivery: (ticket, id, evidence) => {
327
- if ("mode" in evidence) {
328
- if (legacyCore === undefined)
329
- unavailableLegacy();
330
- legacyCore.assertLegacyDelivery(ticket, id, evidence);
331
- }
332
- else
333
- policy.assertChildDelivery(ticket, id, evidence);
334
- },
291
+ assertDelivery: originalAdmissions.assertDelivery,
335
292
  }, });
336
293
  completion = policy.configureAdmission({ nativeSubstrate: settings, resolveOriginalEvidence: bridge.resolveOriginalEvidence,
337
- ...(legacyCore === undefined ? {} : { classifyLegacyTool: legacyCore.classifyLegacyTool }),
338
- revokeParent: (agent, reason) => revokeTree(teardownAgents, bridge.authority.revokeParent, agent, reason) });
294
+ revokeParent: (agent, reason) => revokeTree(teardownAgents, revokeResidency, agent, reason) });
339
295
  // Native non-DSMM direct children remain native. This branch is established
340
296
  // from an actual public physical cut, never from a missing DSMM registration.
341
297
  const nativeEvidence = new WeakSet();
@@ -409,7 +365,9 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
409
365
  }
410
366
  };
411
367
  const detachPolicy = native.authority.bindPolicy(ctx, stable.owner, {
412
- classifyParent: classifyDsmmAgent,
368
+ isNativeEvidence,
369
+ classifyParent: parent => parent.session.header.origin === "subagent" ? classifyDsmmAgent(parent)
370
+ : policy.identity(parent).role === undefined ? "native" : "dsmm",
413
371
  async resolveChildEvidence(ticket, childId, signal) {
414
372
  const evidence = await proveNativeChild(ticket, childId, "continuable", signal);
415
373
  if (evidence !== undefined)
@@ -448,7 +406,7 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
448
406
  };
449
407
  ctx.on("subagent/provider-added", providerChanged, { global: true });
450
408
  ctx.on("subagent/provider-removed", providerChanged, { global: true });
451
- managed.configureContinuablePreflight(async (spec, start) => {
409
+ managed.configureActivationPreflight(async (spec, start) => {
452
410
  const provider = managed.getProvider(spec.provider);
453
411
  const role = provider !== undefined && policy.ownsProvider(provider) ? roleFromProviderName(spec.provider) : undefined;
454
412
  if (role === undefined)
@@ -461,20 +419,13 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
461
419
  signal.throwIfAborted();
462
420
  managed.authority.assertTicket(ticket);
463
421
  policy.assertDelegation(actor, role);
464
- return duringRoleInvocation(actor, invocation, () => start({ ...spec, signal,
465
- request: { ...spec.request, agentOptions: invocationAgentOptions(invocation, spec.request.agentOptions) } }));
422
+ const ceiling = ticket.admission.settings.subagents.maxDepth;
423
+ if (spec.request.maxDepth !== undefined && ceiling !== undefined && spec.request.maxDepth > ceiling)
424
+ throw new SubagentError("Delegation exceeds parent depth ceiling", "UNAUTHORIZED");
425
+ const maxDepth = spec.request.maxDepth ?? managed.resolveMaxDepth(ceiling);
426
+ return duringRoleInvocation(actor, invocation, () => policy.duringDelegation(actor, role, () => start({ ...spec, signal,
427
+ request: { ...spec.request, maxDepth, agentOptions: invocationAgentOptions(invocation, spec.request.agentOptions) } }), undefined, maxDepth));
466
428
  }, lifetime.signal);
467
- const enrolledLegacy = new Map();
468
- if (legacyCore !== undefined) {
469
- ctx.on("agent/disposed", ({ agent }) => { enrolledLegacy.delete(agent); }, { global: true });
470
- ctx.effect(() => async () => {
471
- native.authority.revokeOwner(stable.owner, "core-owner-ended");
472
- await legacyCore.dispose(async () => {
473
- for (const attachment of enrolledLegacy.values())
474
- await managed.drainContinuableChildren(attachment.parent, [attachment.child.id]);
475
- });
476
- });
477
- }
478
429
  const reader = new NativeChildEvidenceReader(ctx, ticket => managed.authority.assertTicket(ticket), history);
479
430
  const background = (ticket) => !ticket.admission.settings.modules.deepwork.enabled ? disabled("module-off")
480
431
  : !ticket.admission.settings.subagents.enableRunInBackground ? disabled("background-disabled")
@@ -486,9 +437,10 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
486
437
  images: ctx.get("attachments") !== undefined ? { enabled: true } : disabled("unavailable"), runtime: managed.authority.view(),
487
438
  });
488
439
  let startupCompletion;
489
- return { bridge, owner: stable.owner, registry: stable.registry, runtime: managed, legacyRead,
440
+ return { bridge, owner: stable.owner, registry: stable.registry, runtime: managed,
490
441
  async admitLlmRequest(agent, signal) {
491
442
  signal.throwIfAborted();
443
+ await managed.authority.waitForPromotion(agent, signal);
492
444
  const dsmmAgent = agent;
493
445
  policy.assertModuleAdmission(dsmmAgent);
494
446
  const identity = policy.identity(dsmmAgent);
@@ -520,50 +472,16 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
520
472
  managed.authority.assertTicket(parentTicket);
521
473
  if (ctx.agents.get(parentTicket.parent.id) !== parentTicket.parent || !ctx.agents.isOwnedBy(agent.id, parentTicket.parent))
522
474
  throw new SubagentError("LLM child ownership changed", "UNAUTHORIZED");
523
- managed.authority.assertDelivery(parentTicket, agent.id, evidence);
475
+ policy.assertChildExecution(bridge.authority.acquireParentTicket(parentTicket.parent), agent.id, evidence);
524
476
  }
525
477
  };
526
478
  assertCurrent();
527
479
  return Object.freeze({ agent, admission, capture: admission.childCapture ?? evidence ?? ticket, epoch: admission.epoch, signal: merged, assertCurrent });
528
480
  },
529
- async afterChildAdmission(agent, signal = lifetime.signal) {
530
- if (legacyCore === undefined || agent.session.header.origin !== "subagent")
531
- return;
532
- signal = AbortSignal.any([signal, lifetime.signal]);
533
- const runtime = getRuntime();
534
- if (runtime === undefined)
535
- throw new DsmmProfileError("unavailable", "Child profile admission is not initialized.");
536
- const admission = await runtime.completeAdmission(agent, signal);
537
- if (admission.childEvidence?.mode !== "legacy-conservative")
538
- return;
539
- const parent = agent.session.header.parentSession === undefined ? undefined : ctx.agents.get(agent.session.header.parentSession);
540
- if (parent === undefined || !ctx.agents.isOwnedBy(agent.id, parent))
541
- throw new SubagentError("Legacy enrollment requires its exact live direct parent", "UNAUTHORIZED");
542
- const previous = enrolledLegacy.get(agent);
543
- if (previous !== undefined) {
544
- if (previous.parent !== parent || previous.admission !== admission)
545
- throw new SubagentError("Legacy enrollment cannot replace its original exact residency", "UNAUTHORIZED");
546
- return;
547
- }
548
- try {
549
- const attachment = await legacyCore.afterChildAdmission(parent, agent, signal);
550
- if (attachment !== undefined)
551
- enrolledLegacy.set(agent, attachment);
552
- }
553
- catch (error) {
554
- // Reject back to the actual native admission owner only after revoking
555
- // this exact residency. That owner retains its original rollback handle.
556
- revokeTree(teardownAgents, bridge.authority.revokeParent, agent, "child-admission-failed");
557
- throw error;
558
- }
559
- },
560
- changeConfiguration(reason, mutate) {
561
- return legacyCore === undefined || enrolledLegacy.size === 0 ? Promise.resolve().then(mutate) : legacyCore.changeConfiguration(reason, mutate);
562
- },
563
481
  dispose(nativeDrain) {
564
482
  for (const parent of teardownAgents.roots())
565
- revokeTree(teardownAgents, bridge.authority.revokeParent, parent, "host-dispose");
566
- return legacyCore === undefined ? nativeDrain() : legacyCore.dispose(nativeDrain);
483
+ revokeTree(teardownAgents, revokeResidency, parent, "host-dispose");
484
+ return nativeDrain();
567
485
  },
568
486
  onAdmissionGuardsInstalled() { lifetime.signal.throwIfAborted(); bridge.onAdmissionGuardsInstalled(); },
569
487
  continueStartup(complete, callerSignal) {
@@ -580,12 +498,9 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
580
498
  },
581
499
  async ready() { await managed.waitUntilReady(lifetime.signal); await startupCompletion; lifetime.signal.throwIfAborted(); },
582
500
  async revokeBeforeDispose(agent, dispose) {
583
- revokeTree(teardownAgents, bridge.authority.revokeParent, agent, "holder-disposed");
501
+ revokeTree(teardownAgents, revokeResidency, agent, "holder-disposed");
584
502
  const nativeDispose = async () => { await stable.registry.drainParent(agent, stable.owner, "holder-disposed"); await dispose(); };
585
- if (legacyCore === undefined)
586
- await nativeDispose();
587
- else
588
- await legacyCore.revokeBeforeDispose(agent, nativeDispose);
503
+ await nativeDispose();
589
504
  },
590
505
  registerControls(scope) {
591
506
  registerRoleControlRpc(scope, { runtime: managed, runs: stable.registry, capabilities,
@@ -635,6 +550,9 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
635
550
  }
636
551
  if ("mode" in evidence)
637
552
  return { evidence: projectChildAdmissionEvidence(evidence, ticket.parentEpoch), prompt, interrupt: prompt };
553
+ const mode = evidence.version === 3 ? evidence.delegationMode : "continuable";
554
+ if (mode === "one-shot")
555
+ prompt = disabled("one-shot");
638
556
  const facts = await reader.read(ticket, entry.id, signal);
639
557
  const observation = await history.observeSession(entry.id, { signal, projectionMode: "none" });
640
558
  try {
@@ -645,7 +563,7 @@ async function integrateManagedSubagentRuntime(ctx, settings, policy, getRuntime
645
563
  const route = evidence.invocation.initialRoute;
646
564
  return { evidence: projectChildAdmissionEvidence(evidence, ticket.parentEpoch), prompt, interrupt: prompt,
647
565
  invocation: { role: evidence.role, label: facts.descriptor.label ?? entry.label ?? evidence.role, level: evidence.invocation.level,
648
- routeSource: evidence.invocation.routeSource, route: live.status === "known" ? live.route : route, mode: "continuable", childId: entry.id },
566
+ routeSource: evidence.invocation.routeSource, route: live.status === "known" ? live.route : route, mode, childId: entry.id },
649
567
  routeComparison: { childId: entry.id, initialRoute: { status: "known", source: "invocation-capture", route }, liveRoute: live } };
650
568
  }
651
569
  finally {
@@ -763,7 +681,7 @@ let UnavailableRoleControls = (() => {
763
681
  }
764
682
  refuse() {
765
683
  const connection = this.ctx.get("connection"), invocation = this.ctx.invocation;
766
- const code = connection === undefined || invocation?.peer !== connection.operator ? "not-owned" : "unavailable";
684
+ const code = connection === undefined || invocation?.peer !== connection.browserPeer ? "not-owned" : "unavailable";
767
685
  throw new RemoteError("dsmm-children/refused", "The Host refused the child control operation.", { code, ...(code === "unavailable" ? { reason: "delivery-fence-unavailable" } : {}) });
768
686
  }
769
687
  describe(_sessionId) { return this.refuse(); }
@@ -774,7 +692,7 @@ let UnavailableRoleControls = (() => {
774
692
  };
775
693
  })();
776
694
  /** Explicit startup entry; it owns one PUBLIC subclass, never a live replacement. */
777
- export const subagentRuntimePlugin = { name: "dsmm-subagent-runtime", inject: ["agents"], Config: SubagentRuntime.Config,
695
+ export const subagentRuntimePlugin = { name: "dsmm-subagent-runtime", inject: DsmmSubagentRuntime.inject, Config: SubagentRuntime.Config,
778
696
  apply(ctx, config) {
779
697
  const runtime = new DsmmSubagentRuntime(ctx, config, classifyDsmmAgent);
780
698
  runtimeScopes.set(runtime, ctx);
@@ -2,6 +2,7 @@ import { Context, Service } from "@deepseek-ai/cordis";
2
2
  import type { SessionHeader, SessionId } from "@deepseek-ai/dsh-session";
3
3
  import { SessionPersistence } from "@deepseek-ai/dsh-session-persistence";
4
4
  import type { SessionAccess, SessionHandle, SessionPersistenceCreateOptions, SessionPersistenceListOptions, SessionPersistenceOpenOptions, SessionPersistenceStatOptions } from "@deepseek-ai/dsh-session-persistence";
5
+ import * as JsonlSessionPersistence from "@deepseek-ai/dsh-session-persistence-jsonl";
5
6
  import type { Config } from "@deepseek-ai/dsh-session-persistence-jsonl";
6
7
  export { DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
7
8
  export type { Config } from "@deepseek-ai/dsh-session-persistence-jsonl";
@@ -12,7 +13,7 @@ export type { Config } from "@deepseek-ai/dsh-session-persistence-jsonl";
12
13
  */
13
14
  export default class DsmmSessionPersistence extends SessionPersistence {
14
15
  readonly config: Config;
15
- static Config: import("@deepseek-ai/schemastery").default<Config>;
16
+ static Config: import("@deepseek-ai/schemastery").default<JsonlSessionPersistence.Config>;
16
17
  readonly name = "dsmm-session-persistence";
17
18
  private readonly inner;
18
19
  private readonly ready;
@@ -1,6 +1,6 @@
1
1
  import { Context, Service } from "@deepseek-ai/cordis";
2
2
  import { SessionHandleClosedError, SessionPersistence, SessionReadOnlyError, materializeAppendBatch } from "@deepseek-ai/dsh-session-persistence";
3
- import JsonlSessionPersistence from "@deepseek-ai/dsh-session-persistence-jsonl";
3
+ import * as JsonlSessionPersistence from "@deepseek-ai/dsh-session-persistence-jsonl";
4
4
  import { isDeepStrictEqual } from "node:util";
5
5
  import { annotateDsmmEvent, DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
6
6
  export { DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
@@ -1,6 +1,7 @@
1
1
  import { foldSubagentDescriptor } from "@deepseek-ai/dsh-subagent";
2
2
  import { isDsmmRoleId } from "./roles.js";
3
3
  import { roleFromProviderName } from "./role-providers.js";
4
+ import { capturedRoleInvocation } from "./role-invocation.js";
4
5
  export function sessionEvents(session) {
5
6
  return session?.snapshotEvents?.() ?? session?.events ?? [];
6
7
  }
@@ -31,7 +32,9 @@ export function resolveEffectiveDsmmRole(agent, settings, modeActive) {
31
32
  if (agent.session.header?.origin === "subagent") {
32
33
  const own = childOwnedSessionEvents(agent.session);
33
34
  const descriptor = foldSubagentDescriptor(own);
34
- role = descriptor?.mode === "one-shot" ? roleFromProviderName(descriptor.provider) : undefined;
35
+ // Native lifecycle mode does not determine an exact Agent's admitted DSMM role.
36
+ role = capturedRoleInvocation(agent)?.target
37
+ ?? (descriptor?.mode === "one-shot" ? roleFromProviderName(descriptor.provider) : undefined);
35
38
  }
36
39
  else {
37
40
  const preset = resolveSelectedAgentPreset(agent.session);
@@ -1,9 +1,9 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { Agent } from "@deepseek-ai/dsh-agent";
3
3
  import type { ContentBlock, MessageId } from "@deepseek-ai/dsh-llm";
4
- import type { SessionId } from "@deepseek-ai/dsh-session";
4
+ import { SessionId } from "@deepseek-ai/dsh-session";
5
5
  import { SubagentRuntime } from "@deepseek-ai/dsh-subagent";
6
- import type { SubagentPromptReceipt, SubagentPromptRequest, SubagentProvider, SubagentSendMessageOptions } from "@deepseek-ai/dsh-subagent";
6
+ import type { SubagentActivation, SubagentActivationSpec, SubagentPromptReceipt, SubagentPromptRequest, SubagentProvider, SubagentSendMessageOptions } from "@deepseek-ai/dsh-subagent";
7
7
  import { DsmmDeliveryAuthority } from "./delivery-authority.js";
8
8
  import type { DeliveryAdmission, DeliveryParentClassifier } from "./delivery-authority.js";
9
9
  export { DsmmDeliveryAuthority } from "./delivery-authority.js";
@@ -15,22 +15,34 @@ declare module "@deepseek-ai/dsh-typert-protocol/types" {
15
15
  };
16
16
  }
17
17
  }
18
- type ContinuableStart = SubagentRuntime["startContinuable"];
19
- type ContinuablePreflight = (spec: Parameters<ContinuableStart>[0], start: ContinuableStart) => ReturnType<ContinuableStart>;
18
+ type ActivationStart = (spec: SubagentActivationSpec) => Promise<SubagentActivation>;
19
+ type ActivationPreflight = (spec: SubagentActivationSpec, start: ActivationStart) => Promise<SubagentActivation>;
20
20
  /** Explicit startup replacement for the stock row, in the SAME Host service scope. */
21
21
  export declare class DsmmSubagentRuntime<A extends DeliveryAdmission = DeliveryAdmission, E = unknown> extends SubagentRuntime {
22
+ static inject: string[];
22
23
  readonly authority: DsmmDeliveryAuthority<A, E>;
23
24
  private readonly waiters;
24
25
  private readonly lifetime;
25
26
  private requiredProviders;
26
- private continuablePreflight?;
27
+ private activationPreflight?;
27
28
  constructor(ctx: Context, config: ConstructorParameters<typeof SubagentRuntime>[1], hostClassifier?: DeliveryParentClassifier);
28
29
  /** Host composition may select spawn/fork names before enabling the policy. */
29
30
  requireProviders(names: readonly string[]): void;
30
31
  registerProvider(provider: SubagentProvider): () => void;
31
32
  /** Host entry route preparation before native normalization loses caller option provenance. */
32
- configureContinuablePreflight(preflight: ContinuablePreflight, signal: AbortSignal): void;
33
- startContinuable(spec: Parameters<ContinuableStart>[0]): ReturnType<ContinuableStart>;
33
+ configureActivationPreflight(preflight: ActivationPreflight, signal: AbortSignal): void;
34
+ startActivation(spec: SubagentActivationSpec & {
35
+ readonly childId: SessionId;
36
+ }): Promise<SubagentActivation & {
37
+ readonly messageId: MessageId;
38
+ }>;
39
+ startActivation(spec: SubagentActivationSpec): Promise<SubagentActivation>;
40
+ private startManaged;
41
+ private operation;
42
+ private coldDelivery;
43
+ private retireTree;
44
+ drainDescendants(parents: readonly Agent[]): Promise<void>;
45
+ drainChildren(parent: Agent, childIds: readonly SessionId[]): Promise<void>;
34
46
  /** Fulfillment proves this exact registry contains the provider, not just a mounted plugin. */
35
47
  waitForProvider(name: string, signal?: AbortSignal): Promise<SubagentProvider>;
36
48
  /** Policy explicitly enabled AND every required provider actually registered. */
@@ -1,21 +1,33 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { SessionId } from "@deepseek-ai/dsh-session";
1
3
  import { SubagentError, SubagentRuntime } from "@deepseek-ai/dsh-subagent";
2
4
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
3
5
  import { TYPERT as NATIVE_SUBAGENT_HOST } from "@deepseek-ai/dsh-subagent/typert";
4
6
  import { DsmmDeliveryAuthority, scopeLifetime } from "./delivery-authority.js";
7
+ import { activationOwnerSignal, DsmmAgentRegistry, duringManagedCreation, exactRegistry, managedCancellation } from "./agent-registry.js";
5
8
  export { DsmmDeliveryAuthority } from "./delivery-authority.js";
6
9
  /** Explicit startup replacement for the stock row, in the SAME Host service scope. */
7
10
  export class DsmmSubagentRuntime extends SubagentRuntime {
11
+ static inject = ["agents", ...SubagentRuntime.inject];
8
12
  authority;
9
13
  waiters = new Set();
10
14
  lifetime = new AbortController();
11
15
  requiredProviders = ["spawn"];
12
- continuablePreflight;
16
+ activationPreflight;
13
17
  constructor(ctx, config, hostClassifier) {
14
18
  if (ctx.get("subagents") !== undefined) {
15
19
  throw new SubagentError("Explicit DSMM startup composition must exclude the stock subagents row; restart with one provider.", "DUPLICATE_PROVIDER");
16
20
  }
17
21
  super(ctx, config);
18
22
  this.authority = new DsmmDeliveryAuthority(ctx, () => this.substrateReady(), () => this.wakeWaiters(), hostClassifier);
23
+ const agents = exactRegistry(ctx.agents);
24
+ if (!(agents instanceof DsmmAgentRegistry))
25
+ throw new SubagentError("Managed activations require the DSMM startup agents provider", "UNSUPPORTED_CAPABILITY");
26
+ const retire = () => { this.lifetime.abort(); for (const agent of agents.list())
27
+ this.authority.revokeParent(agent, "agents-provider-ended"); this.wakeWaiters(); };
28
+ agents.managedLifetime.signal.addEventListener("abort", retire, { once: true });
29
+ if (agents.managedLifetime.signal.aborted)
30
+ retire();
19
31
  ctx.inject(["typert"], (remoteCtx) => {
20
32
  if (remoteCtx.typert.getPackage("@deepseek-ai/dsh-subagent", "host") === undefined) {
21
33
  remoteCtx.typert.register(NATIVE_SUBAGENT_HOST);
@@ -40,17 +52,122 @@ export class DsmmSubagentRuntime extends SubagentRuntime {
40
52
  return dispose;
41
53
  }
42
54
  /** Host entry route preparation before native normalization loses caller option provenance. */
43
- configureContinuablePreflight(preflight, signal) {
55
+ configureActivationPreflight(preflight, signal) {
44
56
  signal.throwIfAborted();
45
- if (this.continuablePreflight !== undefined)
46
- throw new SubagentError("Continuable routing already has a Host owner", "UNAUTHORIZED");
47
- this.continuablePreflight = preflight;
48
- signal.addEventListener("abort", () => { if (this.continuablePreflight === preflight)
49
- this.continuablePreflight = undefined; }, { once: true });
57
+ if (this.activationPreflight !== undefined)
58
+ throw new SubagentError("Activation routing already has a Host owner", "UNAUTHORIZED");
59
+ this.activationPreflight = preflight;
60
+ signal.addEventListener("abort", () => { if (this.activationPreflight === preflight)
61
+ this.activationPreflight = undefined; }, { once: true });
50
62
  }
51
- startContinuable(spec) {
52
- const start = request => super.startContinuable(request);
53
- return this.continuablePreflight === undefined ? start(spec) : this.continuablePreflight(spec, start);
63
+ async startActivation(spec) {
64
+ this.authority.assertSender(spec.request.parent);
65
+ const start = request => this.startManaged(request);
66
+ return this.activationPreflight === undefined ? start(spec) : this.activationPreflight(spec, start);
67
+ }
68
+ async startManaged(spec) {
69
+ const parent = spec.request.parent;
70
+ if (!this.authority.isManaged(parent, "creation"))
71
+ return super.startActivation(spec);
72
+ const provider = this.getProvider(spec.provider);
73
+ if (provider === undefined)
74
+ throw new SubagentError(`Subagent provider "${spec.provider}" is not registered`, "NO_PROVIDER");
75
+ if (provider.prepareContinuable === undefined)
76
+ throw new SubagentError("Managed delegation requires a local activation provider", "UNSUPPORTED_CAPABILITY");
77
+ const ticket = this.authority.acquireParentTicket(parent);
78
+ const childId = spec.childId ?? SessionId(randomUUID());
79
+ const operation = this.operation(parent, childId, "fresh", ticket.owner, spec.delivery === "caller" ? "one-shot" : "continuable");
80
+ let receipt;
81
+ try {
82
+ receipt = await duringManagedCreation(operation, () => super.startActivation({ ...spec, childId,
83
+ signal: AbortSignal.any([spec.signal, ticket.signal, this.lifetime.signal]) }));
84
+ this.authority.promote(operation);
85
+ let disposal;
86
+ const accepted = receipt;
87
+ return { ...accepted, dispose: () => {
88
+ if (disposal !== undefined)
89
+ return disposal;
90
+ this.retireTree(operation.child, "activation-disposed");
91
+ return disposal = accepted.dispose();
92
+ } };
93
+ }
94
+ catch (error) {
95
+ this.authority.retireOperation(operation, "activation-refused");
96
+ if (receipt !== undefined) {
97
+ try {
98
+ await receipt.dispose();
99
+ }
100
+ catch (cleanup) {
101
+ throw new AggregateError([error, cleanup], "Managed activation admission and cleanup failed");
102
+ }
103
+ if (operation.ownerSignal?.aborted)
104
+ throw managedCancellation(operation.ownerSignal.reason);
105
+ }
106
+ throw error;
107
+ }
108
+ }
109
+ operation(parent, childId, kind, owner, delegationMode) {
110
+ this.lifetime.signal.throwIfAborted();
111
+ const operation = { registry: exactRegistry(this.ctx.agents), parent, childId, kind, owner, delegationMode,
112
+ ownerSignal: activationOwnerSignal(), claimed: false, retired: false, entered: agent => this.authority.beginPending(operation, agent) };
113
+ return operation;
114
+ }
115
+ async coldDelivery(parent, childId, owner, deliver) {
116
+ const operation = this.operation(parent, childId, "cold", owner);
117
+ let accepted = false;
118
+ try {
119
+ const receipt = await duringManagedCreation(operation, deliver);
120
+ accepted = true;
121
+ // A competing operation may have established this residency before the native lock.
122
+ if (operation.claimed)
123
+ this.authority.promote(operation);
124
+ return receipt;
125
+ }
126
+ catch (error) {
127
+ this.authority.retireOperation(operation, "cold-delivery-refused");
128
+ const child = operation.child;
129
+ if (accepted && child !== undefined && this.ctx.agents.get(child.id) === child && this.ctx.agents.isOwnedBy(child.id, parent)) {
130
+ try {
131
+ await super.drainChildren(parent, [child.id]);
132
+ }
133
+ catch (cleanup) {
134
+ throw new AggregateError([error, cleanup], "Managed cold admission and cleanup failed");
135
+ }
136
+ }
137
+ throw error;
138
+ }
139
+ }
140
+ retireTree(parent, reason) {
141
+ const registry = this.ctx.agents, pending = [parent], seen = new Set();
142
+ while (pending.length) {
143
+ const agent = pending.pop();
144
+ if (seen.has(agent))
145
+ continue;
146
+ seen.add(agent);
147
+ this.authority.revokeParent(agent, reason);
148
+ for (const child of registry.list())
149
+ if (child !== agent && registry.isOwnedBy(child.id, agent))
150
+ pending.push(child);
151
+ }
152
+ }
153
+ drainDescendants(parents) {
154
+ for (const parent of parents)
155
+ if (this.ctx.agents.get(parent.id) !== parent)
156
+ throw new SubagentError("Drain requires exact live parents", "UNAUTHORIZED");
157
+ for (const parent of parents)
158
+ this.retireTree(parent, "descendants-draining");
159
+ return super.drainDescendants(parents);
160
+ }
161
+ drainChildren(parent, childIds) {
162
+ const registry = this.ctx.agents;
163
+ if (registry.get(parent.id) !== parent)
164
+ throw new SubagentError("Drain requires exact live parent", "UNAUTHORIZED");
165
+ const children = childIds.flatMap(id => { const child = registry.get(id); return child === undefined ? [] : [child]; });
166
+ if (children.some(child => !registry.isOwnedBy(child.id, parent)))
167
+ throw new SubagentError("Drain target is not a direct child", "UNAUTHORIZED");
168
+ for (const child of children)
169
+ this.retireTree(child, "child-draining");
170
+ return super.drainChildren(parent, childIds);
54
171
  }
55
172
  /** Fulfillment proves this exact registry contains the provider, not just a mounted plugin. */
56
173
  waitForProvider(name, signal) {
@@ -61,6 +178,7 @@ export class DsmmSubagentRuntime extends SubagentRuntime {
61
178
  return this.waitFor(() => this.authority.view().deliveryFenceReady ? true : undefined, signal).then(() => { });
62
179
  }
63
180
  async sendMessage(sender, targetId, content, options) {
181
+ this.authority.assertSender(sender);
64
182
  // The SDK alone validates exact residency and adjacency on child -> parent.
65
183
  if (sender.session.header.parentSession === targetId || !this.authority.isManaged(sender)) {
66
184
  return super.sendMessage(sender, targetId, content, options);
@@ -68,20 +186,28 @@ export class DsmmSubagentRuntime extends SubagentRuntime {
68
186
  const ticket = this.authority.acquireParentTicket(sender);
69
187
  const signal = AbortSignal.any([options.signal, ticket.signal]);
70
188
  const evidence = await this.authority.resolveChildEvidence(ticket, targetId, signal);
71
- this.authority.assertDelivery(ticket, targetId, evidence);
189
+ const managed = this.authority.assertDelivery(ticket, targetId, evidence);
72
190
  signal.throwIfAborted();
73
- return super.sendMessage(sender, targetId, content, { ...options, signal });
191
+ if (!managed)
192
+ return super.sendMessage(sender, targetId, content, { ...options, signal });
193
+ return this.coldDelivery(sender, targetId, ticket.owner, () => super.sendMessage(sender, targetId, content, { ...options, signal }));
74
194
  }
75
195
  async prompt(request, callerSignal) {
76
196
  const parent = this.ctx.get("agents")?.get(request.parentSessionId);
77
- if (parent === undefined || !this.authority.isManaged(parent))
197
+ if (parent === undefined)
78
198
  return super.prompt(request, callerSignal);
79
199
  let signal = callerSignal;
200
+ let owner;
201
+ let managed;
80
202
  try {
203
+ this.authority.assertSender(parent);
204
+ if (!this.authority.isManaged(parent))
205
+ return super.prompt(request, callerSignal);
81
206
  const ticket = this.authority.acquireParentTicket(parent);
207
+ owner = ticket.owner;
82
208
  signal = AbortSignal.any([callerSignal, ticket.signal, this.authority.acquireBrowserSignal(this.ctx)]);
83
209
  const evidence = await this.authority.resolveChildEvidence(ticket, request.childSessionId, signal);
84
- this.authority.assertDelivery(ticket, request.childSessionId, evidence);
210
+ managed = this.authority.assertDelivery(ticket, request.childSessionId, evidence);
85
211
  signal.throwIfAborted();
86
212
  }
87
213
  catch (error) {
@@ -93,7 +219,7 @@ export class DsmmSubagentRuntime extends SubagentRuntime {
93
219
  }
94
220
  throw new RemoteError("gateway/internal", "Subagent prompt failed.", {}, { cause: error });
95
221
  }
96
- return super.prompt(request, signal);
222
+ return managed ? this.coldDelivery(parent, request.childSessionId, owner, () => super.prompt(request, signal)) : super.prompt(request, signal);
97
223
  }
98
224
  wakeWaiters() {
99
225
  for (const waiter of this.waiters)