@dsmm/dsmm 0.3.29 → 0.3.31

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 (46) hide show
  1. package/docs/compatibility.md +4 -2
  2. package/docs/testing.md +2 -0
  3. package/docs/web-fetch-fakeip.md +2 -2
  4. package/dsh-plugin.json +1 -1
  5. package/lib/agent-prompt-scope.d.ts +3 -2
  6. package/lib/agent-prompt-scope.js +11 -16
  7. package/lib/client/children-locales.d.ts +4 -4
  8. package/lib/client/role-call-observations.js +2 -2
  9. package/lib/client.js +414 -1288
  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/permission-schema.d.ts +40 -0
  25. package/lib/permission-schema.js +13 -0
  26. package/lib/permission-settings.d.ts +0 -38
  27. package/lib/permission-settings.js +23 -18
  28. package/lib/preset-skills.d.ts +3 -2
  29. package/lib/preset-skills.js +12 -14
  30. package/lib/profile-diagnostics.js +1 -11
  31. package/lib/resident-root.d.ts +10 -0
  32. package/lib/resident-root.js +151 -0
  33. package/lib/role-identity.d.ts +2 -2
  34. package/lib/role-identity.js +1 -5
  35. package/lib/role-llm-runtime.d.ts +12 -2
  36. package/lib/role-llm-runtime.js +28 -18
  37. package/lib/role-llm.d.ts +2 -0
  38. package/lib/role-llm.js +1 -0
  39. package/lib/role-policy.d.ts +2 -0
  40. package/lib/role-policy.js +10 -10
  41. package/lib/role-routing.d.ts +1 -1
  42. package/lib/role-routing.js +4 -3
  43. package/lib/role-subagents.d.ts +2 -2
  44. package/lib/role-subagents.js +43 -63
  45. package/lib/settings.js +2 -1
  46. package/package.json +6 -51
@@ -1,4 +1,3 @@
1
- import z from "@deepseek-ai/schemastery";
2
1
  import type { PermissionRule } from "./permission-rules.js";
3
2
  export type PermissionRuleAction = "inherit" | "allow" | "ask" | "deny";
4
3
  export interface PermissionWebPolicy {
@@ -47,43 +46,6 @@ export declare function parseNativeCommandPattern(input: unknown): NativeCommand
47
46
  /** Literal token prefixes; only the second token may contain alternatives. */
48
47
  export declare function parseSimpleCommandPattern(input: unknown): readonly (readonly string[])[];
49
48
  export declare function parseNativeCommands(input?: unknown): NativeCommandsSettings;
50
- export declare const nativeCommandMatchSchema: z<Schemastery.ObjectS<NoInfer<{
51
- tool: z<"bash" | "pwsh", "bash" | "pwsh", "defined">;
52
- workingDirectory: z<string, string, "defined">;
53
- commandPattern: z<string, string, "defined">;
54
- }>>, Schemastery.ObjectT<NoInfer<{
55
- tool: z<"bash" | "pwsh", "bash" | "pwsh", "defined">;
56
- workingDirectory: z<string, string, "defined">;
57
- commandPattern: z<string, string, "defined">;
58
- }>>, "defined">;
59
- export declare const nativeCommandEntrySchema: z<Schemastery.ObjectS<NoInfer<{
60
- id: z<string, string, "defined">;
61
- mode: z<"allow" | "ask", "allow" | "ask", "defined">;
62
- match: z<Schemastery.ObjectS<NoInfer<{
63
- tool: z<"bash" | "pwsh", "bash" | "pwsh", "defined">;
64
- workingDirectory: z<string, string, "defined">;
65
- commandPattern: z<string, string, "defined">;
66
- }>>, Schemastery.ObjectT<NoInfer<{
67
- tool: z<"bash" | "pwsh", "bash" | "pwsh", "defined">;
68
- workingDirectory: z<string, string, "defined">;
69
- commandPattern: z<string, string, "defined">;
70
- }>>, "defined">;
71
- sandboxMode: z<"workspace-write" | "danger-full-access", "workspace-write" | "danger-full-access", "defined">;
72
- }>>, Schemastery.ObjectT<NoInfer<{
73
- id: z<string, string, "defined">;
74
- mode: z<"allow" | "ask", "allow" | "ask", "defined">;
75
- match: z<Schemastery.ObjectS<NoInfer<{
76
- tool: z<"bash" | "pwsh", "bash" | "pwsh", "defined">;
77
- workingDirectory: z<string, string, "defined">;
78
- commandPattern: z<string, string, "defined">;
79
- }>>, Schemastery.ObjectT<NoInfer<{
80
- tool: z<"bash" | "pwsh", "bash" | "pwsh", "defined">;
81
- workingDirectory: z<string, string, "defined">;
82
- commandPattern: z<string, string, "defined">;
83
- }>>, "defined">;
84
- sandboxMode: z<"workspace-write" | "danger-full-access", "workspace-write" | "danger-full-access", "defined">;
85
- }>>, "defined">;
86
49
  export declare const DEFAULT_PERMISSION_CONTROL: PermissionControlSettings;
87
- export declare const permissionControlSchema: z<PermissionControlSettings>;
88
50
  export declare function resolvePermissionControl(input?: PermissionControlSchemaInput): PermissionControlSettings;
89
51
  //# sourceMappingURL=permission-settings.d.ts.map
@@ -1,4 +1,3 @@
1
- import z from "@deepseek-ai/schemastery";
2
1
  import { parsePermissionRules, permissionRuleRow } from "./permission-rules.js";
3
2
  import { PermissionRefusal } from "./permission-errors.js";
4
3
  /** Bounded static prefix grammar; the optional final star always denotes the whole argv tail. */
@@ -57,25 +56,31 @@ export function parseNativeCommands(input = {}) {
57
56
  });
