@dsmm/dsmm 0.3.0 → 0.3.2

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 (245) hide show
  1. package/README.md +26 -40
  2. package/cordis.patch.yml +9 -13
  3. package/docs/agent-presets.md +26 -14
  4. package/docs/compatibility.md +24 -68
  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 +25 -311
  13. package/docs/roadmap.md +52 -241
  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/ChildPermissions.d.ts +43 -0
  22. package/lib/client/ChildPermissions.js +100 -0
  23. package/lib/client/ChildrenPanel.d.ts +5 -5
  24. package/lib/client/ChildrenPanel.js +6 -18
  25. package/lib/client/DeploymentFields.d.ts +32 -0
  26. package/lib/client/DeploymentFields.js +70 -0
  27. package/lib/client/DeploymentPage.d.ts +21 -6
  28. package/lib/client/DeploymentPage.js +80 -112
  29. package/lib/client/HistoryContinuation.d.ts +7 -0
  30. package/lib/client/HistoryContinuation.js +22 -0
  31. package/lib/client/NativeCommandEntries.d.ts +17 -0
  32. package/lib/client/NativeCommandEntries.js +68 -0
  33. package/lib/client/PermissionPanelEntry.d.ts +8 -0
  34. package/lib/client/PermissionPanelEntry.js +11 -0
  35. package/lib/client/PermissionsPanel.d.ts +3 -1
  36. package/lib/client/PermissionsPanel.js +10 -9
  37. package/lib/client/ProfilesSection.js +8 -6
  38. package/lib/client/RoleAvailability.js +1 -1
  39. package/lib/client/RoleToolView-data.d.ts +35 -0
  40. package/lib/client/RoleToolView-data.js +52 -0
  41. package/lib/client/RoleToolView-locales.d.ts +36 -0
  42. package/lib/client/RoleToolView-locales.js +20 -0
  43. package/lib/client/RoleToolView.d.ts +10 -0
  44. package/lib/client/RoleToolView.js +47 -0
  45. package/lib/client/SessionProfiles.js +51 -24
  46. package/lib/client/TemporaryPermissions.d.ts +21 -0
  47. package/lib/client/TemporaryPermissions.js +94 -0
  48. package/lib/client/children-controller.d.ts +2 -8
  49. package/lib/client/children-controller.js +1 -26
  50. package/lib/client/children-locales.d.ts +27 -52
  51. package/lib/client/children-locales.js +8 -12
  52. package/lib/client/configuration-display.d.ts +5 -0
  53. package/lib/client/configuration-display.js +11 -0
  54. package/lib/client/controller.d.ts +18 -0
  55. package/lib/client/controller.js +118 -28
  56. package/lib/client/deployment-controller.d.ts +13 -1
  57. package/lib/client/deployment-controller.js +84 -24
  58. package/lib/client/deployment-data.d.ts +1 -0
  59. package/lib/client/deployment-data.js +4 -1
  60. package/lib/client/deployment-locales.d.ts +43 -0
  61. package/lib/client/deployment-locales.js +45 -19
  62. package/lib/client/deployment-modules.d.ts +9 -0
  63. package/lib/client/deployment-modules.js +24 -0
  64. package/lib/client/deployment-workspace.d.ts +48 -0
  65. package/lib/client/deployment-workspace.js +123 -0
  66. package/lib/client/history-controller.d.ts +29 -0
  67. package/lib/client/history-controller.js +111 -0
  68. package/lib/client/history-entry.d.ts +11 -0
  69. package/lib/client/history-entry.js +106 -0
  70. package/lib/client/history-locales.d.ts +95 -0
  71. package/lib/client/history-locales.js +41 -0
  72. package/lib/client/index.js +26 -76
  73. package/lib/client/locales.d.ts +13 -0
  74. package/lib/client/locales.js +104 -86
  75. package/lib/client/permission-controller.d.ts +1 -0
  76. package/lib/client/permission-controller.js +3 -2
  77. package/lib/client/permission-locales.d.ts +51 -0
  78. package/lib/client/permission-locales.js +59 -19
  79. package/lib/client/session-labels.js +4 -3
  80. package/lib/client/styles.d.ts +1 -1
  81. package/lib/client/styles.js +9 -8
  82. package/lib/client/temporary-permission-client.d.ts +20 -0
  83. package/lib/client/temporary-permission-client.js +52 -0
  84. package/lib/client/temporary-permission-entry.d.ts +6 -0
  85. package/lib/client/temporary-permission-entry.js +56 -0
  86. package/lib/client.js +5691 -3439
  87. package/lib/commands.js +2 -0
  88. package/lib/config-file-store.d.ts +3 -0
  89. package/lib/config-file-store.js +4 -2
  90. package/lib/config-revision.d.ts +5 -0
  91. package/lib/config-revision.js +11 -0
  92. package/lib/core-permission-authority.js +11 -41
  93. package/lib/deployment-config.d.ts +9 -2
  94. package/lib/deployment-config.js +35 -8
  95. package/lib/deployment-permission-rules.js +19 -7
  96. package/lib/dsh-types.d.ts +1 -1
  97. package/lib/history-candidates.d.ts +30 -0
  98. package/lib/history-candidates.js +176 -0
  99. package/lib/history-codec.d.ts +11 -0
  100. package/lib/history-codec.js +102 -0
  101. package/lib/history-contract.d.ts +44 -0
  102. package/lib/history-contract.js +2 -0
  103. package/lib/history-controller.d.ts +42 -0
  104. package/lib/history-controller.js +329 -0
  105. package/lib/history-policy.d.ts +4 -0
  106. package/lib/history-policy.js +8 -0
  107. package/lib/history-remote.d.ts +28 -0
  108. package/lib/history-remote.js +17 -0
  109. package/lib/history-rpc.d.ts +24 -0
  110. package/lib/history-rpc.js +136 -0
  111. package/lib/history-support.d.ts +15 -0
  112. package/lib/history-support.js +21 -0
  113. package/lib/history-types.d.ts +67 -0
  114. package/lib/history-types.js +2 -0
  115. package/lib/host-llm-startup.js +3 -3
  116. package/lib/host-llm.d.ts +9 -3
  117. package/lib/host-llm.js +48 -8
  118. package/lib/index.d.ts +18 -20
  119. package/lib/index.js +147 -415
  120. package/lib/lifetime.d.ts +4 -0
  121. package/lib/lifetime.js +22 -0
  122. package/lib/live-pi-ai-owner.d.ts +1 -0
  123. package/lib/live-pi-ai-owner.js +8 -4
  124. package/lib/mode.d.ts +3 -2
  125. package/lib/mode.js +28 -41
  126. package/lib/model-routing.d.ts +2 -8
  127. package/lib/model-routing.js +59 -175
  128. package/lib/native-admission.d.ts +77 -0
  129. package/lib/native-admission.js +503 -0
  130. package/lib/native-pi-ai-wire.d.ts +3 -1
  131. package/lib/native-pi-ai-wire.js +47 -13
  132. package/lib/permission-child-control.d.ts +36 -0
  133. package/lib/permission-child-control.js +164 -0
  134. package/lib/permission-control.d.ts +2 -3
  135. package/lib/permission-control.js +7 -0
  136. package/lib/permission-controller.js +2 -2
  137. package/lib/permission-exec-argv.d.ts +32 -0
  138. package/lib/permission-exec-argv.js +171 -0
  139. package/lib/permission-fs-search.js +2 -1
  140. package/lib/permission-fs.js +2 -1
  141. package/lib/permission-native-rules.js +3 -3
  142. package/lib/permission-temporary-files.d.ts +19 -0
  143. package/lib/permission-temporary-files.js +248 -0
  144. package/lib/permission-temporary-grants.d.ts +106 -0
  145. package/lib/permission-temporary-grants.js +198 -0
  146. package/lib/permission-temporary-install.d.ts +25 -0
  147. package/lib/permission-temporary-install.js +86 -0
  148. package/lib/permission-temporary-remote.d.ts +19 -0
  149. package/lib/permission-temporary-remote.js +75 -0
  150. package/lib/permission-temporary-rpc.d.ts +37 -0
  151. package/lib/permission-temporary-rpc.js +154 -0
  152. package/lib/permission-temporary-types.d.ts +47 -0
  153. package/lib/permission-temporary-types.js +2 -0
  154. package/lib/permission-temporary-web.d.ts +11 -0
  155. package/lib/permission-temporary-web.js +154 -0
  156. package/lib/permission-web.js +2 -1
  157. package/lib/preset-registry.js +3 -2
  158. package/lib/preset-skills.d.ts +3 -12
  159. package/lib/preset-skills.js +28 -58
  160. package/lib/profile-diagnostics.d.ts +1 -1
  161. package/lib/profile-diagnostics.js +2 -2
  162. package/lib/profile-remote.js +61 -22
  163. package/lib/profile-rpc.d.ts +4 -3
  164. package/lib/profile-rpc.js +35 -37
  165. package/lib/profile-runtime.d.ts +42 -74
  166. package/lib/profile-runtime.js +314 -617
  167. package/lib/profile-store.d.ts +20 -8
  168. package/lib/profile-store.js +112 -63
  169. package/lib/profile-types.d.ts +19 -4
  170. package/lib/profiles.d.ts +3 -1
  171. package/lib/profiles.js +9 -7
  172. package/lib/prompt-content.d.ts +1 -0
  173. package/lib/prompt-content.js +4 -1
  174. package/lib/prompts.d.ts +2 -12
  175. package/lib/prompts.js +11 -66
  176. package/lib/role-control-remote.d.ts +1 -4
  177. package/lib/role-control-remote.js +8 -36
  178. package/lib/role-control-rpc.d.ts +10 -36
  179. package/lib/role-control-rpc.js +112 -269
  180. package/lib/role-control-types.d.ts +3 -26
  181. package/lib/role-control-types.js +3 -4
  182. package/lib/role-identity.d.ts +5 -0
  183. package/lib/role-identity.js +10 -0
  184. package/lib/role-invocation.d.ts +3 -3
  185. package/lib/role-invocation.js +2 -2
  186. package/lib/role-llm-runtime.js +5 -11
  187. package/lib/role-policy.d.ts +19 -50
  188. package/lib/role-policy.js +136 -508
  189. package/lib/role-providers.d.ts +5 -8
  190. package/lib/role-providers.js +20 -86
  191. package/lib/role-routing.d.ts +1 -3
  192. package/lib/role-routing.js +24 -34
  193. package/lib/role-subagents.d.ts +5 -14
  194. package/lib/role-subagents.js +163 -108
  195. package/lib/runtime-integration.d.ts +5 -78
  196. package/lib/runtime-integration.js +11 -697
  197. package/lib/session-metadata.d.ts +13 -12
  198. package/lib/session-metadata.js +6 -31
  199. package/lib/session-scope.js +2 -1
  200. package/lib/settings.d.ts +5 -18
  201. package/lib/settings.js +19 -43
  202. package/lib/skills.d.ts +1 -0
  203. package/lib/skills.js +5 -1
  204. package/lib/state.d.ts +3 -2
  205. package/lib/state.js +26 -10
  206. package/lib/status.d.ts +1 -9
  207. package/lib/status.js +3 -55
  208. package/lib/web-fetch-address-policy.d.ts +24 -0
  209. package/lib/web-fetch-address-policy.js +189 -0
  210. package/lib/web-fetch-fakeip.d.ts +25 -0
  211. package/lib/web-fetch-fakeip.js +107 -0
  212. package/package.json +124 -106
  213. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-api-gateway@0.2.1-rc.2.patch +13291 -0
  214. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-api-remotes@0.2.1-rc.2.patch +9133 -0
  215. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-client-ui-approval@0.2.1-rc.2.patch +156 -0
  216. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-subagent@0.2.1-rc.2.patch +3546 -0
  217. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-user-approval@0.2.1-rc.2.patch +431 -0
  218. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-web@0.2.1-rc.2.patch +119 -0
  219. package/patches/dsh-approval-settlement/README.md +41 -0
  220. package/patches/dsh-approval-settlement/metadata.json +10 -0
  221. package/patches/dsh-session-activation/@deepseek-ai__dsh-agent-loop@0.2.1-rc.2.patch +383 -0
  222. package/patches/dsh-session-activation/@deepseek-ai__dsh-agent-preset-registry@0.2.1-rc.2.patch +55 -0
  223. package/patches/dsh-session-activation/@deepseek-ai__dsh-api-session-controller@0.2.1-rc.2.patch +16673 -0
  224. package/patches/dsh-session-activation/@deepseek-ai__dsh-client-ui-subagent@0.2.1-rc.2.patch +29 -0
  225. package/patches/dsh-session-activation/@deepseek-ai__dsh-client-ui-workspace@0.2.1-rc.2.patch +196 -0
  226. package/patches/dsh-session-activation/@deepseek-ai__dsh-session-persistence-jsonl@0.2.1-rc.2.patch +35 -0
  227. package/patches/dsh-session-activation/@deepseek-ai__dsh-session-persistence@0.2.1-rc.2.patch +40 -0
  228. package/docs/research/deepseek-v4-pro.md +0 -74
  229. package/docs/research/oh-dsh.md +0 -96
  230. package/lib/agent-registry.d.ts +0 -36
  231. package/lib/agent-registry.js +0 -75
  232. package/lib/child-admission.d.ts +0 -40
  233. package/lib/child-admission.js +0 -151
  234. package/lib/delivery-authority.d.ts +0 -83
  235. package/lib/delivery-authority.js +0 -397
  236. package/lib/native-child-evidence.d.ts +0 -40
  237. package/lib/native-child-evidence.js +0 -104
  238. package/lib/role-runs.d.ts +0 -138
  239. package/lib/role-runs.js +0 -335
  240. package/lib/session-persistence.d.ts +0 -36
  241. package/lib/session-persistence.js +0 -304
  242. package/lib/subagent-runtime.d.ts +0 -57
  243. package/lib/subagent-runtime.js +0 -257
  244. package/prompts/deepseek-flash.md +0 -11
  245. package/prompts/deepseek-v4-pro.md +0 -14
