@dsmm/dsmm 0.3.0 → 0.3.1

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 (166) hide show
  1. package/README.md +26 -40
  2. package/cordis.patch.yml +0 -13
  3. package/docs/agent-presets.md +26 -14
  4. package/docs/compatibility.md +19 -73
  5. package/docs/deferred-native-approval-risk.md +8 -12
  6. package/docs/design.md +25 -254
  7. package/docs/lsp.md +2 -2
  8. package/docs/migration-from-ocmm.md +38 -51
  9. package/docs/model-routing.md +21 -21
  10. package/docs/native-permissions.md +17 -7
  11. package/docs/profiles.md +13 -9
  12. package/docs/releasing.md +34 -280
  13. package/docs/roadmap.md +23 -254
  14. package/docs/runtime-recovery.md +29 -91
  15. package/docs/safety-guards.md +19 -16
  16. package/docs/settings-status.md +23 -11
  17. package/docs/skill-sync.md +17 -17
  18. package/docs/web-fetch-fakeip.md +82 -0
  19. package/lib/child-capture.d.ts +12 -2
  20. package/lib/child-capture.js +22 -5
  21. package/lib/client/ChildrenPanel.d.ts +1 -4
  22. package/lib/client/ChildrenPanel.js +4 -16
  23. package/lib/client/DeploymentFields.d.ts +28 -0
  24. package/lib/client/DeploymentFields.js +68 -0
  25. package/lib/client/DeploymentPage.d.ts +17 -5
  26. package/lib/client/DeploymentPage.js +79 -112
  27. package/lib/client/NativeCommandEntries.d.ts +17 -0
  28. package/lib/client/NativeCommandEntries.js +68 -0
  29. package/lib/client/PermissionsPanel.d.ts +1 -1
  30. package/lib/client/PermissionsPanel.js +8 -8
  31. package/lib/client/ProfilesSection.js +7 -5
  32. package/lib/client/RoleToolView-data.d.ts +35 -0
  33. package/lib/client/RoleToolView-data.js +52 -0
  34. package/lib/client/RoleToolView-locales.d.ts +36 -0
  35. package/lib/client/RoleToolView-locales.js +20 -0
  36. package/lib/client/RoleToolView.d.ts +10 -0
  37. package/lib/client/RoleToolView.js +47 -0
  38. package/lib/client/SessionProfiles.js +39 -15
  39. package/lib/client/children-controller.d.ts +2 -8
  40. package/lib/client/children-controller.js +1 -26
  41. package/lib/client/children-locales.d.ts +27 -52
  42. package/lib/client/children-locales.js +8 -12
  43. package/lib/client/configuration-display.d.ts +5 -0
  44. package/lib/client/configuration-display.js +11 -0
  45. package/lib/client/controller.d.ts +1 -0
  46. package/lib/client/controller.js +20 -13
  47. package/lib/client/deployment-controller.d.ts +13 -1
  48. package/lib/client/deployment-controller.js +84 -24
  49. package/lib/client/deployment-data.d.ts +1 -0
  50. package/lib/client/deployment-data.js +4 -1
  51. package/lib/client/deployment-locales.d.ts +43 -0
  52. package/lib/client/deployment-locales.js +35 -9
  53. package/lib/client/deployment-modules.d.ts +9 -0
  54. package/lib/client/deployment-modules.js +24 -0
  55. package/lib/client/deployment-workspace.d.ts +48 -0
  56. package/lib/client/deployment-workspace.js +123 -0
  57. package/lib/client/index.js +11 -74
  58. package/lib/client/locales.d.ts +7 -0
  59. package/lib/client/locales.js +12 -6
  60. package/lib/client/permission-controller.d.ts +1 -0
  61. package/lib/client/permission-controller.js +3 -2
  62. package/lib/client/permission-locales.d.ts +25 -0
  63. package/lib/client/permission-locales.js +24 -4
  64. package/lib/client/session-labels.js +4 -3
  65. package/lib/client/styles.d.ts +1 -1
  66. package/lib/client/styles.js +9 -8
  67. package/lib/client.js +2713 -2361
  68. package/lib/commands.js +2 -0
  69. package/lib/config-file-store.d.ts +3 -0
  70. package/lib/config-file-store.js +4 -2
  71. package/lib/config-revision.d.ts +5 -0
  72. package/lib/config-revision.js +11 -0
  73. package/lib/core-permission-authority.js +11 -41
  74. package/lib/deployment-config.d.ts +9 -2
  75. package/lib/deployment-config.js +35 -8
  76. package/lib/deployment-permission-rules.js +19 -7
  77. package/lib/dsh-types.d.ts +1 -1
  78. package/lib/host-llm-startup.js +3 -3
  79. package/lib/host-llm.d.ts +9 -3
  80. package/lib/host-llm.js +48 -8
  81. package/lib/index.d.ts +16 -20
  82. package/lib/index.js +130 -416
  83. package/lib/lifetime.d.ts +4 -0
  84. package/lib/lifetime.js +22 -0
  85. package/lib/live-pi-ai-owner.d.ts +1 -0
  86. package/lib/live-pi-ai-owner.js +8 -4
  87. package/lib/mode.d.ts +3 -2
  88. package/lib/mode.js +28 -41
  89. package/lib/model-routing.d.ts +2 -8
  90. package/lib/model-routing.js +59 -175
  91. package/lib/native-admission.d.ts +56 -0
  92. package/lib/native-admission.js +313 -0
  93. package/lib/native-pi-ai-wire.d.ts +3 -1
  94. package/lib/native-pi-ai-wire.js +47 -13
  95. package/lib/permission-control.d.ts +0 -3
  96. package/lib/preset-registry.js +3 -2
  97. package/lib/preset-skills.d.ts +3 -12
  98. package/lib/preset-skills.js +28 -58
  99. package/lib/profile-diagnostics.d.ts +1 -1
  100. package/lib/profile-diagnostics.js +2 -2
  101. package/lib/profile-remote.js +61 -22
  102. package/lib/profile-rpc.d.ts +4 -3
  103. package/lib/profile-rpc.js +33 -37
  104. package/lib/profile-runtime.d.ts +31 -74
  105. package/lib/profile-runtime.js +224 -639
  106. package/lib/profile-store.d.ts +18 -6
  107. package/lib/profile-store.js +104 -62
  108. package/lib/profile-types.d.ts +18 -4
  109. package/lib/profiles.d.ts +3 -1
  110. package/lib/profiles.js +9 -7
  111. package/lib/prompt-content.d.ts +1 -0
  112. package/lib/prompt-content.js +4 -1
  113. package/lib/prompts.d.ts +2 -12
  114. package/lib/prompts.js +11 -66
  115. package/lib/role-control-remote.d.ts +1 -4
  116. package/lib/role-control-remote.js +8 -36
  117. package/lib/role-control-rpc.d.ts +10 -36
  118. package/lib/role-control-rpc.js +112 -269
  119. package/lib/role-control-types.d.ts +3 -26
  120. package/lib/role-control-types.js +3 -4
  121. package/lib/role-identity.d.ts +5 -0
  122. package/lib/role-identity.js +10 -0
  123. package/lib/role-invocation.d.ts +2 -2
  124. package/lib/role-llm-runtime.js +5 -11
  125. package/lib/role-policy.d.ts +19 -50
  126. package/lib/role-policy.js +136 -508
  127. package/lib/role-providers.d.ts +5 -8
  128. package/lib/role-providers.js +20 -86
  129. package/lib/role-routing.d.ts +1 -3
  130. package/lib/role-routing.js +24 -34
  131. package/lib/role-subagents.d.ts +5 -14
  132. package/lib/role-subagents.js +148 -106
  133. package/lib/runtime-integration.d.ts +5 -78
  134. package/lib/runtime-integration.js +11 -697
  135. package/lib/session-metadata.d.ts +13 -12
  136. package/lib/session-metadata.js +6 -31
  137. package/lib/session-scope.js +2 -1
  138. package/lib/settings.d.ts +5 -18
  139. package/lib/settings.js +19 -43
  140. package/lib/state.d.ts +3 -2
  141. package/lib/state.js +26 -10
  142. package/lib/status.d.ts +1 -9
  143. package/lib/status.js +3 -55
  144. package/lib/web-fetch-address-policy.d.ts +24 -0
  145. package/lib/web-fetch-address-policy.js +189 -0
  146. package/lib/web-fetch-fakeip.d.ts +25 -0
  147. package/lib/web-fetch-fakeip.js +107 -0
  148. package/package.json +113 -103
  149. package/docs/research/deepseek-v4-pro.md +0 -74
  150. package/docs/research/oh-dsh.md +0 -96
  151. package/lib/agent-registry.d.ts +0 -36
  152. package/lib/agent-registry.js +0 -75
  153. package/lib/child-admission.d.ts +0 -40
  154. package/lib/child-admission.js +0 -151
  155. package/lib/delivery-authority.d.ts +0 -83
  156. package/lib/delivery-authority.js +0 -397
  157. package/lib/native-child-evidence.d.ts +0 -40
  158. package/lib/native-child-evidence.js +0 -104
  159. package/lib/role-runs.d.ts +0 -138
  160. package/lib/role-runs.js +0 -335
  161. package/lib/session-persistence.d.ts +0 -36
  162. package/lib/session-persistence.js +0 -304
  163. package/lib/subagent-runtime.d.ts +0 -57
  164. package/lib/subagent-runtime.js +0 -257
  165. package/prompts/deepseek-flash.md +0 -11
  166. package/prompts/deepseek-v4-pro.md +0 -14
@@ -1,431 +1,290 @@
1
1
  import { join } from "node:path";
2
- import { createHash, randomUUID } from "node:crypto";
2
+ import { randomBytes } from "node:crypto";
3
+ import { lstatSync } from "node:fs";
4
+ import { Context } from "@deepseek-ai/cordis";
3
5
  import { ProfileStore, validateSessionProfileId } from "./profile-store.js";
