@dsmm/dsmm 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.md +26 -42
  2. package/cordis.patch.yml +1 -0
  3. package/docs/agent-presets.md +26 -14
  4. package/docs/compatibility.md +20 -79
  5. package/docs/deferred-native-approval-risk.md +8 -12
  6. package/docs/design.md +25 -254
  7. package/docs/lsp.md +2 -2
  8. package/docs/migration-from-ocmm.md +38 -51
  9. package/docs/model-routing.md +21 -21
  10. package/docs/native-permissions.md +17 -7
  11. package/docs/profiles.md +13 -9
  12. package/docs/releasing.md +34 -240
  13. package/docs/roadmap.md +23 -254
  14. package/docs/runtime-recovery.md +29 -91
  15. package/docs/safety-guards.md +19 -16
  16. package/docs/settings-status.md +23 -11
  17. package/docs/skill-sync.md +17 -17
  18. package/docs/web-fetch-fakeip.md +82 -0
  19. package/lib/child-capture.d.ts +16 -2
  20. package/lib/child-capture.js +29 -10
  21. package/lib/client/ChildrenPanel.d.ts +1 -4
  22. package/lib/client/ChildrenPanel.js +4 -16
  23. package/lib/client/DeploymentFields.d.ts +28 -0
  24. package/lib/client/DeploymentFields.js +68 -0
  25. package/lib/client/DeploymentPage.d.ts +17 -5
  26. package/lib/client/DeploymentPage.js +79 -112
  27. package/lib/client/NativeCommandEntries.d.ts +17 -0
  28. package/lib/client/NativeCommandEntries.js +68 -0
  29. package/lib/client/PermissionsPanel.d.ts +1 -1
  30. package/lib/client/PermissionsPanel.js +8 -8
  31. package/lib/client/ProfilesSection.js +7 -5
  32. package/lib/client/RoleToolView-data.d.ts +35 -0
  33. package/lib/client/RoleToolView-data.js +52 -0
  34. package/lib/client/RoleToolView-locales.d.ts +36 -0
  35. package/lib/client/RoleToolView-locales.js +20 -0
  36. package/lib/client/RoleToolView.d.ts +10 -0
  37. package/lib/client/RoleToolView.js +47 -0
  38. package/lib/client/SessionProfiles.js +39 -15
  39. package/lib/client/children-controller.d.ts +2 -8
  40. package/lib/client/children-controller.js +1 -26
  41. package/lib/client/children-locales.d.ts +26 -51
  42. package/lib/client/children-locales.js +8 -12
  43. package/lib/client/configuration-display.d.ts +5 -0
  44. package/lib/client/configuration-display.js +11 -0
  45. package/lib/client/controller.d.ts +1 -0
  46. package/lib/client/controller.js +20 -13
  47. package/lib/client/deployment-controller.d.ts +13 -1
  48. package/lib/client/deployment-controller.js +85 -25
  49. package/lib/client/deployment-data.d.ts +1 -0
  50. package/lib/client/deployment-data.js +4 -1
  51. package/lib/client/deployment-locales.d.ts +43 -0
  52. package/lib/client/deployment-locales.js +35 -9
  53. package/lib/client/deployment-modules.d.ts +9 -0
  54. package/lib/client/deployment-modules.js +24 -0
  55. package/lib/client/deployment-workspace.d.ts +48 -0
  56. package/lib/client/deployment-workspace.js +123 -0
  57. package/lib/client/index.js +11 -74
  58. package/lib/client/locales.d.ts +7 -0
  59. package/lib/client/locales.js +12 -6
  60. package/lib/client/permission-controller.d.ts +1 -0
  61. package/lib/client/permission-controller.js +3 -2
  62. package/lib/client/permission-locales.d.ts +25 -0
  63. package/lib/client/permission-locales.js +24 -4
  64. package/lib/client/session-labels.js +4 -3
  65. package/lib/client/styles.d.ts +1 -1
  66. package/lib/client/styles.js +9 -8
  67. package/lib/client.js +2716 -2364
  68. package/lib/commands.js +2 -0
  69. package/lib/config-file-store.d.ts +3 -0
  70. package/lib/config-file-store.js +4 -2
  71. package/lib/config-revision.d.ts +5 -0
  72. package/lib/config-revision.js +11 -0
  73. package/lib/core-permission-authority.js +11 -41
  74. package/lib/deployment-config.d.ts +9 -2
  75. package/lib/deployment-config.js +35 -8
  76. package/lib/deployment-permission-rules.js +19 -7
  77. package/lib/dsh-types.d.ts +1 -1
  78. package/lib/host-llm-startup.js +3 -3
  79. package/lib/host-llm.d.ts +9 -3
  80. package/lib/host-llm.js +48 -8
  81. package/lib/index.d.ts +17 -21
  82. package/lib/index.js +131 -430
  83. package/lib/lifetime.d.ts +4 -0
  84. package/lib/lifetime.js +22 -0
  85. package/lib/live-pi-ai-owner.d.ts +1 -0
  86. package/lib/live-pi-ai-owner.js +8 -4
  87. package/lib/mode.d.ts +3 -2
  88. package/lib/mode.js +28 -41
  89. package/lib/model-routing.d.ts +2 -8
  90. package/lib/model-routing.js +59 -175
  91. package/lib/native-admission.d.ts +56 -0
  92. package/lib/native-admission.js +313 -0
  93. package/lib/native-pi-ai-wire.d.ts +3 -1
  94. package/lib/native-pi-ai-wire.js +47 -13
  95. package/lib/permission-control.d.ts +0 -3
  96. package/lib/permission-rpc.js +3 -3
  97. package/lib/preset-registry.js +3 -2
  98. package/lib/preset-skills.d.ts +3 -12
  99. package/lib/preset-skills.js +28 -58
  100. package/lib/profile-diagnostics.d.ts +1 -1
  101. package/lib/profile-diagnostics.js +2 -2
  102. package/lib/profile-remote.js +61 -22
  103. package/lib/profile-rpc.d.ts +4 -3
  104. package/lib/profile-rpc.js +39 -41
  105. package/lib/profile-runtime.d.ts +31 -74
  106. package/lib/profile-runtime.js +224 -639
  107. package/lib/profile-store.d.ts +18 -6
  108. package/lib/profile-store.js +106 -64
  109. package/lib/profile-types.d.ts +18 -4
  110. package/lib/profiles.d.ts +3 -1
  111. package/lib/profiles.js +9 -7
  112. package/lib/prompt-content.d.ts +1 -0
  113. package/lib/prompt-content.js +4 -1
  114. package/lib/prompts.d.ts +2 -12
  115. package/lib/prompts.js +11 -66
  116. package/lib/role-control-remote.d.ts +1 -4
  117. package/lib/role-control-remote.js +8 -36
  118. package/lib/role-control-rpc.d.ts +10 -36
  119. package/lib/role-control-rpc.js +112 -265
  120. package/lib/role-control-types.d.ts +3 -26
  121. package/lib/role-control-types.js +3 -4
  122. package/lib/role-identity.d.ts +5 -0
  123. package/lib/role-identity.js +10 -0
  124. package/lib/role-invocation.d.ts +2 -2
  125. package/lib/role-llm-runtime.js +5 -11
  126. package/lib/role-policy.d.ts +19 -53
  127. package/lib/role-policy.js +136 -525
  128. package/lib/role-providers.d.ts +5 -8
  129. package/lib/role-providers.js +20 -126
  130. package/lib/role-routing.d.ts +1 -3
  131. package/lib/role-routing.js +24 -34
  132. package/lib/role-subagents.d.ts +5 -14
  133. package/lib/role-subagents.js +149 -97
  134. package/lib/runtime-integration.d.ts +5 -109
  135. package/lib/runtime-integration.js +11 -779
  136. package/lib/session-metadata.d.ts +13 -12
  137. package/lib/session-metadata.js +6 -31
  138. package/lib/session-scope.js +6 -2
  139. package/lib/settings.d.ts +5 -18
  140. package/lib/settings.js +19 -43
  141. package/lib/state.d.ts +3 -2
  142. package/lib/state.js +26 -10
  143. package/lib/status.d.ts +1 -9
  144. package/lib/status.js +3 -55
  145. package/lib/web-fetch-address-policy.d.ts +24 -0
  146. package/lib/web-fetch-address-policy.js +189 -0
  147. package/lib/web-fetch-fakeip.d.ts +25 -0
  148. package/lib/web-fetch-fakeip.js +107 -0
  149. package/package.json +133 -113
  150. package/docs/research/deepseek-v4-pro.md +0 -74
  151. package/docs/research/oh-dsh.md +0 -96
  152. package/lib/child-admission.d.ts +0 -42
  153. package/lib/child-admission.js +0 -162
  154. package/lib/delivery-authority.d.ts +0 -68
  155. package/lib/delivery-authority.js +0 -260
  156. package/lib/legacy-child-policy.d.ts +0 -51
  157. package/lib/legacy-child-policy.js +0 -123
  158. package/lib/legacy-read-composition.d.ts +0 -20
  159. package/lib/legacy-read-composition.js +0 -144
  160. package/lib/legacy-read-contracts.d.ts +0 -157
  161. package/lib/legacy-read-contracts.js +0 -39
  162. package/lib/legacy-read-host.d.ts +0 -19
  163. package/lib/legacy-read-host.js +0 -67
  164. package/lib/legacy-read-integration.d.ts +0 -121
  165. package/lib/legacy-read-integration.js +0 -522
  166. package/lib/legacy-read-proxy.d.ts +0 -26
  167. package/lib/legacy-read-proxy.js +0 -237
  168. package/lib/native-child-evidence.d.ts +0 -42
  169. package/lib/native-child-evidence.js +0 -133
  170. package/lib/role-runs.d.ts +0 -135
  171. package/lib/role-runs.js +0 -304
  172. package/lib/session-persistence.d.ts +0 -35
  173. package/lib/session-persistence.js +0 -304
  174. package/lib/subagent-runtime.d.ts +0 -45
  175. package/lib/subagent-runtime.js +0 -131
  176. package/prompts/deepseek-flash.md +0 -11
  177. package/prompts/deepseek-v4-pro.md +0 -14
  178. package/scripts/cold-profile-composition.mjs +0 -329
  179. package/scripts/cold-profile-sources.mjs +0 -238
  180. package/scripts/migrate-cold-profile.mjs +0 -315
  181. package/scripts/repair-session-log.mjs +0 -476
  182. package/scripts/session-repair-native-verifier.mjs +0 -367
