@dsmm/dsmm 0.3.1 → 0.3.3

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 (54) hide show
  1. package/README.md +2 -2
  2. package/docs/agent-presets.md +5 -5
  3. package/docs/compatibility.md +7 -1
  4. package/docs/migration-from-ocmm.md +1 -1
  5. package/docs/releasing.md +25 -65
  6. package/docs/roadmap.md +37 -2
  7. package/docs/settings-status.md +1 -1
  8. package/lib/client/DeploymentFields.d.ts +6 -2
  9. package/lib/client/DeploymentFields.js +8 -6
  10. package/lib/client/DeploymentPage.d.ts +1 -0
  11. package/lib/client/DeploymentPage.js +4 -3
  12. package/lib/client/ProfilesSection.js +3 -3
  13. package/lib/client/RoleAvailability.js +1 -1
  14. package/lib/client/SessionProfiles.js +21 -18
  15. package/lib/client/controller.d.ts +17 -0
  16. package/lib/client/controller.js +104 -18
  17. package/lib/client/deployment-locales.js +26 -27
  18. package/lib/client/deployment-modules.js +1 -1
  19. package/lib/client/index.js +10 -2
  20. package/lib/client/locales.d.ts +6 -0
  21. package/lib/client/locales.js +148 -124
  22. package/lib/client/permission-locales.js +35 -35
  23. package/lib/client.js +645 -542
  24. package/lib/index.js +10 -5
  25. package/lib/native-admission.d.ts +18 -0
  26. package/lib/native-admission.js +174 -17
  27. package/lib/permission-control.d.ts +2 -0
  28. package/lib/permission-control.js +7 -0
  29. package/lib/permission-controller.js +2 -2
  30. package/lib/permission-native-rules.js +3 -3
  31. package/lib/preset-materializer.js +3 -3
  32. package/lib/preset-registry.d.ts +20 -2
  33. package/lib/preset-registry.js +46 -17
  34. package/lib/preset-skills.d.ts +1 -1
  35. package/lib/preset-skills.js +2 -2
  36. package/lib/profile-diagnostics.js +1 -1
  37. package/lib/profile-remote.js +1 -3
  38. package/lib/profile-rpc.js +2 -0
  39. package/lib/profile-runtime.d.ts +12 -1
  40. package/lib/profile-runtime.js +122 -10
  41. package/lib/profile-store.d.ts +2 -2
  42. package/lib/profile-store.js +8 -1
  43. package/lib/profile-types.d.ts +1 -0
  44. package/lib/role-invocation.d.ts +1 -1
  45. package/lib/role-invocation.js +2 -2
  46. package/lib/role-policy.js +2 -2
  47. package/lib/role-subagents.js +18 -4
  48. package/lib/roles.d.ts +2 -0
  49. package/lib/roles.js +2 -0
  50. package/lib/settings.d.ts +1 -3
  51. package/lib/settings.js +4 -9
  52. package/lib/skills.d.ts +1 -0
  53. package/lib/skills.js +5 -1
  54. package/package.json +37 -33