@@ -1,431 +1,401 @@
1
1
  import { join } from "node:path";
2
- import { createHash, randomUUID } from "node:crypto";
2
+ import { randomBytes } from "node:crypto";
3
+ import { lstatSync, realpathSync } from "node:fs";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { Context } from "@deepseek-ai/cordis";
3
6
  import { ProfileStore, validateSessionProfileId } from "./profile-store.js";
4
- import { DsmmProfileError, profileDocumentWarnings, requiredReason, resolveProfileSettings } from "./profiles.js";
7
+ import { DsmmProfileError, parseProfileDocument, profileDocumentWarnings, requiredReason, resolveProfileSettings, validateProfileId } from "./profiles.js";
5
8
  import { DSMM_ROLES, isDsmmRoleId } from "./roles.js";
9
+ import { freezeSettings, isRootRoleEnabled } from "./settings.js";
6
10
  import { roleRouteRuntimeState } from "./role-routing.js";
7
- import { sessionEvents } from "./session-scope.js";
8
- import { resolveAdmittedDsmmRole as resolveEffectiveDsmmRole } from "./role-policy.js";
11
+ import { resolveAdmittedDsmmRole } from "./role-policy.js";
12
+ import { resolveSelectedAgentPreset, sessionEvents } from "./session-scope.js";
9
13
  import { DeepworkModeController, hasOpenTurn } from "./state.js";
