@dsmm/dsmm 0.2.2 → 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 (182) hide show
  1. package/README.md +26 -42
  2. package/cordis.patch.yml +1 -0
  3. package/docs/agent-presets.md +26 -14
  4. package/docs/compatibility.md +20 -79
  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 -240
  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 +16 -2
  20. package/lib/child-capture.js +29 -10
  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 +26 -51
  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 +85 -25
  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 +2716 -2364
  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 +17 -21
  82. package/lib/index.js +131 -430
  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/permission-rpc.js +3 -3
  97. package/lib/preset-registry.js +3 -2
  98. package/lib/preset-skills.d.ts +3 -12
  99. package/lib/preset-skills.js +28 -58
  100. package/lib/profile-diagnostics.d.ts +1 -1
  101. package/lib/profile-diagnostics.js +2 -2
  102. package/lib/profile-remote.js +61 -22
  103. package/lib/profile-rpc.d.ts +4 -3
  104. package/lib/profile-rpc.js +39 -41
  105. package/lib/profile-runtime.d.ts +31 -74
  106. package/lib/profile-runtime.js +224 -639
  107. package/lib/profile-store.d.ts +18 -6
  108. package/lib/profile-store.js +106 -64
  109. package/lib/profile-types.d.ts +18 -4
  110. package/lib/profiles.d.ts +3 -1
  111. package/lib/profiles.js +9 -7
  112. package/lib/prompt-content.d.ts +1 -0
  113. package/lib/prompt-content.js +4 -1
  114. package/lib/prompts.d.ts +2 -12
  115. package/lib/prompts.js +11 -66
  116. package/lib/role-control-remote.d.ts +1 -4
  117. package/lib/role-control-remote.js +8 -36
  118. package/lib/role-control-rpc.d.ts +10 -36
  119. package/lib/role-control-rpc.js +112 -265
  120. package/lib/role-control-types.d.ts +3 -26
  121. package/lib/role-control-types.js +3 -4
  122. package/lib/role-identity.d.ts +5 -0
  123. package/lib/role-identity.js +10 -0
  124. package/lib/role-invocation.d.ts +2 -2
  125. package/lib/role-llm-runtime.js +5 -11
  126. package/lib/role-policy.d.ts +19 -53
  127. package/lib/role-policy.js +136 -525
  128. package/lib/role-providers.d.ts +5 -8
  129. package/lib/role-providers.js +20 -126
  130. package/lib/role-routing.d.ts +1 -3
  131. package/lib/role-routing.js +24 -34
  132. package/lib/role-subagents.d.ts +5 -14
  133. package/lib/role-subagents.js +149 -97
  134. package/lib/runtime-integration.d.ts +5 -109
  135. package/lib/runtime-integration.js +11 -779
  136. package/lib/session-metadata.d.ts +13 -12
  137. package/lib/session-metadata.js +6 -31
  138. package/lib/session-scope.js +6 -2
  139. package/lib/settings.d.ts +5 -18
  140. package/lib/settings.js +19 -43
  141. package/lib/state.d.ts +3 -2
  142. package/lib/state.js +26 -10
  143. package/lib/status.d.ts +1 -9
  144. package/lib/status.js +3 -55
  145. package/lib/web-fetch-address-policy.d.ts +24 -0
  146. package/lib/web-fetch-address-policy.js +189 -0
  147. package/lib/web-fetch-fakeip.d.ts +25 -0
  148. package/lib/web-fetch-fakeip.js +107 -0
  149. package/package.json +133 -113
  150. package/docs/research/deepseek-v4-pro.md +0 -74
  151. package/docs/research/oh-dsh.md +0 -96
  152. package/lib/child-admission.d.ts +0 -42
  153. package/lib/child-admission.js +0 -162
  154. package/lib/delivery-authority.d.ts +0 -68
  155. package/lib/delivery-authority.js +0 -260
  156. package/lib/legacy-child-policy.d.ts +0 -51
  157. package/lib/legacy-child-policy.js +0 -123
  158. package/lib/legacy-read-composition.d.ts +0 -20
  159. package/lib/legacy-read-composition.js +0 -144
  160. package/lib/legacy-read-contracts.d.ts +0 -157
  161. package/lib/legacy-read-contracts.js +0 -39
  162. package/lib/legacy-read-host.d.ts +0 -19
  163. package/lib/legacy-read-host.js +0 -67
  164. package/lib/legacy-read-integration.d.ts +0 -121
  165. package/lib/legacy-read-integration.js +0 -522
  166. package/lib/legacy-read-proxy.d.ts +0 -26
  167. package/lib/legacy-read-proxy.js +0 -237
  168. package/lib/native-child-evidence.d.ts +0 -42
  169. package/lib/native-child-evidence.js +0 -133
  170. package/lib/role-runs.d.ts +0 -135
  171. package/lib/role-runs.js +0 -304
  172. package/lib/session-persistence.d.ts +0 -35
  173. package/lib/session-persistence.js +0 -304
  174. package/lib/subagent-runtime.d.ts +0 -45
  175. package/lib/subagent-runtime.js +0 -131
  176. package/prompts/deepseek-flash.md +0 -11
  177. package/prompts/deepseek-v4-pro.md +0 -14
  178. package/scripts/cold-profile-composition.mjs +0 -329
  179. package/scripts/cold-profile-sources.mjs +0 -238
  180. package/scripts/migrate-cold-profile.mjs +0 -315
  181. package/scripts/repair-session-log.mjs +0 -476
  182. package/scripts/session-repair-native-verifier.mjs +0 -367
@@ -1,601 +1,212 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { delegationDepthOf, foldSubagentDescriptor, SubagentError } from "@deepseek-ai/dsh-subagent";
2
+ import { SubagentError, delegationDepthOf } from "@deepseek-ai/dsh-subagent";
3
3
  import { symbols } from "@deepseek-ai/cordis";
4
- import { DSMM_ROLE_IDS, DSMM_ROLES, allowedRoleChildren, isDsmmRoleId } from "./roles.js";
4
+ import { DSMM_ROLES, allowedRoleChildren, isDsmmRoleId } from "./roles.js";
5
5
  export { allowedRoleChildren } from "./roles.js";
6
- import { copyJson, freezeSettings, isRootRoleEnabled } from "./settings.js";
7
- import { admissionFromChildCapture, parseChildAdmissionCapture, parseLegacyChildEvidence } from "./child-capture.js";
8
- import { createConservativeLegacyAdmission } from "./legacy-child-policy.js";
9
- export { createConservativeLegacyAdmission as conservativeLegacyAdmission } from "./legacy-child-policy.js";
10
- import { bindRoleInvocation, currentRoleInvocation, resolveRoleInvocation } from "./role-invocation.js";
11
- import { captureRoleRuntimePolicy, resolveRoleRuntimePolicy } from "./routing-policy.js";
12
- import { childOwnedSessionEvents, resolveEffectiveDsmmRole, resolveSelectedAgentPreset } from "./session-scope.js";
13
- import { resolvedModelParameterPolicy } from "./model-parameter-policy.js";
14
- import { modelRouteFromCall, projectModelRouteParameters } from "./role-llm.js";
15
- import { DsmmProfileError } from "./profiles.js";
6
+ import { isRootRoleEnabled } from "./settings.js";
7
+ import { bindRoleInvocation } from "./role-invocation.js";
8
+ import { captureRoleRuntimePolicy } from "./routing-policy.js";
9
+ import { resolveEffectiveDsmmRole, resolveSelectedAgentPreset } from "./session-scope.js";
16
10
  import { scopeParentOf } from "./native-scope.js";
