@dsmm/dsmm 0.3.30 → 0.3.32

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 (48) hide show
  1. package/agent-presets/dsmm-oracle/agent.cordis.yml +2 -0
  2. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +2 -0
  3. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +2 -0
  4. package/agent-presets/dsmm-planner/agent.cordis.yml +1 -0
  5. package/agent-presets/dsmm-reviewer/agent.cordis.yml +2 -0
  6. package/docs/compatibility.md +2 -2
  7. package/dsh-plugin.json +1 -1
  8. package/lib/agent-prompt-scope.d.ts +3 -2
  9. package/lib/agent-prompt-scope.js +11 -16
  10. package/lib/core-permission-authority.js +4 -0
  11. package/lib/host-llm.d.ts +5 -0
  12. package/lib/host-llm.js +9 -0
  13. package/lib/index.js +13 -16
  14. package/lib/live-pi-ai-owner.d.ts +1 -0
  15. package/lib/live-pi-ai-owner.js +2 -1
  16. package/lib/mode.d.ts +3 -2
  17. package/lib/mode.js +8 -12
  18. package/lib/model-routing.js +2 -2
  19. package/lib/native-admission.d.ts +2 -0
  20. package/lib/native-admission.js +80 -24
  21. package/lib/native-pi-ai-wire.js +2 -2
  22. package/lib/native-scope.d.ts +3 -3
  23. package/lib/native-scope.js +5 -6
  24. package/lib/preset-skills.d.ts +3 -2
  25. package/lib/preset-skills.js +12 -14
  26. package/lib/resident-root.d.ts +10 -0
  27. package/lib/resident-root.js +151 -0
  28. package/lib/role-identity.d.ts +2 -2
  29. package/lib/role-identity.js +1 -5
  30. package/lib/role-llm-runtime.d.ts +12 -2
  31. package/lib/role-llm-runtime.js +28 -18
  32. package/lib/role-llm.d.ts +2 -0
  33. package/lib/role-llm.js +1 -0
  34. package/lib/role-policy.d.ts +2 -0
  35. package/lib/role-policy.js +10 -10
  36. package/lib/role-routing.d.ts +1 -1
  37. package/lib/role-routing.js +4 -3
  38. package/lib/role-subagents.d.ts +2 -2
  39. package/lib/role-subagents.js +43 -63
  40. package/package.json +1 -1
  41. package/prompts/source/agents/plan-critic.md +2 -0
  42. package/prompts/source/agents/planner.md +1 -0
  43. package/prompts/source/agents/reviewer.md +2 -0
  44. package/skills/avoid-ai-slop/SKILL.md +1 -1
  45. package/skills/brainstorming/SKILL.md +1 -1
  46. package/skills/receiving-code-review/SKILL.md +2 -2
  47. package/skills/requesting-code-review/SKILL.md +1 -1
  48. package/skills/writing-plans/SKILL.md +1 -1
@@ -5,12 +5,36 @@ import { modelRouteFromCall, modelRouteToCall } from "./role-llm.js";
5
5
  import { prepareDsmmRequest } from "./model-routing.js";
6
6
  import { preparedRequestRouting } from "./request-routing.js";
7
7
  import { roleRouteLock } from "./role-routing.js";
8
+ import { assertResidentRootCurrent } from "./resident-root.js";
9
+ /** Request preparations, route locks and invocation effort belong to the admitting Core's module instance. */
10
+ export function bindCoreLlmAdmission(frame, admission) {
11
+ return Object.freeze({ ...admission, async prepare(proposal) {
12
+ admission.assertCurrent();
13
+ frame.signal.throwIfAborted();
14
+ const request = frame;
15
+ const routed = await prepareDsmmRequest(request, proposal, admission.assertCurrent);
16
+ admission.assertCurrent();
17
+ frame.signal.throwIfAborted();
18
+ const routing = preparedRequestRouting(request);
19
+ if (routing === undefined)
20
+ throw new Error("DSMM request lost its routing capture");
21
+ const bound = Object.freeze({ ...admission, assertCurrent() { admission.assertCurrent(); routing.assertCurrent(); } });
22
+ const effortSource = routing.effortSource ?? captureDsmmEffortSource(frame.agent);
23
+ const config = snapshotDsmmCall(modelRouteToCall(modelRouteFromCall(routed)));
24
+ bound.assertCurrent();
25
+ if (routing.decision.configuredRoot && routing.decision.policy !== undefined) {
26
+ roleRouteLock(request.agent, routing.decision.policy).route = modelRouteFromCall(config);
27
+ }
28
+ return { admission: bound, config, effortSource };
29
+ } });
30
+ }
8
31
  /** Connect the cold Host LLM owner to the existing exact Agent/role admission authority. */