10
- import { freezeSettings, isRootRoleEnabled } from "./settings.js";
11
14
  import { resolveDshHome } from "./dsh-home.js";
12
- import { lstatSync } from "node:fs";
13
15
  import { projectDsmmModules } from "./modules.js";
14
- import { Context } from "@deepseek-ai/cordis";
15
16
  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
17
  import { resolvedModelParameterPolicy } from "./model-parameter-policy.js";
20
- import { scopeLifetime } from "./delivery-authority.js";
18
+ import { scopeLifetime } from "./lifetime.js";
19
+ function newEpoch() { return randomBytes(32).toString("hex"); }
20
+ function selectionState(selection) {
21
+ return { selectedId: selection.selectedId, appliedRevision: selection.appliedRevision, selectionRevision: selection.selectionRevision,
22
+ ...(selection.sourceRevision === undefined ? {} : { sourceRevision: selection.sourceRevision }),
23
+ ...(selection.refreshRequired || selection.selectionRevision === "unavailable" ? { refreshRequired: true } : {}) };
24
+ }
21
25
  function deploymentAdmissionView(admission) {
22
26
  return { modelParameterPolicy: resolvedModelParameterPolicy(admission), settings: { ...readOnlySettings(admission.settings) }, sources: readOnlySettingSources(admission.sources ?? {}),
23
27
  captures: readOnlySettingSources(admission.sourceCaptures?.fields ?? {}), restartRequired: [...admission.restartRequired ?? []], named: admission.profile === null ? null : { ...admission.profile } };
24
28
  }
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. */
29
+ /** Configuration transactions and immutable snapshots; native admission owns Agent binding. */
31
30
  export class DsmmProfileRuntime {
32
31
  ctx;
33
32
  store;
34
33
  options;
35
- childCaptureStore;
36
- getSettings = (agent) => agent === undefined ? this.current.settings : this.bind(agent).settings;
37
- current;
38
- currentDocument = null;
34
+ getSettings = agent => this.admission(agent).settings;
39
35
  baseline;
36
+ current;
37
+ document = null;
40
38
  bound = new WeakMap();
41
- admitting = new WeakSet();
42
- disposedAgents = new WeakSet();
43
- switching = new WeakSet();
44
- admissionObservers = new Set();
39
+ observations = new WeakMap();
40
+ historyAdmissions = new WeakSet();
45
41
  disposed = false;
46
- selectionQueue = Promise.resolve();
42
+ queue = Promise.resolve();
47
43
  mode;
48
44
  constructor(ctx, baseline, store, options = {}) {
49
45
  this.ctx = ctx;
50
46
  this.store = store;
51
47
  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);
48
+ this.baseline = freezeSettings(baseline);
49
+ this.mode = options.modeController ?? new DeepworkModeController(ctx, agent => this.getSettings(agent).modules.deepwork.enabled);
55
50
  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();
51
+ this.getSettings.admission = agent => this.admission(agent);
52
+ this.getSettings.moduleStates = agent => { const admission = this.admission(agent); return projectDsmmModules(this.baseline, admission.deployment, admission, false, options.getMountedPermission); };
53
+ this.getSettings.subagentRuntime = () => this.runtimeView();
59
54
  }
