@dsmm/dsmm 0.3.11 → 0.3.13

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 (59) hide show
  1. package/README.md +2 -2
  2. package/docs/agent-presets.md +4 -4
  3. package/docs/compatibility.md +16 -4
  4. package/docs/deferred-native-approval-risk.md +1 -1
  5. package/docs/design.md +15 -5
  6. package/docs/lsp.md +1 -1
  7. package/docs/maintenance.md +9 -3
  8. package/docs/model-routing.md +6 -6
  9. package/docs/native-permissions.md +1 -1
  10. package/docs/profiles.md +46 -5
  11. package/docs/roadmap.md +3 -3
  12. package/docs/runtime-recovery.md +5 -5
  13. package/docs/safety-guards.md +1 -1
  14. package/docs/settings-status.md +3 -3
  15. package/docs/testing.md +85 -0
  16. package/lib/child-capture.d.ts +9 -0
  17. package/lib/child-capture.js +24 -1
  18. package/lib/client/ProfileModelsDialog.d.ts +23 -0
  19. package/lib/client/ProfileModelsDialog.js +318 -0
  20. package/lib/client/ProfilesSection.js +228 -34
  21. package/lib/client/RoleToolView-data.d.ts +11 -4
  22. package/lib/client/RoleToolView-data.js +48 -1
  23. package/lib/client/RoleToolView-locales.d.ts +12 -4
  24. package/lib/client/RoleToolView-locales.js +12 -6
  25. package/lib/client/RoleToolView.js +49 -9
  26. package/lib/client/SessionProfiles.d.ts +5 -1
  27. package/lib/client/SessionProfiles.js +13 -9
  28. package/lib/client/StructuredEditor.d.ts +60 -0
  29. package/lib/client/StructuredEditor.js +73 -49
  30. package/lib/client/controller.d.ts +10 -0
  31. package/lib/client/controller.js +44 -14
  32. package/lib/client/diagnostics.d.ts +1 -0
  33. package/lib/client/diagnostics.js +9 -0
  34. package/lib/client/locales.d.ts +57 -0
  35. package/lib/client/locales.js +89 -17
  36. package/lib/client/session-labels.js +4 -1
  37. package/lib/client/structured.d.ts +4 -0
  38. package/lib/client/structured.js +16 -1
  39. package/lib/client/styles.d.ts +1 -1
  40. package/lib/client/styles.js +107 -30
  41. package/lib/client.js +2424 -1049
  42. package/lib/host-llm.js +3 -3
  43. package/lib/index.js +1 -1
  44. package/lib/model-routing.d.ts +3 -2
  45. package/lib/model-routing.js +28 -7
  46. package/lib/native-admission.d.ts +2 -0
  47. package/lib/native-admission.js +106 -34
  48. package/lib/profile-runtime.d.ts +11 -0
  49. package/lib/profile-runtime.js +48 -13
  50. package/lib/profile-store.d.ts +4 -1
  51. package/lib/profile-store.js +37 -14
  52. package/lib/role-control-rpc.js +18 -5
  53. package/lib/role-llm-runtime.js +10 -1
  54. package/lib/role-policy.d.ts +4 -3
  55. package/lib/role-policy.js +6 -6
  56. package/lib/role-providers.js +1 -0
  57. package/lib/runtime-recovery.d.ts +2 -2
  58. package/lib/runtime-recovery.js +7 -4
  59. package/package.json +7 -2
package/lib/host-llm.js CHANGED
@@ -6,13 +6,13 @@ import { copyRouteJson } from "./route-json.js";
6
6
  import { modelRouteFromCall } from "./role-llm.js";
7
7
  import { classifyDsmmAgent } from "./runtime-integration.js";
8
8
  import { latestNativeModelSelection } from "./role-routing.js";
9
- import { resolveSelectedAgentPreset } from "./session-scope.js";
10
9
  import { capturedRoleInvocation } from "./role-invocation.js";
11
10
  export function captureDsmmEffortSource(agent) {
12
11
  const current = agent;
13
12
  const invocation = capturedRoleInvocation(current);
14
- if (latestNativeModelSelection(current) !== undefined
15
- || agent.session.header.origin !== "subagent" && !resolveSelectedAgentPreset(current.session)?.startsWith("dsmm-"))
13
+ if (latestNativeModelSelection(current) !== undefined)
14
+ return "native";
15
+ if (agent.session.header.origin !== "subagent")
16
16
  return "native";
17
17
  return invocation?.effortSource ?? (invocation?.routeSource === "inherited" ? "native" : "dsmm-config");
18
18
  }
package/lib/index.js CHANGED
@@ -146,7 +146,7 @@ export async function apply(input, config = {}, startupOptions = {}) {
146
146
  await registerHeadlessRoleTools(scope, controller, candidate, policy, nativeAdmission, agent);
147
147
  return;
148
148
  }
149
- registerModelRouting(scope, controller, candidate);
149
+ registerModelRouting(scope, controller, candidate, agent);
150
150
  registerSafetyGuards(scope, controller, candidate, policy, commandApprovals);