4
6
  import { DsmmProfileError, profileDocumentWarnings, requiredReason, resolveProfileSettings } from "./profiles.js";
5
7
  import { DSMM_ROLES, isDsmmRoleId } from "./roles.js";
8
+ import { freezeSettings, isRootRoleEnabled } from "./settings.js";
6
9
  import { roleRouteRuntimeState } from "./role-routing.js";
7
- import { sessionEvents } from "./session-scope.js";
8
- import { resolveAdmittedDsmmRole as resolveEffectiveDsmmRole } from "./role-policy.js";
10
+ import { resolveAdmittedDsmmRole } from "./role-policy.js";
11
+ import { resolveSelectedAgentPreset, sessionEvents } from "./session-scope.js";
9
12
  import { DeepworkModeController, hasOpenTurn } from "./state.js";
10
- import { freezeSettings, isRootRoleEnabled } from "./settings.js";
11
13
  import { resolveDshHome } from "./dsh-home.js";
12
- import { lstatSync } from "node:fs";
13
14
  import { projectDsmmModules } from "./modules.js";
14
- import { Context } from "@deepseek-ai/cordis";
15
15
  import { readOnlySettings, readOnlySettingSources } from "./status.js";
16
- import { resolveSelectedAgentPreset } from "./session-scope.js";
17
- import { admissionFromChildCapture, parseChildAdmissionCapture, parseLegacyChildEvidence } from "./child-capture.js";
18
- import { normalizeModelRouteJson } from "./route-json.js";
19
16
  import { resolvedModelParameterPolicy } from "./model-parameter-policy.js";
20
- import { scopeLifetime } from "./delivery-authority.js";
17
+ import { scopeLifetime } from "./lifetime.js";
18
+ function newEpoch() { return randomBytes(32).toString("hex"); }
19
+ function selectionState(selection) {
20
+ return { selectedId: selection.selectedId, appliedRevision: selection.appliedRevision, selectionRevision: selection.selectionRevision,
21
+ ...(selection.sourceRevision === undefined ? {} : { sourceRevision: selection.sourceRevision }),
22
+ ...(selection.refreshRequired || selection.selectionRevision === "unavailable" ? { refreshRequired: true } : {}) };
23
+ }
21
24
  function deploymentAdmissionView(admission) {
22
25
  return { modelParameterPolicy: resolvedModelParameterPolicy(admission), settings: { ...readOnlySettings(admission.settings) }, sources: readOnlySettingSources(admission.sources ?? {}),
23
26
  captures: readOnlySettingSources(admission.sourceCaptures?.fields ?? {}), restartRequired: [...admission.restartRequired ?? []], named: admission.profile === null ? null : { ...admission.profile } };
24
27
  }
25
- // Exact live native children retain their capture across DSMM runtime replacement.
26
- const childAdmissions = new WeakMap();
27
- function immutableSettings(settings) {
28
- return freezeSettings(settings);
29
- }
30
- /** Global defaults admit new roots; scoped idle switches replace one root's epoch. */
28
+ /** Configuration transactions and immutable snapshots; native admission owns Agent binding. */
31
29
  export class DsmmProfileRuntime {
32
30
  ctx;
33
31
  store;
34
32
  options;
35
- childCaptureStore;
36
- getSettings = (agent) => agent === undefined ? this.current.settings : this.bind(agent).settings;
37
- current;
38
- currentDocument = null;
33
+ getSettings = agent => this.admission(agent).settings;
39
34
  baseline;
35
+ current;
36
+ document = null;
40
37
  bound = new WeakMap();
41
- admitting = new WeakSet();
42
- disposedAgents = new WeakSet();
43
- switching = new WeakSet();
44
- admissionObservers = new Set();
38
+ observations = new WeakMap();
45
39
  disposed = false;
46
- selectionQueue = Promise.resolve();
40
+ queue = Promise.resolve();
47
41
  mode;
48
42
  constructor(ctx, baseline, store, options = {}) {
49
43
  this.ctx = ctx;
50
44
  this.store = store;
51
45
  this.options = options;
52
- this.childCaptureStore = options.childCaptureStore ?? store;
53
- this.baseline = immutableSettings(baseline);
54
- this.mode = options.modeController ?? new DeepworkModeController({ get: (name) => ctx.get?.(name) }, (agent) => this.getSettings(agent).modules.deepwork.enabled);
46
+ this.baseline = freezeSettings(baseline);
47
+ this.mode = options.modeController ?? new DeepworkModeController(ctx, agent => this.getSettings(agent).modules.deepwork.enabled);
55
48
  this.current = this.prepare(null, { selectedId: null, appliedRevision: null, selectionRevision: "absent" });
56
- this.getSettings.admission = (agent) => this.admission(agent);
57
- this.getSettings.moduleStates = (agent) => { const admission = this.admission(agent); return projectDsmmModules(this.baseline, admission.deployment, admission, false, this.options.getMountedPermission); };
58
- this.getSettings.subagentRuntime = () => this.subagentRuntimeView();
49
+ this.getSettings.admission = agent => this.admission(agent);
50
+ this.getSettings.moduleStates = agent => { const admission = this.admission(agent); return projectDsmmModules(this.baseline, admission.deployment, admission, false, options.getMountedPermission); };
51
+ this.getSettings.subagentRuntime = () => this.runtimeView();
59
52
  }
60
53
  async initialize() {
61
- const retire = () => { this.disposed = true; this.admissionObservers.clear(); for (const agent of this.agents()?.list() ?? [])
62
- if (this.bound.has(agent))
63
- this.options.childAuthority?.revokeParent(agent, "runtime-disposed"); };
64
- if (this.ctx instanceof Context)
65
- scopeLifetime(this.ctx, "dsmm.profiles: retire admission lifecycle", retire);
54
+ const retire = () => { this.disposed = true; };
55
+ if (Context.is(this.ctx))
56
+ scopeLifetime(this.ctx, "dsmm: retire profile writes", retire);
66
57
  else
67
58
  this.ctx.effect?.(() => retire);
68
59
  const selection = await this.store.loadSelection();
69
- if (this.disposed)
70
- throw new DsmmProfileError("disposed", "Profile initialization was disposed.");
71
- this.currentDocument = selection.document === null ? null : freezeSettings(selection.document);
72
- this.current = this.prepare(selection.document, selection);
73
- this.ctx.on?.("agent/created", async ({ agent, signal }) => {
74
- // Factory initialization already owns native maintenance: never whenIdle
75
- // or reserve maintenance from inside this serial creation listener.
76
- await this.completeAdmission(agent, signal);
77
- }, { global: true, prepend: true });
78
- this.ctx.on?.("agent/disposed", ({ agent }) => { this.options.childAuthority?.revokeParent(agent, "agent-disposed"); this.disposedAgents.add(agent); childAdmissions.delete(agent); }, { global: true });
79
- if (this.options.onAdmissionGuardsInstalled !== undefined)
80
- await this.options.onAdmissionGuardsInstalled(this);
81
- // Installation into an already-running host treats those Agents as admitted
82
- // now, while all later profile switches continue to preserve their snapshot.
83
- const visited = new Set(), visiting = new Set();
84
- const admitExisting = async (agent) => {
85
- if (visited.has(agent))
86
- return;
87
- if (visiting.has(agent))
88
- throw new DsmmProfileError("not-owned", "Existing Agent ownership has a cycle; no child authority was inferred.");
89
- visiting.add(agent);
90
- const parent = this.owner(agent);
91
- if (parent !== undefined && this.options.deferRetainedChildren) {
92
- visiting.delete(agent);
93
- return;
94
- }
95
- if (parent !== undefined)
96
- await admitExisting(parent);
97
- await this.completeAdmission(agent, undefined, this.options.startup);
98
- visiting.delete(agent);
99
- visited.add(agent);
100
- };
101
- for (const agent of this.agents()?.list() ?? [])
102
- await admitExisting(agent);
60
+ this.assertCurrent();
61
+ this.document = selection.document === null ? null : freezeSettings(selection.document);
62
+ this.current = this.prepare(this.document, selection);
103
63
  }
104
- admission(agent) { return agent === undefined ? this.current : this.bind(agent); }
105
- /** Host enrollment observes completed exact admissions, never an entered but unpublished policy. */
106
- hasAdmission(agent) { return !this.disposed && !this.disposedAgents.has(agent) && this.bound.has(agent) && this.agents()?.get?.(agent.id) === agent; }
107
- observeAdmissions(observer) {
108
- if (this.disposed)
109
- throw new DsmmProfileError("disposed", "Profile admission observation was disposed.");
110
- this.admissionObservers.add(observer);
111
- return () => { this.admissionObservers.delete(observer); };
64
+ assertCurrent() { if (this.disposed)
65
+ throw new DsmmProfileError("disposed", "DSMM profile owner is retired."); }
66
+ admission(agent) {
67
+ this.assertCurrent();
68
+ if (agent === undefined)
69
+ return this.current;
70
+ const admission = this.bound.get(agent);
71
+ if (admission === undefined || !this.hasAdmission(agent))
72
+ throw new DsmmProfileError("activation", "Agent has no completed live native admission.");
73
+ return admission;
112
74
  }
113
- async announceAdmission(agent) {
114
- for (const observer of this.admissionObservers)
115
- await observer(agent);
75
+ hasAdmission(agent) {
76
+ const owner = this.ctx.get?.("dsmmNativeAdmission");
77
+ return !this.disposed && owner?.lifetime.signal.aborted !== true && this.bound.has(agent) && agent.id !== undefined
78
+ && this.ctx.get?.("agents")?.get(agent.id) === agent;
79
+ }
80
+ /** Called only by the awaited native creation owner after all Agent-scoped installation. */
81
+ publish(agent, admission) {
82
+ this.assertCurrent();
83
+ if (this.bound.has(agent))
84
+ throw new DsmmProfileError("conflict", "Agent admission is immutable.");
85
+ if (!("baseline" in admission) || !("selectedId" in admission) || !("appliedRevision" in admission) || !("selectionRevision" in admission)) {
86
+ throw new DsmmProfileError("activation", "Publication requires the complete configuration candidate.");
87
+ }
88
+ this.bound.set(agent, admission);
89
+ }
90
+ release(agent) { this.bound.delete(agent); }
91
+ async prepareRoot(agent, signal) {
92
+ this.assertRoot(agent);
93
+ signal.throwIfAborted();
94
+ const deployment = await this.options.readDesired?.();
95
+ const selection = await this.store.loadSessionSelection(agent.id);
96
+ this.assertRoot(agent);
97
+ signal.throwIfAborted();
98
+ const candidate = selection.admissionEpoch === null
99
+ ? this.prepare(this.document, this.observedSelection(this.current), newEpoch(), "global-default", deployment)
100
+ : this.prepare(selection.document, selection, selection.admissionEpoch, selection.selectedId === null ? "deployment-baseline" : "session-override", deployment);
101
+ const role = agent.ctx?.get?.("agentPresets")?.composedPreset(agent.ctx) ?? resolveSelectedAgentPreset(agent.session);
102
+ if (role?.startsWith("dsmm-") && (!isDsmmRoleId(role) || !isRootRoleEnabled(candidate.settings, role)))
103
+ throw new DsmmProfileError("activation", "Preset is not eligible for a root Agent.");
104
+ await this.validate(candidate.settings);
105
+ this.assertRoot(agent);
106
+ signal.throwIfAborted();
107
+ return candidate;
116
108
  }
117
109
  async getSession(agent) {
118
110
  this.assertRoot(agent);
119
- const admitted = this.bind(agent);
111
+ const admitted = this.admission(agent);
120
112
  const disk = await this.store.loadSessionSelection(agent.id);
113
+ await this.ctx.get?.("dsmmNativeAdmission")?.ensure?.(agent);
121
114
  this.assertRoot(agent);
122
- if (this.bind(agent) !== admitted)
123
- throw new DsmmProfileError("conflict", "The session admission changed while reading. Refresh before selecting again.");
124
- if ((disk.admissionEpoch === null && admitted.scope !== "global-default") || (disk.admissionEpoch !== null && (disk.admissionEpoch !== admitted.epoch || disk.selectedId !== admitted.selectedId || disk.appliedRevision !== admitted.appliedRevision))) {
125
- throw new DsmmProfileError("conflict", "The session choice changed outside this Host. Its admitted policy was retained; refresh or resume explicitly.");
115
+ if (this.admission(agent) !== admitted || (disk.admissionEpoch === null && admitted.scope !== "global-default")
116
+ || (disk.admissionEpoch !== null && (disk.admissionEpoch !== admitted.epoch || disk.selectedId !== admitted.selectedId || disk.appliedRevision !== admitted.appliedRevision))) {
117
+ throw new DsmmProfileError("conflict", "The session choice changed outside this owner; its admitted configuration was retained.");
126
118
  }
127
- const reason = this.store.readOnly ? "unavailable" : this.switching.has(agent) ? "maintenance" : agent.status === "running" ? "busy" : agent.runMaintenance === undefined ? "unavailable" : undefined;
128
- const role = resolveEffectiveDsmmRole(agent, admitted.settings, this.mode.active(agent, admitted.settings.defaultActive));
129
- const profileModel = this.declaredProfileModel(admitted.settings, role);
130
- return { sessionId: agent.id, globalDefault: selectionState(this.current), selection: selectionState(disk), admittedSelection: selectionState(admitted), scope: admitted.scope,
131
- rolePolicy: roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch), deepwork: this.mode.describe(agent, admitted.settings.defaultActive),
132
- modules: projectDsmmModules(this.baseline, admitted.deployment, admitted, false, this.options.getMountedPermission),
133
- configuration: deploymentAdmissionView(admitted),
134
- warnings: structuredClone(admitted.warnings ?? []), roles: structuredClone(admitted.roleAvailability ?? []), subagentRuntime: this.subagentRuntimeView(),
135
- ...(profileModel === undefined ? {} : { profileModel }),
136
- admissionEpoch: admitted.epoch, switchAllowed: reason === undefined, ...(reason === undefined ? {} : { switchUnavailableReason: reason }) };
119
+ const role = resolveAdmittedDsmmRole(agent, admitted.settings, this.mode.active(agent, admitted.settings.defaultActive));
120
+ const profileModel = role === undefined ? undefined : admitted.settings.roleRouting[role]?.primary;
121
+ const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
122
+ return { sessionId: agent.id, globalDefault: this.observedSelection(this.current), selection: selectionState(disk), admittedSelection: selectionState(admitted), scope: admitted.scope,
123
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), deepwork,
124
+ modules: projectDsmmModules(this.baseline, admitted.deployment, admitted, false, this.options.getMountedPermission), configuration: deploymentAdmissionView(admitted),
125
+ warnings: structuredClone(admitted.warnings ?? []), roles: structuredClone(admitted.roleAvailability ?? []), subagentRuntime: this.runtimeView(),
126
+ ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }), admissionEpoch: admitted.epoch,
127
+ ...this.sessionActions(agent, admitted, deepwork, profileModel !== undefined), switchAllowed: false, switchUnavailableReason: "unavailable" };
137
128
  }