60
55
  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);
56
+ const retire = () => { this.disposed = true; };
57
+ if (Context.is(this.ctx))
58
+ scopeLifetime(this.ctx, "dsmm: retire profile writes", retire);
66
59
  else
67
60
  this.ctx.effect?.(() => retire);
68
61
  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);
62
+ this.assertCurrent();
63
+ this.document = selection.document === null ? null : freezeSettings(selection.document);
64
+ this.current = this.prepare(this.document, selection);
103
65
  }
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); };
66
+ assertCurrent() { if (this.disposed)
67
+ throw new DsmmProfileError("disposed", "DSMM profile owner is retired."); }
68
+ admission(agent) {
69
+ this.assertCurrent();
70
+ if (agent === undefined)
71
+ return this.current;
72
+ const admission = this.bound.get(agent);
73
+ if (admission === undefined || !this.hasAdmission(agent))
74
+ throw new DsmmProfileError("activation", "Agent has no completed live native admission.");
75
+ return admission;
112
76
  }
113
- async announceAdmission(agent) {
114
- for (const observer of this.admissionObservers)
115
- await observer(agent);
77
+ hasAdmission(agent) {
78
+ const owner = this.ctx.get?.("dsmmNativeAdmission");
79
+ return !this.disposed && owner?.lifetime.signal.aborted !== true && this.bound.has(agent) && agent.id !== undefined
80
+ && this.ctx.get?.("agents")?.get(agent.id) === agent;
81
+ }
82
+ /** Called only by the awaited native creation owner after all Agent-scoped installation. */
83
+ publish(agent, admission) {
84
+ this.assertCurrent();
85
+ if (this.bound.has(agent))
86
+ throw new DsmmProfileError("conflict", "Agent admission is immutable.");
87
+ if (!("baseline" in admission) || !("selectedId" in admission) || !("appliedRevision" in admission) || !("selectionRevision" in admission)) {
88
+ throw new DsmmProfileError("activation", "Publication requires the complete configuration candidate.");
89
+ }
90
+ this.bound.set(agent, admission);
91
+ }
92
+ release(agent) { this.bound.delete(agent); }
93
+ /** Prepare an explicit current choice; historical selection files and epochs are not read. */
94
+ async prepareHistory(profileId, signal) {
95
+ this.assertCurrent();
96
+ signal.throwIfAborted();
97
+ if (profileId !== null)
98
+ validateProfileId(profileId);
99
+ const directory = profileId === null ? undefined : this.store.profileDir;
100
+ if (profileId !== null && directory === undefined)
101
+ throw new DsmmProfileError("unavailable", "History continuation requires an observable saved-profile store.");
102
+ const path = directory === undefined ? undefined : join(directory, `${profileId}.jsonc`);
103
+ const observe = () => {
104
+ if (path === undefined)
105
+ return undefined;
106
+ const stat = lstatSync(path, { bigint: true }), parent = lstatSync(directory, { bigint: true });
107
+ if (!stat.isFile() || stat.isSymbolicLink() || !parent.isDirectory() || parent.isSymbolicLink())
108
+ throw new DsmmProfileError("unsafe-path", "The saved profile source is not a regular file.");
109
+ return [realpathSync(directory), parent.dev, parent.ino, stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs];
110
+ };
111
+ const source = observe();
112
+ const saved = profileId === null ? null : await this.store.read(profileId);
113
+ const deployment = await this.options.readDesired?.();
114
+ const document = saved === null ? null : parseProfileDocument(saved.content, saved.id);
115
+ const candidate = this.prepare(document, { selectedId: profileId, appliedRevision: saved?.revision ?? null,
116
+ selectionRevision: "unavailable", ...(saved === null ? {} : { sourceRevision: saved.revision }) }, newEpoch(), profileId === null ? "deployment-baseline" : "session-override", deployment);
117
+ const assertCurrent = () => {
118
+ this.assertCurrent();
119
+ signal.throwIfAborted();
120
+ if (!isDeepStrictEqual(source, observe()))
121
+ throw new DsmmProfileError("conflict", "The saved profile changed during history continuation.");
122
+ };
123
+ await this.validate(candidate.settings);
124
+ assertCurrent();
125
+ this.historyAdmissions.add(candidate);
126
+ return { admission: candidate, ...(saved?.label === undefined ? {} : { label: saved.label }), assertCurrent,
127
+ revalidate: async (currentSignal) => {
128
+ currentSignal.throwIfAborted();
129
+ assertCurrent();
130
+ const desired = await this.options.readDesired?.();
131
+ if (!isDeepStrictEqual(desired, deployment))
132
+ throw new DsmmProfileError("conflict", "Deployment changed during history continuation.");
133
+ await this.validate(candidate.settings);
134
+ currentSignal.throwIfAborted();
135
+ assertCurrent();
136
+ } };
137
+ }
138
+ async prepareRoot(agent, signal) {
139
+ this.assertRoot(agent);
140
+ 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);
148
+ const role = agent.ctx?.get?.("agentPresets")?.composedPreset(agent.ctx) ?? resolveSelectedAgentPreset(agent.session);
149
+ if (role?.startsWith("dsmm-") && (!isDsmmRoleId(role) || !isRootRoleEnabled(candidate.settings, role)))
150
+ throw new DsmmProfileError("activation", "Preset is not eligible for a root Agent.");
151
+ await this.validate(candidate.settings);
152
+ this.assertRoot(agent);
153
+ signal.throwIfAborted();
154
+ return candidate;
116
155
  }