58
57
  return Object.freeze({ enabled: row.enabled ?? false, entries: Object.freeze(entries) });
59
58
  }
60
- export const nativeCommandMatchSchema = z.object({ tool: z.union(["bash", "pwsh"]).required(), workingDirectory: z.string().required(), commandPattern: z.string().required() }).required();
61
- export const nativeCommandEntrySchema = z.object({
62
- id: z.string().required(), mode: z.union(["ask", "allow"]).required(), match: nativeCommandMatchSchema, sandboxMode: z.union(["workspace-write", "danger-full-access"]).required(),
63
- }).required();
64
- const nativeCommands = z.object({ enabled: z.boolean().default(false), entries: z.array(z.union([z.string(), nativeCommandEntrySchema])).default([]) });
65
59
  const webDefault = Object.freeze({ enabled: true, rule: "inherit" });
66
60
  export const DEFAULT_PERMISSION_CONTROL = Object.freeze({ enabled: true, outsideReads: "inherit", webSearch: webDefault, webFetch: webDefault, rules: Object.freeze([]), nativeCommands: parseNativeCommands() });
67
- const action = () => z.union(["inherit", "allow", "ask", "deny"]).default("inherit");
68
- const web = () => z.object({ enabled: z.boolean().default(true), rule: action() }).default({});
69
- export const permissionControlSchema = z.transform(z.object({ enabled: z.boolean().default(true), outsideReads: action(), webSearch: web(), webFetch: web(),
70
- nativeCommands, rules: z.array(z.any()).default([]) }), input => Object.freeze({ ...input, webSearch: Object.freeze(input.webSearch), webFetch: Object.freeze(input.webFetch), rules: parsePermissionRules(input.rules), nativeCommands: parseNativeCommands(input.nativeCommands) }), true);
61
+ function enabled(value) {
62
+ if (value == null)
63
+ return true;
64
+ if (typeof value === "boolean")
65
+ return value;
66
+ throw new PermissionRefusal("validation");
67
+ }
68
+ function action(value) {
69
+ if (value == null)
70
+ return "inherit";
71
+ if (value === "inherit" || value === "allow" || value === "ask" || value === "deny")
72
+ return value;
73
+ throw new PermissionRefusal("validation");
74
+ }
75
+ function webPolicy(input) {
76
+ if (input === undefined)
77
+ return webDefault;
78
+ const row = permissionRuleRow(input, [], ["enabled", "rule"]);
79
+ return Object.freeze({ enabled: enabled(row.enabled), rule: action(row.rule) });
80
+ }
71
81
  export function resolvePermissionControl(input = {}) {
72
- permissionRuleRow(input, [], ["enabled", "outsideReads", "webSearch", "webFetch", "rules", "nativeCommands"]);
73
- if (Object.hasOwn(input, "nativeCommands"))
74
- parseNativeCommands(input.nativeCommands);
75
- for (const web of [input.webSearch, input.webFetch])
76
- if (web !== undefined)
77
- permissionRuleRow(web, [], ["enabled", "rule"]);
78
- const parsed = permissionControlSchema(input);
79
- return Object.freeze({ ...parsed, webSearch: Object.freeze(parsed.webSearch), webFetch: Object.freeze(parsed.webFetch), rules: parsePermissionRules(parsed.rules) });
82
+ const row = permissionRuleRow(input, [], ["enabled", "outsideReads", "webSearch", "webFetch", "rules", "nativeCommands"]);
83
+ return Object.freeze({ enabled: enabled(row.enabled), outsideReads: action(row.outsideReads), webSearch: webPolicy(row.webSearch),
84
+ webFetch: webPolicy(row.webFetch), rules: parsePermissionRules(row.rules ?? []), nativeCommands: parseNativeCommands(row.nativeCommands) });
80
85
  }