@@ -0,0 +1,313 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { getTraceable, symbols } from "@deepseek-ai/cordis";
3
+ import { SessionId } from "@deepseek-ai/dsh-session";
4
+ import { SubagentError, delegationDepthOf } from "@deepseek-ai/dsh-subagent";
5
+ import { freezeSettings } from "./settings.js";
6
+ import { scopeLifetime } from "./lifetime.js";
7
+ import { sessionEvents } from "./session-scope.js";
8
+ import { scopeParentOf } from "./native-scope.js";
9
+ /** Short-lived creation correlations and exact live bindings, never an execution queue. */
10
+ export class NativeAdmission {
11
+ ctx;
12
+ profiles;
13
+ policy;
14
+ lifetime = new AbortController();
15
+ pending = new Map();
16
+ live = new WeakMap();
17
+ candidates = new WeakMap();
18
+ agents = new Set();
19
+ activations = new Set();
20
+ activities = new Map();
21
+ calls = new Map();
22
+ rebindings = new WeakMap();
23
+ guardedTools = new WeakMap();
24
+ agentLifetimes = new WeakMap();
25
+ retirements = new WeakMap();
26
+ ready = false;
27
+ install;
28
+ constructor(ctx, profiles, policy) {
29
+ this.ctx = ctx;
30
+ this.profiles = profiles;
31
+ this.policy = policy;
32
+ scopeLifetime(ctx, "dsmm: close admission before owner teardown", () => {
33
+ this.lifetime.abort();
34
+ this.pending.clear();
35
+ for (const agent of this.agents)
36
+ agent.cancel({ kind: "disposed" });
37
+ });
38
+ ctx.effect(() => async () => {
39
+ const results = await Promise.allSettled([...this.activations].map(activation => activation.dispose()));
40
+ await Promise.allSettled(this.activities.keys());
41
+ const errors = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
42
+ if (errors.length)
43
+ throw new AggregateError(errors, "Native activation teardown failed");
44
+ });
45
+ ctx.on("agent/created", async (frame) => { await this.created(frame.agent, frame.source, frame.signal); }, { global: true, prepend: true });
46
+ ctx.on("agent/disposed", ({ agent }) => {
47
+ void this.retireAgent(agent).catch(() => { });
48
+ this.live.delete(agent);
49
+ this.candidates.delete(agent);
50
+ this.agents.delete(agent);
51
+ for (const activation of this.activations)
52
+ if (activation.childId === agent.id)
53
+ this.activations.delete(activation);
54
+ profiles.release(agent);
55
+ policy.release(agent);
56
+ }, { global: true });
57
+ // Unbound retained Agents are not enrolled by listing. These guards also cover startup failures.
58
+ ctx.on("agent/pre-step", async (frame, next) => { await this.ensure(frame.agent); return next(); }, { global: true, prepend: true });
59
+ ctx.on("agent/request", async (frame, next) => { await this.ensure(frame.agent); return next(); }, { global: true, prepend: true });
60
+ ctx.on("tools/execute", async (exec, next) => { if (exec.agent)
61
+ await this.ensure(exec.agent); return policy.duringToolExecution(exec, next); }, { global: true, prepend: true });
62
+ ctx.on("agent-preset/selected", id => {
63
+ const agent = ctx.agents.get(id);
64
+ if (!agent || !this.live.has(agent))
65
+ return;
66
+ const binding = this.rebindBlank(agent);
67
+ this.rebindings.set(agent, binding);
68
+ void binding.catch(() => { });
69
+ }, { global: true });
70
+ }
71
+ activate(install) { this.lifetime.signal.throwIfAborted(); this.install = install; this.ready = true; }
72
+ get isReady() { return this.ready && !this.lifetime.signal.aborted; }
73
+ 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; }
76
+ invocation(agent) { return this.live.get(agent)?.invocation; }
77
+ async ensure(agent) { await this.rebindings.get(agent); return this.assert(agent); }
78
+ assert(agent) {
79
+ this.lifetime.signal.throwIfAborted();
80
+ this.agentLifetimes.get(agent)?.signal.throwIfAborted();
81
+ const live = this.live.get(agent);
82
+ if (!this.ready || !live || this.ctx.agents.get(agent.id) !== agent)
83
+ throw new SubagentError("No trusted live admission; create a new session", "UNAUTHORIZED");
84
+ if (live.preset !== agent.ctx.get("agentPresets")?.composedPreset(agent.ctx) || live.scopeParent !== scopeParentOf(agent))
85
+ throw new SubagentError("Preset composition changed; create a new session", "UNAUTHORIZED");
86
+ if (live.parent && (this.ctx.agents.get(live.parent.id) !== live.parent || !this.ctx.agents.isOwnedBy(agent.id, live.parent)))
87
+ throw new SubagentError("Parent residency changed", "UNAUTHORIZED");
88
+ if (live.parent)
89
+ this.agentLifetimes.get(live.parent)?.signal.throwIfAborted();
90
+ this.policy.assertModuleAdmission(agent);
91
+ return live.admission;
92
+ }
93
+ async reserve(exec, invocation, provider, maxDepth) {
94
+ const parent = exec.agent;
95
+ if (!parent)
96
+ throw new SubagentError("Calling Agent required", "UNAUTHORIZED");
97
+ const parentAdmission = this.assert(parent);
98
+ this.policy.assertDelegation(parent, invocation.target);
99
+ const toolFilter = this.policy.delegationToolFilter(exec);
100
+ const presets = this.ctx.get("agentPresets");
101
+ if (!presets)
102
+ throw new SubagentError("Native preset registry unavailable", "UNSUPPORTED_CAPABILITY");
103
+ const lease = await presets.acquireScope(invocation.target);
104
+ try {
105
+ exec.signal.throwIfAborted();
106
+ this.assert(parent);
107
+ const currentProvider = this.ctx.get("subagents")?.getProvider(provider.name);
108
+ if (!currentProvider || original(currentProvider) !== original(provider) || this.get(parent) !== parentAdmission)
109
+ throw new SubagentError("Creation dependencies changed", "UNAUTHORIZED");
110
+ const childId = SessionId(randomUUID()), signal = AbortSignal.any([exec.signal, this.lifetime.signal, this.agentLifetimes.get(parent).signal]);
111
+ 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 });
113
+ this.pending.set(childId, pending);
114
+ const revoke = () => { if (this.pending.get(childId) === pending)
115
+ this.pending.delete(childId); };
116
+ signal.addEventListener("abort", revoke, { once: true });
117
+ return { childId, signal, release: async () => { revoke(); signal.removeEventListener("abort", revoke); await lease[Symbol.asyncDispose](); } };
118
+ }
119
+ catch (error) {
120
+ await lease[Symbol.asyncDispose]();
121
+ throw error;
122
+ }
123
+ }
124
+ async duringCall(agent, signal, operation) {
125
+ this.assert(agent);
126
+ const merged = AbortSignal.any([signal, this.lifetime.signal, this.agentLifetimes.get(agent).signal]);
127
+ const task = Promise.resolve().then(() => operation(merged));
128
+ this.calls.set(agent, (this.calls.get(agent) ?? 0) + 1);
129
+ this.activities.set(task, agent);
130
+ try {
131
+ return await task;
132
+ }
133
+ finally {
134
+ this.activities.delete(task);
135
+ const remaining = this.calls.get(agent) - 1;
136
+ if (remaining)
137
+ this.calls.set(agent, remaining);
138
+ else
139
+ this.calls.delete(agent);
140
+ }
141
+ }
142
+ prepare(request, provider) {
143
+ const pending = this.pending.get(request.sessionId);
144
+ if (!pending || pending.parent !== request.parent || original(pending.provider) !== original(provider))
145
+ throw new SubagentError("Role creation requires its exact pending call", "UNAUTHORIZED");
146
+ this.check(pending);
147
+ request.signal.throwIfAborted();
148
+ }
149
+ check(pending) {
150
+ pending.signal.throwIfAborted();
151
+ this.lifetime.signal.throwIfAborted();
152
+ const provider = this.ctx.get("subagents")?.getProvider(pending.provider.name);
153
+ if (this.pending.get(pending.childId) !== pending || this.assert(pending.parent) !== pending.parentAdmission || provider === undefined || original(provider) !== original(pending.provider))
154
+ throw new SubagentError("Pending call lost its owner", "UNAUTHORIZED");
155
+ }
156
+ track(activation) {
157
+ this.activations.add(activation);
158
+ void activation.result.finally(() => { if (!this.ctx.agents.get(activation.childId))
159
+ this.activations.delete(activation); }).catch(() => { });
160
+ if (this.lifetime.signal.aborted)
161
+ void activation.dispose().catch(error => this.ctx.logger.error(error));
162
+ }
163
+ guardTools(agent) {
164
+ const tools = agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools");
165
+ if (!tools)
166
+ return;
167
+ const identity = original(tools), installed = this.guardedTools.get(agent) ?? new Set();
168
+ if (installed.has(identity))
169
+ return;
170
+ installed.add(identity);
171
+ this.guardedTools.set(agent, installed);
172
+ getTraceable(agent.ctx, tools).guard(exec => {
173
+ if (exec.agent !== agent)
174
+ return;
175
+ this.assert(agent);
176
+ const current = agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools");
177
+ if (!current || original(current) !== identity)
178
+ return "The tool realm is no longer the admitted composition";
179
+ this.policy.assertToolExecution(exec);
180
+ return this.policy.preToolDenial(agent, exec.name, undefined, exec);
181
+ });
182
+ }
183
+ retireAgent(agent) {
184
+ const existing = this.retirements.get(agent);
185
+ if (existing)
186
+ return existing;
187
+ this.agentLifetimes.get(agent)?.abort();
188
+ const children = new Set([...this.agents].filter(child => this.live.get(child)?.parent === agent));
189
+ for (const child of children)
190
+ child.cancel({ kind: "disposed" });
191
+ const receipts = [...this.activations].filter(activation => [...children].some(child => child.id === activation.childId));
192
+ const retirement = Promise.allSettled(receipts.map(activation => activation.dispose())).then(results => {
193
+ const errors = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
194
+ if (errors.length)
195
+ throw new AggregateError(errors, "Native descendants failed to retire");
196
+ });
197
+ const settled = retirement.then(async () => { await Promise.allSettled([...this.activities].filter(([, actor]) => actor === agent).map(([activity]) => activity)); });
198
+ this.retirements.set(agent, settled);
199
+ return settled;
200
+ }
201
+ async rebindBlank(agent) {
202
+ const previous = this.live.get(agent);
203
+ this.lifetime.signal.throwIfAborted();
204
+ if (previous.preset === agent.ctx.get("agentPresets")?.composedPreset(agent.ctx) && previous.scopeParent === scopeParentOf(agent))
205
+ return;
206
+ if (previous.parent || (this.calls.get(agent) ?? 0) !== 0 || [...this.pending.values()].some(row => row.parent === agent)
207
+ || this.ctx.agents.list().some(child => this.ctx.agents.isOwnedBy(child.id, agent)) || sessionEvents(agent.session).some(event => event.type === "turn/start"))
208
+ throw new SubagentError("Preset change requires a new session", "UNAUTHORIZED");
209
+ this.policy.validateRootRole(agent, previous.admission);
210
+ const preset = agent.ctx.get("agentPresets")?.composedPreset(agent.ctx), scopeParent = scopeParentOf(agent);
211
+ const getter = () => previous.admission.settings;
212
+ getter.admission = () => previous.admission;
213
+ this.guardTools(agent);
214
+ await this.install(agent, getter);
215
+ this.lifetime.signal.throwIfAborted();
216
+ this.agentLifetimes.get(agent).signal.throwIfAborted();
217
+ if (this.ctx.agents.get(agent.id) !== agent || this.live.get(agent) !== previous || scopeParentOf(agent) !== scopeParent)
218
+ throw new SubagentError("Composition changed during blank admission", "UNAUTHORIZED");
219
+ this.live.set(agent, Object.freeze({ ...previous, preset, scopeParent }));
220
+ }
221
+ async created(agent, source, creationSignal) {
222
+ if (this.live.has(agent)) {
223
+ this.assert(agent);
224
+ return;
225
+ }
226
+ if (!this.ready || !this.install)
227
+ throw new SubagentError("DSMM admission is initializing", "UNAUTHORIZED");
228
+ const signal = AbortSignal.any([...creationSignal ? [creationSignal] : [], this.lifetime.signal]);
229
+ signal.throwIfAborted();
230
+ const parents = this.ctx.agents.list().filter(parent => parent !== agent && this.ctx.agents.isOwnedBy(agent.id, parent));
231
+ const parent = parents[0], preset = agent.ctx.get("agentPresets")?.composedPreset(agent.ctx), presetScope = scopeParentOf(agent), pending = this.pending.get(agent.id);
232
+ if (parents.length > 1 || this.ctx.agents.get(agent.id) !== agent)
233
+ throw new SubagentError("Invalid native ownership", "UNAUTHORIZED");
234
+ let admission;
235
+ if (parent) {
236
+ const parentAdmission = this.assert(parent), controlled = this.policy.identity(parent).role !== undefined;
237
+ if (agent.session.header.parentSession !== parent.id || agent.session.header.origin !== "subagent")
238
+ throw new SubagentError("Invalid native child header", "UNAUTHORIZED");
239
+ if (pending) {
240
+ this.check(pending);
241
+ if (pending.parent !== parent || pending.parentAdmission !== parentAdmission || preset !== pending.invocation.target || agent.session.header.isSeeded
242
+ || scopeParentOf(agent) !== pending.presetScope)
243
+ throw new SubagentError("Child does not match the pending invocation", "UNAUTHORIZED");
244
+ if (pending.maxDepth !== undefined && delegationDepthOf(agent) > pending.maxDepth)
245
+ throw new SubagentError("Child exceeds depth ceiling", "UNAUTHORIZED");
246
+ admission = pending.admission;
247
+ }
248
+ else {
249
+ if (controlled || preset?.startsWith("dsmm-"))
250
+ throw new SubagentError("Use an admitted DSMM role tool; cold recovery is unavailable", "UNAUTHORIZED");
251
+ admission = parentAdmission;
252
+ }
253
+ }
254
+ else {
255
+ if (agent.session.header.origin === "subagent" || pending)
256
+ 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");
260
+ admission = await this.profiles.prepareRoot(agent, signal);
261
+ 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
+ }
265
+ this.agentLifetimes.set(agent, new AbortController());
266
+ scopeLifetime(agent.ctx, "dsmm: retire exact Agent work", () => { void this.retireAgent(agent).catch(() => { }); });
267
+ agent.ctx.effect(() => () => this.retireAgent(agent));
268
+ this.candidates.set(agent, admission);
269
+ this.agents.add(agent);
270
+ // These registrations belong to the Agent, not the plugin owner. Revocation remains effective after unload.
271
+ agent.ctx.on("agent/pre-step", async (frame, next) => { if (frame.agent === agent)
272
+ await this.ensure(agent); return next(); }, { prepend: true });
273
+ agent.ctx.on("agent/request", async (frame, next) => { if (frame.agent === agent)
274
+ await this.ensure(agent); return next(); }, { prepend: true });
275
+ agent.ctx.on("tools/pre-execute", async (exec, next) => { if (exec.agent === agent) {
276
+ await this.ensure(agent);
277
+ const denial = this.policy.preToolDenial(agent, exec.name, undefined, exec);
278
+ if (denial)
279
+ return { kind: "deny", reason: denial };
280
+ } return next(); }, { prepend: true });
281
+ this.guardTools(agent);
282
+ try {
283
+ if (pending)
284
+ 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);
288
+ signal.throwIfAborted();
289
+ this.agentLifetimes.get(agent).signal.throwIfAborted();
290
+ if (pending)
291
+ this.check(pending);
292
+ if (parent)
293
+ this.assert(parent);
294
+ if (this.ctx.agents.get(agent.id) !== agent || preset !== agent.ctx.get("agentPresets")?.composedPreset(agent.ctx)
295
+ || presetScope !== scopeParentOf(agent) || parent && !this.ctx.agents.isOwnedBy(agent.id, parent))
296
+ throw new SubagentError("Agent changed during initialization", "UNAUTHORIZED");
297
+ this.profiles.publish(agent, admission);
298
+ const published = this.profiles.admission(agent);
299
+ this.live.set(agent, Object.freeze({ admission: published, preset, scopeParent: scopeParentOf(agent), parent, invocation: pending?.invocation }));
300
+ if (pending)
301
+ this.pending.delete(agent.id);
302
+ }
303
+ catch (error) {
304
+ this.policy.release(agent);
305
+ throw error;
306
+ }
307
+ finally {
308
+ this.candidates.delete(agent);
309
+ }
310
+ }
311
+ }
312
+ function original(value) { return Reflect.get(value, symbols.original) ?? value; }
313
+ //# sourceMappingURL=native-admission.js.map
@@ -2,7 +2,7 @@ import type { Context } from "@deepseek-ai/cordis";
2
2
  import { PiAiAdapter, Config } from "@deepseek-ai/dsh-llm-pi-ai";