117
156
  async getSession(agent) {
118
157
  this.assertRoot(agent);
119
- const admitted = this.bind(agent);
158
+ const admitted = this.admission(agent);
120
159
  const disk = await this.store.loadSessionSelection(agent.id);
160
+ await this.ctx.get?.("dsmmNativeAdmission")?.ensure?.(agent);
121
161
  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.");
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)))) {
164
+ throw new DsmmProfileError("conflict", "The session choice changed outside this owner; its admitted configuration was retained.");
126
165
  }
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 }) };
166
+ if (disk.admissionEpoch === admitted.epoch)
167
+ this.observations.set(admitted, selectionState(disk));
168
+ return this.sessionSnapshot(agent, admitted, disk);
169
+ }
170
+ sessionSnapshot(agent, admitted, disk, inMaintenance = false) {
171
+ const role = resolveAdmittedDsmmRole(agent, admitted.settings, this.mode.active(agent, admitted.settings.defaultActive));
172
+ const profileModel = role === undefined ? undefined : admitted.settings.roleRouting[role]?.primary;
173
+ const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
174
+ return { sessionId: agent.id, globalDefault: this.observedSelection(this.current), selection: selectionState(disk), admittedSelection: this.observedSelection(admitted), scope: admitted.scope,
175
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), deepwork,
176
+ modules: projectDsmmModules(this.baseline, admitted.deployment, admitted, false, this.options.getMountedPermission), configuration: deploymentAdmissionView(admitted),
177
+ warnings: structuredClone(admitted.warnings ?? []), roles: structuredClone(admitted.roleAvailability ?? []), subagentRuntime: this.runtimeView(),
178
+ ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }), admissionEpoch: admitted.epoch,
179
+ ...this.sessionActions(agent, admitted, deepwork, profileModel !== undefined, inMaintenance), switchAllowed: false, switchUnavailableReason: "unavailable" };
137
180
  }
138
- /** The fourth argument is trusted native caller authority, never wire data. */
139
- async selectMode(request, agent, signal, assertAuthority) {
181
+ async selectMode(request, agent, signal, authority) {
140
182
  this.assertRoot(agent);
141
183
  if (request.sessionId !== agent.id)
142
184
  throw new DsmmProfileError("not-owned", "The native session does not match the captured Agent.");
143
- const admitted = this.bind(agent);
144
- const assertCurrent = (maintenanceSignal) => {
185
+ const admitted = this.admission(agent);
186
+ const check = (maintenanceSignal) => {
145
187
  this.assertRoot(agent);
146
188
  if (signal?.aborted || maintenanceSignal?.aborted)
147
189
  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?.();
190
+ if (this.admission(agent) !== admitted || admitted.epoch !== request.expectedAdmissionEpoch || this.mode.describe(agent, admitted.settings.defaultActive).revision !== request.expectedModeRevision)
191
+ throw new DsmmProfileError("conflict", "The session profile, preset or mode changed.");
192
+ authority?.();
153
193
  };
154
- assertCurrent();
194
+ check();
155
195
  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");
196
+ throw new DsmmProfileError("unavailable", "A mode intent cannot enable an unmounted Deepwork module.");
157
197
  if (agent.status === "running")
158
198
  throw new DsmmProfileError("busy", "Wait for the session to become idle.");
159
199
  if (agent.runMaintenance === undefined)
160
200
  throw new DsmmProfileError("unavailable", "Native idle maintenance is unavailable.");
161
- // Read before the write, so a later read failure cannot misreport a commit.
162
201
  const before = await this.getSession(agent);
163
- assertCurrent();
202
+ check();
164
203
  try {
165
204
  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
- }
205
+ check(maintenanceSignal);
206
+ if (hasOpenTurn(sessionEvents(agent.session)))
207
+ throw new DsmmProfileError("busy", "A session turn is still open.");
208
+ await this.mode.selectIdle(agent, request.active, admitted.settings.defaultActive);
209
+ const role = resolveAdmittedDsmmRole(agent, admitted.settings, this.mode.active(agent, admitted.settings.defaultActive));
210
+ const profileModel = role === undefined ? undefined : admitted.settings.roleRouting[role]?.primary;
211
+ const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
212
+ const { profileModel: _previous, selectModelUnavailableReason: _modelReason, toggleModeUnavailableReason: _modeReason, applyOverlayUnavailableReason: _overlayReason, ...snapshot } = before;
213
+ return { ...snapshot, deepwork, ...this.sessionActions(agent, admitted, deepwork, profileModel !== undefined),
214
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }) };
186
215
  });
187
216
  }
188
217
  catch (error) {
189
218
  if (error instanceof DsmmProfileError)
190
219
  throw error;
191
- throw new DsmmProfileError("maintenance", "The native session refused the Deepwork change. Refresh before retrying.");
220
+ throw new DsmmProfileError("maintenance", "The native session refused the Deepwork change.");
192
221
  }
193
222
  }