9
32
  export function createDsmmRoleLlmOwner(ctx, providers) {
10
33
  const nativeFallback = async (frame, proposal) => {
11
34
  const config = snapshotDsmmCall(proposal);
12
35
  if (requiresDsmmCallAdmission(config, providers, frame.agent))
13
36
  throw new LlmError("Enhanced requests require exact Core admission", "DSMM_NOT_READY");
37
+ assertResidentRootCurrent(frame.agent, ctx.get("dsmmNativeAdmission"));
14
38
  // Missing opaque fields do not prove native equivalence: standard options
15
39
  // must still resolve using this request's complete frozen configuration.
16
40
  await ctx.get("llm").resolveCallConfig(config, frame.signal);
@@ -23,32 +47,18 @@ export function createDsmmRoleLlmOwner(ctx, providers) {
23
47
  if (core === undefined) {
24
48
  return nativeFallback(frame, proposal);
25
49
  }
26
- let admission = await core.admit(frame);
27
- if (admission === undefined) {
50
+ const captured = await core.admit(frame);
51
+ if (captured === undefined) {
28
52
  return nativeFallback(frame, proposal);
29
53
  }
30
54
  const agent = frame.agent;
31
55
  const original = ctx.get("dsmmProfileRuntime").admission(agent);
32
- if (original !== admission.admission)
56
+ if (original !== captured.admission)
33
57
  throw new Error("LLM policy does not own the exact admission");
34
58
  const policy = resolvedModelParameterPolicy(original);
59
+ const { admission, config, effortSource } = await captured.prepare(proposal);
35
60
  admission.assertCurrent();
36
61
  frame.signal.throwIfAborted();
37
- const routed = await prepareDsmmRequest(frame, proposal, admission.assertCurrent);
38
- admission.assertCurrent();
39
- frame.signal.throwIfAborted();
40
- const routing = preparedRequestRouting(frame);
41
- if (routing === undefined)
42
- throw new Error("DSMM request lost its routing capture");
43
- const originalAdmission = admission;
44
- admission = Object.freeze({ ...originalAdmission, assertCurrent() { originalAdmission.assertCurrent(); routing.assertCurrent(); } });
45
- const effortSource = routing.effortSource ?? captureDsmmEffortSource(frame.agent);
46
- const config = snapshotDsmmCall(modelRouteToCall(modelRouteFromCall(routed)));
47
- admission.assertCurrent();
48
- if (routing.decision.configuredRoot && routing.decision.policy !== undefined) {
49
- const lock = roleRouteLock(agent, routing.decision.policy);
50
- lock.route = modelRouteFromCall(config);
51
- }
52
62
  if (policy.mode !== "passthrough") {
53
63
  await ctx.get("llm").resolveCallConfig(config, frame.signal);
54
64
  admission.assertCurrent();
package/lib/role-llm.d.ts CHANGED
@@ -4,11 +4,13 @@ import type { ModelRouteJson } from "./route-json.js";
4
4
  /** Host-owned metadata admission; never a completion or a request authorization. */
5
5
  export interface DsmmLlmRouteResolver {
6
6
  resolveRoute(route: ModelRouteJson, signal?: AbortSignal): Promise<ModelRouteJson>;
7
+ isMissingProviderError?(error: unknown): boolean;
7
8
  }
8
9
  /** Only a public provider-directory lookup can establish this absence. */
9
10
  export declare class DsmmMissingProviderError extends LlmError {
10
11
  constructor();
11
12
  }
13
+ export declare const isMissingProviderError: (error: unknown) => boolean;
12
14
  declare module "@deepseek-ai/cordis" {
13
15
  interface Context {
14
16
  dsmmLlmRoutes: DsmmLlmRouteResolver;
package/lib/role-llm.js CHANGED
@@ -4,6 +4,7 @@ import { normalizeModelRouteJson } from "./route-json.js";
4
4
  export class DsmmMissingProviderError extends LlmError {
5
5
  constructor() { super("The provider route has no registered adapter", "NO_ADAPTER"); }
6
6
  }
7
+ export const isMissingProviderError = (error) => error instanceof DsmmMissingProviderError;
7
8
  const callFields = new Set(["provider", "model", "reasoningEffort", "temperature", "maxTokens", "stop"]);
8
9
  /** Request projection only. The Host supplies provenance; this does not establish admission or ownership. */
9
10
  export function projectModelRouteParameters(input, effortSource, passthrough = true) {
@@ -32,6 +32,8 @@ export declare class DsmmRolePolicy {
32
32
  private readonly getSettings;
33
33
  private readonly executions;
34
34
  private readonly toolCalls;
35
+ private readonly toolIdentities;
36
+ private readonly controlledDefinitions;
35
37
  constructor(ctx: DshContext, getSettings: DsmmSettingsGetter, _mode: DeepworkModeController);
36
38
  private agents;
37
39
  assertLive(agent: DshAgent): void;
@@ -10,8 +10,6 @@ import { captureRoleRuntimePolicy } from "./routing-policy.js";
10
10
  import { resolveEffectiveDsmmRole, resolveSelectedAgentPreset } from "./session-scope.js";
11
11
  import { scopeParentOf } from "./native-scope.js";
12
12
  const liveIdentities = new WeakMap();
13
- const toolIdentities = new WeakMap();
14
- const controlledDefinitions = new WeakSet();
15
13
  export const READONLY_ROLE_DENIED_TOOLS = ["write", "edit", "bash", "pwsh"];
16
14
  const readTools = new Set(["read", "glob", "grep", "read_image", "web_search", "web_fetch", "skill", "load_skill", "structured_output", "send_message", "interrupt_agent", "list_agents", "wait_agent", "team_task_list", "team_task_get", "exit_plan_mode", "ask_user_question", "todo_write", "job_output", "job_list", "job_kill"]);
17
15
  const readLsp = new Set(["status", "diagnostics", "goto_definition", "find_references", "find_symbol_related", "symbols", "prepare_rename"]);
@@ -43,6 +41,8 @@ export class DsmmRolePolicy {
43
41
  getSettings;
44
42
  executions = new AsyncLocalStorage();
45
43
  toolCalls = new WeakMap();
44
+ toolIdentities = new WeakMap();
45
+ controlledDefinitions = new WeakSet();
46
46
  constructor(ctx, getSettings, _mode) {
47
47
  this.ctx = ctx;
48
48
  this.getSettings = getSettings;
@@ -123,7 +123,7 @@ export class DsmmRolePolicy {
123
123
  creatorId: parent.id, maxDepth, preset, epoch: admission.epoch, targetCeiling: upstream.targetCeiling,
124
124
  readOnly: this.readOnly(upstream), toolFilter: inheritToolFilter(upstream.toolFilter, this.visibleToolCeiling(parent)) }));
125
125
  }
126
- release(agent) { liveIdentities.delete(agent); toolIdentities.delete(agent); }
126
+ release(agent) { liveIdentities.delete(agent); this.toolIdentities.delete(agent); }
127
127
  assertModuleAdmission(agent) {
128
128
  this.assertLive(agent);
129
129
  const settings = this.getSettings(agent), identity = liveIdentities.get(agent), selected = this.selected(agent);
@@ -172,16 +172,16 @@ export class DsmmRolePolicy {
172
172
  return { parent, role, epoch: this.identity(parent).epoch };
173
173
  }
174
174
  captureTools(agent, tools, names = [], reset = false) {
175
- const realm = Reflect.get(tools, symbols.original) ?? tools, previous = toolIdentities.get(agent);
175
+ const realm = Reflect.get(tools, symbols.original) ?? tools, previous = this.toolIdentities.get(agent);
176
176
  const definitions = previous === undefined || reset || previous.realm !== realm ? new Map() : previous.definitions;
177
177
  for (const schema of tools.schemas(agent))
178
178
  if (!previous || reset || previous.realm !== realm || names.includes(schema.name)) {
179
179
  const definition = tools.get(schema.name, agent);
180
180
  definitions.set(schema.name, definition);
181
181
  if (names.includes(schema.name))
182
- controlledDefinitions.add(definition);
182
+ this.controlledDefinitions.add(definition);
183
183
  }
184
- toolIdentities.set(agent, { realm, definitions });
184
+ this.toolIdentities.set(agent, { realm, definitions });
185
185
  }
186
186
  toolBlacklistDenial(agent, name, execution) { return this.preToolDenial(agent, name, undefined, execution); }
187
187
  captureToolExecution(execution, _full) {
@@ -197,7 +197,7 @@ export class DsmmRolePolicy {
197
197
  owner: this.identity(agent).owner, parentSession: agent.session.header.parentSession,
198
198
  name: execution.name, args: execution.arguments, callId: execution.callId, signal: execution.signal,
199
199
  toolFilter: this.visibleToolCeiling(agent),
200
- ...(definition === undefined || !controlledDefinitions.has(definition) ? {} : { definition, body: definition.execute, argumentsJson: JSON.stringify(execution.arguments) }) });
200
+ ...(definition === undefined || !this.controlledDefinitions.has(definition) ? {} : { definition, body: definition.execute, argumentsJson: JSON.stringify(execution.arguments) }) });
201
201
  }
202
202
  /** Visible native names are a narrowing ceiling, never permission to execute a definition. */
203
203
  visibleToolCeiling(agent) {
@@ -239,14 +239,14 @@ export class DsmmRolePolicy {
239
239
  preToolDenial(agent, name, tools, execution) {
240
240
  const identity = this.identity(agent), settings = this.getSettings(agent);
241
241
  const native = agent.ctx, realm = tools ?? native.get("agentPresets")?.serviceFor(agent, "tools") ?? native.get("tools");
242
- const definition = realm?.get(name, agent), owned = definition !== undefined && controlledDefinitions.has(definition);
242
+ const definition = realm?.get(name, agent), owned = definition !== undefined && this.controlledDefinitions.has(definition);
243
243
  const target = owned ? roleFromToolName(name) : undefined, merged = owned && ["dsmm_role", "dsmm_category"].includes(name);
244
244
  if (tools && (this.readOnly(identity) || target || merged)) {
245
- const admitted = toolIdentities.get(agent);
245
+ const admitted = this.toolIdentities.get(agent);
246
246
  if (!admitted || admitted.realm !== (Reflect.get(tools, symbols.original) ?? tools) || admitted.definitions.get(name) !== definition)
247
247
  return "Tool definition was not admitted in this Agent realm";
248
248
  }
249
- const nativeOutput = name === "structured_output" && definition !== undefined && toolIdentities.get(agent)?.definitions.get(name) === definition;
249
+ const nativeOutput = name === "structured_output" && definition !== undefined && this.toolIdentities.get(agent)?.definitions.get(name) === definition;
250
250
  if (identity.toolFilter?.allow !== undefined && !identity.toolFilter.allow.includes(name) && !nativeOutput || identity.toolFilter?.deny?.includes(name))
251
251
  return "Tool exceeds inherited filter";
252
252
  const lifetimeOwner = identity.owner ?? identity.parent;
@@ -44,7 +44,7 @@ export declare function sameExactModelRoute(left: Pick<DsmmModelRoute, "provider
44
44
  /** Consumed user intent stays explicit on cold resume and profile re-admission. */
45
45
  export declare function nativeModelSelectionWasAccepted(agent: DshAgent, intent: NativeModelSelectionIntent): boolean;
46
46
  /** Only native, machine-routable absence authorizes initial candidate admission. */
47
- export declare function isUnavailableRouteFailure(error: unknown, nativeRequestFailure?: boolean): boolean;
47
+ export declare function isUnavailableRouteFailure(error: unknown, nativeRequestFailure?: boolean, resolver?: DsmmLlmRouteResolver): boolean;
48
48
  export declare function orderedModelRoutes(candidates: readonly DsmmModelRoute[]): DsmmModelRoute[];
49
49
  /** Exact metadata preparation, never a completion or advisory catalog health check. */
50
50
  export declare function selectInitialModelRoute(llm: DshLlmRuntime, candidates: readonly DsmmModelRoute[], signal?: AbortSignal, resolver?: DsmmLlmRouteResolver, assertCurrent?: () => void): Promise<DsmmModelRoute>;
@@ -134,9 +134,10 @@ export function nativeModelSelectionWasAccepted(agent, intent) {
134
134
  && modelRouteFromHeader(event.data.header).reasoningEffort === intent.route.reasoningEffort);
135
135
  }
136
136
  /** Only native, machine-routable absence authorizes initial candidate admission. */
137
- export function isUnavailableRouteFailure(error, nativeRequestFailure = false) {
137
+ export function isUnavailableRouteFailure(error, nativeRequestFailure = false, resolver) {
138
138
  return isRecord(error) && (error.status === undefined || error.status === 503)
139
- && (error instanceof DsmmMissingProviderError || (error.code === "UNKNOWN_MODEL" && (nativeRequestFailure || error instanceof LlmError)));
139
+ && (error.code === "NO_ADAPTER" && (error instanceof DsmmMissingProviderError || resolver?.isMissingProviderError?.(error) === true)
140
+ || error.code === "UNKNOWN_MODEL" && (nativeRequestFailure || error instanceof LlmError));
140
141
  }
141
142
  export function orderedModelRoutes(candidates) {
142
143
  const routes = [];
@@ -174,7 +175,7 @@ export async function selectInitialModelRouteChoice(llm, candidates, signal, res
174
175
  catch (error) {
175
176
  assertCurrent?.();
176
177
  signal?.throwIfAborted();
177
- if (!isUnavailableRouteFailure(error))
178
+ if (!isUnavailableRouteFailure(error, false, resolver))
178
179
  throw error;
179
180
  unavailable = error;
180
181
  }
@@ -1,7 +1,7 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { Agent } from "@deepseek-ai/dsh-agent";
3
3
  import type { ToolRuntime } from "@deepseek-ai/dsh-tools";
4
- import type { DshAgent, DshContext } from "./dsh-types.js";
4
+ import type { DshAgent } from "./dsh-types.js";
5
5
  import type { DsmmRoleId } from "./roles.js";
6
6
  import { DsmmRolePolicy } from "./role-policy.js";
7
7
  import type { DsmmSettings, DsmmSettingsGetter, DsmmModelRoute } from "./settings.js";
@@ -52,5 +52,5 @@ export declare function callableRoleInventory(settings: DsmmSettings, targets: r
52
52
  /** Exact currently exposed definitions, suitable for E's runtime guidance and safe capability views. */
53
53
  export declare function admittedCallableRoleInventory(agent: DshAgent, settings: DsmmSettings, policy: DsmmRolePolicy, tools: ToolRuntime): readonly DsmmCallableEntry[];
54
54
  /** Published name retained; all native/headless Agents consume one admitted policy. */
55
- export declare function registerHeadlessRoleTools(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, policy: DsmmRolePolicy, admission: NativeAdmission, onlyAgent: DshAgent): Promise<void>;
55
+ export declare function registerHeadlessRoleTools(ctx: Context, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, policy: DsmmRolePolicy, admission: NativeAdmission, agent: DshAgent): void;
56
56
  //# sourceMappingURL=role-subagents.d.ts.map
@@ -1,4 +1,4 @@
1
- import { getTraceable, symbols } from "@deepseek-ai/cordis";
1
+ import { symbols } from "@deepseek-ai/cordis";
2
2
  import { createRequire } from "node:module";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -9,15 +9,13 @@ import { DsmmRolePolicy, roleToolName } from "./role-policy.js";
9
9
  import { roleProviderName } from "./role-providers.js";
10
10
  import { capturedRoleInvocation, invocationAgentOptions, invocationView, resolveRoleInvocation } from "./role-invocation.js";
11
11
  import { childOwnedSessionEvents } from "./session-scope.js";
12
- import { agentForScope, nativeAgentContext, scopeParentOf } from "./native-scope.js";
12
+ import { agentScopeService, nativeAgentContext, scopeParentOf } from "./native-scope.js";
13
13
  import { roleRouteRuntimeState } from "./role-routing.js";
14
14
  import { modelRouteFromCall } from "./role-llm.js";
15
15
  import { buildDsmmDelegationGuidance, buildDsmmTeamGuidance } from "./prompts.js";
16
16
  import { startNativeActivation, supportsNativeNames } from "./native-subagents.js";
17
17
  // Conditional Team tools stay in their native layer: copying a definition would discard its `when` registration.
18
18
  const hostControls = ["send_message", "interrupt_agent", "list_agents", "wait_agent", "exit_plan_mode", "ask_user_question", "todo_write", "job_output", "job_list", "job_kill"];
19
- // Agent-owned policy realms survive a bundle reinstall; do not register another
20
- // delegation/tools layer on the same retained live Agent.
21
19
  const admittedRealms = new WeakMap();
22
20
  const callableDefinitions = new WeakMap();
23
21
  /** Keep native controls on the frozen startup substrate, not desired-save reconciliation. */
@@ -132,9 +130,9 @@ export function admittedCallableRoleInventory(agent, settings, policy, tools) {
132
130
  return targets.length === 0 ? [] : [{ ...registered.entry, targets }];
133
131
  });
134
132
  }
135
- function registerRoleTool(agent, agentCtx, tools, entry, getSettings, policy, admission) {
133
+ function registerRoleTool(agent, ctx, tools, entry, getSettings, policy, admission) {
136
134
  const settings = getSettings(agent);
137
- const subagents = agentCtx.get("subagents");
135
+ const subagents = ctx.get("subagents");
138
136
  if (subagents === undefined)
139
137
  throw new Error("DSMM role tools require native subagents");
140
138
  const named = supportsNativeNames(subagents);
@@ -222,7 +220,7 @@ function registerRoleTool(agent, agentCtx, tools, entry, getSettings, policy, ad
222
220
  pending.signal.throwIfAborted();
223
221
  }
224
222
  try {
225
- const child = agentCtx.agents.get(activation.childId);
223
+ const child = ctx.get("agents").get(activation.childId);
226
224
  if (child === undefined)
227
225
  throw new SubagentError("Native role activation has no live child", "UNAUTHORIZED");
228
226
  await admission.ensure(child);
@@ -260,32 +258,30 @@ function registerRoleTool(agent, agentCtx, tools, entry, getSettings, policy, ad
260
258
  return () => { callableDefinitions.delete(definition); dispose(); };
261
259
  }
262
260
  /** Published name retained; all native/headless Agents consume one admitted policy. */
263
- export async function registerHeadlessRoleTools(ctx, controller, getSettings, policy, admission, onlyAgent) {
264
- const refresh = admittedRealms.get(onlyAgent);
261
+ export function registerHeadlessRoleTools(ctx, controller, getSettings, policy, admission, agent) {
262
+ const refresh = admittedRealms.get(ctx);
265
263
  if (refresh) {
266
264
  refresh();
267
265
  return;
268
266
  }
269
- const states = new WeakMap();
270
- const reconcile = (agent) => {
271
- const state = states.get(agent);
272
- if (state === undefined)
273
- return;
274
- const agentCtx = nativeAgentContext(agent);
275
- const raw = agentCtx.get("agentPresets")?.serviceFor({ ctx: agentCtx }, "tools");
276
- const tools = raw === undefined ? agentCtx.get("tools") : getTraceable(agentCtx, raw);
267
+ if (!getSettings(agent).modules.deepwork.enabled)
268
+ return;
269
+ policy.admit(agent);
270
+ const state = { owned: [], hostDefinitions: [], providers: [] };
271
+ const reconcile = () => {
272
+ const tools = agentScopeService(ctx, "tools");
277
273
  if (tools === undefined)
278
274
  throw new Error("DSMM role tools require native guard/restrict services");
279
275
  const settings = getSettings(agent), identity = policy.identity(agent), targets = policy.targets(agent);
280
- const prompt = agentCtx.get("agentPresets")?.serviceFor(agent, "systemPrompt") ?? agentCtx.get("systemPrompt");
276
+ const prompt = agentScopeService(ctx, "systemPrompt");
281
277
  const promptRealm = Reflect.get(prompt, symbols.original) ?? prompt;
282
278
  if (state.promptRealm !== promptRealm) {
283
279
  state.guidance?.();
284
- state.guidance = getTraceable(agentCtx, prompt).section({ name: "dsmm:delegation", order: 49, text(context) {
285
- if (context.scope !== agent && agentForScope(ctx, context.scope) !== agent)
280
+ state.guidance = prompt.section({ name: "dsmm:delegation", order: 49, text(context) {
281
+ if (context.scope !== agent)
286
282
  return "";
287
- const identity = policy.identity(agent), tools = states.get(agent)?.tools, settings = getSettings(agent);
288
- const teams = agentCtx.get?.("agentTeams");
283
+ const identity = policy.identity(agent), tools = state.tools, settings = getSettings(agent);
284
+ const teams = ctx.get?.("agentTeams");
289
285
  const toolSet = context.toolSet;
290
286
  const teamGuidance = teams?.isEnabled(agent) && toolSet !== undefined
291
287
  ? buildDsmmTeamGuidance([...toolSet.view(agent).keys()]) : "";
@@ -296,14 +292,14 @@ export async function registerHeadlessRoleTools(ctx, controller, getSettings, po
296
292
  delegation: tools === undefined ? [] : admittedCallableRoleInventory(agent, settings, policy, tools),
297
293
  ...(captured === undefined ? {} : { invocation: roleInvocationObservation(captured, DSMM_ROLES.find(role => role.id === captured.target).name, "continuable", getSettings, agent, { childId: agent.id }) }),
298
294
  runtimeAdmission: getSettings.subagentRuntime?.(), capabilities: { continuable: true, nativeChildDelivery: true,
299
- nativeTree: typeof agentCtx.get("subagents")?.rootOf === "function",
300
- ...(agentCtx.get("dsmmChildren") === undefined ? {} : { nativeBrowserPrompt: { surface: "conversation.dsmm-children" } }) } });
295
+ nativeTree: typeof ctx.get("subagents")?.rootOf === "function",
296
+ ...(ctx.get("dsmmChildren") === undefined ? {} : { nativeBrowserPrompt: { surface: "conversation.dsmm-children" } }) } });
301
297
  return [delegationGuidance, teamGuidance].filter(Boolean).join("\n\n");
302
298
  } });
303
299
  state.promptRealm = promptRealm;
304
300
  }
305
- const subagents = agentCtx.get("subagents");
306
- const host = ctx.get?.("tools");
301
+ const subagents = ctx.get("subagents");
302
+ const host = ctx.get("tools");
307
303
  const names = [...hostControls, ...host?.schemas().map((row) => row.name).filter((name) => name.startsWith(`mcp__${settings.lsp.serverName}__`)) ?? []];
308
304
  const definitions = names.map((name) => host?.get(name));
309
305
  const providers = targets.map(role => {
@@ -338,48 +334,32 @@ export async function registerHeadlessRoleTools(ctx, controller, getSettings, po
338
334
  }
339
335
  const inventory = callableRoleInventory(settings, targets.filter(role => subagents?.getProvider(roleProviderName(role))?.capabilities.depthLimit === true));
340
336
  for (const entry of inventory)
341
- state.owned.push(registerRoleTool(agent, agentCtx, tools, entry, getSettings, policy, admission));
337
+ state.owned.push(registerRoleTool(agent, ctx, tools, entry, getSettings, policy, admission));
342
338
  policy.captureTools(agent, tools, [...inventory.map(entry => entry.name), ...names], !sameRealm || !sameParent);
343
339
  state.signature = signature;
344
340
  state.providers = providers;
345
341
  state.hostDefinitions = definitions;
346
342
  state.parentScope = parentScope;
347
343
  };
348
- const onCreated = ({ agent }) => {
349
- if (states.has(agent) || admittedRealms.has(agent))
350
- return;
351
- if (!getSettings(agent).modules.deepwork.enabled)
352
- return;
353
- const agentCtx = nativeAgentContext(agent);
354
- policy.admit(agent);
355
- states.set(agent, { owned: [], hostDefinitions: [], providers: [] });
356
- const retire = () => {
357
- stopIdentity();
358
- const state = states.get(agent);
359
- state?.restriction?.();
360
- state?.guard?.();
361
- state?.guidance?.();
362
- for (const dispose of state?.owned ?? [])
363
- dispose();
364
- states.delete(agent);
365
- admittedRealms.delete(agent);
366
- admission.lifetime.signal.removeEventListener("abort", retire);
367
- };
368
- admission.lifetime.signal.addEventListener("abort", retire, { once: true });
369
- agentCtx.effect(() => retire);
370
- try {
371
- reconcile(agent);
372
- }
373
- catch (error) {
374
- retire();
375
- throw error;
376
- }
377
- admittedRealms.set(agent, () => reconcile(agent));
378
- };
379
- // Native assembly collects sections before its waterfall. Admission/mode/preset
380
- // changes must update the Agent layer before that collection begins.
381
- const stopIdentity = controller.watch(agent => { if (agent === onlyAgent)
382
- reconcile(agent); });
383
- onCreated({ agent: onlyAgent });
344
+ // Native assembly collects sections before its waterfall. Update the Agent layer before collection.
345
+ const stopIdentity = controller.watch(changed => { if (changed === agent)
346
+ reconcile(); });
347
+ const retire = ctx.effect(() => () => {
348
+ stopIdentity();
349
+ state.restriction?.();
350
+ state.guard?.();
351
+ state.guidance?.();
352
+ for (const dispose of state.owned)
353
+ dispose();
354
+ admittedRealms.delete(ctx);
355
+ });
356
+ try {
357
+ reconcile();
358
+ admittedRealms.set(ctx, reconcile);
359
+ }
360
+ catch (error) {
361
+ retire();
362
+ throw error;
363
+ }
384
364
  }
385
365
  //# sourceMappingURL=role-subagents.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsmm/dsmm",
3
- "version": "0.3.30",
3
+ "version": "0.3.32",
4
4
  "description": "Native Deepwork roles, routing, profiles, and permission controls for DeepSeek Harness.",
5
5
  "author": "Hugefiver",
6
6
  "license": "LicenseRef-AAAPL",
@@ -20,6 +20,8 @@ Trace the user's necessary outcome states and failure conditions to a feasible d
20
20
 
21
21
  Treat as blockers only issues that contradict an explicit requirement or constraint, omit a necessary prerequisite, preserve a known failing regression, create a concrete security/data-loss/compatibility/release/runtime risk, or conflict with an external API, provider, protocol, platform, packaging, or release contract. Recommend the smallest useful correction without expanding scope.
22
22
 
23
+ For a missing required safeguard, cite the governing requirement and the gap. For an additional safeguard, treat its absence as a blocker only when a concrete failure path escapes existing controls. If the plan makes valid work wait for redundant validation or approval, recommend removing that gate while retaining the actual boundary check. Hypothetical future uses and optional hardening do not hold up implementation.
24
+
23
25
  Everything else is a non-blocking note and does not delay implementation. Give current findings and supporting evidence as clear prose rather than protocol fields or approval tokens. Every substantive blocker must be corrected, rebutted with concrete evidence, or escalated for clarification; it cannot be relabeled advisory and ignored. Critique informs judgment and does not authorize implementation or delivery.
24
26
 
25
27
  Do not require another review merely because the plan changed. Revisit only affected claims and dependent risks when a blocker is newly identified or resolved, or relevant new evidence or another substantive input could change the prior conclusion. Wording changes, repeated concerns, and unchanged uncertainty are not progress; stop and return an unresolved blocker rather than continuing a no-progress loop. Do not require hashes, a fixed receipt or verdict format, a fixed iteration count, or an open-ended loop. Do not object to preference, optional polish, or a merely better approach.
@@ -9,6 +9,7 @@ You are the plan-only agent. From the agreed goal and direct evidence, produce a
9
9
  - Read, search, and analyze. Return a complete Markdown product plan when durable coordination is useful or requested; the authorized coordinator persists it if an artifact is needed. This native planner is read-only, including plan files: do not use shell, write/edit or a child proxy to persist one. Non-product coordination and reports stay in conversation unless explicitly requested as deliverables. Do not edit source, tests, configuration, or product documentation.
10
10
  - Reserve `docs/superpowers/specs/` and `docs/superpowers/plans/` for final product requirements to be delivered. Each artifact describes one final deliverable, not development decisions, rejected alternatives, assumption rationale/cost, or change history. Changed requirements use separate plans. Non-product tasks, regardless of complexity, use conversation coordination or a task-owned temporary plan outside those directories.
11
11
  - Plan around the ideal end state, dependencies, interfaces, material risks, wave goals, and useful outcome evidence. Record decisions an implementer cannot safely infer: necessary paths and names, interface signatures and types, requirement-fixed values, and decisive test assertions or observable results. Do not transcribe implementation bodies already determined by those decisions. Treat steps and ordering as informed guidance that execution may adjust as evidence changes, not as a hard script.
12
+ - Choose the simplest design that delivers the approved behavior and preserves contracts outside the authorized change. Validate at trust boundaries and reuse an established guarantee for as long as it holds. Add an abstraction, retry, fallback, lock, or approval step only when a current requirement or concrete failure path needs it; keep independent work moving.
12
13
  - Plan verification around valid requirements, functionality, and external interfaces, including material input classes and failure conditions implied by the approved behavior and local contracts. Attach plausible regression coverage to the owning task; when an important behavior remains unjudged, state why and what evidence is missing without imposing a fixed review-focus heading, list, or quota. Do not expand scope from speculation or add descriptive-text locks. Requirement changes update tests; removed components lose their dedicated tests rather than gaining absence tests. Git commits bound compatibility: interim uncommitted behavior need not be preserved, but existing committed contracts and API/security/data/permission/irreversible-action authorization remain binding.
13
14
  - Return unresolved software design choices that affect implementation to the orchestrator for `brainstorming`; use `writing-plans` techniques proportionally rather than imposing ceremony.
14
15
  - Use direct tools first. A leaf read-only `code-search`, `doc-search`, or equivalent lookup is allowed only to resolve a named fact. If evidence leaves a genuinely difficult decision, report the blocker to the orchestrator for optional `hard-reasoning`; strict or high-risk conditions alone do not qualify.
@@ -16,6 +16,8 @@ Tests cover valid requirements, functionality, and external interfaces. Reject s
16
16
 
17
17
  Evaluate existing evidence by material relevance; request missing or affected coverage instead of blanket reruns for unrelated code, dependency, or environment changes. Explicitly name any important behavior you considered but cannot judge, why, and the missing evidence; do not require a dedicated heading, list, or quota. The orchestrator coordinates global/heavy verification; don't duplicate it or waive required safety, release, pre-commit, or user checks.
18
18
 
19
+ Trace a local defect far enough to establish its impact and the smallest correction. Prefer a local fix when it restores the contract. Extend the investigation only as far as the changed behavior or a concrete risk warrants; assess independent defects in the diff on their own impact. Look for unnecessary complexity in the diff, such as an abstraction with no current consumer or a check that repeats an upstream guarantee. When complexity is the only issue, suggest a simpler alternative as non-blocking advice. Process rules about stopping your own unnecessary work do not require cleanup of the reviewed diff. If the change violates a requirement or creates a concrete safety risk, report that finding separately at its actual severity.
20
+
19
21
  Report material findings first with severity when useful, file path, concrete evidence, likely impact, and the smallest valid correction. Judge whether useful functionality is complete, interfaces are clear, and meaningful regression and real-surface evidence support the result. Review informs engineering judgment; it is not delivery authorization or a protocol gate. Repeat only the affected review for a newly identified or resolved blocker, a substantive correction, or relevant new evidence; repeated concerns or unchanged uncertainty do not justify another pass. Apply strict review only when the user explicitly requests it or a scoped, concrete high-risk condition warrants it.
20
22
 
21
23
  Use direct read/search tools first; a leaf read-only lookup may verify one finding but returns evidence, not delegated judgment. Never dispatch planner, reviewer, any Oracle profile, plan-critic, clarifier, coordinator, or an implementation agent.
@@ -18,7 +18,7 @@ Future flexibility alone is not a requirement. Do not add configuration switches
18
18
 
19
19
  For a proposed validation, retry, fallback, exception handler, or recovery layer, identify what it detects and how it changes rejection, recovery, or diagnosis. Validate at genuine trust boundaries; use established internal guarantees instead of repeatedly defending against impossible states.
20
20
 
21
- Preserve authentication, authorization, input handling, data integrity, protocol checks, supported compatibility, accessibility, and necessary recovery. Simplicity is not permission to remove them. Keep valid safeguards even when their code is longer.
21
+ Keep the safeguards the feature relies on, such as authorization at a protected operation or validation at a public input. For ordinary failures, prefer the project's standard error path. Add a fallback only when it gives the user a correct, useful result.
22
22
 
23
23
  Do not turn a failed read into a successful empty result, swallow an error behind a plausible default, or retry a side effect without the required safety guarantees. Propagate failures or handle them according to the existing contract. Fix incorrect types rather than suppressing them with `as any`, `@ts-ignore`, or `@ts-expect-error`.
24
24
 
@@ -80,7 +80,7 @@ Use a clarifier or ask the user only when missing information would change the d
80
80
 
81
81
  Present alternatives only when there is a real decision with meaningful trade-offs. Give as many viable approaches as the decision warrants, including one when the evidence supports a single clear path. Explain the recommendation using project evidence, constraints, reversibility, risk, and cost.
82
82
 
83
- Do not manufacture alternatives, architecture, or refactoring to make the process appear thorough. Follow established patterns and apply YAGNI.
83
+ Start with what the user needs to accomplish in normal use. Choose a familiar design that delivers that outcome. Where the business contract tolerates temporary inconsistency, allow independent operations to proceed and reconcile their results instead of serializing the whole workflow. Match safeguards to the system's actual exposure and the consequences of failure; reserve high-assurance designs for an explicit requirement or a credible risk that ordinary controls do not cover.
84
84
 
85
85
  ## Outcome-Oriented Design
86
86
 
@@ -36,8 +36,8 @@ Code review requires technical evaluation, not emotional performance.
36
36
  2. Restate or clarify the technical requirement when needed.
37
37
  3. Verify the claim against current code, requirements, and evidence.
38
38
  4. Classify it as a product defect, harness/tool/environment failure, evidence gap, optional improvement, incorrect finding, or decision that changes approved intent.
39
- 5. Apply the smallest justified correction or push back with evidence.
40
- 6. Rerun only affected verification and review surfaces.
39
+ 5. Correct a verified defect or rebut an incorrect claim with evidence. A simplification suggestion may stand as advice without a fix, rebuttal, or further review.
40
+ 6. If a correction changes behavior or the evidence for a required claim, revisit only the affected checks or review.
41
41
 
42
42
  A reviewer status, verdict label, acknowledgement, or receipt-shaped response is informational. The cited code, reasoning, and evidence determine whether action is required. Reviewer approval is not a substitute for verification.
43
43
 
@@ -87,7 +87,7 @@ Read the reviewer's analysis, cited code, and evidence. A status label, acknowle
87
87
 
88
88
  - Fix validated Critical or Important product defects before relying on the result.
89
89
  - Supply missing required evidence when the implementation may be sound but proof is insufficient.
90
- - Record or defer Minor suggestions according to scope and value.
90
+ - Treat a simpler design or optional hardening as non-blocking advice. For a proposed safeguard to block delivery, identify the unmet requirement or the concrete risk to the supported use case.
91
91
  - Push back with requirements, code, or evidence when a finding is wrong.
92
92
  - Preserve real security, data-loss, protocol/API, compatibility, release, and irreversible-operation safeguards.
93
93
 
@@ -45,7 +45,7 @@ For complex product implementation, skip the planner/critic sequence only when t
45
45
  Before decomposing work:
46
46
 
47
47
  - Read the approved design or requirements and the relevant repository evidence.
48
- - Describe the current state and the ideal end state.
48
+ - Describe how the user reaches the requested outcome on the normal path. Plan recovery where it lets the task finish correctly; when an operation cannot recover, report its failure and let independent operations continue.
49
49
  - Identify dependencies, interfaces, ownership boundaries, and ordering constraints.
50
50
  - Surface material risks: security, data loss, compatibility, protocols/APIs, irreversible operations, and difficult rollback.
51
51
  - Check external constraints such as budget, mandated/prohibited stack, scale, privacy, compliance, accessibility, and platform requirements. Do not invent constraints.