151
151
  if (startup.settings.modules.deepwork.enabled) {
152
152
  if (ctx.get("subagents") !== undefined)
@@ -1,5 +1,6 @@
1
- import type { DshContext } from "./dsh-types.js";
1
+ import type { AgentRequestFrame, DshLlmCallConfig, DshAgent, DshContext } from "./dsh-types.js";
2
2
  import type { DsmmSettingsGetter } from "./settings.js";
3
3
  import type { DeepworkModeController } from "./state.js";
4
- export declare function registerModelRouting(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter): void;
4
+ export declare function prepareDsmmRequest(frame: AgentRequestFrame, proposal: DshLlmCallConfig, assertCurrent: () => void): Promise<DshLlmCallConfig>;
5
+ export declare function registerModelRouting(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, agent?: DshAgent): void;
5
6
  //# sourceMappingURL=model-routing.d.ts.map
@@ -1,3 +1,4 @@
1
+ import { DsmmAwareLlmRuntime } from "./host-llm.js";
1
2
  import { applyModelRoute, clearRoleRouteLock, effectiveRoleFallbackRoutes, establishRolePolicy, latestNativeModelSelection, nativeModelSelectionWasAccepted, orderedModelRoutes, persistedRoleRoute, pinRoleRoute, roleRouteLock, selectInitialModelRoute, sameExactModelRoute, sameModelRoute, takeAdmittedRecoveryRoute } from "./role-routing.js";
2
3
  import { resolveAdmittedDsmmRole } from "./role-policy.js";
3
4
  import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
@@ -6,7 +7,14 @@ import { capturedRoleInvocation } from "./role-invocation.js";
6
7
  import { modelRouteFromCall } from "./role-llm.js";
7
8
  import { configuredModelParameterPolicy, resolvedModelParameterPolicy } from "./model-parameter-policy.js";
8
9
  import { registerRuntimeRecovery } from "./runtime-recovery.js";
9
- export function registerModelRouting(ctx, controller, getSettings) {
10
+ const preparations = new WeakMap();
11
+ export async function prepareDsmmRequest(frame, proposal, assertCurrent) {
12
+ const prepare = preparations.get(frame.agent);
13
+ if (!prepare)
14
+ throw new Error("Admitted Agent has no request preparation binding");
15
+ return prepare(frame, proposal, assertCurrent);
16
+ }
17
+ export function registerModelRouting(ctx, controller, getSettings, agent) {
10
18
  const installedContexts = new WeakSet();
11
19
  const install = (readyCtx) => {
12
20
  if (installedContexts.has(readyCtx) || readyCtx.on === undefined)
@@ -16,16 +24,19 @@ export function registerModelRouting(ctx, controller, getSettings) {
16
24
  const assembledSelections = new WeakMap();
17
25
  let dispose, disposeAgent, disposeAssembly;
18
26
  try {
19
- registerRuntimeRecovery(readyCtx, controller, getSettings);
27
+ const owned = agent !== undefined && readyCtx.get?.("llm") instanceof DsmmAwareLlmRuntime;
28
+ let recovery;
29
+ registerRuntimeRecovery(readyCtx, controller, getSettings, owned ? prepare => { recovery = prepare; } : undefined);
20
30
  disposeAssembly = readyCtx.on("system-prompt/assemble", async (_assembly, context, next) => {
21
31
  if (context.agent !== undefined && context.signal !== undefined)
22
32
  assembledSelections.set(context.agent, { signal: context.signal, intent: latestNativeModelSelection(context.agent) });
23
33
  return next();
24
34
  }, { prepend: true });
25
- dispose = readyCtx.on("agent/request", async (frame, next) => {
26
- const downstream = await next();
35
+ const prepare = async (frame, proposal, assertCurrent = () => frame.signal.throwIfAborted()) => {
36
+ const downstream = recovery === undefined ? proposal : await recovery(frame, proposal);
27
37
  if (frame.signal.aborted)
28
38
  return downstream;
39
+ assertCurrent();
29
40
  const settings = getSettings(frame.agent), admission = getSettings.admission?.(frame.agent);
30
41
  const parameterPolicy = admission === undefined ? configuredModelParameterPolicy(settings) : resolvedModelParameterPolicy(admission);
31
42
  if (!settings.modules.deepwork.enabled)
@@ -37,6 +48,7 @@ export function registerModelRouting(ctx, controller, getSettings) {
37
48
  const invocation = capturedRoleInvocation(frame.agent);
38
49
  const primary = invocation?.initialRoute ?? policy?.primary;
39
50
  const identity = await establishRolePolicy(frame, settings, role, readyCtx, admission?.epoch);
51
+ assertCurrent();
40
52
  frame.signal.throwIfAborted();
41
53
  const fallbacks = effectiveRoleFallbackRoutes(settings, role);
42
54
  const currentStep = isCurrentRecoveryStep(ordinaryRoot ? sessionEvents(frame.agent.session) : childOwnedSessionEvents(frame.agent.session), frame.turn, frame.step);
@@ -59,9 +71,10 @@ export function registerModelRouting(ctx, controller, getSettings) {
59
71
  return downstream;
60
72
  }
61
73
  const llm = frame.agent.ctx?.get?.("llm") ?? readyCtx.get?.("llm") ?? readyCtx.llm;
74
+ const assembledManual = manual !== undefined && sameModelRoute(downstream, manual.route) && downstream.reasoningEffort === manual.route.reasoningEffort;
62
75
  if (manual !== undefined && lock?.manualSelectionSeq !== manual.seq
63
- && (sameModelRoute(downstream, manual.route) && downstream.reasoningEffort === manual.route.reasoningEffort || nativeModelSelectionWasAccepted(frame.agent, manual))) {
64
- const selected = modelRouteFromCall(downstream);
76
+ && (assembledManual || nativeModelSelectionWasAccepted(frame.agent, manual))) {
77
+ const selected = assembledManual ? modelRouteFromCall(downstream) : manual.route;
65
78
  const generation = (lock?.generation ?? -1) + 1;
66
79
  lock = pinRoleRoute(frame.agent, identity, selected, [selected, ...fallbacks], { preserveCandidates: parameterPolicy.mode === "native-defaults" });
67
80
  lock.manualSelectionSeq = manual.seq;
@@ -86,6 +99,7 @@ export function registerModelRouting(ctx, controller, getSettings) {
86
99
  const inherited = modelRouteFromCall(downstream);
87
100
  const candidates = invocation?.candidates ?? orderedModelRoutes([primary ?? inherited, ...fallbacks]);
88
101
  const selected = accepted ?? invocation?.initialRoute ?? (exactPolicy ? await selectInitialModelRoute(llm ?? {}, candidates, frame.signal, parameterPolicy.mode === "passthrough" ? readyCtx.get?.("dsmmLlmRoutes") : undefined) : inherited);
102
+ assertCurrent();
89
103
  frame.signal.throwIfAborted();
90
104
  lock = pinRoleRoute(frame.agent, identity, selected, candidates, { preserveCandidates: parameterPolicy.mode === "native-defaults", initialCandidate: accepted ?? invocation?.selectedCandidate });
91
105
  if (accepted !== undefined)
@@ -93,7 +107,14 @@ export function registerModelRouting(ctx, controller, getSettings) {
93
107
  lockedAgents.add(frame.agent);
94
108
  }
95
109
  return applyModelRoute(downstream, lock.route);
96
- }, { prepend: true });
110
+ };
111
+ if (owned) {
112
+ preparations.set(agent, prepare);
113
+ dispose = () => { if (preparations.get(agent) === prepare)
114
+ preparations.delete(agent); };
115
+ }
116
+ else
117
+ dispose = readyCtx.on("agent/request", async (frame, next) => prepare(frame, await next()), { prepend: true });
97
118
  disposeAgent = readyCtx.on("agent/disposed", ({ agent }) => { lockedAgents.delete(agent); clearRoleRouteLock(agent); }, { global: true });
98
119
  }
99
120
  catch (error) {
@@ -20,6 +20,8 @@ export declare class NativeAdmission {
20
20
  readonly policy: DsmmRolePolicy;
21
21
  readonly lifetime: AbortController;
22
22
  private readonly pending;
23
+ private readonly providers;
24
+ registerProvider(provider: SubagentProvider): void;
23
25
  private readonly live;
24
26
  private readonly candidates;
25
27
  private readonly agents;
@@ -2,15 +2,19 @@ import { randomUUID } from "node:crypto";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { getTraceable, symbols } from "@deepseek-ai/cordis";
4
4
  import { SessionId } from "@deepseek-ai/dsh-session";
5
- import { SubagentError, delegationDepthOf } from "@deepseek-ai/dsh-subagent";
5
+ import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
6
+ import { SubagentError, delegationDepthOf, foldSubagentDescriptor } from "@deepseek-ai/dsh-subagent";
6
7
  import { freezeSettings } from "./settings.js";
7
8
  import { scopeLifetime } from "./lifetime.js";
8
- import { sessionEvents } from "./session-scope.js";
9
- import { scopeParentOf } from "./native-scope.js";
9
+ import { sessionEvents, childOwnedSessionEvents } from "./session-scope.js";
10
+ import { scopeParentOf, scopeOf } from "./native-scope.js";
10
11
  import { DsmmProfileError } from "./profiles.js";
11
12
  import { roleProviderName } from "./roles.js";
12
13
  import { resolveRoleInvocation } from "./role-invocation.js";
13
14
  import { resolvedModelParameterPolicy } from "./model-parameter-policy.js";
15
+ import { roleFromProviderName } from "./role-providers.js";
16
+ import { isDsmmRoleId } from "./roles.js";
17
+ import { latestNativeModelSelection } from "./role-routing.js";
14
18
  /** Short-lived creation correlations and exact live bindings, never an execution queue. */
15
19
  export class NativeAdmission {
16
20
  ctx;
@@ -18,6 +22,8 @@ export class NativeAdmission {
18
22
  policy;
19
23
  lifetime = new AbortController();
20
24
  pending = new Map();
25
+ providers = new Map();
26
+ registerProvider(provider) { this.providers.set(provider.name, provider); }
21
27
  live = new WeakMap();
22
28
  candidates = new WeakMap();
23
29
  agents = new Set();
@@ -65,7 +71,7 @@ export class NativeAdmission {
65
71
  profiles.release(agent);
66
72
  policy.release(agent);
67
73
  }, { global: true });
68
- // Only exact DSMM captures are guarded; native reconstruction is not an admission request.
74
+ // Exact admitted and failed-admission objects stay guarded through retirement.
69
75
  ctx.on("agent/pre-step", async (frame, next) => { await this.guardExecution(frame.agent); return next(); }, { global: true, prepend: true });
70
76
  ctx.on("agent/request", async (frame, next) => { await this.guardExecution(frame.agent); return next(); }, { global: true, prepend: true });
71
77
  ctx.on("tools/execute", async (exec, next) => {
@@ -148,6 +154,11 @@ export class NativeAdmission {
148
154
  throw new SubagentError("Session configuration maintenance is in progress", "UNAUTHORIZED");
149
155
  if (!this.isReady || !live || this.ctx.agents.get(agent.id) !== agent)
150
156
  throw new SubagentError("No trusted live admission; create a new session", "UNAUTHORIZED");
157
+ if (this.ctx.get("sessions")?.get(agent.id) !== agent.session || agent.session.id !== agent.id || agent.session.header.id !== agent.id
158
+ || scopeOf(agent.ctx) !== agent || original(agent.ctx.get("agents")) !== original(this.ctx.agents)
159
+ || live.dependencies && this.dependencies(agent).some((value, index) => value !== live.dependencies[index])
160
+ || live.provider && this.ctx.get("subagents")?.getProvider(live.provider.name) !== live.provider)
161
+ throw new SubagentError("Native admission dependencies changed", "UNAUTHORIZED");
151
162
  if (live.preset !== agent.ctx.get("agentPresets")?.composedPreset(agent.ctx) || live.scopeParent !== scopeParentOf(agent))
152
163
  throw new SubagentError("Preset composition changed; create a new session", "UNAUTHORIZED");
153
164
  if (live.parent && (this.ctx.agents.get(live.parent.id) !== live.parent || !this.ctx.agents.isOwnedBy(agent.id, live.parent)))
@@ -393,7 +404,7 @@ export class NativeAdmission {
393
404
  this.agentLifetimes.get(agent).signal.throwIfAborted();
394
405
  if (!this.isReady || this.ctx.agents.get(agent.id) !== agent || this.live.get(agent) !== previous || scopeParentOf(agent) !== scopeParent)
395
406
  throw new SubagentError("Composition changed during blank admission", "UNAUTHORIZED");
396
- this.live.set(agent, Object.freeze({ ...previous, preset, scopeParent }));
407
+ this.live.set(agent, Object.freeze({ ...previous, preset, scopeParent, dependencies: this.dependencies(agent) }));
397
408
  }
398
409
  async created(agent, source, creationSignal) {
399
410
  if (this.owns(agent)) {
@@ -401,21 +412,55 @@ export class NativeAdmission {
401
412
  return;
402
413
  }
403
414
  const pending = this.pending.get(agent.id);
404
- // Native resume, promotion and durable provider recovery do not restore a DSMM role grant.
405
- if (source === "resume" && pending === undefined)
406
- return;
407
415
  if (pending && source !== "startup")
408
416
  throw new SubagentError("Role creation requires its first pending call", "UNAUTHORIZED");
409
417
  if (!this.isReady || !this.install)
410
418
  throw new SubagentError("DSMM admission is initializing", "UNAUTHORIZED");
411
- const signal = AbortSignal.any([...creationSignal ? [creationSignal] : [], this.lifetime.signal]);
419
+ let signal = AbortSignal.any([...creationSignal ? [creationSignal] : [], this.lifetime.signal]);
412
420
  signal.throwIfAborted();
413
421
  const parents = this.ctx.agents.list().filter(parent => parent !== agent && this.ctx.agents.isOwnedBy(agent.id, parent));
414
422
  const parent = parents[0], preset = agent.ctx.get("agentPresets")?.composedPreset(agent.ctx), presetScope = scopeParentOf(agent);
415
- if (parents.length > 1 || this.ctx.agents.get(agent.id) !== agent)
423
+ if (parents.length > 1 || this.ctx.agents.get(agent.id) !== agent || this.ctx.get("sessions")?.get(agent.id) !== agent.session
424
+ || agent.session.id !== agent.id || agent.session.header.id !== agent.id || scopeOf(agent.ctx) !== agent
425
+ || original(agent.ctx.get("agents")) !== original(this.ctx.agents))
416
426
  throw new SubagentError("Invalid native ownership", "UNAUTHORIZED");
417
- if (!pending && (parent && !this.owns(parent) || !parent && agent.session.header.origin === "subagent"))
427
+ const own = childOwnedSessionEvents(agent.session);
428
+ const descriptor = foldSubagentDescriptor(own);
429
+ if (!pending && parent && !this.owns(parent)) {
430
+ if (descriptor && roleFromProviderName(descriptor.provider) || isDsmmRoleId(preset)
431
+ || source === "resume" && await this.profiles.readChildIdentity(agent.id, parent.id))
432
+ throw new SubagentError("Role continuation requires an admitted parent", "UNAUTHORIZED");
418
433
  return;
434
+ }
435
+ if (!parent && (!this.ctx.agents.roots().includes(agent) || agent.session.header.origin === "subagent" || descriptor !== undefined))
436
+ throw new SubagentError("Child requires its native parent", "UNAUTHORIZED");
437
+ this.agentLifetimes.set(agent, new AbortController());
438
+ signal = AbortSignal.any([signal, this.agentLifetimes.get(agent).signal, ...parent ? [this.agentLifetimes.get(parent).signal] : []]);
439
+ scopeLifetime(agent.ctx, "dsmm: retire exact Agent work", () => { void this.retireAgent(agent).catch(() => { }); });
440
+ agent.ctx.effect(() => async () => {
441
+ try {
442
+ await this.retireAgent(agent);
443
+ }
444
+ finally {
445
+ this.live.delete(agent);
446
+ this.candidates.delete(agent);
447
+ this.agents.delete(agent);
448
+ this.profiles.release(agent);
449
+ this.policy.release(agent);
450
+ }
451
+ });
452
+ const dependencies = this.dependencies(agent);
453
+ const parentAdmission = parent ? this.assert(parent) : undefined;
454
+ const check = () => {
455
+ signal.throwIfAborted();
456
+ this.agentLifetimes.get(agent).signal.throwIfAborted();
457
+ if (!this.isReady || this.ctx.agents.get(agent.id) !== agent || this.ctx.get("sessions")?.get(agent.id) !== agent.session
458
+ || scopeOf(agent.ctx) !== agent || original(agent.ctx.get("agents")) !== original(this.ctx.agents)
459
+ || this.dependencies(agent).some((value, index) => value !== dependencies[index]) || scopeParentOf(agent) !== presetScope || preset !== agent.ctx.get("agentPresets")?.composedPreset(agent.ctx)
460
+ || parent && (this.assert(parent) !== parentAdmission || !this.ctx.agents.isOwnedBy(agent.id, parent)))
461
+ throw new SubagentError("Activation owner changed", "UNAUTHORIZED");
462
+ };
463
+ let continuation, independent = false, continuationProvider;
419
464
  let admission;
420
465
  if (parent) {
421
466
  const parentAdmission = this.assert(parent), controlled = this.policy.identity(parent).role !== undefined;
@@ -430,6 +475,46 @@ export class NativeAdmission {
430
475
  throw new SubagentError("Child exceeds depth ceiling", "UNAUTHORIZED");
431
476
  admission = pending.admission;
432
477
  }
478
+ else if (source === "resume") {
479
+ if (descriptor?.mode !== "continuable")
480
+ throw new SubagentError("Native child is not continuable", "NOT_RESUMABLE");
481
+ const subagents = this.ctx.get("subagents");
482
+ const rows = await subagents.listChildren(parent.id, signal);
483
+ check();
484
+ const row = rows.find(row => row.id === agent.id);
485
+ if (!row || row.mode !== "continuable")
486
+ throw new SubagentError("Native child catalog mismatch", "UNAUTHORIZED");
487
+ const metadata = await this.profiles.readChildIdentity(agent.id, parent.id);
488
+ check();
489
+ const ownPreset = own.find(event => event.type === "agent-preset/selected" || event.type === "subagent/descriptor");
490
+ independent = ownPreset?.type === "agent-preset/selected";
491
+ if (!independent && (preset !== parent.ctx.get("agentPresets")?.composedPreset(parent.ctx) || presetScope !== scopeParentOf(parent)))
492
+ throw new SubagentError("Inherited composition changed", "UNAUTHORIZED");
493
+ const nativeRole = roleFromProviderName(descriptor.provider) ?? (independent && isDsmmRoleId(preset) ? preset : undefined);
494
+ if (metadata && nativeRole && metadata.role !== nativeRole)
495
+ throw new SubagentError("Child role identity conflict", "UNAUTHORIZED");
496
+ const role = nativeRole ?? metadata?.role;
497
+ if (!role) {
498
+ admission = await this.profiles.prepareChild(agent, parentAdmission, signal);
499
+ check();
500
+ }
501
+ else {
502
+ continuationProvider = this.providers.get(roleProviderName(role));
503
+ const currentProvider = continuationProvider && subagents.getProvider(continuationProvider.name);
504
+ if (!continuationProvider || !currentProvider || original(currentProvider) !== original(continuationProvider))
505
+ throw new SubagentError("Role provider is unavailable", "UNAUTHORIZED");
506
+ admission = await this.profiles.prepareChild(agent, parentAdmission, signal, metadata);
507
+ check();
508
+ if (!admission.settings.modules.deepwork.enabled || !admission.settings.roles[role])
509
+ throw new SubagentError("Role is disabled", "UNAUTHORIZED");
510
+ this.policy.assertDelegation(parent, role);
511
+ const manual = latestNativeModelSelection(agent)?.route;
512
+ continuation = await resolveRoleInvocation(parent, role, admission.settings, signal, metadata ? { level: metadata.level } : {}, manual === undefined ? undefined : {
513
+ provider: manual.provider, model: manual.model, ...(manual.reasoningEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(manual.reasoningEffort) })
514
+ }, resolvedModelParameterPolicy(admission));
515
+ check();
516
+ }
517
+ }
433
518
  else {
434
519
  if (controlled || preset?.startsWith("dsmm-"))
435
520
  throw new SubagentError("Use an admitted DSMM role tool", "UNAUTHORIZED");
@@ -440,22 +525,9 @@ export class NativeAdmission {
440
525
  if (pending)
441
526
  throw new SubagentError("Missing exact parent", "UNAUTHORIZED");
442
527
  admission = await this.profiles.prepareRoot(agent, signal);
528
+ check();
443
529
  this.policy.validateRootRole(agent, admission);
444
530
  }
445
- this.agentLifetimes.set(agent, new AbortController());
446
- scopeLifetime(agent.ctx, "dsmm: retire exact Agent work", () => { void this.retireAgent(agent).catch(() => { }); });
447
- agent.ctx.effect(() => async () => {
448
- try {
449
- await this.retireAgent(agent);
450
- }
451
- finally {
452
- this.live.delete(agent);
453
- this.candidates.delete(agent);
454
- this.agents.delete(agent);
455
- this.profiles.release(agent);
456
- this.policy.release(agent);
457
- }
458
- });
459
531
  this.candidates.set(agent, admission);
460
532
  this.agents.add(agent);
461
533
  // These registrations belong to the Agent, not the plugin owner. Revocation remains effective after unload.
@@ -473,21 +545,21 @@ export class NativeAdmission {
473
545
  try {
474
546
  if (pending)
475
547
  this.policy.bindChild(agent, parent, admission, pending.invocation, pending.maxDepth, pending.toolFilter);
548
+ else if (continuation)
549
+ this.policy.bindChild(agent, parent, admission, continuation, this.ctx.get("subagents").resolveMaxDepth(admission.settings.subagents.maxDepth), this.policy.visibleToolCeiling(parent), independent);
476
550
  else if (parent)
477
- this.policy.bindInheritedChild(agent, parent, admission);
551
+ this.policy.bindInheritedChild(agent, parent, admission, source === "resume");
478
552
  await this.install(agent, this.getter(agent));
479
- signal.throwIfAborted();
480
- this.agentLifetimes.get(agent).signal.throwIfAborted();
553
+ check();
554
+ await this.profiles.revalidateActivation(admission);
555
+ check();
481
556
  if (pending)
482
557
  this.check(pending);
483
- if (parent)
484
- this.assert(parent);
485
- if (!this.isReady || this.ctx.agents.get(agent.id) !== agent || preset !== agent.ctx.get("agentPresets")?.composedPreset(agent.ctx)
486
- || presetScope !== scopeParentOf(agent) || parent && !this.ctx.agents.isOwnedBy(agent.id, parent))
487
- throw new SubagentError("Agent changed during initialization", "UNAUTHORIZED");
558
+ if (continuationProvider && this.ctx.get("subagents").getProvider(continuationProvider.name) !== continuationProvider)
559
+ throw new SubagentError("Role provider changed", "UNAUTHORIZED");
488
560
  this.profiles.publish(agent, admission);
489
561
  const published = this.profiles.admission(agent);
490
- this.live.set(agent, Object.freeze({ admission: published, preset, scopeParent: scopeParentOf(agent), parent, invocation: pending?.invocation }));
562
+ this.live.set(agent, Object.freeze({ admission: published, preset, scopeParent: scopeParentOf(agent), parent, invocation: pending?.invocation ?? continuation, dependencies, provider: pending?.provider ?? continuationProvider }));
491
563
  if (pending)
492
564
  this.pending.delete(agent.id);
493
565
  }
@@ -5,12 +5,16 @@ import type { DsmmProfileDocument } from "./profiles.js";
5
5
  import type { DsmmProfileAdmission, DsmmSettings, DsmmSettingsGetter, DsmmDeploymentSnapshot } from "./settings.js";
6
6
  import { DeepworkModeController } from "./state.js";
7
7
  import type { DsmmMountedPermissionGetter } from "./modules.js";
8
+ import type { ChildAdmissionIdentity } from "./child-capture.js";
8
9
  export interface DsmmProfileRuntimeStore {
9
10
  readonly profileDir?: string;
10
11
  readonly readOnly?: boolean;
11
12
  readonly origin?: "central" | "legacy" | "explicit";
12
13
  readonly writeRestriction?: string;
13
14
  loadSelection(): Promise<LoadedProfileSelection>;
15
+ loadSelectionIdentity(): Promise<LoadedProfileSelection>;
16
+ loadSessionSelectionIdentity(id: string): Promise<LoadedSessionProfileSelection>;
17
+ readChildIdentity(childId: string, parentId: string): Promise<ChildAdmissionIdentity | null>;
14
18
  describe(): Promise<ProfileSnapshot>;
15
19
  read(id: string): Promise<ProfileReadResult>;
16
20
  save(request: ProfileSaveRequest, assertCurrent?: () => void): Promise<ProfileReadResult>;
@@ -55,6 +59,8 @@ export declare class DsmmProfileRuntime {
55
59
  private readonly bound;
56
60
  private readonly observations;
57
61
  private readonly historyAdmissions;
62
+ private readonly activationChecks;
63
+ private readonly sessionObservations;
58
64
  private disposed;
59
65
  private queue;
60
66
  private readonly mode;
@@ -69,6 +75,11 @@ export declare class DsmmProfileRuntime {
69
75
  /** Prepare an explicit current choice; historical selection files and epochs are not read. */
70
76
  prepareHistory(profileId: string | null, signal: AbortSignal): Promise<PreparedHistoryProfile>;
71
77
  prepareRoot(agent: DshAgent, signal: AbortSignal): Promise<AdmittedProfile>;
78
+ readChildIdentity(childId: string, parentId: string): Promise<ChildAdmissionIdentity | null>;
79
+ prepareChild(agent: DshAgent, parent: DsmmProfileAdmission, signal: AbortSignal, identity?: ChildAdmissionIdentity | null): Promise<AdmittedProfile>;
80
+ private currentSelection;
81
+ private prepareActivation;
82
+ revalidateActivation(admission: DsmmProfileAdmission): Promise<void>;
72
83
  getSession(agent: DshAgent): Promise<DsmmSessionProfileSnapshot>;
73
84
  private sessionSnapshot;
74
85
  selectMode(request: SessionModeSelectRequest, agent: DshAgent, signal?: AbortSignal, authority?: () => void): Promise<DsmmSessionProfileSnapshot>;
@@ -38,6 +38,8 @@ export class DsmmProfileRuntime {
38
38
  bound = new WeakMap();
39
39
  observations = new WeakMap();
40
40
  historyAdmissions = new WeakSet();
41
+ activationChecks = new WeakMap();
42
+ sessionObservations = new WeakMap();
41
43
  disposed = false;
42
44
  queue = Promise.resolve();
43
45
  mode;
@@ -58,7 +60,7 @@ export class DsmmProfileRuntime {
58
60
  scopeLifetime(this.ctx, "dsmm: retire profile writes", retire);
59
61
  else
60
62
  this.ctx.effect?.(() => retire);
61
- const selection = await this.store.loadSelection();
63
+ const selection = await this.currentSelection(await this.store.loadSelectionIdentity());
62
64
  this.assertCurrent();
63
65
  this.document = selection.document === null ? null : freezeSettings(selection.document);
64
66
  this.current = this.prepare(this.document, selection);
@@ -138,29 +140,62 @@ export class DsmmProfileRuntime {
138
140
  async prepareRoot(agent, signal) {
139
141
  this.assertRoot(agent);
140
142
  signal.throwIfAborted();
141
- const deployment = await this.options.readDesired?.();
142
- const selection = await this.store.loadSessionSelection(agent.id);
143
- this.assertRoot(agent);
144
- signal.throwIfAborted();
145
- const candidate = selection.admissionEpoch === null
146
- ? this.prepare(this.document, this.observedSelection(this.current), newEpoch(), "global-default", deployment)
147
- : this.prepare(selection.document, selection, selection.admissionEpoch, selection.selectedId === null ? "deployment-baseline" : "session-override", deployment);
143
+ const candidate = await this.prepareActivation(agent.id, signal);
148
144
  const role = agent.ctx?.get?.("agentPresets")?.composedPreset(agent.ctx) ?? resolveSelectedAgentPreset(agent.session);
149
145
  if (role?.startsWith("dsmm-") && (!isDsmmRoleId(role) || !isRootRoleEnabled(candidate.settings, role)))
150
146
  throw new DsmmProfileError("activation", "Preset is not eligible for a root Agent.");
151
- await this.validate(candidate.settings);
152
147
  this.assertRoot(agent);
153
148
  signal.throwIfAborted();
154
149
  return candidate;
155
150
  }
151
+ readChildIdentity(childId, parentId) { return this.store.readChildIdentity(childId, parentId); }
152
+ prepareChild(agent, parent, signal, identity = null) {
153
+ return this.prepareActivation(agent.id, signal, identity === null ? parent : { scope: identity.profileId === null ? "deployment-baseline" : "session-override", profile: identity.profileId === null ? null : { id: identity.profileId, revision: "" } }, parent.settings.subagents.maxDepth);
154
+ }
155
+ async currentSelection(pointer) {
156
+ if (pointer.selectedId === null)
157
+ return pointer;
158
+ const saved = await this.store.read(pointer.selectedId);
159
+ return { ...pointer, appliedRevision: saved.revision, sourceRevision: saved.revision, content: saved.content,
160
+ document: parseProfileDocument(saved.content, saved.id), warnings: saved.warnings };
161
+ }
162
+ async prepareActivation(sessionId, signal, inherited, parentMaxDepth) {
163
+ const own = await this.store.loadSessionSelectionIdentity(sessionId);
164
+ const scope = own.admissionEpoch !== null ? own.selectedId === null ? "deployment-baseline" : "session-override" : inherited?.scope ?? "global-default";
165
+ const pointer = own.admissionEpoch !== null ? own : scope === "global-default" ? await this.store.loadSelectionIdentity()
166
+ : { selectedId: inherited?.profile?.id ?? null, appliedRevision: null, selectionRevision: "absent", document: null, content: null };
167
+ const selected = await this.currentSelection(pointer);
168
+ const deployment = await this.options.readDesired?.();
169
+ const prepared = this.prepare(selected.document, selected, newEpoch(), scope, deployment);
170
+ const candidate = parentMaxDepth === undefined ? prepared : freezeSettings({ ...prepared, settings: { ...prepared.settings,
171
+ subagents: { ...prepared.settings.subagents, maxDepth: Math.min(parentMaxDepth, prepared.settings.subagents.maxDepth ?? parentMaxDepth) } } });
172
+ const check = async () => {
173
+ this.assertCurrent();
174
+ signal.throwIfAborted();
175
+ const latestOwn = await this.store.loadSessionSelectionIdentity(sessionId);
176
+ const latest = scope === "global-default" && own.admissionEpoch === null ? await this.store.loadSelectionIdentity() : pointer;
177
+ if (latestOwn.selectionRevision !== own.selectionRevision || latest.selectionRevision !== pointer.selectionRevision
178
+ || selected.selectedId !== null && (await this.store.read(selected.selectedId)).revision !== selected.appliedRevision
179
+ || !isDeepStrictEqual(await this.options.readDesired?.(), deployment))
180
+ throw new DsmmProfileError("conflict", "Configuration changed during activation.");
181
+ this.assertCurrent();
182
+ signal.throwIfAborted();
183
+ };
184
+ await this.validate(candidate.settings);
185
+ await check();
186
+ this.activationChecks.set(candidate, check);
187
+ this.sessionObservations.set(candidate, own.selectionRevision);
188
+ return candidate;
189
+ }
190
+ async revalidateActivation(admission) { await this.activationChecks.get(admission)?.(); }
156
191
  async getSession(agent) {
157
192
  this.assertRoot(agent);
158
193
  const admitted = this.admission(agent);
159
- const disk = await this.store.loadSessionSelection(agent.id);
194
+ const disk = await this.store.loadSessionSelectionIdentity(agent.id);
160
195
  await this.ctx.get?.("dsmmNativeAdmission")?.ensure?.(agent);
161
196
  this.assertRoot(agent);
162
- if (this.admission(agent) !== admitted || !this.historyAdmissions.has(admitted) && ((disk.admissionEpoch === null && admitted.scope !== "global-default")
163
- || (disk.admissionEpoch !== null && (disk.admissionEpoch !== admitted.epoch || disk.selectedId !== admitted.selectedId || disk.appliedRevision !== admitted.appliedRevision)))) {
197
+ if (this.admission(agent) !== admitted || (this.sessionObservations.has(admitted) ? disk.selectionRevision !== this.sessionObservations.get(admitted) : !this.historyAdmissions.has(admitted) && ((disk.admissionEpoch === null && admitted.scope !== "global-default")
198
+ || (disk.admissionEpoch !== null && (disk.admissionEpoch !== admitted.epoch || disk.selectedId !== admitted.selectedId || disk.appliedRevision !== admitted.appliedRevision))))) {
164
199
  throw new DsmmProfileError("conflict", "The session choice changed outside this owner; its admitted configuration was retained.");
165
200
  }
166
201
  if (disk.admissionEpoch === admitted.epoch)
@@ -295,7 +330,7 @@ export class DsmmProfileRuntime {
295
330
  const disk = await this.store.describe();
296
331
  this.assertCurrent();
297
332
  const current = this.current;
298
- const changed = disk.selectedId !== current.selectedId || disk.appliedRevision !== current.appliedRevision
333
+ const changed = disk.selectedId !== current.selectedId
299
334
  || (this.observedSelection(current).selectionRevision !== "unavailable" && disk.selectionRevision !== this.observedSelection(current).selectionRevision);
300
335
  if (!changed && disk.selectionError === undefined)
301
336
  this.observations.set(current, selectionState(disk));
@@ -2,7 +2,7 @@ import type { Stats, BigIntStats } from "node:fs";
2
2
  import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSelectionState, ProfileSnapshot, SessionProfileSelectRequest } from "./profile-types.js";
3
3
  import type { DsmmProfileDocument } from "./profiles.js";
4
4
  import type { ProfileDiagnostic } from "./profile-diagnostics.js";
5
- import type { ChildAdmissionCapture } from "./child-capture.js";
5
+ import type { ChildAdmissionCapture, ChildAdmissionIdentity } from "./child-capture.js";
6
6
  export type SaveProfileRequest = ProfileSaveRequest;
7
7
  export type SelectProfileRequest = ProfileSelectRequest;
8
8
  export interface LoadedProfileSelection extends ProfileSelectionState {
@@ -67,6 +67,8 @@ export declare class ProfileStore {
67
67
  /** The optional fence belongs to the trusted server caller, never the saved document. */
68
68
  save(request: ProfileSaveRequest, assertCurrent?: () => void): Promise<ProfileReadResult>;
69
69
  loadSelection(): Promise<LoadedProfileSelection>;
70
+ loadSelectionIdentity(): Promise<LoadedProfileSelection>;
71
+ loadSessionSelectionIdentity(sessionId: string): Promise<LoadedSessionProfileSelection>;
70
72
  loadSessionSelection(sessionId: string): Promise<LoadedSessionProfileSelection>;
71
73
  selectSession<T>(request: SessionProfileSelectRequest, epoch: string, validateCandidate: (document: DsmmProfileDocument | null) => T | Promise<T>, commit: SessionProfileCommit<T>): Promise<{
72
74
  selection: LoadedSessionProfileSelection;
@@ -94,6 +96,7 @@ export declare class ProfileStore {
94
96
  /** Host-only immutable state. No RPC exposes this writer or a filesystem path. */
95
97
  createChildAdmission(input: ChildAdmissionCapture, assertCurrent?: () => void): Promise<ChildAdmissionCapture>;
96
98
  readChildAdmission(childId: string, parentId: string): Promise<ChildAdmissionCapture | null>;
99
+ readChildIdentity(childId: string, parentId: string): Promise<ChildAdmissionIdentity | null>;
97
100
  /** Only a trusted native session-deleted handler may call this; drain never does. */
98
101
  deleteChildAdmission(childId: string, parentId: string): Promise<void>;
99
102
  private childAdmission;