194
- selectSession(request, agent, signal, assertAuthority) {
223
+ async selectSession(request, agent, signal, authority) {
195
224
  this.assertRoot(agent);
225
+ if (this.historyAdmissions.has(this.admission(agent)))
226
+ throw new DsmmProfileError("unavailable", "A continued historical Agent is not a blank configuration target.");
196
227
  if (request.sessionId !== agent.id)
197
228
  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) => {
229
+ const previous = this.admission(agent);
230
+ const owner = this.ctx.get?.("dsmmNativeAdmission");
231
+ const check = (maintenanceSignal) => {
203
232
  this.assertRoot(agent);
204
233
  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
- }
234
+ throw new DsmmProfileError("cancelled", "The session configuration change was cancelled.");
235
+ if (this.admission(agent) !== previous || previous.epoch !== request.expectedAdmissionEpoch || this.ctx.get?.("dsmmNativeAdmission") !== owner) {
236
+ throw new DsmmProfileError("conflict", "The admitted session configuration changed; refresh before selecting again.");
219
237
  }
220
- assertAuthority?.();
238
+ authority?.();
221
239
  };
222
- assertCurrent();
240
+ check();
241
+ if (owner?.beginBlank === undefined || agent.runMaintenance === undefined)
242
+ throw new DsmmProfileError("unavailable", "Native blank-session configuration maintenance is unavailable.");
223
243
  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;
244
+ throw new DsmmProfileError("busy", "Wait for the session to become idle.");
228
245
  try {
229
- operation = agent.runMaintenance(async (maintenanceSignal) => {
230
- this.switching.add(agent);
246
+ return await agent.runMaintenance(async (maintenanceSignal) => {
247
+ check(maintenanceSignal);
248
+ const transaction = owner.beginBlank(agent, signal === undefined ? maintenanceSignal : AbortSignal.any([maintenanceSignal, signal]), () => check(maintenanceSignal));
249
+ const assertCurrent = () => transaction.assertCurrent();
250
+ let next, response;
231
251
  try {
232
- assertCurrent(maintenanceSignal);
233
252
  const epoch = newEpoch();
234
- let profileModel;
235
- let committed;
236
- let next;
237
253
  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;
254
+ const deployment = await this.options.readDesired?.();
255
+ assertCurrent();
256
+ const candidate = this.prepare(document, { selectedId: request.id, appliedRevision: null, selectionRevision: "unavailable" }, epoch, request.id === null ? "deployment-baseline" : "session-override", deployment ?? previous.deployment);
257
+ await this.validate(candidate.settings);
258
+ assertCurrent();
259
+ return { candidate, document };
255
260
  }, {
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);
261
+ assertCurrent,
262
+ prepare: async (selection, prepared) => {
263
+ assertCurrent();
264
+ const candidate = prepared.candidate;
265
+ next = this.profileAdmission(selection, candidate.settings, selection.admissionEpoch, candidate.scope, candidate.baseline, candidate.deployment, candidate.restartRequired, prepared.document, selection.warnings);
266
+ await transaction.prepare(next, () => { response = this.sessionSnapshot(agent, next, selection, true); });
267
+ assertCurrent();
265
268
  },
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
- }
269
+ committed: () => { this.bound.set(agent, next); transaction.committed(); },
274
270
  });
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 };
271
+ this.observations.set(next, selectionState(result.selection));
272
+ return { ...response, selection: selectionState(result.selection), admittedSelection: selectionState(result.selection),
273
+ ...(result.selection.refreshRequired ? { refreshRequired: true } : {}) };
288
274
  }
289
275
  finally {
290
- this.switching.delete(agent);
276
+ await transaction.close();
291
277
  }
292
278
  });
293
279
  }
294
280
  catch (error) {
295
281
  if (error instanceof DsmmProfileError)
296
282
  throw error;
297
- throw new DsmmProfileError("maintenance", "Another activity owns the session's idle maintenance phase. No selection was queued or committed.");
283
+ throw new DsmmProfileError("maintenance", "The native session refused the configuration change.");
298
284
  }
299
- return operation;
285
+ }
286
+ assertRoot(agent) {
287
+ this.assertCurrent();
288
+ validateSessionProfileId(agent.id);
289
+ const agents = this.ctx.get?.("agents");
290
+ if (agents?.get(agent.id) !== agent || !agents.roots().includes(agent) || agent.session.header?.origin === "subagent")
291
+ throw new DsmmProfileError("not-owned", "The exact live root Agent is required.");
300
292
  }
301
293
  async describe() {
302
- const persisted = await this.store.describe();
294
+ this.assertCurrent();
295
+ const disk = await this.store.describe();
296
+ this.assertCurrent();
303
297
  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
- };
298
+ const changed = disk.selectedId !== current.selectedId || disk.appliedRevision !== current.appliedRevision
299
+ || (this.observedSelection(current).selectionRevision !== "unavailable" && disk.selectionRevision !== this.observedSelection(current).selectionRevision);
300
+ if (!changed && disk.selectionError === undefined)
301
+ this.observations.set(current, selectionState(disk));
302
+ const { sourceRevision: _source, ...snapshot } = disk;
303
+ return { ...snapshot, selectedId: current.selectedId, appliedRevision: current.appliedRevision,
304
+ ...(current.sourceRevision === undefined ? {} : { sourceRevision: current.sourceRevision }),
305
+ selectedWarnings: structuredClone(current.warnings ?? []), editorDefaults: structuredClone(this.baseline.runtimePolicy), roles: this.editorRoles(current),
306
+ ...(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
307
  }
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));
308
+ read(id) { this.assertCurrent(); return this.store.read(id); }
309
+ save(request, authority) {
310
+ const assertCurrent = () => { this.assertCurrent(); authority?.(); };
311
+ assertCurrent();
312
+ return this.store.save(request, assertCurrent);
336
313
  }
314
+ getStartupSettings() { return this.baseline; }
315
+ previewDeployment(desired) { return deploymentAdmissionView(this.prepare(this.document, this.current, newEpoch(), "global-default", desired)); }
337
316
  async describeDeployment(agent) {
317
+ this.assertCurrent();
338
318
  const desired = await this.options.readDesired?.();
339
- return { startup: this.options.startup ?? null, desired: desired ?? null, admission: this.admission(agent) };
319
+ this.assertCurrent();
320
+ return { startup: this.options.startup ?? null, desired: desired ?? null, admission: agent === undefined ? null : this.admission(agent) };
340
321
  }