138
- /** The fourth argument is trusted native caller authority, never wire data. */
139
- async selectMode(request, agent, signal, assertAuthority) {
129
+ async selectMode(request, agent, signal, authority) {
140
130
  this.assertRoot(agent);
141
131
  if (request.sessionId !== agent.id)
142
132
  throw new DsmmProfileError("not-owned", "The native session does not match the captured Agent.");
143
- const admitted = this.bind(agent);
144
- const assertCurrent = (maintenanceSignal) => {
133
+ const admitted = this.admission(agent);
134
+ const check = (maintenanceSignal) => {
145
135
  this.assertRoot(agent);
146
136
  if (signal?.aborted || maintenanceSignal?.aborted)
147
137
  throw new DsmmProfileError("cancelled", "The Deepwork change was cancelled.");
148
- const mode = this.mode.describe(agent, admitted.settings.defaultActive);
149
- if (this.bind(agent) !== admitted || admitted.epoch !== request.expectedAdmissionEpoch || mode.revision !== request.expectedModeRevision) {
150
- throw new DsmmProfileError("conflict", "The session profile, preset or mode changed. Refresh before retrying.");
151
- }
152
- assertAuthority?.();
138
+ if (this.admission(agent) !== admitted || admitted.epoch !== request.expectedAdmissionEpoch || this.mode.describe(agent, admitted.settings.defaultActive).revision !== request.expectedModeRevision)
139
+ throw new DsmmProfileError("conflict", "The session profile, preset or mode changed.");
140
+ authority?.();
153
141
  };
154
- assertCurrent();
142
+ check();
155
143
  if (request.active && !admitted.settings.modules.deepwork.enabled)
156
- throw new DsmmProfileError("unavailable", "Deepwork module is not admitted in this session; changing mode cannot enable it.", "modules.deepwork.enabled");
144
+ throw new DsmmProfileError("unavailable", "A mode intent cannot enable an unmounted Deepwork module.");
157
145
  if (agent.status === "running")
158
146
  throw new DsmmProfileError("busy", "Wait for the session to become idle.");
159
147
  if (agent.runMaintenance === undefined)
160
148
  throw new DsmmProfileError("unavailable", "Native idle maintenance is unavailable.");
161
- // Read before the write, so a later read failure cannot misreport a commit.
162
149
  const before = await this.getSession(agent);
163
- assertCurrent();
150
+ check();
164
151
  try {
165
152
  return await agent.runMaintenance(async (maintenanceSignal) => {
166
- this.switching.add(agent);
167
- try {
168
- assertCurrent(maintenanceSignal);
169
- if (hasOpenTurn(sessionEvents(agent.session)))
170
- throw new DsmmProfileError("busy", "A session turn is still open.");
171
- try {
172
- await this.mode.selectIdle(agent, request.active, admitted.settings.defaultActive);
173
- }
174
- catch {
175
- throw new DsmmProfileError("io", "The session mode could not be saved. Refresh before retrying.");
176
- }
177
- const role = resolveEffectiveDsmmRole(agent, admitted.settings, this.mode.active(agent, admitted.settings.defaultActive));
178
- const profileModel = this.declaredProfileModel(admitted.settings, role);
179
- const { profileModel: _previousModel, rolePolicy: _previousPolicy, ...snapshot } = before;
180
- return { ...snapshot, deepwork: this.mode.describe(agent, admitted.settings.defaultActive),
181
- rolePolicy: roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch), ...(profileModel === undefined ? {} : { profileModel }) };
182
- }
183
- finally {
184
- this.switching.delete(agent);
185
- }
153
+ check(maintenanceSignal);
154
+ if (hasOpenTurn(sessionEvents(agent.session)))
155
+ throw new DsmmProfileError("busy", "A session turn is still open.");
156
+ await this.mode.selectIdle(agent, request.active, admitted.settings.defaultActive);
157
+ const role = resolveAdmittedDsmmRole(agent, admitted.settings, this.mode.active(agent, admitted.settings.defaultActive));
158
+ const profileModel = role === undefined ? undefined : admitted.settings.roleRouting[role]?.primary;
159
+ const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
160
+ const { profileModel: _previous, selectModelUnavailableReason: _modelReason, toggleModeUnavailableReason: _modeReason, applyOverlayUnavailableReason: _overlayReason, ...snapshot } = before;
161
+ return { ...snapshot, deepwork, ...this.sessionActions(agent, admitted, deepwork, profileModel !== undefined),
162
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }) };
186
163
  });
187
164
  }