81
86
  //# sourceMappingURL=permission-settings.js.map
@@ -1,6 +1,7 @@
1
- import type { DshAgent, DshContext } from "./dsh-types.js";
1
+ import { type Context } from "@deepseek-ai/cordis";
2
+ import type { DshAgent } from "./dsh-types.js";
2
3
  import type { DsmmSettingsGetter } from "./settings.js";
3
4
  import type { DeepworkModeController } from "./state.js";
4
5
  /** 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, catalogReady?: () => boolean): void;
6
+ export declare function registerAgentSkills(ctx: Context, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, agent: DshAgent, catalogReady?: () => boolean): void;
6
7
  //# sourceMappingURL=preset-skills.d.ts.map
@@ -1,10 +1,10 @@
1
- import { getTraceable } from "@deepseek-ai/cordis";
1
+ import { symbols } from "@deepseek-ai/cordis";
2
2
  import { registerBundledSkills } from "./skills.js";
3
- import { nativeAgentContext, scopeParentOf } from "./native-scope.js";
3
+ import { agentScopeService, 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, catalogReady) {
7
- const refresh = bindings.get(agent);
6
+ export function registerAgentSkills(ctx, controller, getSettings, agent, catalogReady) {
7
+ const refresh = bindings.get(ctx);
8
8
  if (refresh) {
9
9
  refresh();
10
10
  return;
@@ -12,28 +12,26 @@ export function registerAgentSkills(ctx, controller, getSettings, agent, lifetim
12
12
  let mounted;
13
13
  const remove = () => { mounted?.provider.dispose(); mounted = undefined; };
14
14
  const reconcile = () => {
15
- const agentCtx = nativeAgentContext(agent), settings = getSettings(agent);
15
+ const settings = getSettings(agent);
16
16
  if (!settings.modules.deepwork.enabled || !controller.active(agent, settings.defaultActive)) {
17
17
  remove();
18
18
  return;
19
19
  }
20
- const presets = ctx.get?.("agentPresets");
21
- const raw = presets?.serviceFor(agent, "skills") ?? agentCtx.get("skills"), parent = scopeParentOf(agent);
22
- if (raw === undefined)
20
+ const skills = agentScopeService(ctx, "skills"), parent = scopeParentOf(agent);
21
+ if (skills === undefined)
23
22
  throw new Error("Active skills require the native skill registry");
24
- if (mounted?.parent === parent && mounted?.registry === raw) {
23
+ const realm = Reflect.get(skills, symbols.original) ?? skills;
24
+ if (mounted?.parent === parent && mounted?.realm === realm) {
25
25
  mounted.provider.invalidate();
26
26
  return;
27
27
  }
28
28
  remove();
29
- mounted = { parent, registry: raw, provider: registerBundledSkills(agentCtx, getTraceable(agentCtx, raw), { agent, controller, getSettings, catalogReady }) };
29
+ mounted = { parent, realm, provider: registerBundledSkills(ctx, skills, { agent, controller, getSettings, catalogReady }) };
30
30
  };
31
31
  const stopMode = controller.watch(changed => { if (changed === agent)
32
32
  reconcile(); });
33
- bindings.set(agent, reconcile);
34
- const dispose = () => { stopMode(); remove(); bindings.delete(agent); lifetime.removeEventListener("abort", dispose); };
35
- lifetime.addEventListener("abort", dispose, { once: true });
36
- ctx.effect?.(() => dispose);
33
+ bindings.set(ctx, reconcile);
34
+ ctx.effect(() => () => { stopMode(); remove(); bindings.delete(ctx); });
37
35
  reconcile();
38
36
  }
39
37
  //# sourceMappingURL=preset-skills.js.map
@@ -1,6 +1,5 @@
1
1
  import { findNodeAtLocation, parseTree } from "jsonc-parser";
2
2
  import { DSMM_RATE_LIMIT_BOUNDS } from "./routing-policy.js";
3
- import { permissionControlSchema } from "./permission-settings.js";
4
3
  export const PROFILE_DIAGNOSTIC_REASONS = {
5
4
  "invalid-jsonc": "Use one valid document with supported JSON syntax.",
6
5
  "duplicate-field": "Remove the duplicate field.",
@@ -15,15 +14,6 @@ export const PROFILE_DIAGNOSTIC_REASONS = {
15
14
  "blank-label": "The label is blank; the profile ID is used for display."
16
15
  };
17
16
  export const DEPRECATED_DSMM_FIELDS = ["deepseekV4ProMaxReasoningPresets", "deepseekFlashMaxReasoningPresets", "deepseekV4ProCalibration", "deepseekV4ProDefaultReasoningEffort", "deepseekFlashCalibration", "deepseekFlashDefaultReasoningEffort"];
18
- function schemaFieldShape(schema) {
19
- if (schema.type === "transform")
20
- return schemaFieldShape(schema.inner);
21
- if (schema.type === "object")
22
- return Object.fromEntries(Object.entries(schema.dict ?? {}).map(([key, child]) => [key, schemaFieldShape(child)]));
23
- if (schema.type === "array")
24
- return [schemaFieldShape(schema.inner)];
25
- return null;
26
- }
27
17
  // Closed wire grammar: dynamic role/skill names are declared identifiers, not arbitrary object keys.
28
18
  const roleId = /^dsmm-(?:orchestrator|planner|plan-critic|builder|reviewer|oracle|oracle-2nd|creative|code-search|doc-search|clarifier|media-reader|frontend|hard-reasoning|research|quick|coding|normal-task|complex|deep|documenting|cross-cutting)$/u;
29
19
  const skillId = /^(?:brainstorming|writing-plans|requesting-code-review|receiving-code-review|subagent-driven-development|dispatching-parallel-agents|avoid-ai-slop|remove-ai-slops|debugging|frontend|git-master|ast-grep|coding-agent-sessions|init-deep|using-git-worktrees|report-fidelity)$/u;
@@ -31,7 +21,7 @@ const route = { provider: null, model: null, reasoningEffort: null };
31
21
  const rateLimit = Object.fromEntries(Object.keys(DSMM_RATE_LIMIT_BOUNDS).map(key => [key, null]));
32
22
  const roleRouting = { primary: route, fallbackRoutes: [route], strategy: null, rateLimit, levels: { low: route, high: route, max: route } };
33
23
  const configFields = {
34
- permissionControl: schemaFieldShape(permissionControlSchema),
24
+ permissionControl: { enabled: null, outsideReads: null, webSearch: { enabled: null, rule: null }, webFetch: { enabled: null, rule: null }, rules: [null], nativeCommands: { enabled: null, entries: [null] } },
35
25
  modelParameters: { passthrough: null },
36
26
  rootModelPolicy: null,
37
27
  locale: null, modeName: null, section: null, defaultActive: null, promptOrder: null,
@@ -0,0 +1,10 @@
1
+ import type { Agent } from "@deepseek-ai/dsh-agent";
2
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
3
+ import type { NativeAdmission } from "./native-admission.js";
4
+ export declare function assertResidentRootCurrent(agent: Agent, owner: NativeAdmission | undefined): void;
5
+ export declare function markResidentAgent(agent: Agent, owner: NativeAdmission, root: boolean): void;
6
+ export declare function captureResidentTool(agent: Agent, owner: NativeAdmission, token: ToolExecution["token"]): void;
7
+ export declare function guardResidentRealm(agent: Agent): void;
8
+ export declare function publishResidentAgent(agent: Agent, owner: NativeAdmission): void;
9
+ export declare function restoreResidentRoot(agent: Agent, owner: NativeAdmission, install: (signal: AbortSignal) => Promise<void>): Promise<void> | undefined;
10
+ //# sourceMappingURL=resident-root.d.ts.map
@@ -0,0 +1,151 @@
1
+ import { getTraceable, symbols } from "@deepseek-ai/cordis";
2
+ import { SubagentError } from "@deepseek-ai/dsh-subagent";
3
+ import { scopeLifetime } from "./lifetime.js";
4
+ import { scopeOf, scopeParentOf } from "./native-scope.js";
5
+ // Reloaded ESM graphs share only exact resident objects, never session-id authority.
6
+ const key = Symbol.for("@dsmm/dsmm/resident-roots");
7
+ const records = Reflect.get(globalThis, key) ?? new WeakMap();
8
+ if (!Reflect.has(globalThis, key))
9
+ Object.defineProperty(globalThis, key, { value: records });
10
+ const original = (value) => value && (Reflect.get(value, symbols.original) ?? value);
11
+ const deny = () => { throw new SubagentError("Resident root has no current DSMM admission", "UNAUTHORIZED"); };
12
+ function current(record) {
13
+ if (record.version !== 1 || !record.active || !record.owner?.isReady)
14
+ return deny();
15
+ return record.owner;
16
+ }
17
+ export function assertResidentRootCurrent(agent, owner) {
18
+ const record = records.get(agent);
19
+ if (record && original(current(record)) !== original(owner))
20
+ deny();
21
+ }
22
+ function claim(record, owner) {
23
+ record.owner = owner;
24
+ const revoke = () => {
25
+ if (record.owner !== owner)
26
+ return;
27
+ record.active = false;
28
+ record.owner = undefined;
29
+ record.afterDrain = undefined;
30
+ record.detachOwner = undefined;
31
+ };
32
+ owner.lifetime.signal.addEventListener("abort", revoke, { once: true });
33
+ record.detachOwner = () => owner.lifetime.signal.removeEventListener("abort", revoke);
34
+ }
35
+ export function markResidentAgent(agent, owner, root) {
36
+ if (records.has(agent))
37
+ deny();
38
+ const deployment = owner.ctx.get("dsmmDeploymentConfig");
39
+ const record = { version: 1, root, registry: original(owner.ctx.agents), sessions: original(owner.ctx.get("sessions")),
40
+ deploymentKey: deployment?.hostProfileKey, home: deployment?.home,
41
+ session: agent.session, presets: original(agent.ctx.get("agentPresets")), profile: original(owner.ctx.get("profileContext")),
42
+ active: false, published: false, disposed: false,
43
+ tools: new WeakSet(), tokens: new Set() };
44
+ records.set(agent, record);
45
+ scopeLifetime(agent.ctx, "dsmm: revoke resident root", () => {
46
+ record.detachOwner?.();
47
+ record.detachOwner = undefined;
48
+ record.active = false;
49
+ record.disposed = true;
50
+ record.owner = undefined;
51
+ record.afterDrain = undefined;
52
+ });
53
+ agent.ctx.on("agent/pre-step", async (frame, next) => { if (frame.agent === agent)
54
+ await current(record).ensure(agent); return next(); }, { prepend: true });
55
+ agent.ctx.on("agent/request", async (frame, next) => { if (frame.agent === agent)
56
+ await current(record).ensure(agent); return next(); }, { prepend: true });
57
+ agent.ctx.on("tools/pre-execute", async (exec, next) => {
58
+ if (exec.agent === agent) {
59
+ const owner = current(record);
60
+ record.tokens.add(exec.token);
61
+ await owner.ensure(agent);
62
+ }
63
+ return next();
64
+ }, { prepend: true });
65
+ agent.ctx.on("tools/execute", async (exec, next) => {
66
+ if (exec.agent === agent) {
67
+ current(record).assert(agent);
68
+ if (!record.tokens.has(exec.token))
69
+ deny();
70
+ }
71
+ return next();
72
+ }, { prepend: true });
73
+ agent.ctx.on("tools/result", exec => {
74
+ if (exec.agent === agent && record.tokens.delete(exec.token) && !record.tokens.size)
75
+ record.afterDrain?.();
76
+ });
77
+ claim(record, owner);
78
+ guardResidentRealm(agent);
79
+ }
80
+ export function captureResidentTool(agent, owner, token) {
81
+ const record = records.get(agent);
82
+ if (!record)
83
+ return;
84
+ assertResidentRootCurrent(agent, owner);
85
+ record.tokens.add(token);
86
+ }
87
+ export function guardResidentRealm(agent) {
88
+ const record = records.get(agent);
89
+ const tools = agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools");
90
+ if (!record || !tools)
91
+ return;
92
+ const realm = original(tools);
93
+ if (record.tools.has(realm))
94
+ return;
95
+ getTraceable(agent.ctx, tools).guard(exec => {
96
+ if (exec.agent !== agent)
97
+ return;
98
+ current(record).assert(agent);
99
+ if (!record.tokens.has(exec.token) || realm !== original(agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools")))
100
+ deny();
101
+ });
102
+ record.tools.add(realm);
103
+ }
104
+ export function publishResidentAgent(agent, owner) {
105
+ const record = records.get(agent);
106
+ if (record.disposed || original(record.owner) !== original(owner) || !owner.isReady)
107
+ deny();
108
+ record.scopeParent = scopeParentOf(agent);
109
+ record.preset = agent.ctx.get("agentPresets")?.composedPreset(agent.ctx);
110
+ record.published = record.active = true;
111
+ }
112
+ export function restoreResidentRoot(agent, owner, install) {
113
+ const record = records.get(agent);
114
+ if (!record || record.version !== 1 || !record.root || record.disposed || !record.published || record.owner)
115
+ return;
116
+ const valid = () => record.profile === original(owner.ctx.get("profileContext")) && record.registry === original(owner.ctx.agents) && record.registry === original(agent.ctx.get("agents"))
117
+ && record.deploymentKey === owner.ctx.get("dsmmDeploymentConfig")?.hostProfileKey && record.home === owner.ctx.get("dsmmDeploymentConfig")?.home
118
+ && record.sessions === original(owner.ctx.get("sessions")) && record.session === agent.session && owner.ctx.get("sessions")?.get(agent.id) === record.session
119
+ && record.presets === original(agent.ctx.get("agentPresets")) && record.preset === agent.ctx.get("agentPresets")?.composedPreset(agent.ctx)
120
+ && record.scopeParent === scopeParentOf(agent) && scopeOf(agent.ctx) === agent && owner.ctx.agents.get(agent.id) === agent;
121
+ if (!valid())
122
+ deny();
123
+ claim(record, owner);
124
+ const admit = (signal) => {
125
+ if (record.owner !== owner || !owner.isReady || !valid())
126
+ deny();
127
+ return install(signal);
128
+ };
129
+ const report = (error) => { if (!owner.lifetime.signal.aborted)
130
+ owner.ctx.logger.warn("Resident root %s remains revoked: %s", agent.id, error); };
131
+ const start = () => {
132
+ record.afterDrain = undefined;
133
+ if (record.disposed || record.owner !== owner)
134
+ return;
135
+ // Ordinary tool calls can outlive both the turn and the retiring plugin.
136
+ // A busy Agent/maintenance task also has to converge before taking its place.
137
+ try {
138
+ return agent.runMaintenance(admit);
139
+ }
140
+ catch {
141
+ void agent.whenIdle().then(() => {
142
+ if (!record.disposed && record.owner === owner)
143
+ return agent.runMaintenance(admit);
144
+ }).catch(report);
145
+ }
146
+ };
147
+ if (!record.tokens.size)
148
+ return start();
149
+ record.afterDrain = () => { void start()?.catch(report); };
150
+ }
151
+ //# sourceMappingURL=resident-root.js.map
@@ -1,5 +1,5 @@
1
- import type { DshAgent } from "./dsh-types.js";
1
+ import type { SystemPrompt } from "@deepseek-ai/dsh-system-prompt";
2
2
  import type { DsmmRoleId } from "./roles.js";
3
3
  /** The caller supplies the policy-admitted identity; only its Agent layer is changed. */