341
- select(request) {
342
- const operation = this.selectionQueue.then(async () => {
343
- let selectedDocument = null;
322
+ select(request, authority) {
323
+ const assertCurrent = () => { this.assertCurrent(); authority?.(); };
324
+ const operation = this.queue.then(async () => {
325
+ assertCurrent();
326
+ const before = await this.describe();
327
+ assertCurrent();
344
328
  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();
329
+ let document = null;
330
+ let next;
331
+ let response;
332
+ const result = await this.store.select(request, async (value) => {
333
+ document = value === null ? null : freezeSettings(value);
334
+ const settings = freezeSettings(resolveProfileSettings(baseline, value?.settings ?? {}));
335
+ await this.validate(settings);
336
+ assertCurrent();
337
+ return settings;
338
+ }, { prepare: (selection, settings) => {
339
+ assertCurrent();
340
+ next = this.profileAdmission(selection, settings, newEpoch(), "global-default", baseline, this.current.deployment, this.current.restartRequired, document, selection.warnings);
341
+ const { selectionError: _error, sourceRevision: _source, refreshRequired: _refresh, ...snapshot } = before;
342
+ response = { ...snapshot, ...selectionState(selection), selectedWarnings: structuredClone(next.warnings ?? []), roles: this.editorRoles(next) };
343
+ },
344
+ committed: () => { this.current = next; this.document = document; } }, assertCurrent);
345
+ this.observations.set(next, selectionState(result.selection));
346
+ const { refreshRequired: _refresh, ...snapshot } = response;
347
+ return { ...snapshot, ...selectionState(result.selection) };
356
348
  });
357
- this.selectionQueue = operation.catch(() => undefined);
349
+ this.queue = operation.catch(() => undefined);
358
350
  return operation;
359
351
  }
360
352
  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;
353
+ const desired = deployment?.settings ?? this.baseline, effective = structuredClone(desired), restartRequired = [];
354
+ effective.modules.deepwork.enabled &&= this.baseline.modules.deepwork.enabled;
355
+ effective.subagents.allowRouteOverride &&= this.baseline.subagents.allowRouteOverride;
356
+ if (desired.modules.deepwork.enabled && !this.baseline.modules.deepwork.enabled)
357
+ restartRequired.push("modules.deepwork.enabled");
366
358
  if (desired.subagents.allowRouteOverride && !this.baseline.subagents.allowRouteOverride)
367
359
  restartRequired.push("subagents.allowRouteOverride");
368
360
  if (this.baseline.subagents.maxDepth !== undefined && (desired.subagents.maxDepth === undefined || desired.subagents.maxDepth > this.baseline.subagents.maxDepth)) {
369
361
  effective.subagents.maxDepth = this.baseline.subagents.maxDepth;
370
362
  restartRequired.push("subagents.maxDepth");
371
363
  }
372
- if (desired.modules.deepwork.enabled && !this.baseline.modules.deepwork.enabled)
373
- restartRequired.push("modules.deepwork.enabled");
374
364
  for (const role of DSMM_ROLES) {
375
365
  if (desired.roles[role.id] && !this.baseline.roles[role.id])
376
366
  restartRequired.push(`roles.${role.id}`);
377
- effective.roles[role.id] = desired.roles[role.id] && this.baseline.roles[role.id];
378
- }
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");
367
+ effective.roles[role.id] &&= this.baseline.roles[role.id];
383
368
  }
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
369
  for (const key of ["modeName", "promptOrder", "presets", "lsp"]) {
388
370
  if (JSON.stringify(desired[key]) !== JSON.stringify(this.baseline[key]))
389
371
  restartRequired.push(key);
390
372
  Object.assign(effective, { [key]: this.baseline[key] });
391
373
  }
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))
374
+ if (desired.permissionControl.enabled !== this.baseline.permissionControl.enabled)
375
+ restartRequired.push("permissionControl.enabled");
376
+ effective.permissionControl = { ...effective.permissionControl, enabled: this.baseline.permissionControl.enabled };
377
+ if (deployment !== undefined && this.options.startup !== undefined && (deployment.profile.section ?? deployment.global.section) !== (this.options.startup.profile.section ?? this.options.startup.global.section))
394
378
  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);
379
+ const baseline = freezeSettings(effective);
380
+ return this.profileAdmission(selection, freezeSettings(resolveProfileSettings(baseline, document?.settings ?? {})), epoch, scope, baseline, deployment, restartRequired, document, selection.warnings);
397
381
  }
