@dsmm/dsmm 0.3.0 → 0.3.1

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