3
3
  import type { Options, PiAiAdapterOptions } from "@deepseek-ai/dsh-llm-pi-ai";
4
4
  import type { LlmAdapter } from "@deepseek-ai/dsh-llm";
5
- import type { DsmmLlmGeneration } from "./host-llm.js";
5
+ import type { DsmmLlmCallConfig, DsmmLlmGeneration } from "./host-llm.js";
6
6
  import type { DsmmLlmRouteResolver } from "./role-llm.js";
7
7
  export interface DsmmPiAiOwnerOptions {
8
8
  readonly config: Options;
@@ -14,6 +14,8 @@ export interface DsmmPiAiOwnerOptions {
14
14
  export interface DsmmPiAiProviderOwner extends DsmmLlmRouteResolver {
15
15
  readonly stockAdapter: PiAiAdapter;
16
16
  readonly providers: readonly string[];
17
+ requiresRaw(config: DsmmLlmCallConfig): boolean;
18
+ supportsNativeStop(provider: string): boolean;
17
19
  generation(provider: string): DsmmLlmGeneration;
18
20
  }
19
21
  declare module "@deepseek-ai/cordis" {
@@ -3,14 +3,16 @@ import { brandString } from "@deepseek-ai/dsh-brand";
3
3
  import { PiAiAdapter, Config } from "@deepseek-ai/dsh-llm-pi-ai";
4
4
  import { createModels, createProvider, envApiKeyAuth, hasApi } from "@earendil-works/pi-ai";
5
5
  import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
6
+ import { getBuiltinModels, getBuiltinProviders } from "@earendil-works/pi-ai/providers/all";
6
7
  import { buildBaseOptions } from "@earendil-works/pi-ai/api/simple-options";
7
8
  import { LlmError, ReasoningEffortId, assertUsableApiKey, attributionHeaders, freezeMessage, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
8
- import { snapshotDsmmCall } from "./host-llm.js";
9
+ import { singleUsePreparedStream, snapshotDsmmCall } from "./host-llm.js";
9
10
  import { DsmmMissingProviderError, modelRouteToCall } from "./role-llm.js";
10
11
  import { normalizeModelRouteJson } from "./route-json.js";
11
12
  function normalizeDeclaredProfiles(config) {
12
13
  const profiles = new Map();
13
- for (const [provider, profile] of Object.entries(Config(config).providers.get())) {
14
+ const normalized = Config(config);
15
+ for (const [provider, profile] of Object.entries(normalized.providers.get())) {
14
16
  if (profile.api !== "openai-completions" || !profile.baseURL || !profile.apiKeyEnv || !profile.models?.length
15
17
  || profile.modelOverrides !== undefined && Object.keys(profile.modelOverrides).length > 0) {
16
18
  throw new LlmError("Raw execution requires an explicit completions endpoint, credential reference and finite model list without catalog overrides", "UNSUPPORTED_ROUTE_PARAMETERS");
@@ -30,8 +32,15 @@ function normalizeDeclaredProfiles(config) {
30
32
  throw new LlmError("Declared models must have input modalities", "INVALID_CONFIG");
31
33
  if (!Number.isSafeInteger(contextWindow) || contextWindow <= 0 || !Number.isSafeInteger(maxTokens) || maxTokens <= 0)
32
34
  throw new LlmError("Model capacities must be positive integers", "INVALID_CONFIG");
35
+ const efforts = entry.reasoningEfforts;
36
+ const thinkingLevelMap = {
37
+ off: null, minimal: null, low: null, medium: null, high: null, xhigh: null, max: null,
38
+ ...(efforts || {}),
39
+ };
40
+ if (efforts && efforts.off === null)
41
+ delete thinkingLevelMap.off;
33
42
  return { id: entry.id, name: entry.name ?? entry.id, provider, api: "openai-completions", baseUrl: profile.baseURL,
34
- reasoning: false, input, contextWindow: contextWindow, maxTokens: maxTokens,
43
+ reasoning: !!efforts, ...(efforts ? { thinkingLevelMap } : {}), input, contextWindow: contextWindow, maxTokens: maxTokens,
35
44
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
36
45
  compat: { ...profile.compat, ...entry.compat } };
37
46
  });
@@ -68,7 +77,7 @@ function protectedHeaders(headers) {
68
77
  return Object.fromEntries(result);
69
78
  }
70
79
  /** Public provider composition preserves the SDK's native content/replay/stream translator. */
71
- function rawProvider(provider, generation, request, assertCurrent) {
80
+ function rawProvider(provider, generation, request, assertCurrent, effortSource) {
72
81
  return {
73
82
  ...provider,
74
83
  streamSimple(model, context, options) {
@@ -92,14 +101,22 @@ function rawProvider(provider, generation, request, assertCurrent) {
92
101
  if (tokenField !== undefined && !Object.hasOwn(payload, tokenField))
93
102
  throw new LlmError("Raw token field does not match the declared model protocol", "INVALID_REQUEST");
94
103
  const body = { ...payload, ...request.customParameters };
95
- if (request.reasoningEffort !== undefined)
104
+ if (effortSource === "dsmm-config" && request.reasoningEffort !== undefined)
96
105
  Reflect.set(body, "reasoning_effort", request.reasoningEffort);
97
106
  if (request.stop !== undefined)
98
107
  Reflect.set(body, "stop", [...request.stop]);
99
108
  return body;
100
109
  },
101
110
  };
102
- return generation.stream(exact, context, { ...wireOptions, transformHeaders: protectedHeaders });
111
+ const transformHeaders = (headers) => {
112
+ assertCurrent();
113
+ request.signal?.throwIfAborted();
114
+ return protectedHeaders(headers);
115
+ };
116
+ if (effortSource === "native")
117
+ return generation.streamSimple(exact, context, { ...options,
118
+ ...(typeof rawBudget === "number" ? { maxTokens: rawBudget } : {}), onPayload: wireOptions.onPayload, transformHeaders });
119
+ return generation.stream({ ...exact, reasoning: false, thinkingLevelMap: undefined }, context, { ...wireOptions, transformHeaders });
103
120
  },
104
121
  };
105
122
  }
@@ -186,6 +203,8 @@ export function createDsmmPiAiProviderOwner(ctx, options, borrowed) {
186
203
  for (const profile of profiles.values())
187
204
  models.setProvider(profile.piProvider);
188
205
  const owner = Object.freeze({ stockAdapter, providers,
206
+ requiresRaw: (config) => config.customParameters !== undefined || config.stop !== undefined && profiles.has(config.provider),
207
+ supportsNativeStop: (provider) => !profiles.has(provider),
189
208
  async resolveRoute(input, signal) {
190
209
  const route = normalizeModelRouteJson(input);
191
210
  signal?.throwIfAborted();
@@ -213,16 +232,22 @@ export function createDsmmPiAiProviderOwner(ctx, options, borrowed) {
213
232
  throw new LlmError("Provider is not owned by this Host", "NO_ADAPTER");
214
233
  return Object.freeze({ identity, signal: borrowed === undefined ? life.signal : AbortSignal.any([life.signal, borrowed.signal]), retryPolicy: profile.retryPolicy, assertCurrent,
215
234
  ...(profile.reasoning === undefined ? {} : { defaultReasoningEffort: ReasoningEffortId(profile.reasoning) }),
216
- async prepareCall(selectedProvider, model, signal, assertAdmission) {
235
+ async prepareCall(selectedProvider, model, signal, assertAdmission, effortSource) {
217
236
  const assertCall = () => { signal.throwIfAborted(); assertCurrent(); assertAdmission?.(); };
218
237
  assertCall();
219
238
  if (selectedProvider !== provider || models.getModel(provider, model) === undefined)
220
239
  throw new LlmError("Provider has no exact declared model", "UNKNOWN_MODEL");
221
- const metadata = await (borrowed?.adapter ?? stockAdapter).resolveModel(provider, model, signal);
240
+ const prepared = await (borrowed?.adapter ?? stockAdapter).prepareCall(provider, model, signal);
222
241
  assertCall();
223
- return { model: metadata, stream(request) {
242
+ if (prepared.model.provider !== provider || prepared.model.id !== model)
243
+ throw new LlmError("Provider resolved another model", "INVALID_ADAPTER");
244
+ const catalogProvider = getBuiltinProviders().find(id => id === provider);
245
+ const catalogModel = catalogProvider !== undefined && getBuiltinModels(catalogProvider).some(entry => entry.id === model);
246
+ return { model: prepared.model, stream: singleUsePreparedStream(request => {
224
247
  assertCall();
225
248
  request.signal?.throwIfAborted();
249
+ if (request.provider !== provider || request.model !== model)
250
+ throw new LlmError("Raw request changed its prepared route", "INVALID_PREPARED_CALL");
226
251
  const extended = request;
227
252
  const checked = snapshotDsmmCall({ provider: request.provider, model: request.model,
228
253
  ...(request.reasoningEffort === undefined ? {} : { reasoningEffort: request.reasoningEffort }),
@@ -231,8 +256,17 @@ export function createDsmmPiAiProviderOwner(ctx, options, borrowed) {
231
256
  ...(request.stop === undefined ? {} : { stop: request.stop }),
232
257
  ...(extended.customParameters === undefined ? {} : { customParameters: extended.customParameters }),
233
258
  });
234
- const projectedProfiles = new Map([...profiles].map(([id, item]) => [id, { ...item, reasoning: undefined,
235
- piProvider: rawProvider(item.piProvider, models, { ...request, ...checked }, assertCall) }]));
259
+ if (catalogModel)
260
+ throw new LlmError("Raw execution cannot reproduce implicit catalog model semantics", "UNSUPPORTED_ROUTE_PARAMETERS");
261
+ const source = effortSource?.() ?? "dsmm-config";
262
+ if (source === "native") {
263
+ if (prepared.model.reasoning !== undefined && models.getModel(provider, model)?.thinkingLevelMap === undefined
264
+ || Object.hasOwn(checked.customParameters ?? {}, "reasoning_effort")) {
265
+ throw new LlmError("Native raw execution requires its declared wire mapping and cannot replace native effort with raw effort", "UNSUPPORTED_ROUTE_PARAMETERS");
266
+ }
267
+ }
268
+ const projectedProfiles = new Map([...profiles].map(([id, item]) => [id, { ...item, reasoning: source === "native" ? item.reasoning : undefined,
269
+ piProvider: rawProvider(item.piProvider, models, { ...request, ...checked }, assertCall, source) }]));
236
270
  const credentialSignal = request.signal === undefined ? life.signal : AbortSignal.any([life.signal, request.signal]);
237
271
  const rawAdapter = new PiAiAdapter({ ...adapterOptions, profiles: () => projectedProfiles,
238
272
  resolveApiKey: async (selectedProvider, selectedProfile) => {
@@ -248,8 +282,8 @@ export function createDsmmPiAiProviderOwner(ctx, options, borrowed) {
248
282
  const { replayState: _replay, ...source } = message.source;
249
283
  return freezeMessage({ ...message, source });
250
284
  });
251
- return rawAdapter.stream({ ...native, messages });
252
- } };
285
+ return rawAdapter.stream({ ...native, ...(source === "native" && request.reasoningEffort !== undefined ? { reasoningEffort: request.reasoningEffort } : {}), messages });
286
+ }) };
253
287
  },
254
288
  });
255
289
  },
@@ -1,11 +1,9 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { Agent } from "@deepseek-ai/dsh-agent";
3
3
  import type { PreToolDecision, ToolDefinition, ToolExecution, ToolRunContext } from "@deepseek-ai/dsh-tools";
4
- import type { RoleRunHolder } from "./role-runs.js";
5
4
  import type { NativeCommandEntry } from "./permission-settings.js";
6
5
  import type { NativePermissionMode } from "./permission-native-access.js";
7
6
  export { PermissionRefusal } from "./permission-errors.js";
8
- export type PermissionRunHolder = Pick<RoleRunHolder, "state" | "owner" | "invocation" | "holderSignal" | "drained">;
9
7
  export interface PermissionExecutionAuthority {
10
8
  readonly agent: Agent;
11
9
  readonly root: Agent;
@@ -15,7 +13,6 @@ export interface PermissionExecutionAuthority {
15
13
  readonly owner: object;
16
14
  readonly ownerGeneration: string | number;
17
15
  readonly signal: AbortSignal;
18
- readonly run?: PermissionRunHolder;
19
16
  }
20
17
  export type PermissionRootApprovalAuthority = Pick<PermissionExecutionAuthority, "root" | "realm" | "admissionRevision" | "permissionRevision" | "owner" | "ownerGeneration" | "signal">;
21
18
  export interface PermissionExecutionIntegrity {
@@ -63,17 +63,17 @@ let DsmmPermissionsHost = (() => {
63
63
  return Promise.resolve().then(() => {
64
64
  const id = SessionId(parsePermissionSessionId(sessionId));
65
65
  const invocation = this.ctx.invocation, connection = this.ctx.get("connection");
66
- if (invocation?.peer === undefined || connection === undefined || invocation.peer !== connection.operator)
66
+ if (invocation?.peer === undefined || connection === undefined || invocation.peer !== connection.browserPeer)
67
67
  throw new PermissionRefusal("not-owned");
68
68
  const peer = invocation.peer, owner = permissionOriginal(connection), agents = this.ctx.get("agents"), root = agents?.get(id);
69
69
  if (root === undefined)
70
70
  throw new PermissionRefusal("not-owned");
71
- const signal = AbortSignal.any([invocation.signal, this.lifetime.signal]);
71
+ const signal = AbortSignal.any([invocation.signal, peer.signal, this.lifetime.signal]);
72
72
  const check = () => {
73
73
  const current = this.ctx.get("connection"), registry = this.ctx.get("agents");
74
74
  if (signal.aborted)
75
75
  throw new PermissionRefusal("cancelled");
76
- if (current === undefined || permissionOriginal(current) !== owner || current.operator !== peer || registry?.get(id) !== root
76
+ if (current === undefined || permissionOriginal(current) !== owner || current.browserPeer !== peer || registry?.get(id) !== root
77
77
  || root.id !== sessionId || root.session.id !== sessionId || root.session.header.origin === "subagent" || !registry.roots().includes(root)
78
78
  || registry.list().some(agent => agent !== root && registry.isOwnedBy(id, agent)))
79
79
  throw new PermissionRefusal("not-owned");
@@ -1,7 +1,6 @@
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";
5
4
  import { allowedRoleChildren, readonlyRoleTool, roleFromToolName, READONLY_ROLE_DENIED_TOOLS } from "./role-policy.js";
6
5
  import { nativeStandingFullAccess } from "./permission-native-access.js";
7
6
  import { scopeParentOf } from "./native-scope.js";
@@ -14,7 +13,7 @@ export function registerRolePresets(ctx, getSettings) {
14
13
  throw new Error("dsmm requires the native DSH agentPresets registry");
15
14
  const settings = getSettings();
16
15
  const enabled = DSMM_ROLE_IDS.filter((id) => settings.modules.deepwork.enabled && settings.roles[id]);
17
- const active = DSMM_ROLES.filter((role) => isRootRoleEnabled(settings, role.id));
16
+ const active = DSMM_ROLES.filter((role) => enabled.includes(role.id));
18
17
  const disposers = [];
19
18
  try {
20
19
  for (const role of active) {
@@ -130,6 +129,8 @@ export function registerRolePresets(ctx, getSettings) {
130
129
  }
131
130
  };
132
131
  if (ctx.inject !== undefined) {
132
+ if (ctx.get?.("agentPresets") !== undefined)
133
+ return install(ctx);
133
134
  return Promise.resolve(ctx.inject(["agentPresets"], install)).then(() => undefined);
134
135
  }
135
136
  else if (ctx.get?.("agentPresets") !== undefined || ctx.agentPresets !== undefined) {
@@ -1,15 +1,6 @@
1
- import Schema from "@deepseek-ai/schemastery";
2
- import type { DshContext } from "./dsh-types.js";
3
- import type { DsmmSkillName } from "./skills.js";
1
+ import type { DshAgent, DshContext } from "./dsh-types.js";
4
2
  import type { DsmmSettingsGetter } from "./settings.js";
5
3
  import type { DeepworkModeController } from "./state.js";
6
- export declare const name = "dsmm/preset-skills";
7
- export declare const inject: readonly [];
8
- export interface PresetSkillsConfig {
9
- skills?: DsmmSkillName[];
10
- }
11
- export declare const Config: Schema<PresetSkillsConfig>;
12
- export declare function apply(ctx: DshContext, config?: PresetSkillsConfig): void;
13
- export declare function registerAgentSkills(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter): void;
14
- export default apply;
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;
15
6
  //# sourceMappingURL=preset-skills.d.ts.map