package/lib/index.js CHANGED
@@ -119,7 +119,12 @@ export async function apply(input, config = {}, startupOptions = {}) {
119
119
  const nativeAdmission = admission;
120
120
  if (startup.settings.modules.deepwork.enabled) {
121
121
  const presets = ctx.inject(["agentPresets"], async (scope) => {
122
- await registerRolePresets(scope, () => startup.settings);
122
+ await registerRolePresets(scope, () => startup.settings, agent => { try {
123
+ return policy.identity(agent).role;
124
+ }
125
+ catch {
126
+ return undefined;
127
+ } });
123
128
  const providers = scope.inject(["subagents"], async (runtimeScope) => {
124
129
  registerRoleProviders(runtimeScope, () => startup.settings, nativeAdmission);
125
130
  await registerNativeSubagentControls(runtimeScope);
@@ -137,18 +142,18 @@ export async function apply(input, config = {}, startupOptions = {}) {
137
142
  admission.activate(async (agent, candidate) => {
138
143
  candidate.subagentRuntime = () => runtimeAdmissionView(ctx);
139
144
  const scope = agent.ctx;
140
- if (candidate().modules.deepwork.enabled) {
141
- registerAgentSkills(scope, controller, candidate, agent, admission.lifetime.signal);
145
+ if (startup.settings.modules.deepwork.enabled) {
146
+ registerAgentSkills(scope, controller, candidate, agent, admission.lifetime.signal, () => !nativeAdmission.isSelecting(agent));
142
147
  registerDeepworkPrompt(scope, controller, candidate, { section: startup.profile.section ?? startup.global.section }, agent, admission.lifetime.signal);
143
148
  }
144
149
  if (installed.has(agent)) {
145
- if (candidate().modules.deepwork.enabled && ctx.get("subagents") !== undefined)
150
+ if (startup.settings.modules.deepwork.enabled && ctx.get("subagents") !== undefined)
146
151
  await registerHeadlessRoleTools(scope, controller, candidate, policy, nativeAdmission, agent);
147
152
  return;
148
153
  }
149
154
  registerModelRouting(scope, controller, candidate);
150
155
  registerSafetyGuards(scope, controller, candidate, policy);
151
- if (candidate().modules.deepwork.enabled) {
156
+ if (startup.settings.modules.deepwork.enabled) {
152
157
  if (ctx.get("subagents") !== undefined)
153
158
  await registerHeadlessRoleTools(scope, controller, candidate, policy, nativeAdmission, agent);
154
159
  }
@@ -7,6 +7,7 @@ import type { DsmmProfileRuntime } from "./profile-runtime.js";
7
7
  import type { DsmmProfileAdmission } from "./settings.js";
8
8
  import type { ResolvedRoleInvocation } from "./role-invocation.js";
9
9
  import type { DsmmRolePolicy } from "./role-policy.js";
10
+ import type { SessionActionUnavailableReason } from "./profile-types.js";
10
11
  declare module "@deepseek-ai/cordis" {
11
12
  interface Context {
12
13
  dsmmNativeAdmission: NativeAdmission;
@@ -29,16 +30,33 @@ export declare class NativeAdmission {
29
30
  private readonly guardedTools;
30
31
  private readonly agentLifetimes;
31
32
  private readonly retirements;
33
+ private readonly installing;
34
+ private readonly selecting;
35
+ private readonly failedInstallations;
36
+ private readonly blankUpdates;
37
+ private readonly getters;
38
+ private readonly executions;
32
39
  private ready;
33
40
  private install?;
34
41
  constructor(ctx: Context, profiles: DsmmProfileRuntime, policy: DsmmRolePolicy);
35
42
  activate(install: NonNullable<NativeAdmission["install"]>): void;
36
43
  get isReady(): boolean;
44
+ isSelecting(agent: Agent): boolean;
37
45
  get(agent: Agent): DsmmProfileAdmission | undefined;
38
46
  configuration(agent: Agent): DsmmProfileAdmission;
47
+ private getter;
48
+ private dependencies;
39
49
  invocation(agent: Agent): ResolvedRoleInvocation | undefined;
40
50
  ensure(agent: Agent): Promise<DsmmProfileAdmission>;
41
51
  assert(agent: Agent): DsmmProfileAdmission;
52
+ blankReason(agent: Agent, allowQueued?: boolean): SessionActionUnavailableReason | undefined;
53
+ /** Reserved by runMaintenance; newly queued input belongs to the accepted choice. */
54
+ beginBlank(agent: Agent, signal: AbortSignal, assertAuthority: () => void): {
55
+ assertCurrent(): void;
56
+ prepare(admission: DsmmProfileAdmission, describe: () => void): Promise<void>;
57
+ committed(): void;
58
+ close(): Promise<void>;
59
+ };
42
60
  reserve(exec: Readonly<ToolExecution>, invocation: ResolvedRoleInvocation, provider: SubagentProvider, maxDepth?: number): Promise<{
43
61
  childId: SessionId;
44
62
  release(): Promise<void>;
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import { getTraceable, symbols } from "@deepseek-ai/cordis";
3
4
  import { SessionId } from "@deepseek-ai/dsh-session";
4
5
  import { SubagentError, delegationDepthOf } from "@deepseek-ai/dsh-subagent";
@@ -6,6 +7,10 @@ import { freezeSettings } from "./settings.js";
6
7
  import { scopeLifetime } from "./lifetime.js";
7
8
  import { sessionEvents } from "./session-scope.js";
8
9
  import { scopeParentOf } from "./native-scope.js";
10
+ import { DsmmProfileError } from "./profiles.js";
11
+ import { roleProviderName } from "./roles.js";
12
+ import { resolveRoleInvocation } from "./role-invocation.js";
13
+ import { resolvedModelParameterPolicy } from "./model-parameter-policy.js";
9
14
  /** Short-lived creation correlations and exact live bindings, never an execution queue. */
10
15
  export class NativeAdmission {
11
16
  ctx;
@@ -23,6 +28,12 @@ export class NativeAdmission {
23
28
  guardedTools = new WeakMap();
24
29
  agentLifetimes = new WeakMap();
25
30
  retirements = new WeakMap();
31
+ installing = new AsyncLocalStorage();
32
+ selecting = new WeakSet();
33
+ failedInstallations = new WeakSet();
34
+ blankUpdates = new WeakMap();
35
+ getters = new WeakMap();
36
+ executions = new WeakMap();
26
37
  ready = false;
27
38
  install;
28
39
  constructor(ctx, profiles, policy) {
@@ -59,6 +70,17 @@ export class NativeAdmission {
59
70
  ctx.on("agent/request", async (frame, next) => { await this.ensure(frame.agent); return next(); }, { global: true, prepend: true });
60
71
  ctx.on("tools/execute", async (exec, next) => { if (exec.agent)
61
72
  await this.ensure(exec.agent); return policy.duringToolExecution(exec, next); }, { global: true, prepend: true });
73
+ ctx.on("tools/pre-execute", async (exec, next) => {
74
+ if (exec.agent) {
75
+ const active = this.executions.get(exec.agent) ?? new Set();
76
+ active.add(exec.token);
77
+ this.executions.set(exec.agent, active);
78
+ await this.ensure(exec.agent);
79
+ }
80
+ return next();
81
+ }, { global: true, prepend: true });
82
+ ctx.on("tools/result", exec => { if (exec.agent)
83
+ this.executions.get(exec.agent)?.delete(exec.token); }, { global: true });
62
84
  ctx.on("agent-preset/selected", id => {
63
85
  const agent = ctx.agents.get(id);
64
86
  if (!agent || !this.live.has(agent))
@@ -70,15 +92,41 @@ export class NativeAdmission {
70
92
  }
71
93
  activate(install) { this.lifetime.signal.throwIfAborted(); this.install = install; this.ready = true; }
72
94
  get isReady() { return this.ready && !this.lifetime.signal.aborted; }
95
+ isSelecting(agent) { return this.selecting.has(agent); }
73
96
  get(agent) { return this.live.get(agent)?.admission; }
74
- configuration(agent) { const value = this.candidates.get(agent) ?? this.get(agent); if (!value)
75
- throw new SubagentError("No trusted live admission", "UNAUTHORIZED"); return value; }
97
+ configuration(agent) {
98
+ const preview = this.installing.getStore();
99
+ const value = preview?.agent === agent ? preview.admission : this.candidates.get(agent) ?? this.get(agent);
100
+ if (!value)
101
+ throw new SubagentError("No trusted live admission", "UNAUTHORIZED");
102
+ return value;
103
+ }
104
+ getter(agent) {
105
+ let getter = this.getters.get(agent);
106
+ if (getter === undefined) {
107
+ getter = () => this.configuration(agent).settings;
108
+ getter.admission = () => this.configuration(agent);
109
+ this.getters.set(agent, getter);
110
+ }
111
+ return getter;
112
+ }
113
+ dependencies(agent) {
114
+ const presets = agent.ctx.get("agentPresets");
115
+ return [presets, agent.ctx.get("subagents"), agent.ctx.get("llm"),
116
+ presets?.serviceFor(agent, "tools") ?? agent.ctx.get("tools"),
117
+ presets?.serviceFor(agent, "systemPrompt") ?? agent.ctx.get("systemPrompt"),
118
+ presets?.serviceFor(agent, "skills") ?? agent.ctx.get("skills")].map(service => service === undefined ? undefined : original(service));
119
+ }
76
120
  invocation(agent) { return this.live.get(agent)?.invocation; }
77
121
  async ensure(agent) { await this.rebindings.get(agent); return this.assert(agent); }
78
122
  assert(agent) {
79
123
  this.lifetime.signal.throwIfAborted();
80
124
  this.agentLifetimes.get(agent)?.signal.throwIfAborted();
81
125
  const live = this.live.get(agent);
126
+ if (this.failedInstallations.has(agent))
127
+ throw new SubagentError("Session configuration restoration failed; create a new session", "UNAUTHORIZED");
128
+ if (this.selecting.has(agent))
129
+ throw new SubagentError("Session configuration maintenance is in progress", "UNAUTHORIZED");
82
130
  if (!this.ready || !live || this.ctx.agents.get(agent.id) !== agent)
83
131
  throw new SubagentError("No trusted live admission; create a new session", "UNAUTHORIZED");
84
132
  if (live.preset !== agent.ctx.get("agentPresets")?.composedPreset(agent.ctx) || live.scopeParent !== scopeParentOf(agent))
@@ -90,6 +138,112 @@ export class NativeAdmission {
90
138
  this.policy.assertModuleAdmission(agent);
91
139
  return live.admission;
92
140
  }
141
+ blankReason(agent, allowQueued = false) {
142
+ if (!this.isReady || this.failedInstallations.has(agent) || this.ctx.agents.get(agent.id) !== agent || !this.ctx.agents.roots().includes(agent) || this.dependencies(agent).some(value => value === undefined))
143
+ return "runtime-unavailable";
144
+ const live = this.live.get(agent);
145
+ if (!live || live.parent || agent.session.header.origin === "subagent" || agent.session.header.isSeeded
146
+ || sessionEvents(agent.session).some(event => ["turn/start", "step/start", "request/header", "assistant/message", "tool/call"].includes(event.type)))
147
+ return "new-session-required";
148
+ if (agent.status !== "idle" || (this.calls.get(agent) ?? 0) !== 0 || (this.executions.get(agent)?.size ?? 0) !== 0 || [...this.pending.values()].some(row => row.parent === agent)
149
+ || this.ctx.agents.list().some(child => this.ctx.agents.isOwnedBy(child.id, agent))
150
+ || this.selecting.has(agent) && !allowQueued
151
+ || !allowQueued && (agent.inbox.nextTurn.length !== 0 || agent.inbox.nextStep.length !== 0))
152
+ return "busy";
153
+ if (agent.runMaintenance === undefined)
154
+ return "maintenance";
155
+ if (live.preset !== agent.ctx.get("agentPresets")?.composedPreset(agent.ctx) || live.scopeParent !== scopeParentOf(agent)
156
+ || this.agentLifetimes.get(agent)?.signal.aborted)
157
+ return "runtime-unavailable";
158
+ return undefined;
159
+ }
160
+ /** Reserved by runMaintenance; newly queued input belongs to the accepted choice. */
161
+ beginBlank(agent, signal, assertAuthority) {
162
+ const reason = this.blankReason(agent);
163
+ if (reason !== undefined)
164
+ throw new DsmmProfileError(reason === "busy" ? "busy" : "unavailable", "Only an unstarted live session can select its configuration.");
165
+ const previous = this.live.get(agent);
166
+ this.assert(agent);
167
+ const captured = this.dependencies(agent);
168
+ const preparationSignal = AbortSignal.any([signal, this.lifetime.signal, this.agentLifetimes.get(agent).signal]);
169
+ this.selecting.add(agent);
170
+ let finish;
171
+ const completion = new Promise(resolve => { finish = resolve; });
172
+ this.blankUpdates.set(agent, completion);
173
+ let prepared = false, committed = false;
174
+ let publication;
175
+ let providers = new Map();
176
+ const assertCurrent = () => {
177
+ assertAuthority();
178
+ preparationSignal.throwIfAborted();
179
+ if (this.live.get(agent) !== previous || this.blankReason(agent, true) !== undefined || this.dependencies(agent).some((value, index) => value !== captured[index])) {
180
+ throw new DsmmProfileError("conflict", "The session owner or composition changed before configuration commit.");
181
+ }
182
+ for (const [name, expected] of providers) {
183
+ const current = agent.ctx.get("subagents")?.getProvider(name);
184
+ if (current === undefined || original(current) !== original(expected) || current.capabilities.depthLimit !== true) {
185
+ throw new DsmmProfileError("conflict", "A required native provider changed before configuration commit.");
186
+ }
187
+ }
188
+ };
189
+ const install = (admission) => this.installing.run({ agent, admission }, () => this.install(agent, this.getter(agent)));
190
+ return {
191
+ assertCurrent,
192
+ prepare: async (admission, describe) => {
193
+ assertCurrent();
194
+ this.policy.validateRootRole(agent, admission);
195
+ await this.installing.run({ agent, admission }, async () => {
196
+ const targets = this.policy.targets(agent);
197
+ providers = new Map([...targets.map(roleProviderName), ...targets.length === 0 ? [] : ["spawn"]].map(name => {
198
+ const provider = agent.ctx.get("subagents")?.getProvider(name);
199
+ if (provider?.capabilities.depthLimit !== true)
200
+ throw new DsmmProfileError("activation", "An enabled role has no admitted native provider.");
201
+ return [name, provider];
202
+ }));
203
+ for (const role of targets) {
204
+ const preset = await agent.ctx.get("agentPresets").resolve(role);
205
+ assertCurrent();
206
+ if (preset.broken !== undefined)
207
+ throw new DsmmProfileError("activation", "An enabled role preset is unavailable.", role);
208
+ const routing = admission.settings.roleRouting[role];
209
+ if (routing?.primary !== undefined || routing?.fallbackRoutes !== undefined) {
210
+ await resolveRoleInvocation(agent, role, admission.settings, preparationSignal, {}, undefined, resolvedModelParameterPolicy(admission));
211
+ assertCurrent();
212
+ }
213
+ for (const level of ["low", "high", "max"])
214
+ if (routing?.levels?.[level] !== undefined) {
215
+ await resolveRoleInvocation(agent, role, admission.settings, preparationSignal, { level }, undefined, resolvedModelParameterPolicy(admission));
216
+ assertCurrent();
217
+ }
218
+ }
219
+ });
220
+ assertCurrent();
221
+ prepared = true;
222
+ await install(admission);
223
+ assertCurrent();
224
+ this.installing.run({ agent, admission }, describe);
225
+ publication = Object.freeze({ ...previous, admission });
226
+ },
227
+ committed: () => { this.live.set(agent, publication); committed = true; },
228
+ close: async () => {
229
+ try {
230
+ if (prepared && !committed && this.ctx.agents.get(agent.id) === agent && !this.lifetime.signal.aborted)
231
+ await install(previous.admission);
232
+ }
233
+ catch (error) {
234
+ this.failedInstallations.add(agent);
235
+ const refusal = new DsmmProfileError("activation", "Session configuration restoration failed. Execution is disabled; create a new session.");
236
+ refusal.cause = error;
237
+ throw refusal;
238
+ }
239
+ finally {
240
+ this.selecting.delete(agent);
241
+ this.blankUpdates.delete(agent);
242
+ finish();
243
+ }
244
+ },
245
+ };
246
+ }
93
247
  async reserve(exec, invocation, provider, maxDepth) {
94
248
  const parent = exec.agent;
95
249
  if (!parent)
@@ -100,7 +254,10 @@ export class NativeAdmission {
100
254
  const presets = this.ctx.get("agentPresets");
101
255
  if (!presets)
102
256
  throw new SubagentError("Native preset registry unavailable", "UNSUPPORTED_CAPABILITY");
103
- const lease = await presets.acquireScope(invocation.target);
257
+ // The child shares the parent's standing composition; its role is carried
258
+ // by the admitted invocation, not by an own registered preset.
259
+ const expectedPreset = presets.composedPreset(parent.ctx);
260
+ const lease = await presets.acquireScope(expectedPreset);
104
261
  try {
105
262
  exec.signal.throwIfAborted();
106
263
  this.assert(parent);
@@ -109,7 +266,7 @@ export class NativeAdmission {
109
266
  throw new SubagentError("Creation dependencies changed", "UNAUTHORIZED");
110
267
  const childId = SessionId(randomUUID()), signal = AbortSignal.any([exec.signal, this.lifetime.signal, this.agentLifetimes.get(parent).signal]);
111
268
  const admission = freezeSettings({ ...parentAdmission, settings: structuredClone(parentAdmission.settings) });
112
- const pending = Object.freeze({ childId, parent, parentAdmission, callId: exec.callId, invocation, admission, provider, presetScope: lease.key, signal, maxDepth, toolFilter });
269
+ const pending = Object.freeze({ childId, parent, parentAdmission, callId: exec.callId, invocation, admission, provider, expectedPreset, presetScope: lease.key, signal, maxDepth, toolFilter });
113
270
  this.pending.set(childId, pending);
114
271
  const revoke = () => { if (this.pending.get(childId) === pending)
115
272
  this.pending.delete(childId); };
@@ -199,19 +356,22 @@ export class NativeAdmission {
199
356
  return settled;
200
357
  }
201
358
  async rebindBlank(agent) {
202
- const previous = this.live.get(agent);
359
+ await this.blankUpdates.get(agent);
203
360
  this.lifetime.signal.throwIfAborted();
361
+ const previous = this.live.get(agent);
362
+ if (previous === undefined)
363
+ throw new SubagentError("The blank Agent owner was retired", "UNAUTHORIZED");
204
364
  if (previous.preset === agent.ctx.get("agentPresets")?.composedPreset(agent.ctx) && previous.scopeParent === scopeParentOf(agent))
205
365
  return;
366
+ if (this.selecting.has(agent))
367
+ throw new SubagentError("Session configuration maintenance owns the blank composition", "UNAUTHORIZED");
206
368
  if (previous.parent || (this.calls.get(agent) ?? 0) !== 0 || [...this.pending.values()].some(row => row.parent === agent)
207
369
  || this.ctx.agents.list().some(child => this.ctx.agents.isOwnedBy(child.id, agent)) || sessionEvents(agent.session).some(event => event.type === "turn/start"))
208
370
  throw new SubagentError("Preset change requires a new session", "UNAUTHORIZED");
209
371
  this.policy.validateRootRole(agent, previous.admission);
210
372
  const preset = agent.ctx.get("agentPresets")?.composedPreset(agent.ctx), scopeParent = scopeParentOf(agent);
211
- const getter = () => previous.admission.settings;
212
- getter.admission = () => previous.admission;
213
373
  this.guardTools(agent);
214
- await this.install(agent, getter);
374
+ await this.install(agent, this.getter(agent));
215
375
  this.lifetime.signal.throwIfAborted();
216
376
  this.agentLifetimes.get(agent).signal.throwIfAborted();
217
377
  if (this.ctx.agents.get(agent.id) !== agent || this.live.get(agent) !== previous || scopeParentOf(agent) !== scopeParent)
@@ -238,7 +398,7 @@ export class NativeAdmission {
238
398
  throw new SubagentError("Invalid native child header", "UNAUTHORIZED");
239
399
  if (pending) {
240
400
  this.check(pending);
241
- if (pending.parent !== parent || pending.parentAdmission !== parentAdmission || preset !== pending.invocation.target || agent.session.header.isSeeded
401
+ if (pending.parent !== parent || pending.parentAdmission !== parentAdmission || preset !== pending.expectedPreset || agent.session.header.isSeeded
242
402
  || scopeParentOf(agent) !== pending.presetScope)
243
403
  throw new SubagentError("Child does not match the pending invocation", "UNAUTHORIZED");
244
404
  if (pending.maxDepth !== undefined && delegationDepthOf(agent) > pending.maxDepth)
@@ -254,13 +414,12 @@ export class NativeAdmission {
254
414
  else {
255
415
  if (agent.session.header.origin === "subagent" || pending)
256
416
  throw new SubagentError("Missing exact parent", "UNAUTHORIZED");
257
- // A resume may have opened the native log, but cannot recover DSMM authorization.
258
- if ((source !== "startup" || agent.session.header.isSeeded) && (preset?.startsWith("dsmm-") || sessionEvents(agent.session).some(event => ["deepwork/mode", "dsmm/role-policy"].includes(event.type))))
259
- throw new SubagentError("DSMM cold recovery is unavailable", "UNAUTHORIZED");
417
+ // A resumed session receives a fresh admission from the current deployment:
418
+ // its persisted history stays readable user intent, while no old
419
+ // authorization survives — delegation authority and child residency can
420
+ // never be reconstructed from a log.
260
421
  admission = await this.profiles.prepareRoot(agent, signal);
261
422
  this.policy.validateRootRole(agent, admission);
262
- if ((source !== "startup" || agent.session.header.isSeeded) && admission.settings.defaultActive)
263
- throw new SubagentError("Historical sessions are not automatically admitted to Deepwork", "UNAUTHORIZED");
264
423
  }
265
424
  this.agentLifetimes.set(agent, new AbortController());
266
425
  scopeLifetime(agent.ctx, "dsmm: retire exact Agent work", () => { void this.retireAgent(agent).catch(() => { }); });
@@ -282,9 +441,7 @@ export class NativeAdmission {
282
441
  try {
283
442
  if (pending)
284
443
  this.policy.bindChild(agent, parent, admission, pending.invocation, pending.maxDepth, pending.toolFilter);
285
- const getter = () => admission.settings;
286
- getter.admission = () => admission;
287
- await this.install(agent, getter);
444
+ await this.install(agent, this.getter(agent));
288
445
  signal.throwIfAborted();
289
446
  this.agentLifetimes.get(agent).signal.throwIfAborted();
290
447
  if (pending)
@@ -41,6 +41,8 @@ export interface PermissionRegistration {
41
41
  export declare function permissionOriginal(value: object): object;
42
42
  type Request = Parameters<Context["approval"]["request"]>[0];
43
43
  type Outcome = Awaited<ReturnType<Context["approval"]["request"]>>;
44
+ /** Explicitly audited DSMM approval adapters retain identity through the patched dispatcher. */
45
+ export declare function permissionApprovalAdapter(ctx: Context, listener: (request: Request, next: () => Promise<Outcome>) => Promise<Outcome>): typeof listener;
44
46
  export declare function isSandboxWidening(requested: NativeCommandEntry["sandboxMode"], standing: string | undefined): boolean;
45
47
  /** Permission admission precedes native approval; subsequent checks enforce execution integrity only. */
46
48
  export declare class PermissionControl {
@@ -6,6 +6,13 @@ import { PermissionRefusal, permissionOutcome } from "./permission-errors.js";
6
6
  import { nativeStandingFullAccess } from "./permission-native-access.js";
7
7
  export { PermissionRefusal } from "./permission-errors.js";
8
8
  export function permissionOriginal(value) { return Reflect.get(value, symbols.original) ?? value; }
9
+ /** Explicitly audited DSMM approval adapters retain identity through the patched dispatcher. */
10
+ export function permissionApprovalAdapter(ctx, listener) {
11
+ const approval = ctx.get("approval"), factory = approval && Reflect.get(approval, "createForwarder");
12
+ if (typeof factory !== "function")
13
+ return listener;
14
+ return Reflect.apply(factory, approval, [listener]);
15
+ }
9
16
  export function isSandboxWidening(requested, standing) {
10
17
  return standing === "read-only" || standing === "workspace-write" && requested === "danger-full-access";
11
18
  }
@@ -1,7 +1,7 @@
1
1
  import { Service } from "@deepseek-ai/cordis";
2
2
  import { HarnessError } from "@deepseek-ai/dsh-llm";
3
3
  import { TOOL_ABORTED } from "@deepseek-ai/dsh-tools";
4
- import { isSandboxWidening, PermissionControl, PermissionRefusal } from "./permission-control.js";
4
+ import { isSandboxWidening, PermissionControl, PermissionRefusal, permissionApprovalAdapter } from "./permission-control.js";
5
5
  import { classifyPermissionShell } from "./permission-shell.js";
6
6
  import { nativeCommandMatch } from "./permission-native-command.js";
7
7
  import { NATIVE_PERMISSION_CAPABILITIES, registerNativePermissionRules } from "./permission-native-rules.js";
@@ -109,7 +109,7 @@ export class DsmmPermissionController extends Service {
109
109
  },
110
110
  });
111
111
  ctx.tools.guard(exec => this.permissions.guard(exec));
112
- ctx.on("approval/request", (request, next) => this.permissions.answerer(request, next), { prepend: true, global: true });
112
+ ctx.on("approval/request", permissionApprovalAdapter(ctx, (request, next) => this.permissions.answerer(request, next)), { prepend: true, global: true });
113
113
  ctx.on("tools/result", exec => { this.permissions.finish(exec); }, { global: true });
114
114
  ctx.on("agent/disposed", ({ agent }) => { this.permissions.revokeAgent(agent); }, { global: true });
115
115
  }
@@ -1,5 +1,5 @@
1
1
  import { isAbsolute, resolve } from "node:path";
2
- import { PermissionRefusal } from "./permission-control.js";
2
+ import { PermissionRefusal, permissionApprovalAdapter } from "./permission-control.js";
3
3
  import { permissionOutcome } from "./permission-errors.js";
4
4
  import { classifyPermissionShell, parsePermissionShellReadPaths } from "./permission-shell.js";
5
5
  import { intersectPermissionActions } from "./permission-rules.js";
@@ -249,13 +249,13 @@ export function registerNativePermissionRules(ctx, options) {
249
249
  }
250
250
  return downstream;
251
251
  }, { prepend: true, global: true });
252
- const unapproval = ctx.on("approval/request", async (request, next) => {
252
+ const unapproval = ctx.on("approval/request", permissionApprovalAdapter(ctx, async (request, next) => {
253
253
  const ask = request.displayReason === undefined ? undefined : asks.get(request.displayReason);
254
254
  if (ask === undefined || request.agent !== ask.exec.agent || request.signal !== ask.exec.signal || request.callId !== ask.exec.callId || request.toolName !== ask.exec.name)
255
255
  return next();
256
256
  checkIntegrity(ask.exec, ask.binding);
257
257
  return permissionOutcome(next, ask.binding.signal, "cancelled");
258
- }, { prepend: true, global: true });
258
+ }), { prepend: true, global: true });
259
259
  const unguard = tools.guard(exec => {
260
260
  const binding = bindings.get(exec.token);
261
261
  if (binding === undefined)
@@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSy
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { isAbsolute, join, relative, sep } from "node:path";
4
4
  import { DSMM_ROLES, DSMM_ROLE_IDS, renderAgentCordis, renderPresetMetadata } from "./roles.js";
5
- import { isRoleEnabled } from "./settings.js";
5
+ import { isRoleEnabled, isRootRoleEnabled } from "./settings.js";
6
6
  import { enabledSkillNames } from "./skills.js";
7
7
  export const DSMM_MANAGED_PRESET_MARKER = ".dsmm-managed-preset";
8
8
  export const DSMM_MANAGED_PRESET_MARKER_VERSION = 1;
@@ -71,12 +71,12 @@ export function reconcileRolePresets({ root, settings, filesystem: filesystemOve
71
71
  };
72
72
  });
73
73
  for (const knownDirectory of knownDirectories) {
74
- if (settings.presets.materialize && isRoleEnabled(settings, knownDirectory.role.id) && knownDirectory.ownership === "foreign") {
74
+ if (settings.presets.materialize && isRootRoleEnabled(settings, knownDirectory.role.id) && knownDirectory.ownership === "foreign") {
75
75
  throw new Error(`dsmm preset directory is foreign and will not be claimed: ${knownDirectory.directory}`);
76
76
  }
77
77
  }
78
78
  for (const knownDirectory of knownDirectories) {
79
- if (settings.presets.materialize && isRoleEnabled(settings, knownDirectory.role.id)) {
79
+ if (settings.presets.materialize && isRootRoleEnabled(settings, knownDirectory.role.id)) {
80
80
  if (knownDirectory.ownership === "absent") {
81
81
  publishNewRoleDirectory(canonicalRoot, root, knownDirectory.role.id, settings, filesystem);
82
82
  }
@@ -1,5 +1,23 @@
1
1
  import type { DshContext } from "./dsh-types.js";
2
2
  import type { DsmmSettings } from "./settings.js";
3
- /** Declare roles to DSH 0.2's native registry; directories are not discovery inputs. */
4
- export declare function registerRolePresets(ctx: DshContext, getSettings: () => DsmmSettings): void | Promise<void>;
3
+ interface NativeScopedTools {
4
+ get(name: string, scope?: object): unknown;
5
+ restrict(filter: {
6
+ deny: string[];
7
+ }): () => void;
8
+ }
9
+ interface NativeAgent {
10
+ ctx: {
11
+ tools?: NativeScopedTools;
12
+ get?<T>(name: string): T | undefined;
13
+ };
14
+ id?: string;
15
+ }
16
+ /**
17
+ * Declare the selectable dispatcher composition to DSH 0.2's native registry;
18
+ * directories are not discovery inputs. `roleIdentity` reports the admitted
19
+ * delegation role of an Agent, whose composition is shared with its parent.
20
+ */
21
+ export declare function registerRolePresets(ctx: DshContext, getSettings: () => DsmmSettings, roleIdentity?: (agent: NativeAgent) => string | undefined): void | Promise<void>;
22
+ export {};
5
23
  //# sourceMappingURL=preset-registry.d.ts.map
@@ -1,19 +1,29 @@
1
1
  import { Context as NativeContext, getTraceable } from "@deepseek-ai/cordis";
2
2
  import { DSMM_ROLES, DSMM_ROLE_IDS, rolePluginRows } from "./roles.js";
3
3
  import { enabledSkillNames } from "./skills.js";
4
+ import { isRootRoleEnabled } from "./settings.js";
4
5
  import { allowedRoleChildren, readonlyRoleTool, roleFromToolName, READONLY_ROLE_DENIED_TOOLS } from "./role-policy.js";
5
6
  import { nativeStandingFullAccess } from "./permission-native-access.js";
6
7
  import { scopeParentOf } from "./native-scope.js";
7
- /** Declare roles to DSH 0.2's native registry; directories are not discovery inputs. */
8
- export function registerRolePresets(ctx, getSettings) {
8
+ /**
9
+ * Declare the selectable dispatcher composition to DSH 0.2's native registry;
10
+ * directories are not discovery inputs. `roleIdentity` reports the admitted
11
+ * delegation role of an Agent, whose composition is shared with its parent.
12
+ */
13
+ export function registerRolePresets(ctx, getSettings, roleIdentity) {
9
14
  const install = async (readyCtx) => {
10
15
  const registry = readyCtx.get?.("agentPresets")
11
16
  ?? readyCtx.agentPresets;
12
17
  if (registry === undefined)
13
18
  throw new Error("dsmm requires the native DSH agentPresets registry");
14
19
  const settings = getSettings();
15
- const enabled = DSMM_ROLE_IDS.filter((id) => settings.modules.deepwork.enabled && settings.roles[id]);
16
- const active = DSMM_ROLES.filter((role) => enabled.includes(role.id));
20
+ // Only the dispatcher is a user-selectable composition. Delegation targets
21
+ // share their parent's standing composition and carry their role entirely
22
+ // through the admitted invocation and per-Agent registrations.
23
+ // Only the dispatcher is a user-selectable composition. Delegation targets
24
+ // share their parent's standing composition and carry their role entirely
25
+ // through the admitted invocation and per-Agent registrations.
26
+ const active = DSMM_ROLES.filter((role) => isRootRoleEnabled(settings, role.id));
17
27
  const disposers = [];
18
28
  try {
19
29
  for (const role of active) {
@@ -24,16 +34,23 @@ export function registerRolePresets(ctx, getSettings) {
24
34
  order: role.order,
25
35
  // Profiles do not replace standing native compositions. Child routes
26
36
  // are admitted by the role provider from the parent's fixed snapshot.
27
- plugins: rolePluginRows(role, enabledSkillNames(settings), enabled)
37
+ plugins: rolePluginRows(role, enabledSkillNames(settings), DSMM_ROLE_IDS.filter((id) => settings.modules.deepwork.enabled && settings.roles[id]))
28
38
  }));
29
39
  }
30
- // A direct selection of a read-only preset must be restricted at the Agent
31
- // scope: preset-local fs registrations cannot be filtered within their own layer.
32
- // Blank Agents can switch presets without another agent/created event.
40
+ // A directly selected read-only preset and a delegated read-only child
41
+ // must both be restricted at the Agent scope: preset-local fs
42
+ // registrations cannot be filtered within their own layer. Delegation
43
+ // children share their parent's composition, so their role comes from
44
+ // the admitted invocation identity, not from composedPreset.
45
+ const roleOf = (agent) => roleIdentity?.(agent) ?? registry.composedPreset(agent.ctx);
46
+ const agents = readyCtx.get?.("agents")
47
+ ?? readyCtx.agents;
48
+ if (agents === undefined)
49
+ throw new Error("dsmm native preset restriction requires DSH Agent registry");
33
50
  const states = new WeakMap();
34
51
  const restrictedAgents = new Set();
35
52
  const denial = (agent, name) => {
36
- const role = registry.composedPreset(agent.ctx);
53
+ const role = roleOf(agent);
37
54
  if (!isReadonlyRole(role))
38
55
  return undefined;
39
56
  const target = roleFromToolName(name);
@@ -41,13 +58,23 @@ export function registerRolePresets(ctx, getSettings) {
41
58
  : allowedRoleChildren(role).includes(target) && settings.roles[target] ? undefined : "dsmm read-only role does not permit this delegation";
42
59
  };
43
60
  const reconcile = (agent) => {
44
- const selected = registry.composedPreset(agent.ctx);
61
+ const identityRole = roleIdentity?.(agent);
62
+ // A delegation child's identity is bound by native admission's created
63
+ // guard, which may still be in flight during this synchronous
64
+ // reconcile. A parented agent with no bound identity stays pending
65
+ // instead of concluding "not read-only" from a not-yet-bound role.
66
+ const agentId = agent.id;
67
+ const parented = agentId !== undefined && agents.list().some(other => other !== agent && agents.isOwnedBy(agentId, other));
68
+ const pendingIdentity = roleIdentity !== undefined && identityRole === undefined && parented;
69
+ const selected = pendingIdentity ? undefined : identityRole ?? registry.composedPreset(agent.ctx);
45
70
  const previous = states.get(agent);
46
71
  if (previous !== undefined && previous.role === selected && (previous.pending || !isReadonlyRole(selected) || previous.disposeRestriction !== undefined))
47
72
  return;
48
- states.set(agent, { role: selected, pending: true });
73
+ states.set(agent, { role: selected, pending: pendingIdentity || undefined });
49
74
  previous?.disposeRestriction?.();
50
75
  restrictedAgents.delete(agent);
76
+ if (pendingIdentity)
77
+ return;
51
78
  if (!isReadonlyRole(selected)) {
52
79
  states.set(agent, { role: selected });
53
80
  return;
@@ -63,9 +90,15 @@ export function registerRolePresets(ctx, getSettings) {
63
90
  if (tools?.restrict === undefined)
64
91
  throw new Error(`dsmm read-only role requires DSH tools restrict: ${selected}`);
65
92
  restrictedAgents.add(agent);
66
- // Only inherited tools are maskable; own-layer tools remain subject to runtime denial.
93
+ // A delegation child shares its parent's standing composition realm,
94
+ // where a realm-level restriction would also mask the writable
95
+ // parent. Such children are fenced per-Agent through the runtime
96
+ // denial above instead; schema masking applies only to a directly
97
+ // selected read-only composition with its own realm.
67
98
  const inheritedScope = scopeParentOf(agent);
68
- const disposeRestriction = tools.restrict({ deny: READONLY_ROLE_DENIED_TOOLS.filter(name => tools.get(name, inheritedScope) !== undefined) });
99
+ const sharedRealmChild = roleIdentity !== undefined && roleIdentity(agent) === selected;
100
+ const maskable = READONLY_ROLE_DENIED_TOOLS.filter(name => tools.get(name, inheritedScope) !== undefined);
101
+ const disposeRestriction = sharedRealmChild || maskable.length === 0 ? () => { } : tools.restrict({ deny: maskable });
69
102
  states.set(agent, { role: selected, disposeRestriction });
70
103
  }
71
104
  catch (error) {
@@ -74,10 +107,6 @@ export function registerRolePresets(ctx, getSettings) {
74
107
  throw error;
75
108
  }
76
109
  };
77
- const agents = readyCtx.get?.("agents")
78
- ?? readyCtx.agents;
79
- if (agents === undefined)
80
- throw new Error("dsmm native preset restriction requires DSH Agent registry");
81
110
  const onPreExecute = readyCtx.on?.("tools/pre-execute", async (execution, next) => {
82
111
  const agent = execution.agent;
83
112
  if (agent === undefined || agents.get(agent.id) !== agent)
@@ -2,5 +2,5 @@ import type { DshAgent, DshContext } from "./dsh-types.js";
2
2
  import type { DsmmSettingsGetter } from "./settings.js";
3
3
  import type { DeepworkModeController } from "./state.js";
4
4
  /** Admission owns installation; mode changes only invalidate this Agent's lazy provider. */
5
- export declare function registerAgentSkills(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, agent: DshAgent, lifetime: AbortSignal): void;
5
+ export declare function registerAgentSkills(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, agent: DshAgent, lifetime: AbortSignal, catalogReady?: () => boolean): void;
6
6
  //# sourceMappingURL=preset-skills.d.ts.map
@@ -3,7 +3,7 @@ import { registerBundledSkills } from "./skills.js";
3
3
  import { nativeAgentContext, scopeParentOf } from "./native-scope.js";
4
4
  const bindings = new WeakMap();
5
5
  /** Admission owns installation; mode changes only invalidate this Agent's lazy provider. */
6
- export function registerAgentSkills(ctx, controller, getSettings, agent, lifetime) {
6
+ export function registerAgentSkills(ctx, controller, getSettings, agent, lifetime, catalogReady) {
7
7
  const refresh = bindings.get(agent);
8
8
  if (refresh) {
9
9
  refresh();
@@ -26,7 +26,7 @@ export function registerAgentSkills(ctx, controller, getSettings, agent, lifetim
26
26
  return;
27
27
  }
28
28
  remove();
29
- mounted = { parent, registry: raw, provider: registerBundledSkills(agentCtx, getTraceable(agentCtx, raw), { agent, controller, getSettings }) };
29
+ mounted = { parent, registry: raw, provider: registerBundledSkills(agentCtx, getTraceable(agentCtx, raw), { agent, controller, getSettings, catalogReady }) };
30
30
  };
31
31
  const stopMode = controller.watch(changed => { if (changed === agent)
32
32
  reconcile(); });