398
- profileAdmission(selection, settings, epoch, scope, baseline = this.baseline, deployment = this.options.startup, restartRequired = [], document = null, warnings = profileDocumentWarnings(document)) {
382
+ profileAdmission(selection, settings, epoch, scope, baseline, deployment, restartRequired = [], document = null, warnings = profileDocumentWarnings(document)) {
399
383
  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)) {
384
+ const fields = Object.fromEntries(Object.keys(sources).map(path => [path, "deployment"]));
385
+ for (const prefix of ["modeName", "promptOrder", "presets", "lsp", "permissionControl.enabled", ...restartRequired]) {
386
+ for (const path of Object.keys(sources).filter(path => path === prefix || path.startsWith(`${prefix}.`))) {
404
387
  delete sources[path];
405
388
  delete fields[path];
406
389
  }
407
- for (const [path, source] of Object.entries(this.options.startup?.sources ?? {}).filter(([path]) => matches(path))) {
390
+ for (const [path, source] of Object.entries(this.options.startup?.sources ?? {}).filter(([path]) => path === prefix || path.startsWith(`${prefix}.`))) {
408
391
  sources[path] = source;
409
392
  fields[path] = "startup";
410
393
  }
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
394
  }
424
395
  const mark = (value, path) => {
425
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
396
+ if (value !== null && typeof value === "object" && !Array.isArray(value))
426
397
  for (const [key, child] of Object.entries(value))
427
398
  mark(child, [...path, key]);
428
- }
429
399
  else {
430
400
  sources[path.join(".")] = "named-session";
431
401
  fields[path.join(".")] = "named-session";
@@ -434,348 +404,78 @@ export class DsmmProfileRuntime {
434
404
  for (const [role, policy] of Object.entries(document?.settings.roleRouting ?? {})) {
435
405
  const prefixes = [...policy?.primary === undefined ? [] : [`roleRouting.${role}.primary.`], ...Object.keys(policy?.levels ?? {}).map(level => `roleRouting.${role}.levels.${level}.`)];
436
406
  for (const prefix of prefixes)
437
- for (const path of Object.keys(sources).filter((path) => path.startsWith(prefix))) {
407
+ for (const path of Object.keys(sources).filter(path => path.startsWith(prefix))) {
438
408
  delete sources[path];
439
409
  delete fields[path];
440
410
  }
441
411
  }
442
412
  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);
413
+ return freezeSettings({ ...selectionState(selection), settings, baseline, epoch, scope, ...(deployment === undefined ? {} : { deployment }),
414
+ warnings, restartRequired: [...restartRequired], sources, sourceCaptures: { fields, ...(this.options.startup === undefined ? {} : { startup: { globalRevision: this.options.startup.globalRevision, nativeRevision: this.options.startup.nativeRevision } }) }, subagentRuntime: this.runtimeView(),
415
+ ...(this.store.origin === undefined ? {} : { store: { origin: this.store.origin, readOnly: this.store.readOnly === true, ...(this.store.writeRestriction === undefined ? {} : { writeRestriction: this.store.writeRestriction }) } }),
416
+ roleAvailability: this.roleAvailability(settings, baseline, deployment, document),
417
+ profile: selection.selectedId === null || selection.appliedRevision === null ? null : { id: selection.selectedId, revision: selection.appliedRevision } });
732
418
  }
733
419
  roleAvailability(settings, baseline, deployment, document) {
734
420
  return DSMM_ROLES.map(role => {
735
421
  const required = requiredReason(settings, role.id), named = document?.settings.roles?.[role.id];
736
422
  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
423
  const reason = !settings.modules.deepwork.enabled ? "module-off" : !desired ? "deployment-disabled" : !startup ? "startup-unavailable" : named === false ? "profile-disabled" : undefined;
739
424
  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
425
  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 };
426
+ ...(named === undefined ? {} : { namedEnabled: named }), admitted: settings.modules.deepwork.enabled && settings.roles[role.id], ...(reason === undefined ? {} : { reason }),
427
+ source: named !== undefined ? "named-session" : startupCeiling ? this.options.startup?.sources[`roles.${role.id}`] ?? "defaults" : deployment?.sources[`roles.${role.id}`] ?? "defaults",
428
+ capture: named !== undefined ? "named-session" : startupCeiling ? "startup" : "deployment" };
744
429
  });
745
430
  }
746
- async validate(settings, auditPresets = true) {
431
+ editorRoles(admission) {
432
+ return DSMM_ROLES.map(role => {
433
+ const configured = this.baseline.roleRouting[role.id];
434
+ const runtimePolicy = { ...(configured?.strategy === undefined ? {} : { strategy: configured.strategy }), ...(configured?.rateLimit === undefined ? {} : { rateLimit: structuredClone(configured.rateLimit) }) };
435
+ 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 }) };
436
+ });
437
+ }
438
+ sessionActions(agent, admission, mode, hasProfileModel, inMaintenance = false) {
439
+ const llm = agent.ctx?.get?.("llm") ?? this.ctx.get?.("llm");
440
+ const selectModelUnavailableReason = !hasProfileModel ? "model-unconfigured" : llm?.resolveCallConfig === undefined ? "model-service-unavailable" : undefined;
441
+ const owner = this.ctx.get?.("dsmmNativeAdmission");
442
+ const ready = owner?.isReady === true && this.ctx.get?.("subagents") !== undefined && this.ctx.get?.("agentPresets") !== undefined;
443
+ const toggleModeUnavailableReason = agent.status === "running" || hasOpenTurn(sessionEvents(agent.session)) ? "busy"
444
+ : agent.runMaintenance === undefined ? "maintenance" : !mode.active && (!this.baseline.modules.deepwork.enabled || !admission.settings.modules.deepwork.enabled) ? "module-off"
445
+ : mode.locked || !mode.active && !ready ? "runtime-unavailable" : undefined;
446
+ const applyOverlayUnavailableReason = this.historyAdmissions.has(admission) ? "new-session-required" : this.store.readOnly ? "runtime-unavailable" : owner?.blankReason?.(agent, inMaintenance) ?? (owner?.blankReason === undefined ? "runtime-unavailable" : undefined);
447
+ return { canSelectModel: selectModelUnavailableReason === undefined, ...(selectModelUnavailableReason === undefined ? {} : { selectModelUnavailableReason }),
448
+ canToggleMode: toggleModeUnavailableReason === undefined, ...(toggleModeUnavailableReason === undefined ? {} : { toggleModeUnavailableReason }),
449
+ canApplyOverlay: applyOverlayUnavailableReason === undefined, ...(applyOverlayUnavailableReason === undefined ? {} : { applyOverlayUnavailableReason }) };
450
+ }
451
+ async validate(settings) {
747
452
  if (!settings.modules.deepwork.enabled)
748
453
  return;
749
454
  if (this.options.validateCandidate !== undefined) {
750
455
  await this.options.validateCandidate(settings);
751
456
  return;
752
457
  }
753
- if (!auditPresets)
458
+ if (this.options.runtimeView !== undefined && !this.runtimeView().deliveryFenceReady)
754
459
  return;
755
460
  const registry = this.ctx.get?.("agentPresets");
756
- if (registry !== undefined) {
757
- for (const role of DSMM_ROLES.filter((role) => isRootRoleEnabled(settings, role.id))) {
461
+ if (registry !== undefined)
462
+ for (const role of DSMM_ROLES.filter(role => isRootRoleEnabled(settings, role.id))) {
758
463
  try {
759
- const preset = await registry.resolve(role.id);
760
- if (preset.broken !== undefined)
464
+ if ((await registry.resolve(role.id)).broken !== undefined)
761
465
  throw new Error("unusable root preset");
762
466
  }
763
467
  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);
468
+ throw new DsmmProfileError("activation", "An enabled root preset is unavailable.", role.id);
765
469
  }
766
470
  }
767
- }
768
471
  }
472
+ observedSelection(admission) { return this.observations.get(admission) ?? selectionState(admission); }
473
+ runtimeView() { return this.options.runtimeView?.() ?? { binding: "unavailable", deliveryFenceReady: false, restartRequired: true, reason: "authority-not-ready" }; }
769
474
  }
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
475
  export async function createProfileRuntime(ctx, baseline, options = {}) {
776
476
  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.");
477
+ if (!profile?.dir)
478
+ throw new DsmmProfileError("activation", "Profiles require an exact native profile directory.");
779
479
  const legacy = join(profile.dir, "dsmm-profiles");
780
480
  let exists = false;
781
481
  try {
@@ -783,15 +483,12 @@ export async function createProfileRuntime(ctx, baseline, options = {}) {
783
483
  exists = true;
784
484
  }
785
485
  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.");
486
+ if (error.code !== "ENOENT")
487
+ throw error;
788
488
  }
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";
489
+ const entry = options.startup?.entryId ?? (Context.is(ctx) ? ctx.fiber.entry?.id : undefined) ?? "trusted-direct";
792
490
  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 });
491
+ const runtime = new DsmmProfileRuntime(ctx, baseline, store, options);
795
492
  await runtime.initialize();
796
493
  return runtime;
797
494
  }