4
- export declare function registerRoleHarnessIdentity(agent: DshAgent, role: DsmmRoleId, child?: boolean): () => void;
4
+ export declare function registerRoleHarnessIdentity(prompt: SystemPrompt, role: DsmmRoleId, child?: boolean): () => void;
5
5
  //# sourceMappingURL=role-identity.d.ts.map
@@ -1,11 +1,7 @@
1
- import { getTraceable } from "@deepseek-ai/cordis";
2
- import { nativeAgentContext } from "./native-scope.js";
3
1
  import { buildRoleIdentity } from "./prompt-content.js";
4
2
  import { DSMM_ROLES } from "./roles.js";
5
3
  /** The caller supplies the policy-admitted identity; only its Agent layer is changed. */
6
- export function registerRoleHarnessIdentity(agent, role, child = false) {
7
- const ctx = nativeAgentContext(agent);
8
- const prompt = getTraceable(ctx, ctx.get("agentPresets")?.serviceFor({ ctx }, "systemPrompt") ?? ctx.get("systemPrompt"));
4
+ export function registerRoleHarnessIdentity(prompt, role, child = false) {
9
5
  const definition = DSMM_ROLES.find(row => row.id === role);
10
6
  const identity = prompt.section({ name: "harness:identity", order: prompt.getSectionOrder("HARNESS_IDENTITY"),
11
7
  text: buildRoleIdentity(definition) });
@@ -1,10 +1,19 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
- import type { DsmmLlmHostOwner, DsmmLlmAdmission, DsmmLlmRequestFrame, DsmmLlmCallConfig } from "./host-llm.js";
2
+ import type { DsmmEffortSource, DsmmLlmHostOwner, DsmmLlmAdmission, DsmmLlmRequestFrame, DsmmLlmCallConfig } from "./host-llm.js";
3
3
  import type { DsmmPiAiProviderOwner } from "./native-pi-ai-wire.js";
4
+ interface CoreLlmAdmission extends DsmmLlmAdmission {
5
+ prepare(proposal: DsmmLlmCallConfig): Promise<{
6
+ admission: DsmmLlmAdmission;
7
+ config: DsmmLlmCallConfig;
8
+ effortSource: DsmmEffortSource;
9
+ }>;
10
+ }
4
11
  export interface DsmmCoreLlmOwner {
5
12
  /** Undefined is only the physically owned ordinary-native child path. */
6
- admit(frame: DsmmLlmRequestFrame): Promise<DsmmLlmAdmission | undefined>;
13
+ admit(frame: DsmmLlmRequestFrame): Promise<CoreLlmAdmission | undefined>;
7
14
  }
15
+ /** Request preparations, route locks and invocation effort belong to the admitting Core's module instance. */
16
+ export declare function bindCoreLlmAdmission(frame: DsmmLlmRequestFrame, admission: DsmmLlmAdmission): CoreLlmAdmission;
8
17
  declare module "@deepseek-ai/cordis" {
9
18
  interface Context {
10
19
  dsmmCoreLlmOwner: DsmmCoreLlmOwner;
@@ -14,4 +23,5 @@ declare module "@deepseek-ai/cordis" {
14
23
  export declare function createDsmmRoleLlmOwner(ctx: Context, providers: Pick<DsmmPiAiProviderOwner, "generation"> & {
15
24
  requiresRaw?(config: DsmmLlmCallConfig): boolean;
16
25
  }): DsmmLlmHostOwner;
26
+ export {};
17
27
  //# sourceMappingURL=role-llm-runtime.d.ts.map
@@ -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
  }