17
11
  const liveIdentities = new WeakMap();
18
12
  const toolIdentities = new WeakMap();
19
13
  const controlledDefinitions = new WeakSet();
20
14
  export const READONLY_ROLE_DENIED_TOOLS = ["write", "edit", "bash", "pwsh"];
15
+ const readTools = new Set(["read", "glob", "grep", "read_image", "web_search", "web_fetch", "skill", "load_skill", "structured_output", "send_message", "interrupt_agent", "exit_plan_mode", "ask_user_question", "todo_write", "job_output", "job_list", "job_kill"]);
16
+ const readLsp = new Set(["status", "diagnostics", "goto_definition", "find_references", "find_symbol_related", "symbols", "prepare_rename"]);
17
+ export function roleToolName(role) { return role.replace(/-/gu, "_"); }
18
+ export function roleFromToolName(name) { return name === "explore" ? "dsmm-code-search" : DSMM_ROLES.find(row => roleToolName(row.id) === name)?.id; }
19
+ export function readonlyRoleTool(name, settings) { return readTools.has(name) || name === `mcp__${settings.lsp.serverName}__${name.split("__").at(-1)}` && readLsp.has(name.split("__").at(-1)); }
21
20
  export function inheritToolFilter(parent, requested) {
22
21
  if (parent === undefined && requested === undefined)
23
22
  return undefined;
24
- const allow = parent?.allow === undefined ? requested?.allow : requested?.allow === undefined ? parent.allow
25
- : parent.allow.filter((name) => requested.allow.includes(name));
26
- const deny = [...new Set([...parent?.deny ?? [], ...requested?.deny ?? []])];
27
- return Object.freeze({ ...(allow === undefined ? {} : { allow: Object.freeze([...allow]) }),
28
- ...(parent?.deny === undefined && requested?.deny === undefined ? {} : { deny: Object.freeze(deny) }) });
23
+ const allow = parent?.allow === undefined ? requested?.allow : requested?.allow === undefined ? parent.allow : parent.allow.filter(name => requested.allow.includes(name));
24
+ return Object.freeze({ ...(allow === undefined ? {} : { allow: Object.freeze([...allow]) }), deny: Object.freeze([...new Set([...parent?.deny ?? [], ...requested?.deny ?? []])]) });
29
25
  }
30
26
  export function resolveAdmittedDsmmRole(agent, settings, active) {
31
- if (!settings.modules.deepwork.enabled)
32
- return undefined;
33
- const identity = liveIdentities.get(agent)?.identity;
34
- return identity?.role === undefined ? resolveEffectiveDsmmRole(agent, settings, active)
35
- : identity.role !== undefined && settings.roles[identity.role] ? identity.role : undefined;
27
+ return liveIdentities.get(agent)?.role ?? resolveEffectiveDsmmRole(agent, settings, active);
36
28
  }