188
165
  catch (error) {
189
166
  if (error instanceof DsmmProfileError)
190
167
  throw error;
191
- throw new DsmmProfileError("maintenance", "The native session refused the Deepwork change. Refresh before retrying.");
168
+ throw new DsmmProfileError("maintenance", "The native session refused the Deepwork change.");
192
169
  }
193
170
  }
194
- selectSession(request, agent, signal, assertAuthority) {
171
+ async selectSession(_request, agent, _signal, _authority) {
195
172
  this.assertRoot(agent);
196
- if (request.sessionId !== agent.id)
197
- throw new DsmmProfileError("not-owned", "The native session does not match the captured Agent.");
198
- const admitted = this.bind(agent);
199
- const modeRevision = this.mode.describe(agent, admitted.settings.defaultActive).revision;
200
- const coreOnly = () => resolveEffectiveDsmmRole(agent, admitted.settings, this.mode.active(agent, admitted.settings.defaultActive)) === undefined;
201
- let requiresDelivery = this.options.childAuthority !== undefined && !coreOnly();
202
- const assertCurrent = (maintenanceSignal) => {
203
- this.assertRoot(agent);
204
- if (signal?.aborted || maintenanceSignal?.aborted)
205
- throw new DsmmProfileError("cancelled", "Session profile selection was cancelled; the previous admission was retained.");
206
- if (this.bind(agent) !== admitted || admitted.epoch !== request.expectedAdmissionEpoch || this.mode.describe(agent, admitted.settings.defaultActive).revision !== modeRevision)
207
- throw new DsmmProfileError("conflict", "The session admission changed. Refresh before selecting again.");
208
- if (this.options.childAuthority !== undefined) {
209
- if (requiresDelivery)
210
- this.assertDeliveryFence();
211
- if (!requiresDelivery && this.options.childAuthority.assertCoreParentAdmission !== undefined) {
212
- this.options.childAuthority.assertCoreParentAdmission(agent, this.options.childAuthorityOwner ?? this, admitted);
213
- }
214
- else {
215
- const ticket = this.options.childAuthority.acquireParentTicket(agent);
216
- if (ticket.admission !== admitted || ticket.owner !== (this.options.childAuthorityOwner ?? this))
217
- throw new DsmmProfileError("not-owned", "The stable Host authority does not own this exact admission.");
218
- }
219
- }
220
- assertAuthority?.();
221
- };
222
- assertCurrent();
223
- if (agent.status === "running")
224
- throw new DsmmProfileError("busy", "The session is running. Wait for its current activity before selecting a profile.");
225
- if (agent.runMaintenance === undefined)
226
- throw new DsmmProfileError("unavailable", "Native idle maintenance is unavailable; no session selection was committed.");
227
- let operation;
228
- try {
229
- operation = agent.runMaintenance(async (maintenanceSignal) => {
230
- this.switching.add(agent);
231
- try {
232
- assertCurrent(maintenanceSignal);
233
- const epoch = newEpoch();
234
- let profileModel;
235
- let committed;
236
- let next;
237
- const result = await this.store.selectSession(request, epoch, async (document) => {
238
- const prepared = immutableSettings(resolveProfileSettings(admitted.baseline, document?.settings ?? {}));
239
- const candidate = { settings: prepared, epoch, scope: request.id === null ? "deployment-baseline" : "session-override",
240
- profile: document === null ? null : { id: document.id, revision: request.expectedRevision } };
241
- this.assertRootRole(agent, prepared);
242
- this.validateRootRole(agent, candidate);
243
- const controlled = !coreOnly() || resolveEffectiveDsmmRole(agent, prepared, this.mode.active(agent, prepared.defaultActive)) !== undefined;
244
- requiresDelivery ||= controlled && (this.options.childAuthority !== undefined
245
- || ["roles", "guards", "subagents"].some(key => JSON.stringify(Reflect.get(prepared, key)) !== JSON.stringify(Reflect.get(admitted.settings, key))));
246
- if (requiresDelivery)
247
- this.assertDeliveryFence();
248
- await this.validate(prepared, requiresDelivery);
249
- assertCurrent(maintenanceSignal);
250
- this.assertRootRole(agent, prepared);
251
- this.validateRootRole(agent, candidate);
252
- const role = resolveEffectiveDsmmRole(agent, prepared, this.mode.active(agent, prepared.defaultActive));
253
- profileModel = this.declaredProfileModel(prepared, role);
254
- return prepared;
255
- }, {
256
- assertCurrent: () => assertCurrent(maintenanceSignal),
257
- prepare: (selection, settings) => {
258
- next = this.profileAdmission(selection, settings, epoch, request.id === null ? "deployment-baseline" : "session-override", admitted.baseline, admitted.deployment, admitted.restartRequired, selection.document, selection.warnings);
259
- this.validateRootRole(agent, next);
260
- if (!requiresDelivery && this.options.childAuthority?.prepareCoreParentAdmission !== undefined) {
261
- this.options.childAuthority.prepareCoreParentAdmission(agent, this.options.childAuthorityOwner ?? this, admitted, next);
262
- }
263
- else
264
- this.options.childAuthority?.prepareParentAdmission(agent, admitted.epoch, next);
265
- },
266
- committed: (selection, settings) => {
267
- const install = () => { this.bound.set(agent, next); };
268
- if (this.options.childAuthority !== undefined)
269
- this.options.childAuthority.publishParentAdmission(agent, admitted.epoch, next, install);
270
- else
271
- install();
272
- committed = next;
273
- }
274
- });
275
- try {
276
- this.mode.changed(agent);
277
- }
278
- catch { /* Observers cannot undo a successful durable admission publication. */ }
279
- // A committed selection remains a successful transaction even if a
280
- // queued wake or disposal wins immediately when maintenance releases.
281
- return { sessionId: request.sessionId, globalDefault: selectionState(this.current), selection: selectionState(result.selection), admittedSelection: selectionState(result.selection),
282
- deepwork: this.mode.describe(agent, result.prepared.defaultActive),
283
- modules: projectDsmmModules(this.baseline, committed.deployment, committed, false, this.options.getMountedPermission),
284
- configuration: deploymentAdmissionView(committed),
285
- warnings: structuredClone(committed.warnings ?? []), roles: structuredClone(committed.roleAvailability ?? []), subagentRuntime: this.subagentRuntimeView(),
286
- ...(profileModel === undefined ? {} : { profileModel }),
287
- scope: request.id === null ? "deployment-baseline" : "session-override", admissionEpoch: epoch, switchAllowed: true };
288
- }
289
- finally {
290
- this.switching.delete(agent);
291
- }
292
- });
293
- }
294
- catch (error) {
295
- if (error instanceof DsmmProfileError)
296
- throw error;
297
- throw new DsmmProfileError("maintenance", "Another activity owns the session's idle maintenance phase. No selection was queued or committed.");
298
- }
299
- return operation;
173
+ throw new DsmmProfileError("unavailable", "Live Apply is unavailable; save and select a default for new sessions.");
174
+ }
175
+ assertRoot(agent) {
176
+ this.assertCurrent();
177
+ validateSessionProfileId(agent.id);
178
+ const agents = this.ctx.get?.("agents");
179
+ if (agents?.get(agent.id) !== agent || !agents.roots().includes(agent) || agent.session.header?.origin === "subagent")
180
+ throw new DsmmProfileError("not-owned", "The exact live root Agent is required.");
300
181
  }
301
182
  async describe() {
302
- const persisted = await this.store.describe();
183
+ this.assertCurrent();
184
+ const disk = await this.store.describe();
185
+ this.assertCurrent();
303
186
  const current = this.current;
304
- const changedOutsideHost = persisted.selectedId !== current.selectedId
305
- || persisted.appliedRevision !== current.appliedRevision
306
- || persisted.selectionRevision !== current.selectionRevision;
307
- return {
308
- ...persisted,
309
- selectedWarnings: structuredClone(current.warnings ?? []),
310
- roles: DSMM_ROLES.map((role) => {
311
- const configured = this.baseline.roleRouting[role.id];
312
- const runtimePolicy = { ...(configured?.strategy === undefined ? {} : { strategy: configured.strategy }),
313
- ...(configured?.rateLimit === undefined ? {} : { rateLimit: structuredClone(configured.rateLimit) }) };
314
- return { id: role.id, label: role.name, enabled: this.current.settings.roles[role.id], availability: this.current.roleAvailability?.find(state => state.id === role.id),
315
- ...(Object.keys(runtimePolicy).length === 0 ? {} : { runtimePolicy }) };
316
- }),
317
- editorDefaults: structuredClone(this.baseline.runtimePolicy),
318
- selectedId: current.selectedId,
319
- appliedRevision: current.appliedRevision,
320
- // Keep the disk revision for CAS, but never label its unvalidated policy
321
- // as admitted in this Host. Existing Agent snapshots remain untouched.
322
- ...(persisted.selectionError === undefined && changedOutsideHost ? {
323
- selectionError: {
324
- code: "conflict",
325
- message: "The persisted selection changed outside this Host. New Agents still use this Host's admitted current policy; reapply the desired profile or restart."
326
- }
327
- } : {})
328
- };
187
+ const changed = disk.selectedId !== current.selectedId || disk.appliedRevision !== current.appliedRevision
188
+ || (this.observedSelection(current).selectionRevision !== "unavailable" && disk.selectionRevision !== this.observedSelection(current).selectionRevision);
189
+ if (!changed && disk.selectionError === undefined)
190
+ this.observations.set(current, selectionState(disk));
191
+ const { sourceRevision: _source, ...snapshot } = disk;
192
+ return { ...snapshot, selectedId: current.selectedId, appliedRevision: current.appliedRevision,
193
+ ...(current.sourceRevision === undefined ? {} : { sourceRevision: current.sourceRevision }),
194
+ selectedWarnings: structuredClone(current.warnings ?? []), editorDefaults: structuredClone(this.baseline.runtimePolicy), roles: this.editorRoles(current),
195
+ ...(disk.selectionError === undefined && changed ? { selectionError: { code: "conflict", message: "The persisted selection changed outside this Host. Reapply the desired profile or restart; the admitted policy was retained." } } : {}) };
329
196
  }
330
- read(id) { return this.store.read(id); }
331
- save(request) { return this.store.save(request); }
332
- getStartupSettings() { return this.baseline; }
333
- /** Preview uses the admission path but neither binds nor creates an Agent. */
334
- previewDeployment(desired) {
335
- return deploymentAdmissionView(this.prepare(this.currentDocument, this.current, this.current.epoch, "global-default", desired));
197
+ read(id) { this.assertCurrent(); return this.store.read(id); }
198
+ save(request, authority) {
199
+ const assertCurrent = () => { this.assertCurrent(); authority?.(); };
200
+ assertCurrent();
201
+ return this.store.save(request, assertCurrent);
336
202
  }
203
+ getStartupSettings() { return this.baseline; }
204
+ previewDeployment(desired) { return deploymentAdmissionView(this.prepare(this.document, this.current, newEpoch(), "global-default", desired)); }
337
205
  async describeDeployment(agent) {
206
+ this.assertCurrent();
338
207
  const desired = await this.options.readDesired?.();
339
- return { startup: this.options.startup ?? null, desired: desired ?? null, admission: this.admission(agent) };
208
+ this.assertCurrent();
209
+ return { startup: this.options.startup ?? null, desired: desired ?? null, admission: agent === undefined ? null : this.admission(agent) };
340
210
  }
341
- select(request) {
342
- const operation = this.selectionQueue.then(async () => {
343
- let selectedDocument = null;
211
+ select(request, authority) {
212
+ const assertCurrent = () => { this.assertCurrent(); authority?.(); };
213
+ const operation = this.queue.then(async () => {
214
+ assertCurrent();
215
+ const before = await this.describe();
216
+ assertCurrent();
344
217
  const baseline = this.current.baseline;
345
- const result = await this.store.select(request, async (document) => {
346
- selectedDocument = document === null ? null : freezeSettings(document);
347
- const prepared = immutableSettings(resolveProfileSettings(baseline, document?.settings ?? {}));
348
- await this.validate(prepared);
349
- return prepared;
350
- });
351
- // There is no await between successful durable commit and publication of
352
- // the complete settings value. Draft saves never reach this assignment.
353
- this.current = this.profileAdmission(result.selection, result.prepared, newEpoch(), "global-default", baseline, this.options.startup, this.current.restartRequired, selectedDocument, result.selection.warnings);
354
- this.currentDocument = selectedDocument;
355
- return this.describe();
218
+ let document = null;
219
+ let next;
220
+ let response;
221
+ const result = await this.store.select(request, async (value) => {
222
+ document = value === null ? null : freezeSettings(value);
223
+ const settings = freezeSettings(resolveProfileSettings(baseline, value?.settings ?? {}));
224
+ await this.validate(settings);
225
+ assertCurrent();
226
+ return settings;
227
+ }, { prepare: (selection, settings) => {
228
+ assertCurrent();
229
+ next = this.profileAdmission(selection, settings, newEpoch(), "global-default", baseline, this.current.deployment, this.current.restartRequired, document, selection.warnings);
230
+ const { selectionError: _error, sourceRevision: _source, refreshRequired: _refresh, ...snapshot } = before;
231
+ response = { ...snapshot, ...selectionState(selection), selectedWarnings: structuredClone(next.warnings ?? []), roles: this.editorRoles(next) };
232
+ },
233
+ committed: () => { this.current = next; this.document = document; } }, assertCurrent);
234
+ this.observations.set(next, selectionState(result.selection));
235
+ const { refreshRequired: _refresh, ...snapshot } = response;
236
+ return { ...snapshot, ...selectionState(result.selection) };
356
237
  });
357
- this.selectionQueue = operation.catch(() => undefined);
238
+ this.queue = operation.catch(() => undefined);
358
239
  return operation;
359
240
  }
360
241
  prepare(document, selection, epoch = newEpoch(), scope = "global-default", deployment = this.options.startup) {
361
- const desired = deployment?.settings ?? this.baseline;
362
- const effective = structuredClone(desired);
363
- const restartRequired = [];
364
- effective.modules.deepwork.enabled = desired.modules.deepwork.enabled && this.baseline.modules.deepwork.enabled;
365
- effective.subagents.allowRouteOverride = desired.subagents.allowRouteOverride && this.baseline.subagents.allowRouteOverride;
242
+ const desired = deployment?.settings ?? this.baseline, effective = structuredClone(desired), restartRequired = [];
243
+ effective.modules.deepwork.enabled &&= this.baseline.modules.deepwork.enabled;
244
+ effective.subagents.allowRouteOverride &&= this.baseline.subagents.allowRouteOverride;
245
+ if (desired.modules.deepwork.enabled && !this.baseline.modules.deepwork.enabled)
246
+ restartRequired.push("modules.deepwork.enabled");
366
247
  if (desired.subagents.allowRouteOverride && !this.baseline.subagents.allowRouteOverride)
367
248
  restartRequired.push("subagents.allowRouteOverride");
368
249
  if (this.baseline.subagents.maxDepth !== undefined && (desired.subagents.maxDepth === undefined || desired.subagents.maxDepth > this.baseline.subagents.maxDepth)) {
369
250
  effective.subagents.maxDepth = this.baseline.subagents.maxDepth;
370
251
  restartRequired.push("subagents.maxDepth");
371
252
  }
372
- if (desired.modules.deepwork.enabled && !this.baseline.modules.deepwork.enabled)
373
- restartRequired.push("modules.deepwork.enabled");
374
253
  for (const role of DSMM_ROLES) {
375
254
  if (desired.roles[role.id] && !this.baseline.roles[role.id])
376
255
  restartRequired.push(`roles.${role.id}`);
377
- effective.roles[role.id] = desired.roles[role.id] && this.baseline.roles[role.id];
256
+ effective.roles[role.id] &&= this.baseline.roles[role.id];
378
257
  }
379
- const capability = desired.subagents.backgroundMode === "continuable" ? this.options.subagentCapabilities?.continuable : this.options.subagentCapabilities?.backgroundJobs;
380
- if (desired.subagents.enableRunInBackground && capability === false) {
381
- effective.subagents.enableRunInBackground = false;
382
- restartRequired.push("subagents");
383
- }
384
- if (desired.permissionControl.enabled !== this.baseline.permissionControl.enabled)
385
- restartRequired.push("permissionControl.enabled");
386
- effective.permissionControl = { ...desired.permissionControl, enabled: this.baseline.permissionControl.enabled };
387
258
  for (const key of ["modeName", "promptOrder", "presets", "lsp"]) {
388
259
  if (JSON.stringify(desired[key]) !== JSON.stringify(this.baseline[key]))
389
260
  restartRequired.push(key);
390
261
  Object.assign(effective, { [key]: this.baseline[key] });
391
262
  }
392
- if (deployment !== undefined && this.options.startup !== undefined
393
- && (deployment.profile.section ?? deployment.global.section) !== (this.options.startup.profile.section ?? this.options.startup.global.section))
263
+ if (desired.permissionControl.enabled !== this.baseline.permissionControl.enabled)
264
+ restartRequired.push("permissionControl.enabled");
265
+ effective.permissionControl = { ...effective.permissionControl, enabled: this.baseline.permissionControl.enabled };
266
+ if (deployment !== undefined && this.options.startup !== undefined && (deployment.profile.section ?? deployment.global.section) !== (this.options.startup.profile.section ?? this.options.startup.global.section))
394
267
  restartRequired.push("section");
395
- const baseline = immutableSettings(effective);
396
- return this.profileAdmission(selection, immutableSettings(resolveProfileSettings(baseline, document?.settings ?? {})), epoch, scope, baseline, deployment, restartRequired, document, selection.warnings);
268
+ const baseline = freezeSettings(effective);
269
+ return this.profileAdmission(selection, freezeSettings(resolveProfileSettings(baseline, document?.settings ?? {})), epoch, scope, baseline, deployment, restartRequired, document, selection.warnings);
397
270
  }
398
- profileAdmission(selection, settings, epoch, scope, baseline = this.baseline, deployment = this.options.startup, restartRequired = [], document = null, warnings = profileDocumentWarnings(document)) {
271
+ profileAdmission(selection, settings, epoch, scope, baseline, deployment, restartRequired = [], document = null, warnings = profileDocumentWarnings(document)) {
399
272
  const sources = { ...deployment?.sources };
400
- const fields = Object.fromEntries(Object.keys(sources).map((path) => [path, "deployment"]));
401
- const pinStartup = (prefix) => {
402
- const matches = (path) => path === prefix || path.startsWith(`${prefix}.`);
403
- for (const path of Object.keys(sources).filter(matches)) {
273
+ const fields = Object.fromEntries(Object.keys(sources).map(path => [path, "deployment"]));
274
+ for (const prefix of ["modeName", "promptOrder", "presets", "lsp", "permissionControl.enabled", ...restartRequired]) {
275
+ for (const path of Object.keys(sources).filter(path => path === prefix || path.startsWith(`${prefix}.`))) {
404
276
  delete sources[path];
405
277
  delete fields[path];
406
278
  }
407
- for (const [path, source] of Object.entries(this.options.startup?.sources ?? {}).filter(([path]) => matches(path))) {
279
+ for (const [path, source] of Object.entries(this.options.startup?.sources ?? {}).filter(([path]) => path === prefix || path.startsWith(`${prefix}.`))) {
408
280
  sources[path] = source;
409
281
  fields[path] = "startup";
410
282
  }
411
- };
412
- for (const key of ["modeName", "promptOrder", "presets", "lsp", "permissionControl.enabled"])
413
- pinStartup(key);
414
- if (deployment?.settings.modules.deepwork.enabled && !baseline.modules.deepwork.enabled)
415
- pinStartup("modules.deepwork.enabled");
416
- if (deployment?.settings.subagents.allowRouteOverride && !baseline.subagents.allowRouteOverride)
417
- pinStartup("subagents.allowRouteOverride");
418
- if (deployment !== undefined && deployment.settings.subagents.maxDepth !== baseline.subagents.maxDepth)
419
- pinStartup("subagents.maxDepth");
420
- for (const role of DSMM_ROLES) {
421
- if (deployment?.settings.roles[role.id] && !baseline.roles[role.id])
422
- pinStartup(`roles.${role.id}`);
423
283
  }
424
284
  const mark = (value, path) => {
425
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
285
+ if (value !== null && typeof value === "object" && !Array.isArray(value))
426
286
  for (const [key, child] of Object.entries(value))
427
287
  mark(child, [...path, key]);
428
- }
429
288
  else {
430
289
  sources[path.join(".")] = "named-session";
431
290
  fields[path.join(".")] = "named-session";
@@ -434,348 +293,77 @@ export class DsmmProfileRuntime {
434
293
  for (const [role, policy] of Object.entries(document?.settings.roleRouting ?? {})) {
435
294
  const prefixes = [...policy?.primary === undefined ? [] : [`roleRouting.${role}.primary.`], ...Object.keys(policy?.levels ?? {}).map(level => `roleRouting.${role}.levels.${level}.`)];
436
295
  for (const prefix of prefixes)
437
- for (const path of Object.keys(sources).filter((path) => path.startsWith(prefix))) {
296
+ for (const path of Object.keys(sources).filter(path => path.startsWith(prefix))) {
438
297
  delete sources[path];
439
298
  delete fields[path];
440
299
  }
441
300
  }
442
301
  mark(document?.settings ?? {}, []);
443
- return Object.freeze({ ...selectionState(selection), settings, baseline, epoch, scope, ...(deployment === undefined ? {} : { deployment }),
444
- warnings: freezeSettings(warnings), roleAvailability: freezeSettings(this.roleAvailability(settings, baseline, deployment, document)), subagentRuntime: freezeSettings(this.subagentRuntimeView()),
445
- ...(this.store.origin === undefined ? {} : { store: Object.freeze({ origin: this.store.origin, readOnly: this.store.readOnly === true,
446
- ...(this.store.writeRestriction === undefined ? {} : { writeRestriction: this.store.writeRestriction }) }) }),
447
- sources: Object.freeze(sources), sourceCaptures: Object.freeze({ fields: Object.freeze(fields), ...(this.options.startup === undefined ? {} : { startup: Object.freeze({
448
- globalRevision: this.options.startup.globalRevision, nativeRevision: this.options.startup.nativeRevision
449
- }) }) }), restartRequired: Object.freeze([...restartRequired]), profile: selection.selectedId === null || selection.appliedRevision === null ? null : Object.freeze({ id: selection.selectedId, revision: selection.appliedRevision }) });
450
- }
451
- declaredProfileModel(settings, role) {
452
- const primary = role === undefined ? undefined : settings.roleRouting[role]?.primary;
453
- return primary === undefined ? undefined : normalizeModelRouteJson(primary);
454
- }
455
- agents() { return this.ctx.get?.("agents"); }
456
- bind(agent) {
457
- const existing = this.bound.get(agent);
458
- if (existing !== undefined)
459
- return existing;
460
- if (this.admitting.has(agent))
461
- throw new DsmmProfileError("activation", "The session's profile admission has not completed.");
462
- if (agent.id !== undefined && this.agents()?.get !== undefined) {
463
- // Native enter() precedes serial created admission. An early RPC or
464
- // extension (including unpublished setup) cannot make a native root skip
465
- // its persisted sidecar by eagerly creating a default binding.
466
- throw new DsmmProfileError("activation", "The native session has not completed its awaited profile admission.");
467
- }
468
- // The native factory enters the exact child/owner pair before announcing
469
- // creation. Durable lineage and inherited persona never establish ownership.
470
- const parent = this.owner(agent);
471
- if (parent === undefined && agent.session.header?.origin === "subagent")
472
- throw new DsmmProfileError("not-owned", "A child requires exact direct-parent admission, not current root defaults.");
473
- if (parent !== undefined)
474
- throw new DsmmProfileError("activation", "A retained child must complete role validation and authority registration before its settings are published.");
475
- const admitted = this.current;
476
- this.assertRootRole(agent, admitted.settings);
477
- this.validateRootRole(agent, admitted);
478
- this.bound.set(agent, admitted);
479
- try {
480
- this.options.childAuthority?.registerParent(agent, admitted, this.options.childAuthorityOwner ?? this);
481
- }
482
- catch (error) {
483
- this.bound.delete(agent);
484
- throw error;
485
- }
486
- return admitted;
487
- }
488
- owner(agent) {
489
- const agents = this.agents();
490
- return agent.id === undefined ? undefined : agents?.list().find((candidate) => candidate !== agent && agents.isOwnedBy(agent.id, candidate));
491
- }
492
- assertRoot(agent) {
493
- if (this.disposed || this.disposedAgents.has(agent))
494
- throw new DsmmProfileError("disposed", "The session or profile service was disposed; no selection was committed.");
495
- validateSessionProfileId(agent.id);
496
- const agents = this.agents();
497
- if (agents?.get === undefined)
498
- throw new DsmmProfileError("unavailable", "Native live Agent lookup is unavailable; no session selection was committed.");
499
- if (agents.get(agent.id) !== agent || this.owner(agent) !== undefined || agent.session.header?.origin === "subagent") {
500
- throw new DsmmProfileError("not-owned", "Session profile selection requires the exact live ordinary root Agent.");
501
- }
502
- }
503
- /** Host-only awaited completion for fresh, retained and cold exact Agents; no execution occurs here. */
504
- async completeAdmission(agent, signal, startup) {
505
- await this.admit(agent, signal, startup);
506
- return this.bound.get(agent);
507
- }
508
- async admit(agent, signal, startup) {
509
- if (this.bound.has(agent))
510
- return;
511
- const parent = this.owner(agent);
512
- if (parent !== undefined) {
513
- this.assertDeliveryFence();
514
- if (this.options.childAdmission === undefined)
515
- throw new DsmmProfileError("unavailable", "Child admission completion is not installed; no child policy was inferred from its current parent.");
516
- const ticket = this.options.childAuthority.acquireParentTicket(parent);
517
- this.assertOwnedParentTicket(ticket);
518
- const merged = AbortSignal.any([ticket.signal, ...signal === undefined ? [] : [signal]]);
519
- const prepared = await this.options.childAdmission.prepare(agent, parent, ticket, merged);
520
- merged.throwIfAborted();
521
- await this.completeChildAdmission(agent, parent, prepared, merged);
522
- return;
523
- }
524
- if (agent.session.header?.origin === "subagent")
525
- throw new DsmmProfileError("not-owned", "A child cannot be admitted as a new root without its exact live direct parent.");
526
- if (agent.id === undefined) {
527
- this.bind(agent);
528
- return;
529
- }
530
- this.admitting.add(agent);
531
- try {
532
- signal?.throwIfAborted();
533
- const deployment = startup ?? await this.options.readDesired?.();
534
- signal?.throwIfAborted();
535
- const selection = await this.store.loadSessionSelection(agent.id);
536
- signal?.throwIfAborted();
537
- if (this.disposed || this.disposedAgents.has(agent))
538
- throw new DsmmProfileError("disposed", "The session was disposed during profile admission.");
539
- const registry = this.agents();
540
- if (registry?.get !== undefined && registry.get(agent.id) !== agent)
541
- throw new DsmmProfileError("not-owned", "The live session changed during profile admission.");
542
- const candidate = selection.admissionEpoch === null
543
- ? this.options.readDesired === undefined ? this.current : this.prepare(this.currentDocument, this.current, newEpoch(), "global-default", deployment)
544
- : this.prepare(selection.document, selection, selection.admissionEpoch, selection.selectedId === null ? "deployment-baseline" : "session-override", deployment);
545
- this.assertRootRole(agent, candidate.settings);
546
- this.validateRootRole(agent, candidate);
547
- if (this.options.readDesired !== undefined)
548
- await this.validate(candidate.settings);
549
- signal?.throwIfAborted();
550
- if (this.disposed || this.disposedAgents.has(agent))
551
- throw new DsmmProfileError("disposed", "The session was disposed during deployment admission.");
552
- if (registry?.get !== undefined && registry.get(agent.id) !== agent)
553
- throw new DsmmProfileError("not-owned", "The live session changed during deployment admission.");
554
- this.assertRootRole(agent, candidate.settings);
555
- this.validateRootRole(agent, candidate);
556
- this.bound.set(agent, candidate);
557
- try {
558
- this.options.childAuthority?.registerParent(agent, candidate, this.options.childAuthorityOwner ?? this);
559
- }
560
- catch (error) {
561
- this.bound.delete(agent);
562
- throw error;
563
- }
564
- await this.announceAdmission(agent);
565
- signal?.throwIfAborted();
566
- if (this.disposed || this.disposedAgents.has(agent))
567
- throw new DsmmProfileError("disposed", "Root enrollment lost its live admission.");
568
- if (registry?.get !== undefined && registry.get(agent.id) !== agent)
569
- throw new DsmmProfileError("not-owned", "Root enrollment lost its exact residency.");
570
- }
571
- finally {
572
- this.admitting.delete(agent);
573
- }
574
- }
575
- /** Awaited native creation completion: evidence + persistence + role identity + exact-parent authority. */
576
- async completeChildAdmission(agent, parent, prepared, signal) {
577
- this.assertDeliveryFence();
578
- if (this.options.childAdmission === undefined)
579
- throw new DsmmProfileError("unavailable", "Child role validation is unavailable.");
580
- const ticket = this.options.childAuthority.acquireParentTicket(parent);
581
- this.assertOwnedParentTicket(ticket);
582
- const merged = AbortSignal.any([ticket.signal, ...signal === undefined ? [] : [signal]]);
583
- const evidence = "mode" in prepared.evidence ? parseLegacyChildEvidence(prepared.evidence) : parseChildAdmissionCapture(prepared.evidence);
584
- const check = () => {
585
- merged.throwIfAborted();
586
- if (this.disposed || this.disposedAgents.has(agent) || this.owner(agent) !== parent || this.agents()?.get?.(agent.id) !== agent || this.agents()?.get?.(parent.id) !== parent || evidence.childSessionId !== agent.id || evidence.parentSessionId !== parent.id)
587
- throw new DsmmProfileError("not-owned", "The exact child or its direct parent changed during admission.");
588
- const current = this.options.childAuthority.acquireParentTicket(parent);
589
- this.assertOwnedParentTicket(current);
590
- if (current.admission !== ticket.admission || current.owner !== ticket.owner)
591
- throw new DsmmProfileError("conflict", "The child creation parent ticket changed.");
592
- };
593
- check();
594
- if (prepared.creation && "mode" in evidence)
595
- throw new DsmmProfileError("validation", "New children require a full original capture, not legacy evidence.");
596
- const original = "mode" in evidence ? prepared.admission : admissionFromChildCapture(evidence, this.baseline);
597
- const retained = childAdmissions.get(agent);
598
- if (retained !== undefined && retained.parent !== parent)
599
- throw new DsmmProfileError("not-owned", "The retained child's exact direct parent changed.");
600
- if (retained !== undefined && prepared.creation)
601
- throw new DsmmProfileError("validation", "A retained child cannot be admitted as a new creation.");
602
- if (retained !== undefined && JSON.stringify(retained.evidence) !== JSON.stringify(evidence))
603
- throw new DsmmProfileError("corrupt-selection", "Retained child evidence cannot be replaced by a new parent policy.");
604
- const admission = retained?.admission ?? freezeSettings({ ...original, baseline: original.settings,
605
- selectedId: original.profile?.id ?? null, appliedRevision: original.profile?.revision ?? null, selectionRevision: "absent" });
606
- if (!("mode" in evidence)) {
607
- if (prepared.creation && evidence.originalAdmissionEpoch !== ticket.parentEpoch)
608
- throw new DsmmProfileError("conflict", "The child creation invocation epoch changed.");
609
- if (prepared.admission.epoch !== evidence.originalAdmissionEpoch || JSON.stringify(prepared.admission.profile) !== JSON.stringify(evidence.profilePin))
610
- throw new DsmmProfileError("validation", "Child admission identity does not match its original capture.");
611
- if (this.options.childCapturePersistence === "resident") {
612
- if (!prepared.creation && retained === undefined)
613
- throw new DsmmProfileError("unavailable", "Resident-only child capture has no cold restart guarantee.");
614
- }
615
- else {
616
- if (this.childCaptureStore.readChildAdmission === undefined || this.childCaptureStore.createChildAdmission === undefined)
617
- throw new DsmmProfileError("unavailable", "Durable child capture storage is unavailable.");
618
- if (prepared.creation)
619
- await this.childCaptureStore.createChildAdmission(evidence, check);
620
- else {
621
- const stored = await this.childCaptureStore.readChildAdmission(evidence.childSessionId, evidence.parentSessionId);
622
- if (JSON.stringify(stored) !== JSON.stringify(evidence))
623
- throw new DsmmProfileError("corrupt-selection", "The child evidence does not match its immutable stored capture.");
624
- }
625
- }
626
- }
627
- else {
628
- if (prepared.admission.profile !== null)
629
- throw new DsmmProfileError("validation", "Legacy admission cannot synthesize an original profile pin.");
630
- if (this.childCaptureStore.readChildAdmission === undefined)
631
- throw new DsmmProfileError("unavailable", "Legacy admission requires a safe capture-absence check.");
632
- if (await this.childCaptureStore.readChildAdmission(evidence.childSessionId, evidence.parentSessionId) !== null)
633
- throw new DsmmProfileError("corrupt-selection", "A captured child cannot be downgraded to legacy recovery.");
634
- }
635
- check();
636
- this.options.childAdmission.validateRole(agent, parent, { ...prepared, evidence, admission, retained: retained !== undefined });
637
- check();
638
- this.bound.set(agent, admission);
639
- try {
640
- this.options.childAuthority.registerParent(agent, admission, this.options.childAuthorityOwner ?? this);
641
- }
642
- catch (error) {
643
- this.bound.delete(agent);
644
- throw error;
645
- }
646
- childAdmissions.set(agent, { parent, admission, evidence });
647
- await this.announceAdmission(agent);
648
- check();
649
- }
650
- /** C's scoped resolver callback: original resident/durable evidence, then explicit trusted legacy folds. */
651
- async resolveOriginalChildEvidence(ticket, childId, signal, readLegacy) {
652
- validateSessionProfileId(childId);
653
- const merged = AbortSignal.any([ticket.signal, signal]);
654
- const check = () => {
655
- merged.throwIfAborted();
656
- this.assertDeliveryFence();
657
- if (this.disposed || this.disposedAgents.has(ticket.parent) || this.agents()?.get?.(ticket.parent.id) !== ticket.parent)
658
- throw new DsmmProfileError("not-owned", "Original child evidence requires its exact live direct parent.");
659
- const current = this.options.childAuthority.acquireParentTicket(ticket.parent);
660
- this.assertOwnedParentTicket(current);
661
- if (current.owner !== ticket.owner || current.admission !== ticket.admission || current.parentEpoch !== ticket.parentEpoch)
662
- throw new DsmmProfileError("conflict", "The original child evidence ticket changed.");
663
- };
664
- check();
665
- const child = this.agents().get(childId);
666
- if (child !== undefined && this.owner(child) !== ticket.parent)
667
- throw new DsmmProfileError("not-owned", "Original evidence is scoped to the actual direct child, not an ancestor.");
668
- const retained = child === undefined ? undefined : childAdmissions.get(child);
669
- if (retained !== undefined && retained.parent !== ticket.parent)
670
- throw new DsmmProfileError("not-owned", "The retained evidence has a different exact parent.");
671
- const checkChild = () => {
672
- const current = this.agents().get(childId);
673
- if (current !== undefined && this.owner(current) !== ticket.parent)
674
- throw new DsmmProfileError("not-owned", "The addressed child's direct owner changed during evidence reading.");
675
- if (retained !== undefined && (current !== child || childAdmissions.get(child) !== retained))
676
- throw new DsmmProfileError("conflict", "The retained child residency changed during evidence reading.");
677
- };
678
- const stored = await this.childCaptureStore.readChildAdmission?.(childId, ticket.parent.id);
679
- check();
680
- checkChild();
681
- if (stored !== undefined && stored !== null) {
682
- const capture = parseChildAdmissionCapture(stored);
683
- if (capture.childSessionId !== childId || capture.parentSessionId !== ticket.parent.id || retained !== undefined && JSON.stringify(retained.evidence) !== JSON.stringify(capture))
684
- throw new DsmmProfileError("corrupt-selection", "Original child capture identity does not match its scoped residency.");
685
- return capture;
686
- }
687
- if (retained !== undefined) {
688
- if (!("mode" in retained.evidence)) {
689
- if (this.options.childCapturePersistence !== "resident")
690
- throw new DsmmProfileError("corrupt-selection", "The durable original child capture is missing; legacy recovery is not allowed.");
691
- return retained.evidence;
692
- }
693
- if (stored === undefined)
694
- throw new DsmmProfileError("unavailable", "Legacy evidence requires a safe capture-absence check.");
695
- return retained.evidence;
696
- }
697
- if (stored === undefined || readLegacy === undefined)
698
- throw new DsmmProfileError("unavailable", "Original capture is unavailable; only an explicit trusted legacy evidence reader can recover a captureless child.");
699
- const evidence = parseLegacyChildEvidence(await readLegacy(ticket, childId, merged));
700
- check();
701
- checkChild();
702
- if (evidence.childSessionId !== childId || evidence.parentSessionId !== ticket.parent.id)
703
- throw new DsmmProfileError("not-owned", "Legacy evidence does not identify the addressed direct child.");
704
- return evidence;
705
- }
706
- assertOwnedParentTicket(ticket) {
707
- if (ticket.owner !== (this.options.childAuthorityOwner ?? this) || this.bound.get(ticket.parent) !== ticket.admission || ticket.parentEpoch !== ticket.admission.epoch)
708
- throw new DsmmProfileError("not-owned", "Child admission requires this entry's exact completed parent admission and owner.");
709
- }
710
- subagentRuntimeView() {
711
- const view = this.options.childAuthority?.view() ?? { binding: "unavailable", deliveryFenceReady: false, restartRequired: true, reason: "explicit-composition-required" };
712
- if (view.binding === "dsmm" && view.deliveryFenceReady && (this.options.childAdmission === undefined || this.options.validateRootRole === undefined))
713
- return { ...view, deliveryFenceReady: false, restartRequired: true, reason: "authority-not-ready" };
714
- return view;
715
- }
716
- assertDeliveryFence() {
717
- const view = this.subagentRuntimeView();
718
- if (view.binding !== "dsmm" || !view.deliveryFenceReady || this.options.childAuthority === undefined)
719
- throw new DsmmProfileError("unavailable", "This operation requires the explicit DSMM SubagentRuntime composition and ready Host admission authority; configure and restart before retrying.");
720
- }
721
- assertRootRole(agent, settings) {
722
- const role = resolveSelectedAgentPreset(agent.session);
723
- if (isDsmmRoleId(role) && (!settings.modules.deepwork.enabled || !settings.roles[role]))
724
- throw new DsmmProfileError("activation", "The selected root role is disabled by the candidate admission.", `settings.roles.${role}`, "deployment-ceiling");
725
- if (role === "dsmm-planner" && !settings.presets.plannerRootEnabled)
726
- throw new DsmmProfileError("activation", "The Planner root preset is disabled in the startup admission.", "settings.presets.plannerRootEnabled", "deployment-ceiling");
727
- }
728
- validateRootRole(agent, admission) {
729
- if (this.options.childAuthority !== undefined && this.options.validateRootRole === undefined)
730
- throw new DsmmProfileError("unavailable", "Root role admission completion is unavailable; no direct-parent authority was registered.");
731
- this.options.validateRootRole?.(agent, admission);
302
+ return freezeSettings({ ...selectionState(selection), settings, baseline, epoch, scope, ...(deployment === undefined ? {} : { deployment }),
303
+ warnings, restartRequired: [...restartRequired], sources, sourceCaptures: { fields, ...(this.options.startup === undefined ? {} : { startup: { globalRevision: this.options.startup.globalRevision, nativeRevision: this.options.startup.nativeRevision } }) }, subagentRuntime: this.runtimeView(),
304
+ ...(this.store.origin === undefined ? {} : { store: { origin: this.store.origin, readOnly: this.store.readOnly === true, ...(this.store.writeRestriction === undefined ? {} : { writeRestriction: this.store.writeRestriction }) } }),
305
+ roleAvailability: this.roleAvailability(settings, baseline, deployment, document),
306
+ profile: selection.selectedId === null || selection.appliedRevision === null ? null : { id: selection.selectedId, revision: selection.appliedRevision } });
732
307
  }
733
308
  roleAvailability(settings, baseline, deployment, document) {
734
309
  return DSMM_ROLES.map(role => {
735
310
  const required = requiredReason(settings, role.id), named = document?.settings.roles?.[role.id];
736
311
  const startup = this.baseline.roles[role.id], desired = deployment?.settings.roles[role.id] ?? baseline.roles[role.id];
737
- const admitted = settings.modules.deepwork.enabled && settings.roles[role.id];
738
312
  const reason = !settings.modules.deepwork.enabled ? "module-off" : !desired ? "deployment-disabled" : !startup ? "startup-unavailable" : named === false ? "profile-disabled" : undefined;
739
313
  const startupCeiling = !startup && desired;
740
- const source = named !== undefined ? "named-session" : startupCeiling ? this.options.startup?.sources[`roles.${role.id}`] ?? "defaults" : deployment?.sources[`roles.${role.id}`] ?? "defaults";
741
- const capture = named !== undefined ? "named-session" : startupCeiling ? "startup" : "deployment";
742
314
  return { id: role.id, required: required !== undefined, ...(required === undefined ? {} : { requiredReason: required }), startupAvailable: startup, deploymentEnabled: desired,
743
- ...(named === undefined ? {} : { namedEnabled: named }), admitted, ...(reason === undefined ? {} : { reason }), source, capture };
315
+ ...(named === undefined ? {} : { namedEnabled: named }), admitted: settings.modules.deepwork.enabled && settings.roles[role.id], ...(reason === undefined ? {} : { reason }),
316
+ source: named !== undefined ? "named-session" : startupCeiling ? this.options.startup?.sources[`roles.${role.id}`] ?? "defaults" : deployment?.sources[`roles.${role.id}`] ?? "defaults",
317
+ capture: named !== undefined ? "named-session" : startupCeiling ? "startup" : "deployment" };
744
318
  });
745
319
  }
746
- async validate(settings, auditPresets = true) {
320
+ editorRoles(admission) {
321
+ return DSMM_ROLES.map(role => {
322
+ const configured = this.baseline.roleRouting[role.id];
323
+ const runtimePolicy = { ...(configured?.strategy === undefined ? {} : { strategy: configured.strategy }), ...(configured?.rateLimit === undefined ? {} : { rateLimit: structuredClone(configured.rateLimit) }) };
324
+ return { id: role.id, label: role.name, enabled: admission.settings.roles[role.id], availability: admission.roleAvailability?.find(row => row.id === role.id), ...(Object.keys(runtimePolicy).length === 0 ? {} : { runtimePolicy }) };
325
+ });
326
+ }
327
+ sessionActions(agent, admission, mode, hasProfileModel) {
328
+ const llm = agent.ctx?.get?.("llm") ?? this.ctx.get?.("llm");
329
+ const selectModelUnavailableReason = !hasProfileModel ? "model-unconfigured" : llm?.resolveCallConfig === undefined ? "model-service-unavailable" : undefined;
330
+ const owner = this.ctx.get?.("dsmmNativeAdmission");
331
+ const ready = owner?.isReady === true && this.ctx.get?.("subagents") !== undefined && this.ctx.get?.("agentPresets") !== undefined;
332
+ const toggleModeUnavailableReason = agent.status === "running" || hasOpenTurn(sessionEvents(agent.session)) ? "busy"
333
+ : agent.runMaintenance === undefined ? "maintenance" : !mode.active && (!this.baseline.modules.deepwork.enabled || !admission.settings.modules.deepwork.enabled) ? "module-off"
334
+ : mode.locked || !mode.active && !ready ? "runtime-unavailable" : undefined;
335
+ return { canSelectModel: selectModelUnavailableReason === undefined, ...(selectModelUnavailableReason === undefined ? {} : { selectModelUnavailableReason }),
336
+ canToggleMode: toggleModeUnavailableReason === undefined, ...(toggleModeUnavailableReason === undefined ? {} : { toggleModeUnavailableReason }),
337
+ canApplyOverlay: false, applyOverlayUnavailableReason: "new-session-required" };
338
+ }
339
+ async validate(settings) {
747
340
  if (!settings.modules.deepwork.enabled)
748
341
  return;
749
342
  if (this.options.validateCandidate !== undefined) {
750
343
  await this.options.validateCandidate(settings);
751
344
  return;
752
345
  }
753
- if (!auditPresets)
346
+ if (this.options.runtimeView !== undefined && !this.runtimeView().deliveryFenceReady)
754
347
  return;
755
348
  const registry = this.ctx.get?.("agentPresets");
756
- if (registry !== undefined) {
757
- for (const role of DSMM_ROLES.filter((role) => isRootRoleEnabled(settings, role.id))) {
349
+ if (registry !== undefined)
350
+ for (const role of DSMM_ROLES.filter(role => isRootRoleEnabled(settings, role.id))) {
758
351
  try {
759
- const preset = await registry.resolve(role.id);
760
- if (preset.broken !== undefined)
352
+ if ((await registry.resolve(role.id)).broken !== undefined)
761
353
  throw new Error("unusable root preset");
762
354
  }
763
355
  catch {
764
- throw new DsmmProfileError("activation", "An enabled DW root preset is unavailable. Resolve the native preset loading error before applying a profile.", role.id);
356
+ throw new DsmmProfileError("activation", "An enabled root preset is unavailable.", role.id);
765
357
  }
766
358
  }
767
- }
768
359
  }
360
+ observedSelection(admission) { return this.observations.get(admission) ?? selectionState(admission); }
361
+ runtimeView() { return this.options.runtimeView?.() ?? { binding: "unavailable", deliveryFenceReady: false, restartRequired: true, reason: "authority-not-ready" }; }
769
362
  }
770
- function newEpoch() { return createHash("sha256").update(randomUUID()).digest("hex"); }
771
- function selectionState(selection) {
772
- return { selectedId: selection.selectedId, appliedRevision: selection.appliedRevision, selectionRevision: selection.selectionRevision };
773
- }
774
- /** No guessed home fallback: native deployment context owns this directory. */
775
363
  export async function createProfileRuntime(ctx, baseline, options = {}) {
776
364
  const profile = ctx.get?.("profileContext");
777
- if (typeof profile?.dir !== "string" || profile.dir.trim() === "")
778
- throw new DsmmProfileError("activation", "Deepwork profiles require the native deployment profile directory.");
365
+ if (!profile?.dir)
366
+ throw new DsmmProfileError("activation", "Profiles require an exact native profile directory.");
779
367
  const legacy = join(profile.dir, "dsmm-profiles");
780
368
  let exists = false;
781
369
  try {
@@ -783,15 +371,12 @@ export async function createProfileRuntime(ctx, baseline, options = {}) {
783
371
  exists = true;
784
372
  }
785
373
  catch (error) {
786
- if (!(error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT"))
787
- throw new DsmmProfileError("unsafe-path", "The current profile's legacy store could not be safely checked.");
374
+ if (error.code !== "ENOENT")
375
+ throw error;
788
376
  }
789
- // Loader callers use its actual public entry key. The old trusted non-Loader
790
- // constructor path has one compatibility namespace, not a guessed entry.
791
- const entry = options.startup?.entryId ?? (ctx instanceof Context ? ctx.fiber.entry?.id : undefined) ?? "trusted-direct";
377
+ const entry = options.startup?.entryId ?? (Context.is(ctx) ? ctx.fiber.entry?.id : undefined) ?? "trusted-direct";
792
378
  const store = exists ? ProfileStore.fromLegacy(legacy) : ProfileStore.fromCentral(resolveDshHome(profile.home), profile.dir, entry);
793
- const childCaptureStore = options.childCaptureStore ?? (exists ? ProfileStore.fromCentral(resolveDshHome(profile.home), profile.dir, entry) : store);
794
- const runtime = new DsmmProfileRuntime(ctx, baseline, store, { ...options, childCaptureStore });
379
+ const runtime = new DsmmProfileRuntime(ctx, baseline, store, options);
795
380
  await runtime.initialize();
796
381
  return runtime;
797
382
  }