37
- const readTools = new Set(["read", "glob", "grep", "read_image", "web_search", "web_fetch", "skill", "load_skill", "structured_output", "send_message", "interrupt_agent", "exit_plan_mode", "ask_user_question", "todo_write", "job_output", "job_list", "job_kill"]);
38
- const readLsp = new Set(["status", "diagnostics", "goto_definition", "find_references", "find_symbol_related", "symbols", "prepare_rename"]);
39
- export function roleToolName(role) { return role.replace(/-/gu, "_"); }
40
- export function roleFromToolName(name) {
41
- return name === "explore" ? "dsmm-code-search" : DSMM_ROLES.find((row) => roleToolName(row.id) === name)?.id;
42
- }
43
- export function readonlyRoleTool(name, settings) {
44
- return readTools.has(name) || name === `mcp__${settings.lsp.serverName}__${name.split("__").at(-1)}`
45
- && readLsp.has(name.split("__").at(-1));
46
- }
47
- /** Identity admission only: native services retain every run, inbox and retry lifecycle. */
29
+ /** Role and exact-call restrictions; no child creation or execution owner. */
48
30
  export class DsmmRolePolicy {
49
31
  ctx;
50
32
  getSettings;
51
33
  mode;
52
- calls = new AsyncLocalStorage();
53
34
  executions = new AsyncLocalStorage();
54
35
  toolCalls = new WeakMap();
55
- providers = new WeakSet();
56
- continuableCreations = new Map();
57
- preparedInvocations = new WeakMap();
58
- preparedCaptures = new WeakMap();
59
- collaborators;
60
36
  constructor(ctx, getSettings, mode) {
61
37
  this.ctx = ctx;
62
38
  this.getSettings = getSettings;
63
39
  this.mode = mode;
64
- ctx.effect?.(() => () => { for (const pending of this.continuableCreations.values())
65
- pending.detach(); this.continuableCreations.clear(); });
66
- }
67
- captureProvider(provider) { this.providers.add(provider); }
68
- ownsProvider(provider) { return this.providers.has(provider); }
69
- revokeResidency(agent) { this.collaborators?.revokeParent(agent, "native-run-disposed"); }
70
- configureAdmission(collaborators) {
71
- this.collaborators = collaborators;
72
- return { prepare: (agent, parent, ticket, signal) => this.prepareChildAdmission(agent, parent, ticket, signal),
73
- validateRole: (agent, parent, candidate) => this.validatePreparedRole(agent, parent, candidate) };
74
40
  }
41
+ agents() { const agents = this.ctx.get?.("agents"); if (!agents)
42
+ throw new SubagentError("Native registry unavailable", "UNAUTHORIZED"); return agents; }
43
+ assertLive(agent) { if (!agent.id || this.agents().get(agent.id) !== agent)
44
+ throw new SubagentError("Exact live Agent required", "UNAUTHORIZED"); }
45
+ selected(agent) { return agent.ctx.get("agentPresets")?.composedPreset(agent.ctx) ?? resolveSelectedAgentPreset(agent.session); }
75
46
  validateRootRole(agent, admission) {
76
47
  this.assertLive(agent);
77
- this.assertPlannerRootAdmission(agent, admission.settings);
78
- const selected = agent.ctx?.get?.("agentPresets")?.composedPreset(agent.ctx)
79
- ?? resolveSelectedAgentPreset(agent.session);
80
- const implicit = !selected?.startsWith("dsmm-") && admission.settings.modules.deepwork.enabled && this.mode.active(agent, admission.settings.defaultActive) ? "dsmm-orchestrator" : undefined;
81
- const role = selected?.startsWith("dsmm-") ? selected : implicit;
82
- if (role !== undefined && (!isDsmmRoleId(role) || !admission.settings.modules.deepwork.enabled || !admission.settings.roles[role]
83
- || role === "dsmm-planner" && !isRootRoleEnabled(admission.settings, role))) {
84
- throw new SubagentError("Standing DSMM root role is not admitted", "UNAUTHORIZED");
85
- }
48
+ const selected = this.selected(agent);
49
+ if (selected?.startsWith("dsmm-") && (!isDsmmRoleId(selected) || !isRootRoleEnabled(admission.settings, selected)))
50
+ throw new SubagentError("Preset is not eligible as a root", "UNAUTHORIZED");
86
51
  }
87
- recordContinuableCreation(childId, parent, role, invocation, expectedEpoch, signal) {
88
- signal.throwIfAborted();
89
- const admitted = this.assertDelegation(parent, role);
90
- if (admitted.epoch !== expectedEpoch)
91
- throw new SubagentError("Parent admission changed during continuable preflight", "UNAUTHORIZED");
92
- const abort = () => { this.continuableCreations.delete(childId); };
93
- signal.addEventListener("abort", abort, { once: true });
94
- this.continuableCreations.set(childId, { parent, role, epoch: admitted.epoch, invocation, detach: () => signal.removeEventListener("abort", abort) });
95
- }
96
- async prepareChildAdmission(agent, parent, ticket, signal) {
97
- signal.throwIfAborted();
98
- ticket.signal.throwIfAborted();
99
- this.assertLive(agent);
100
- this.assertLive(parent);
101
- if (ticket.parent !== parent || this.getSettings.admission?.(parent) !== ticket.admission || ticket.parentEpoch !== ticket.admission.epoch)
102
- throw new SubagentError("Child preparation requires the exact parent admission ticket", "UNAUTHORIZED");
103
- const call = this.calls.getStore(), pending = this.continuableCreations.get(agent.id);
104
- this.continuableCreations.delete(agent.id);
105
- pending?.detach();
106
- const descriptor = foldSubagentDescriptor(childOwnedSessionEvents(agent.session));
107
- let invocation = call?.parent === parent ? currentRoleInvocation(parent, call.role) : pending?.parent === parent ? pending.invocation : undefined;
108
- if (invocation === undefined && pending?.parent === parent) {
109
- if (pending.epoch !== ticket.parentEpoch || descriptor?.mode !== "continuable")
110
- throw new SubagentError("Fresh continuable identity or parent epoch changed", "UNAUTHORIZED");
111
- const explicit = descriptor.agentProvider === undefined && descriptor.agentModel === undefined && descriptor.agentReasoningEffort === undefined ? undefined
112
- : { provider: descriptor.agentProvider, model: descriptor.agentModel, reasoningEffort: descriptor.agentReasoningEffort };
113
- invocation = await resolveRoleInvocation(parent, pending.role, ticket.admission.settings, signal, {}, explicit);
114
- signal.throwIfAborted();
115
- ticket.signal.throwIfAborted();
116
- }
117
- if (invocation === undefined) {
118
- if (this.collaborators === undefined)
119
- throw new SubagentError("Original child evidence resolver is unavailable", "UNAUTHORIZED");
120
- const evidence = await this.collaborators.resolveOriginalEvidence(ticket, agent.id, signal);
121
- signal.throwIfAborted();
122
- ticket.signal.throwIfAborted();
123
- return { evidence, admission: "mode" in evidence ? createConservativeLegacyAdmission(evidence, ticket.admission, this.collaborators.nativeSubstrate)
124
- : admissionFromChildCapture(evidence, this.collaborators.nativeSubstrate), creation: false };
125
- }
126
- if ((call?.parent === parent ? call.epoch : pending.epoch) !== ticket.parentEpoch)
127
- throw new SubagentError("Child invocation parent epoch changed", "UNAUTHORIZED");
128
- const settings = ticket.admission.settings, parentIdentity = this.identity(parent);
129
- const filter = inheritToolFilter(parentIdentity.toolFilter, call?.toolFilter ?? (descriptor?.mode === "continuable" ? descriptor.toolFilter : undefined));
130
- const runtimePolicyCapture = copyJson({ modules: { deepwork: settings.modules.deepwork }, roleRouting: settings.roleRouting,
131
- runtimePolicy: settings.runtimePolicy, workflow: settings.workflow, guards: settings.guards, runtimeRecovery: settings.runtimeRecovery,
132
- defaultActive: settings.defaultActive, deepseekV4ProCalibration: settings.deepseekV4ProCalibration,
133
- deepseekV4ProDefaultReasoningEffort: settings.deepseekV4ProDefaultReasoningEffort, deepseekFlashCalibration: settings.deepseekFlashCalibration,
134
- deepseekFlashDefaultReasoningEffort: settings.deepseekFlashDefaultReasoningEffort, skills: settings.skills,
135
- subagents: { enableRunInBackground: settings.subagents.enableRunInBackground, backgroundMode: settings.subagents.backgroundMode } });
136
- if (invocation.routeSource === "level" || invocation.routeSource === "invocation-route") {
137
- const { reasoningEffort, ...route } = invocation.requestedPolicy?.primary ?? invocation.requestedRoute ?? invocation.initialRoute;
138
- runtimePolicyCapture.roleRouting[invocation.target] = { ...runtimePolicyCapture.roleRouting[invocation.target],
139
- primary: { ...route, ...(invocation.exactEffort && reasoningEffort !== undefined ? { reasoningEffort } : {}) },
140
- fallbackRoutes: (invocation.requestedPolicy ?? invocation.policy).fallbackRoutes.map(route => ({ ...route })) };
141
- }
142
- const capture = parseChildAdmissionCapture({ version: 2, childSessionId: agent.id, parentSessionId: parent.id, role: invocation.target,
143
- modelParameterPolicy: invocation.modelParameterPolicy ?? resolvedModelParameterPolicy(ticket.admission),
144
- profilePin: ticket.admission.profile, originalAdmissionEpoch: ticket.parentEpoch,
145
- invocation: { level: invocation.effectiveLevel, initialRoute: invocation.initialRoute, requestedRoute: invocation.requestedRoute ?? invocation.initialRoute,
146
- effortSource: invocation.effortSource ?? (invocation.routeSource === "inherited" ? "native" : "dsmm-config"), routeSource: invocation.routeSource }, runtimePolicyCapture,
147
- authorityCeiling: { roles: DSMM_ROLE_IDS.filter(id => settings.roles[id]), readOnly: this.readOnly(parentIdentity) || DSMM_ROLES.find(row => row.id === invocation.target).access === "read-only",
148
- ...(filter === undefined ? {} : { toolFilter: filter }), allowRouteOverride: settings.subagents.allowRouteOverride,
149
- maxDepth: settings.subagents.maxDepth ?? call?.maxDepth ?? parent.ctx.get("subagents").resolveMaxDepth() },
150
- ...(settings.locale === undefined ? {} : { locale: settings.locale }), toolTopology: settings.subagents.toolTopology });
151
- this.preparedInvocations.set(agent, invocation);
152
- this.preparedCaptures.set(agent, capture);
153
- return { evidence: capture, admission: admissionFromChildCapture(capture, this.collaborators?.nativeSubstrate ?? settings), creation: true };
154
- }
155
- /** Used at A's single awaited completion point; old original epochs remain valid facts. */
156
- validatePreparedRole(agent, parent, candidate) {
52
+ bindChild(agent, parent, admission, invocation, maximum, toolFilter) {
157
53
  this.assertLive(agent);
158
54
  this.assertLive(parent);
159
- const evidence = "mode" in candidate.evidence ? parseLegacyChildEvidence(candidate.evidence) : parseChildAdmissionCapture(candidate.evidence);
160
- if (evidence.childSessionId !== agent.id || evidence.parentSessionId !== parent.id || agent.session.header.parentSession !== parent.id || !this.agents().isOwnedBy(agent.id, parent))
161
- throw new SubagentError("Child evidence does not match exact native lineage", "UNAUTHORIZED");
162
- this.assertDelegation(parent, evidence.role);
163
- const descriptor = foldSubagentDescriptor(childOwnedSessionEvents(agent.session));
164
- if (descriptor === undefined ? !candidate.creation || this.preparedInvocations.get(agent)?.target !== evidence.role
165
- : descriptor.provider !== `dsmm-role-${evidence.role.slice(5)}` || !candidate.creation && descriptor.mode !== "continuable") {
166
- throw new SubagentError("Native descriptor or trusted fresh invocation does not match the original role", "UNAUTHORIZED");
167
- }
168
- const original = candidate.admission;
169
- if (!original.settings.modules.deepwork.enabled || !original.settings.roles[evidence.role])
170
- throw new SubagentError("Original child role/module is disabled", "UNAUTHORIZED");
171
- if (descriptor?.mode === "continuable") {
172
- const route = "mode" in evidence ? evidence.route : evidence.invocation.initialRoute;
173
- if (descriptor.agentProvider !== undefined && descriptor.agentProvider !== route.provider || descriptor.agentModel !== undefined && descriptor.agentModel !== route.model
174
- || descriptor.agentReasoningEffort !== undefined && descriptor.agentReasoningEffort !== route.reasoningEffort)
175
- throw new SubagentError("Original route does not match native descriptor provenance", "UNAUTHORIZED");
176
- }
177
- const prior = liveIdentities.get(agent);
178
- if (candidate.retained && prior !== undefined) {
179
- if (prior.identity.parent !== parent || prior.identity.role !== evidence.role || prior.identity.epoch !== original.epoch || prior.admission !== original)
180
- throw new SubagentError("Retained role identity or original admission reference cannot be replaced", "UNAUTHORIZED");
181
- return;
182
- }
183
- let invocation;
184
- let filter;
185
- let readOnly;
186
- if ("mode" in evidence) {
187
- if (evidence.depth !== delegationDepthOf(agent))
188
- throw new SubagentError("Legacy depth evidence does not match its physical native lineage", "UNAUTHORIZED");
189
- const safe = evidence.toolFilter?.allow?.filter(name => readonlyRoleTool(name, original.settings) && !["interrupt_agent", "job_kill"].includes(name)) ?? [];
190
- filter = inheritToolFilter({ allow: safe }, evidence.toolFilter);
191
- readOnly = true;
192
- invocation = freezeSettings({ target: evidence.role, effectiveLevel: "normal", routeSource: "inherited", initialRoute: evidence.route,
193
- candidates: [evidence.route], exactEffort: evidence.route.reasoningEffort !== undefined, modelParameterPolicy: resolvedModelParameterPolicy(original), effortSource: "native",
194
- policy: { ...resolveRoleRuntimePolicy(original.settings, evidence.role), primary: evidence.route, fallbackRoutes: [] } });
195
- }
196
- else {
197
- if (candidate.creation && JSON.stringify(this.preparedCaptures.get(agent)) !== JSON.stringify(evidence))
198
- throw new SubagentError("Fresh capture does not match its trusted prepared invocation and ceiling", "UNAUTHORIZED");
199
- if (original.epoch !== evidence.originalAdmissionEpoch || candidate.creation && this.getSettings.admission?.(parent).epoch !== evidence.originalAdmissionEpoch)
200
- throw new SubagentError("Original capture or creation epoch does not match", "UNAUTHORIZED");
201
- const depth = delegationDepthOf(agent);
202
- if (depth > evidence.authorityCeiling.maxDepth)
203
- throw new SubagentError("Original child depth ceiling is exceeded", "UNAUTHORIZED");
204
- readOnly = evidence.authorityCeiling.readOnly;
205
- if (!readOnly && DSMM_ROLES.find(row => row.id === evidence.role).access === "read-only")
206
- throw new SubagentError("Original capture cannot weaken read-only role identity", "UNAUTHORIZED");
207
- filter = evidence.authorityCeiling.toolFilter;
208
- const nativeFilter = descriptor?.mode === "continuable" ? descriptor.toolFilter : undefined;
209
- if (nativeFilter !== undefined && JSON.stringify(inheritToolFilter(filter, nativeFilter)) !== JSON.stringify(filter))
210
- throw new SubagentError("Original capture exceeds native descriptor tool restriction", "UNAUTHORIZED");
211
- const policy = resolveRoleRuntimePolicy(original.settings, evidence.role);
212
- const level = evidence.invocation.level === "normal" ? undefined : original.settings.roleRouting[evidence.role]?.levels?.[evidence.invocation.level];
213
- const modelParameterPolicy = resolvedModelParameterPolicy(original);
214
- const fallbacks = policy.fallbackRoutes.map(route => modelRouteFromCall(projectModelRouteParameters(route, "dsmm-config", modelParameterPolicy.mode !== "native-defaults")));
215
- invocation = freezeSettings({ target: evidence.role, effectiveLevel: evidence.invocation.level, routeSource: evidence.invocation.routeSource,
216
- initialRoute: evidence.invocation.initialRoute, candidates: [evidence.invocation.initialRoute, ...fallbacks], modelParameterPolicy,
217
- ...(evidence.version === 1 ? {} : { requestedRoute: evidence.invocation.requestedRoute, effortSource: evidence.invocation.effortSource, requestedPolicy: policy }),
218
- exactEffort: evidence.invocation.routeSource === "invocation-route" ? policy.primary?.reasoningEffort !== undefined
219
- : evidence.invocation.routeSource === "level" && level?.reasoningEffort !== undefined,
220
- policy: { ...policy, primary: evidence.invocation.initialRoute, fallbackRoutes: fallbacks } });
221
- const fresh = this.preparedInvocations.get(agent);
222
- if (candidate.creation && fresh !== undefined)
223
- invocation = fresh;
224
- }
225
- const identity = Object.freeze({ role: evidence.role, child: true, parent, epoch: original.epoch, readOnly,
226
- ...(filter === undefined ? {} : { toolFilter: inheritToolFilter(undefined, filter) }) });
227
- this.captureIdentity(agent, identity, original);
228
- bindRoleInvocation(agent, invocation, "mode" in evidence ? undefined : evidence);
229
- captureRoleRuntimePolicy(original.settings, evidence.role, invocation.policy);
230
- const call = this.calls.getStore();
231
- if (candidate.creation && call?.parent === parent && call.role === evidence.role)
232
- call.admittedChild?.(agent);
233
- this.preparedInvocations.delete(agent);
234
- this.preparedCaptures.delete(agent);
235
- }
236
- assertChildDelivery(ticket, childId, raw) {
237
- ticket.signal.throwIfAborted();
238
- this.assertLive(ticket.parent);
239
- if (this.getSettings.admission?.(ticket.parent) !== ticket.admission || ticket.admission.epoch !== ticket.parentEpoch)
240
- throw new SubagentError("Delivery parent admission changed", "UNAUTHORIZED");
241
- const evidence = "mode" in raw ? parseLegacyChildEvidence(raw) : parseChildAdmissionCapture(raw);
242
- if (evidence.childSessionId !== childId || evidence.parentSessionId !== ticket.parent.id)
243
- throw new SubagentError("Delivery evidence is not this direct child", "UNAUTHORIZED");
244
- this.assertDelegation(ticket.parent, evidence.role);
245
- const depth = delegationDepthOf(ticket.parent) + 1;
246
- const maximum = ticket.admission.settings.subagents.maxDepth ?? ticket.parent.ctx.get("subagents")?.resolveMaxDepth();
247
- if (maximum !== undefined && depth > maximum || !("mode" in evidence) && depth > evidence.authorityCeiling.maxDepth)
248
- throw new SubagentError("Delivery exceeds the original or current delegation depth ceiling", "UNAUTHORIZED");
249
- if (!("mode" in evidence) && (!evidence.runtimePolicyCapture.modules.deepwork.enabled || !evidence.authorityCeiling.roles.includes(evidence.role)))
250
- throw new SubagentError("Original child role is not permitted", "UNAUTHORIZED");
251
- }
252
- readOnly(identity) { return identity.readOnly === true || DSMM_ROLES.find(row => row.id === identity.role)?.access === "read-only"; }
253
- agents() {
254
- const registry = this.ctx.get?.("agents");
255
- if (registry === undefined)
256
- throw new SubagentError("DSMM delegation requires native live Agent ownership", "UNAUTHORIZED");
257
- return registry;
258
- }
259
- assertLive(agent) {
260
- if (agent.id === undefined || this.agents().get(agent.id) !== agent)
261
- throw new SubagentError("DSMM delegation requires the exact live Agent", "UNAUTHORIZED");
262
- }
263
- isAdmittedChild(agent) {
264
- const admitted = liveIdentities.get(agent), identity = admitted?.identity;
265
- return admitted?.admission !== undefined && identity?.child === true && identity.parent !== undefined
266
- && this.agents().get(identity.parent.id) === identity.parent && this.agents().isOwnedBy(agent.id, identity.parent);
267
- }
268
- assertPlannerRootAdmission(agent, settings) {
269
- if (settings.presets.plannerRootEnabled)
270
- return;
271
- const selected = resolveSelectedAgentPreset(agent.session);
272
- const composed = agent.ctx?.get?.("agentPresets")?.composedPreset(agent.ctx);
273
- if (selected !== "dsmm-planner" && composed !== "dsmm-planner")
274
- return;
275
- // Origin metadata alone cannot exempt a Root from this admission boundary.
276
- if (this.isAdmittedChild(agent))
277
- return;
278
- throw new SubagentError("Standing DSMM root role is not admitted", "UNAUTHORIZED");
279
- }
280
- /** Core fence runs before native prompt/body assembly or provider execution. */
55
+ this.assertDelegation(parent, invocation.target);
56
+ if (!this.agents().isOwnedBy(agent.id, parent) || agent.session.header?.parentSession !== parent.id || this.selected(agent) !== invocation.target)
57
+ throw new SubagentError("Child lineage or composition mismatch", "UNAUTHORIZED");
58
+ if (maximum !== undefined && delegationDepthOf(agent) > maximum)
59
+ throw new SubagentError("Delegation depth exceeded", "UNAUTHORIZED");
60
+ const upstream = this.identity(parent);
61
+ liveIdentities.set(agent, Object.freeze({ role: invocation.target, child: true, parent, epoch: admission.epoch,
62
+ readOnly: this.readOnly(upstream) || DSMM_ROLES.find(row => row.id === invocation.target).access === "read-only",
63
+ toolFilter: inheritToolFilter(inheritToolFilter(upstream.toolFilter, toolFilter), this.visibleToolCeiling(parent)) }));
64
+ bindRoleInvocation(agent, invocation);
65
+ captureRoleRuntimePolicy(admission.settings, invocation.target, invocation.policy);
66
+ }
67
+ release(agent) { liveIdentities.delete(agent); toolIdentities.delete(agent); }
281
68
  assertModuleAdmission(agent) {
282
69
  this.assertLive(agent);
283
- const settings = this.getSettings(agent);
284
- this.assertPlannerRootAdmission(agent, settings);
285
- const selected = agent.ctx?.get?.("agentPresets")?.composedPreset(agent.ctx)
286
- ?? resolveSelectedAgentPreset(agent.session);
287
- const descriptor = foldSubagentDescriptor(childOwnedSessionEvents(agent.session));
288
- const provider = descriptor === undefined ? undefined : this.ctx.get?.("subagents")?.getProvider(descriptor.provider);
289
- const providerRole = descriptor?.provider.startsWith("dsmm-role-") && (provider === undefined || this.providers.has(provider))
290
- ? `dsmm-${descriptor.provider.slice("dsmm-role-".length)}` : undefined;
291
- if (agent.session.header?.origin !== "subagent" && selected?.startsWith("dsmm-")
292
- && !isDsmmRoleId(selected))
293
- throw new SubagentError("DSMM unknown standing root is not admitted", "UNAUTHORIZED");
294
- const implicit = agent.session.header?.origin !== "subagent" && settings.modules.deepwork.enabled && this.mode.active(agent, settings.defaultActive) ? "dsmm-orchestrator" : undefined;
295
- const role = providerRole ?? (isDsmmRoleId(selected) ? selected : implicit);
296
- if (role !== undefined && (!settings.modules.deepwork.enabled || !isDsmmRoleId(role) || !settings.roles[role])) {
297
- throw new SubagentError("Deepwork module or role is not admitted in this Agent; standing presets and child resume cannot enable it", "UNAUTHORIZED");
298
- }
299
- if (role === "dsmm-planner" && !isRootRoleEnabled(settings, role) && !this.isAdmittedChild(agent)) {
300
- throw new SubagentError("Standing DSMM root role is not admitted", "UNAUTHORIZED");
301
- }
70
+ const settings = this.getSettings(agent), identity = liveIdentities.get(agent), selected = this.selected(agent);
71
+ if (identity?.child) {
72
+ this.assertLive(identity.parent);
73
+ if (!this.agents().isOwnedBy(agent.id, identity.parent) || selected !== identity.role)
74
+ throw new SubagentError("Child admission no longer matches composition", "UNAUTHORIZED");
75
+ }
76
+ else if (agent.session.header?.origin !== "subagent")
77
+ this.validateRootRole(agent, this.getSettings.admission(agent));
78
+ const role = identity?.role ?? (isDsmmRoleId(selected) ? selected : undefined);
79
+ if (role && (!settings.modules.deepwork.enabled || !settings.roles[role]))
80
+ throw new SubagentError("Role is disabled in the immutable admission", "UNAUTHORIZED");
302
81
  }
303
82
  identity(agent) {
304
83
  this.assertLive(agent);
305
- const execution = this.executions.getStore(), call = execution === undefined ? undefined : this.toolCalls.get(execution);
306
- if (call?.active && call.agent === agent && call.identity !== undefined)
307
- return call.identity;
308
- const existing = liveIdentities.get(agent)?.identity;
309
- if (existing?.child)
310
- return existing;
311
- const parent = this.agents().list().find((row) => row !== agent && this.agents().isOwnedBy(agent.id, row));
312
- if (parent !== undefined) {
313
- if (existing === undefined)
314
- throw new SubagentError("DSMM child role identity was not admitted", "UNAUTHORIZED");
84
+ const existing = liveIdentities.get(agent);
85
+ if (existing)
315
86
  return existing;
316
- }
317
- const settings = this.getSettings(agent);
318
- this.assertPlannerRootAdmission(agent, settings);
319
- const selected = agent.ctx?.get?.("agentPresets")?.composedPreset(agent.ctx);
320
- const role = isDsmmRoleId(selected) ? selected : settings.modules.deepwork.enabled && agent.session.header?.origin !== "subagent" && this.mode.active(agent, settings.defaultActive) ? "dsmm-orchestrator" : undefined;
321
- if (role === "dsmm-planner" && !isRootRoleEnabled(settings, role)) {
322
- throw new SubagentError("Standing DSMM root role is not admitted", "UNAUTHORIZED");
323
- }
324
- return Object.freeze({ role, child: agent.session.header?.origin === "subagent", epoch: this.getSettings.admission?.(agent).epoch ?? "trusted-direct" });
325
- }
87
+ const settings = this.getSettings(agent), selected = this.selected(agent);
88
+ const parent = this.agents().list().find(row => row !== agent && this.agents().isOwnedBy(agent.id, row));
89
+ if (!parent)
90
+ this.validateRootRole(agent, this.getSettings.admission(agent));
91
+ const role = parent ? undefined : isDsmmRoleId(selected) ? selected : settings.modules.deepwork.enabled && this.mode.active(agent, settings.defaultActive) ? "dsmm-orchestrator" : undefined;
92
+ return Object.freeze({ role, child: parent !== undefined, parent, epoch: this.getSettings.admission(agent).epoch });
93
+ }
94
+ admit(agent) { return this.identity(agent); }
95
+ readOnly(identity) { return identity.readOnly === true || DSMM_ROLES.find(row => row.id === identity.role)?.access === "read-only"; }
326
96
  targets(agent) {
327
- const execution = this.executions.getStore(), call = execution === undefined ? undefined : this.toolCalls.get(execution);
328
- if (call?.active && call.agent === agent && call.targets !== undefined)
329
- return call.targets;
330
- const identity = this.identity(agent);
331
- const settings = this.getSettings(agent);
332
- if (!settings.modules.deepwork.enabled || identity.role === undefined || !settings.roles[identity.role])
97
+ const identity = this.identity(agent), settings = this.getSettings(agent);
98
+ if (!settings.modules.deepwork.enabled || !identity.role || !settings.roles[identity.role])
333
99
  return [];
334
- return allowedRoleChildren(identity.role, identity.child).filter((role) => settings.roles[role]
335
- && (!this.readOnly(identity) || DSMM_ROLES.find(row => row.id === role).access === "read-only")
336
- && (identity.toolFilter?.allow === undefined || identity.toolFilter.allow.includes(roleToolName(role)))
100
+ return allowedRoleChildren(identity.role, identity.child).filter(role => settings.roles[role] && (!this.readOnly(identity) || DSMM_ROLES.find(row => row.id === role).access === "read-only")
101
+ && (identity.toolFilter?.allow === undefined || [roleToolName(role), DSMM_ROLES.find(row => row.id === role)?.kind === "category" ? "dsmm_category" : "dsmm_role"].some(name => identity.toolFilter.allow.includes(name)))
337
102
  && !identity.toolFilter?.deny?.includes(roleToolName(role)));
338
103
  }
339
104
  assertDelegation(parent, role) {
340
- const execution = this.executions.getStore(), call = execution === undefined ? undefined : this.toolCalls.get(execution);
341
- if (call?.active && call.agent === parent && call.target === role && call.identity !== undefined)
342
- return { parent, role, epoch: call.identity.epoch };
343
- const identity = this.identity(parent);
105
+ this.assertModuleAdmission(parent);
344
106
  if (!this.targets(parent).includes(role))
345
- throw new SubagentError(`DSMM ${identity.role ?? "unadmitted Agent"} cannot delegate ${role}`, "UNAUTHORIZED");
346
- return { parent, role, epoch: identity.epoch };
107
+ throw new SubagentError("Role delegation is not admitted", "UNAUTHORIZED");
108
+ return { parent, role, epoch: this.identity(parent).epoch };
347
109
  }
348
- duringDelegation(parent, role, operation, toolFilter, maxDepth, admittedChild) {
349
- const identity = this.assertDelegation(parent, role), outer = this.calls.getStore();
350
- const upstream = outer?.parent === parent && outer.role === role && outer.epoch === identity.epoch ? outer.admittedChild : undefined;
351
- const notify = admittedChild === undefined ? upstream : upstream === undefined ? admittedChild : (agent) => { upstream(agent); admittedChild(agent); };
352
- return this.calls.run({ ...identity, toolFilter, maxDepth, admittedChild: notify }, operation);
353
- }
354
- prepareContinuable(parent, role, signal) {
355
- signal.throwIfAborted();
356
- return this.assertDelegation(parent, role);
357
- }
358
- admit(agent) {
359
- this.assertLive(agent);
360
- const agents = this.agents();
361
- const parent = agents.list().find((row) => row !== agent && agents.isOwnedBy(agent.id, row));
362
- const existing = liveIdentities.get(agent);
363
- if (existing !== undefined) {
364
- // A retained child owns its original capture, not its parent's newer
365
- // mode/profile or a reinstall's replacement settings getter.
366
- if (parent === undefined || existing.identity.parent !== parent || existing.readEpoch() !== existing.identity.epoch) {
367
- throw new SubagentError("DSMM retained child admission no longer matches its exact owner or captured epoch", "UNAUTHORIZED");
368
- }
369
- this.assertLive(parent);
370
- return existing.identity;
371
- }
372
- if (parent === undefined)
373
- return this.identity(agent);
374
- const original = this.getSettings.admission?.(agent);
375
- if (original?.childCapture !== undefined) {
376
- this.validatePreparedRole(agent, parent, { evidence: original.childCapture, admission: original, creation: false, retained: false });
377
- return liveIdentities.get(agent).identity;
378
- }
379
- throw new SubagentError("DSMM child requires the completed original role/capture admission; generic spawn cannot bypass delegation policy", "UNAUTHORIZED");
380
- }
381
- captureIdentity(agent, identity, admission) {
382
- liveIdentities.set(agent, { identity, admission, readEpoch: () => this.getSettings.admission?.(agent).epoch ?? "trusted-direct" });
383
- return identity;
384
- }
385
- captureTools(agent, tools, controlledNames = [], reset = false) {
386
- const realm = Reflect.get(tools, symbols.original) ?? tools;
387
- const previous = toolIdentities.get(agent);
110
+ captureTools(agent, tools, names = [], reset = false) {
111
+ const realm = Reflect.get(tools, symbols.original) ?? tools, previous = toolIdentities.get(agent);
388
112
  const definitions = previous === undefined || reset || previous.realm !== realm ? new Map() : previous.definitions;
389
- for (const schema of tools.schemas(agent)) {
390
- if (previous === undefined || reset || previous.realm !== realm || controlledNames.includes(schema.name)) {
113
+ for (const schema of tools.schemas(agent))
114
+ if (!previous || reset || previous.realm !== realm || names.includes(schema.name)) {
391
115
  const definition = tools.get(schema.name, agent);
392
116
  definitions.set(schema.name, definition);
393
- if (controlledNames.includes(schema.name))
117
+ if (names.includes(schema.name))
394
118
  controlledDefinitions.add(definition);
395
119
  }
396
- }
397
120
  toolIdentities.set(agent, { realm, definitions });
398
121
  }
399
- /** Existing exact role denials only; missing admission or capability proof is not a blacklist. */
400
- toolBlacklistDenial(agent, name, execution) {
401
- return this.executions.exit(() => this.blacklistDenial(agent, name, execution));
402
- }
403
- blacklistDenial(agent, name, execution) {
404
- this.assertLive(agent);
405
- const captured = liveIdentities.get(agent)?.identity;
406
- if (captured?.toolFilter?.deny?.includes(name))
407
- return "DSMM child native toolFilter does not permit this tool";
408
- if (captured?.readOnly === true && READONLY_ROLE_DENIED_TOOLS.includes(name)
409
- && this.isAdmittedChild(agent))
410
- return "DSMM read-only role does not permit this tool";
411
- const definition = toolIdentities.get(agent)?.definitions.get(name);
412
- const native = agent.ctx, tools = native.get("agentPresets")?.serviceFor(agent, "tools") ?? native.get("tools");
413
- if (definition === undefined || tools?.get(name, agent) !== definition)
414
- return undefined;
415
- let identity, settings;
416
- try {
417
- identity = this.identity(agent);
418
- settings = this.getSettings(agent);
419
- }
420
- catch (error) {
421
- if (error instanceof DsmmProfileError && !["disposed", "not-owned", "cancelled"].includes(error.code)
422
- || error instanceof SubagentError && error.code === "UNAUTHORIZED")
423
- return undefined;
424
- throw error;
425
- }
426
- if (identity.role === undefined)
427
- return undefined;
428
- if (!settings.modules.deepwork.enabled || !settings.roles[identity.role])
429
- return "DSMM role is disabled in this Agent admission";
430
- const args = execution?.arguments;
431
- const target = roleFromToolName(name) ?? (name === "dsmm_role" ? args?.role : name === "dsmm_category" ? args?.category : undefined);
432
- if (isDsmmRoleId(target) && controlledDefinitions.has(definition)
433
- && (!settings.roles[target] || !allowedRoleChildren(identity.role, identity.child).includes(target)))
434
- return `DSMM delegation to ${target} is not permitted`;
435
- if (this.readOnly(identity) && READONLY_ROLE_DENIED_TOOLS.includes(name))
436
- return "DSMM read-only role does not permit this tool";
437
- return undefined;
438
- }
439
- captureToolExecution(execution, full) {
122
+ toolBlacklistDenial(agent, name, execution) { return this.preToolDenial(agent, name, undefined, execution); }
123
+ captureToolExecution(execution, _full) {
440
124
  const agent = execution.agent;
441
- if (agent === undefined)
125
+ if (!agent)
126
+ return;
127
+ if (this.toolCalls.has(execution))
442
128
  return;
443
129
  this.assertLive(agent);
444
- const native = agent.ctx, agents = native.get("agents");
445
- const tools = native.get("agentPresets")?.serviceFor(agent, "tools") ?? native.get("tools");
446
- const definition = tools?.get(execution.name, agent);
447
- const owned = definition !== undefined && controlledDefinitions.has(definition);
448
- const call = { active: false, agent, context: native, registry: Reflect.get(agents, symbols.original) ?? agents,
130
+ const agents = agent.ctx.get("agents"), tools = agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools"), definition = tools?.get(execution.name, agent);
131
+ this.toolCalls.set(execution, { agent, context: agent.ctx, registry: Reflect.get(agents, symbols.original) ?? agents,
449
132
  realm: tools === undefined ? undefined : Reflect.get(tools, symbols.original) ?? tools, scopeParent: scopeParentOf(agent),
450
133
  parents: agents.list().filter(parent => parent !== agent && agents.isOwnedBy(agent.id, parent)), parentSession: agent.session.header.parentSession,
451
134
  name: execution.name, args: execution.arguments, callId: execution.callId, signal: execution.signal,
452
- ...!owned ? {} : { definition, body: definition.execute, argumentsJson: JSON.stringify(execution.arguments) } };
453
- this.toolCalls.set(execution, call);
454
- if (!owned)
455
- return;
456
- this.executions.exit(() => {
457
- try {
458
- call.identity = this.identity(agent);
459
- call.targets = this.targets(agent);
460
- const args = execution.arguments;
461
- const target = roleFromToolName(execution.name) ?? (execution.name === "dsmm_role" ? args?.role : execution.name === "dsmm_category" ? args?.category : undefined);
462
- if (isDsmmRoleId(target))
463
- call.target = target;
464
- }
465
- catch (error) {
466
- if (!full || !(error instanceof DsmmProfileError || error instanceof SubagentError))
467
- throw error;
468
- }
469
- });
135
+ toolFilter: this.visibleToolCeiling(agent),
136
+ ...(definition === undefined || !controlledDefinitions.has(definition) ? {} : { definition, body: definition.execute, argumentsJson: JSON.stringify(execution.arguments) }) });
137
+ }
138
+ /** Visible native names are a narrowing ceiling, never permission to execute a definition. */
139
+ visibleToolCeiling(agent) {
140
+ const native = agent.ctx, tools = native.get("agentPresets")?.serviceFor(agent, "tools") ?? native.get("tools");
141
+ if (!tools)
142
+ throw new SubagentError("Native tools unavailable", "UNAUTHORIZED");
143
+ return Object.freeze({ allow: Object.freeze(tools.schemas(agent).map(tool => tool.name)) });
144
+ }
145
+ delegationToolFilter(execution) {
146
+ this.assertToolExecution(execution);
147
+ const call = this.toolCalls.get(execution);
148
+ if (!call)
149
+ throw new SubagentError("Native tool execution capture required", "UNAUTHORIZED");
150
+ return call.toolFilter;
470
151
  }
471
152
  assertToolExecution(execution) {
472
153
  execution.signal.throwIfAborted();
473
- if (execution.agent === undefined)
154
+ const agent = execution.agent;
155
+ if (!agent)
474
156
  return;
475
- this.assertLive(execution.agent);
157
+ this.assertModuleAdmission(agent);
476
158
  const call = this.toolCalls.get(execution);
477
- if (call === undefined)
159
+ if (!call)
478
160
  return;
479
161
  call.signal.throwIfAborted();
480
- const agent = execution.agent, agents = agent.ctx.get("agents");
481
- const tools = agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools");
162
+ const agents = agent.ctx.get("agents"), tools = agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools");
482
163
  const parents = agents.list().filter(parent => parent !== agent && agents.isOwnedBy(agent.id, parent));
483
164
  if (agent !== call.agent || agent.ctx !== call.context || (Reflect.get(agents, symbols.original) ?? agents) !== call.registry
484
165
  || (tools === undefined ? undefined : Reflect.get(tools, symbols.original) ?? tools) !== call.realm || scopeParentOf(agent) !== call.scopeParent
485
166
  || agent.session.header.parentSession !== call.parentSession || parents.length !== call.parents.length || parents.some(parent => !call.parents.includes(parent)))
486
- throw new SubagentError("Native tool caller ownership changed", "UNAUTHORIZED");
487
- if (call.definition === undefined)
488
- return;
489
- const current = tools?.get(call.name, agent);
490
- if (execution.name !== call.name || execution.arguments !== call.args || execution.callId !== call.callId || JSON.stringify(execution.arguments) !== call.argumentsJson
491
- || call.definition.execute !== call.body || current !== undefined && current !== call.definition)
492
- throw new SubagentError("Owned tool registration or invocation changed", "UNAUTHORIZED");
167
+ throw new SubagentError("Tool caller ownership changed", "UNAUTHORIZED");
168
+ if (call.definition && (execution.name !== call.name || execution.arguments !== call.args || execution.callId !== call.callId || JSON.stringify(execution.arguments) !== call.argumentsJson
169
+ || call.definition.execute !== call.body || tools?.get(call.name, agent) !== call.definition))
170
+ throw new SubagentError("Tool invocation changed", "UNAUTHORIZED");
493
171
  }
494
172
  beforeToolDecision(operation) { return this.executions.exit(operation); }
495
- async duringToolExecution(execution, operation) {
496
- this.assertToolExecution(execution);
497
- const call = this.toolCalls.get(execution);
498
- if (call !== undefined)
499
- call.active = true;
500
- try {
501
- return await this.executions.run(execution, operation);
502
- }
503
- finally {
504
- if (call !== undefined)
505
- call.active = false;
506
- }
507
- }
508
- toolDenial(agent, name, tools, execution) {
509
- const scoped = this.executions.getStore();
510
- const active = execution ?? (scoped !== undefined && this.toolCalls.get(scoped)?.active ? scoped : undefined);
511
- if (active !== undefined && active.agent === agent && active.name === name) {
512
- this.assertToolExecution(active);
513
- return undefined;
514
- }
515
- if (tools === undefined)
516
- return this.toolBlacklistDenial(agent, name);
517
- return this.preToolDenial(agent, name, tools);
518
- }
173
+ duringToolExecution(execution, operation) { this.assertToolExecution(execution); return this.executions.run(execution, operation); }
174
+ toolDenial(agent, name, tools, execution) { return this.preToolDenial(agent, name, tools, execution); }
519
175
  preToolDenial(agent, name, tools, execution) {
520
- return this.executions.exit(() => this.permissionDenial(agent, name, tools, execution));
521
- }
522
- permissionDenial(agent, name, tools, execution) {
523
- const identity = this.identity(agent);
524
- const settings = this.getSettings(agent);
176
+ const identity = this.identity(agent), settings = this.getSettings(agent);
525
177
  const native = agent.ctx, realm = tools ?? native.get("agentPresets")?.serviceFor(agent, "tools") ?? native.get("tools");
526
- const definition = realm?.get(name, agent);
527
- const owned = definition !== undefined && controlledDefinitions.has(definition);
528
- const controlled = owned && (name === "dsmm_role" || name === "dsmm_category");
529
- const target = owned ? roleFromToolName(name) : undefined;
530
- const readonly = identity.readOnly || DSMM_ROLES.find((row) => row.id === identity.role)?.access === "read-only";
531
- const checkedRealm = tools ?? (execution === undefined ? undefined : realm);
532
- if (checkedRealm !== undefined && (readonly || target !== undefined || controlled)) {
178
+ const definition = realm?.get(name, agent), owned = definition !== undefined && controlledDefinitions.has(definition);
179
+ const target = owned ? roleFromToolName(name) : undefined, merged = owned && ["dsmm_role", "dsmm_category"].includes(name);
180
+ if (tools && (this.readOnly(identity) || target || merged)) {
533
181
  const admitted = toolIdentities.get(agent);
534
- if (admitted === undefined || admitted.realm !== (Reflect.get(checkedRealm, symbols.original) ?? checkedRealm)
535
- || admitted.definitions.get(name) !== checkedRealm.get(name, agent))
536
- return "DSMM tool definition was not admitted in this exact Agent realm";
537
- }
538
- if (target !== undefined)
539
- return DSMM_ROLES.find(row => row.id === target).kind !== "role" || settings.subagents.toolTopology !== "per-role" ? "DSMM obsolete per-target entry is not callable in this topology"
540
- : this.targets(agent).includes(target) ? undefined : `DSMM delegation to ${target} is not permitted`;
541
- if (controlled) {
542
- const kind = name === "dsmm_role" ? "role" : "category";
543
- if (name === "dsmm_role" && settings.subagents.toolTopology !== "parameterized" || !this.targets(agent).some(role => DSMM_ROLES.find(row => row.id === role).kind === kind))
544
- return "DSMM merged delegation entry is not admitted";
545
- // Native merged-entry restrictions and the per-target ceiling both apply.
546
- if (identity.toolFilter?.allow !== undefined && !identity.toolFilter.allow.includes(name) || identity.toolFilter?.deny?.includes(name))
547
- return "DSMM native filter does not permit this merged entry";
548
- const args = execution?.arguments;
549
- const target = kind === "role" ? args?.role : args?.category;
550
- if (isDsmmRoleId(target) && !this.targets(agent).includes(target))
551
- return `DSMM delegation to ${target} is not permitted`;
552
- return undefined;
553
- }
554
- if (identity.toolFilter?.allow !== undefined && !identity.toolFilter.allow.includes(name) && name !== "structured_output"
555
- || identity.toolFilter?.deny?.includes(name))
556
- return "DSMM child native toolFilter does not permit this tool";
557
- if (name === "send_message" && liveIdentities.get(agent)?.admission?.childEvidence?.mode === "legacy-conservative") {
558
- const realm = tools ?? agent.ctx.get("tools"), parent = identity.parent;
559
- const capability = realm === undefined ? undefined : this.collaborators?.classifyLegacyTool?.(name, realm, agent);
560
- if (parent === undefined || realm === undefined || capability?.kind !== "child-report" || realm.get(name, agent) !== capability.definition)
561
- return "DSMM legacy report requires its audited native capability";
562
- try {
563
- this.assertLive(parent);
564
- this.assertDelegation(parent, identity.role);
565
- if (execution !== undefined) {
566
- capability.assertArguments(execution.arguments);
567
- const args = execution.arguments;
568
- if (args === null || typeof args !== "object" || args.agent_id !== parent.id)
569
- return "DSMM legacy report destination must be this exact direct parent";
570
- }
571
- }
572
- catch {
573
- return "DSMM legacy report arguments or current parent authority are not admitted";
574
- }
575
- }
576
- if (readonly && !readonlyRoleTool(name, settings))
577
- return "DSMM read-only role does not permit this tool";
578
- if (identity.role === undefined)
579
- return identity.child && settings.modules.deepwork.enabled && ["subagent", "spawn", "fork"].includes(name) ? "DSMM unadmitted children cannot delegate" : undefined;
580
- if (!settings.modules.deepwork.enabled || !settings.roles[identity.role])
581
- return "DSMM role is disabled in this Agent admission";
582
- if (["subagent", "spawn", "fork"].includes(name))
583
- return "Use the admitted DSMM role tools; generic delegation is not a role-policy bypass";
182
+ if (!admitted || admitted.realm !== (Reflect.get(tools, symbols.original) ?? tools) || admitted.definitions.get(name) !== definition)
183
+ return "Tool definition was not admitted in this Agent realm";
184
+ }
185
+ const nativeOutput = name === "structured_output" && definition !== undefined && toolIdentities.get(agent)?.definitions.get(name) === definition;
186
+ if (identity.toolFilter?.allow !== undefined && !identity.toolFilter.allow.includes(name) && !nativeOutput || identity.toolFilter?.deny?.includes(name))
187
+ return "Tool exceeds inherited filter";
188
+ if (identity.toolFilter && identity.parent && name !== "structured_output") {
189
+ const parent = identity.parent, parentTools = parent.ctx.get("agentPresets")?.serviceFor(parent, "tools") ?? parent.ctx.get("tools");
190
+ if (!parentTools?.get(name, parent))
191
+ return "Parent no longer exposes this capability";
192
+ const denied = this.preToolDenial(identity.parent, name, undefined, execution);
193
+ if (denied)
194
+ return denied;
195
+ }
196
+ if (target)
197
+ return this.targets(agent).includes(target) ? undefined : "Role delegation is not permitted";
198
+ if (merged) {
199
+ const kind = name === "dsmm_role" ? "role" : "category", args = execution?.arguments;
200
+ if (!this.targets(agent).some(id => DSMM_ROLES.find(row => row.id === id)?.kind === kind))
201
+ return "Delegation entry is not admitted";
202
+ const requested = args?.[kind];
203
+ return isDsmmRoleId(requested) && !this.targets(agent).includes(requested) ? "Requested role is not admitted" : undefined;
204
+ }
205
+ if (this.readOnly(identity) && !readonlyRoleTool(name, settings))
206
+ return "Read-only role does not permit this tool";
207
+ if (identity.role && ["subagent", "spawn", "fork"].includes(name))
208
+ return "Use admitted DSMM role tools";
584
209
  return undefined;
585
210
  }
586
- installDrain(agent) {
587
- const native = agent.ctx;
588
- if (native === undefined)
589
- throw new Error("DSMM native role lifecycle requires an Agent context");
590
- native.effect(() => async () => {
591
- this.collaborators?.revokeParent?.(agent, "role-residency-disposed");
592
- const agents = this.agents();
593
- if (agents.get(agent.id) !== agent)
594
- throw new Error("DSMM Agent was detached before continuable descendants drained");
595
- await native.get("subagents")?.drainContinuableDescendants([agent]);
596
- liveIdentities.delete(agent);
597
- toolIdentities.delete(agent);
598
- });
599
- }
600
211
  }
601
212
  //# sourceMappingURL=role-policy.js.map