@dsmm/dsmm 0.1.4 → 0.1.5

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 (52) hide show
  1. package/README.md +12 -12
  2. package/docs/compatibility.md +8 -6
  3. package/docs/migration-from-ocmm.md +8 -0
  4. package/docs/model-routing.md +19 -5
  5. package/docs/profiles.md +21 -9
  6. package/docs/releasing.md +23 -15
  7. package/docs/runtime-recovery.md +39 -14
  8. package/docs/settings-status.md +7 -7
  9. package/lib/client/ProfilesSection.js +7 -3
  10. package/lib/client/SessionProfiles.d.ts +19 -0
  11. package/lib/client/SessionProfiles.js +24 -0
  12. package/lib/client/StructuredEditor.d.ts +11 -0
  13. package/lib/client/StructuredEditor.js +74 -0
  14. package/lib/client/controller.d.ts +38 -0
  15. package/lib/client/controller.js +153 -11
  16. package/lib/client/index.d.ts +2 -0
  17. package/lib/client/index.js +20 -0
  18. package/lib/client/locales.d.ts +89 -0
  19. package/lib/client/locales.js +45 -2
  20. package/lib/client/session-labels.d.ts +8 -0
  21. package/lib/client/session-labels.js +13 -0
  22. package/lib/client/structured.d.ts +18 -0
  23. package/lib/client/structured.js +98 -0
  24. package/lib/client/styles.d.ts +1 -1
  25. package/lib/client/styles.js +12 -1
  26. package/lib/client.js +969 -74
  27. package/lib/commands.js +1 -0
  28. package/lib/dsh-types.d.ts +16 -0
  29. package/lib/index.js +27 -1
  30. package/lib/model-routing.js +93 -23
  31. package/lib/profile-remote.d.ts +7 -1
  32. package/lib/profile-remote.js +115 -2
  33. package/lib/profile-rpc.d.ts +9 -1
  34. package/lib/profile-rpc.js +99 -2
  35. package/lib/profile-runtime.d.ts +24 -5
  36. package/lib/profile-runtime.js +182 -31
  37. package/lib/profile-store.d.ts +19 -1
  38. package/lib/profile-store.js +120 -10
  39. package/lib/profile-types.d.ts +41 -1
  40. package/lib/profiles.d.ts +1 -1
  41. package/lib/profiles.js +34 -2
  42. package/lib/role-providers.js +12 -2
  43. package/lib/role-routing.d.ts +37 -3
  44. package/lib/role-routing.js +107 -35
  45. package/lib/routing-policy.d.ts +32 -0
  46. package/lib/routing-policy.js +92 -0
  47. package/lib/runtime-recovery.js +213 -52
  48. package/lib/settings.d.ts +27 -1
  49. package/lib/settings.js +29 -7
  50. package/lib/status.d.ts +9 -1
  51. package/lib/status.js +29 -8
  52. package/package.json +5 -1
@@ -1,10 +1,11 @@
1
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
2
- import { classifyRecoveryFailure, foldAttemptedRecoveryRoutes, foldDurableRecoveryWork, isCurrentRecoveryStep, selectFallbackRoute } from "./recovery-policy.js";
1
+ import { createUserMessage, expandAssistantStream } from "@deepseek-ai/dsh-llm";
2
+ import { foldDurableRecoveryWork, isCurrentRecoveryStep } from "./recovery-policy.js";
3
3
  import { isDsmmRoleId } from "./roles.js";
4
- import { applyModelRoute, effectiveRoleFallbackRoutes, recordAdmittedRecoveryRoute, rolePolicyIdentity, sameModelRoute } from "./role-routing.js";
4
+ import { applyModelRoute, isUnavailableRouteFailure, latestNativeModelSelection, liveRolePolicyIdentity, recordAdmittedRecoveryRoute, roleRouteLock, sameModelRoute, selectInitialModelRoute } from "./role-routing.js";
5
5
  import { childOwnedSessionEvents, resolveEffectiveDsmmRole, resolveSelectedAgentPreset, sessionEvents } from "./session-scope.js";
6
+ import { resolveRoleRuntimePolicy } from "./routing-policy.js";
6
7
  const installedContexts = new WeakSet();
7
- const RECOVERY_WARNING = "dsmm runtime recovery could not evaluate fallback; preserving the host request-error decision";
8
+ const RECOVERY_WARNING = "dsmm runtime recovery refused an unproven or exhausted retry";
8
9
  const CONTINUATION_WARNING = "dsmm runtime recovery continuation steering failed for turn";
9
10
  function warnSafely(ctx, message) {
10
11
  try {
@@ -15,27 +16,77 @@ function warnSafely(ctx, message) {
15
16
  function recoveryEvents(agent) {
16
17
  return agent.session.header?.origin === "subagent" ? childOwnedSessionEvents(agent.session) : sessionEvents(agent.session);
17
18
  }
19
+ function isRecord(value) {
20
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21
+ }
22
+ function isRateLimit(failure) {
23
+ if (["AUTH", "MISSING_CREDENTIAL", "INVALID_CREDENTIAL", "QUOTA", "ACCOUNT_QUOTA", "CONTEXT_WINDOW_EXCEEDED", "INVALID_ARGS", "CANCELLED", "ABORTED"].includes(failure.code) || failure.status === 402)
24
+ return false;
25
+ return failure.code === "RATE_LIMIT" || failure.status === 429;
26
+ }
27
+ function outputChunk(chunk) {
28
+ // Block boundaries and even empty fragments are protocol output, not proof of absence.
29
+ return chunk.type !== "usage" && chunk.type !== "finish";
30
+ }
31
+ function positiveNoOutput(frame, attempt, consumed = false) {
32
+ if (attempt === undefined || !attempt.valid || attempt.output || (attempt.consumed && !consumed) || attempt.failure !== frame.failure
33
+ || attempt.turn !== frame.turn || attempt.step !== frame.step || attempt.eventType !== "assistant/attempt"
34
+ || attempt.seq === undefined || attempt.route.provider !== frame.provider)
35
+ return false;
36
+ const events = recoveryEvents(frame.agent);
37
+ if (frame.agent.session.requestHeader?.() !== attempt.header)
38
+ return false;
39
+ const settlements = events.filter((event) => "seq" in event && event.seq === attempt.seq);
40
+ if (settlements.length !== 1)
41
+ return false;
42
+ const settlement = settlements[0];
43
+ if (settlement?.type !== "assistant/attempt" || !isRecord(settlement.data)
44
+ || settlement.data.turn !== frame.turn || settlement.data.step !== frame.step || !Array.isArray(settlement.data.stream))
45
+ return false;
46
+ const later = events.slice(events.indexOf(settlement) + 1);
47
+ if (later.some((event) => ["assistant/attempt", "assistant/message", "tool/call", "tool/result", "request/header", "step/start", "step/end", "turn/end"].includes(event.type)))
48
+ return false;
49
+ try {
50
+ const chunks = expandAssistantStream(settlement.data.stream);
51
+ const finish = chunks.at(-1)?.chunk;
52
+ return chunks.length === attempt.chunks && chunks.every(({ chunk }) => !outputChunk(chunk))
53
+ && finish?.type === "finish" && finish.reason.kind === "error"
54
+ && JSON.stringify(finish.reason.failure) === JSON.stringify(frame.failure);
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
18
60
  export function registerRuntimeRecovery(ctx, controller, getSettings) {
19
61
  if (installedContexts.has(ctx) || ctx.on === undefined)
20
62
  return;
21
63
  installedContexts.add(ctx);
22
64
  let pendingByAgent = new WeakMap();
23
- let reservedByAgent = new WeakMap();
65
+ let attemptsByAgent = new WeakMap();
24
66
  let continuationsByAgent = new WeakMap();
67
+ const waits = new Set();
68
+ let active = true;
25
69
  let disposeRequest;
26
70
  let disposeRequestError;
27
71
  let disposeTurnStopping;
72
+ let disposeAssistantStream;
28
73
  const reset = () => {
29
74
  const request = disposeRequest;
30
75
  const requestError = disposeRequestError;
31
76
  const turnStopping = disposeTurnStopping;
77
+ const assistantStream = disposeAssistantStream;
78
+ active = false;
79
+ for (const wait of waits)
80
+ wait.abort();
32
81
  disposeRequest = undefined;
33
82
  disposeRequestError = undefined;
34
83
  disposeTurnStopping = undefined;
35
84
  pendingByAgent = new WeakMap();
36
- reservedByAgent = new WeakMap();
85
+ attemptsByAgent = new WeakMap();
37
86
  continuationsByAgent = new WeakMap();
38
87
  installedContexts.delete(ctx);
88
+ if (typeof assistantStream === "function")
89
+ assistantStream();
39
90
  if (typeof turnStopping === "function")
40
91
  turnStopping();
41
92
  if (typeof requestError === "function")
@@ -44,11 +95,67 @@ export function registerRuntimeRecovery(ctx, controller, getSettings) {
44
95
  request();
45
96
  };
46
97
  try {
98
+ disposeAssistantStream = ctx.on("agent/assistant-stream", ({ agent, frame }) => {
99
+ if (!active)
100
+ return;
101
+ if (frame.type === "start") {
102
+ const settings = getSettings(agent);
103
+ const role = resolveEffectiveDsmmRole(agent, settings, controller.active(agent, settings.defaultActive));
104
+ const policy = liveRolePolicyIdentity(agent, settings, role, getSettings.admission?.(agent).epoch);
105
+ const lock = policy === undefined ? undefined : roleRouteLock(agent, policy);
106
+ const header = agent.session.requestHeader?.();
107
+ if (header === undefined) {
108
+ attemptsByAgent.delete(agent);
109
+ return;
110
+ }
111
+ const previous = attemptsByAgent.get(agent);
112
+ const attempt = { id: frame.attemptId, turn: frame.turn, step: frame.step, revision: frame.revision, chunks: 0,
113
+ route: { provider: header.config.provider, model: header.config.model }, header, policy, generation: lock?.generation, manualSelectionSeq: lock?.manualSelectionSeq,
114
+ valid: Number.isSafeInteger(frame.revision) && frame.revision >= 1 && (previous === undefined || frame.revision === previous.revision + 1), output: false, consumed: false };
115
+ attemptsByAgent.set(agent, attempt);
116
+ if (lock !== undefined)
117
+ lock.attempts += 1;
118
+ return;
119
+ }
120
+ const attempt = attemptsByAgent.get(agent);
121
+ if (attempt === undefined)
122
+ return;
123
+ if (attempt.id !== frame.attemptId || frame.revision !== attempt.revision + 1 || frame.index !== attempt.chunks || attempt.seq !== undefined) {
124
+ attempt.valid = false;
125
+ return;
126
+ }
127
+ attempt.revision = frame.revision;
128
+ if (frame.type === "chunk") {
129
+ attempt.chunks += 1;
130
+ attempt.output ||= outputChunk(frame.chunk);
131
+ if (frame.chunk.type === "finish" && (frame.chunk.reason.kind === "error" || frame.chunk.reason.kind === "aborted"))
132
+ attempt.failure = frame.chunk.reason.failure;
133
+ return;
134
+ }
135
+ if (frame.outcome.kind !== "committed") {
136
+ attempt.valid = false;
137
+ return;
138
+ }
139
+ attempt.seq = frame.outcome.seq;
140
+ attempt.eventType = frame.outcome.eventType;
141
+ const lock = attempt.policy === undefined ? undefined : roleRouteLock(agent, attempt.policy);
142
+ if (lock !== undefined && (attempt.output || frame.outcome.eventType === "assistant/message")) {
143
+ lock.startupSettled = true;
144
+ if (frame.outcome.eventType === "assistant/message") {
145
+ lock.retries = 0;
146
+ lock.rateLimits = 0;
147
+ }
148
+ }
149
+ }, { prepend: true });
47
150
  disposeRequest = ctx.on("agent/request", async (frame, next) => {
48
151
  const downstream = await next();
49
152
  const pending = pendingByAgent.get(frame.agent);
50
153
  if (pending === undefined)
51
154
  return downstream;
155
+ if (latestNativeModelSelection(frame.agent)?.seq !== pending.manualSelectionSeq) {
156
+ pendingByAgent.delete(frame.agent);
157
+ throw new Error("dsmm retry was superseded by an explicit native model selection");
158
+ }
52
159
  if (frame.signal.aborted || !isCurrentRecoveryStep(recoveryEvents(frame.agent), pending.turn, pending.step)) {
53
160
  pendingByAgent.delete(frame.agent);
54
161
  return downstream;
@@ -58,72 +165,126 @@ export function registerRuntimeRecovery(ctx, controller, getSettings) {
58
165
  if (pending.policy !== undefined) {
59
166
  const settings = getSettings(frame.agent);
60
167
  const role = resolveEffectiveDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive));
61
- if (role !== pending.role || rolePolicyIdentity(settings, role) !== pending.policy) {
168
+ if (role !== pending.role || liveRolePolicyIdentity(frame.agent, settings, role, getSettings.admission?.(frame.agent).epoch) !== pending.policy) {
62
169
  pendingByAgent.delete(frame.agent);
63
- reservedByAgent.delete(frame.agent);
64
170
  return downstream;
65
171
  }
66
172
  }
67
- const reserved = reservedByAgent.get(frame.agent);
68
173
  const accepted = frame.agent.session.requestHeader?.()?.config;
69
- if (reserved !== undefined && accepted !== undefined && !sameModelRoute(accepted, reserved.route) && !sameModelRoute(accepted, pending.route)) {
174
+ const lock = pending.policy === undefined ? undefined : roleRouteLock(frame.agent, pending.policy);
175
+ if (!active || lock === undefined || lock.generation !== pending.generation || attemptsByAgent.get(frame.agent) !== pending.attempt
176
+ || accepted === undefined || !sameModelRoute(accepted, pending.failedRoute)) {
70
177
  pendingByAgent.delete(frame.agent);
71
178
  return downstream;
72
179
  }
73
180
  pendingByAgent.delete(frame.agent);
181
+ lock.route = { ...pending.route };
74
182
  recordAdmittedRecoveryRoute(frame, pending.route);
75
183
  return applyModelRoute(downstream, pending.route);
76
184
  }, { prepend: true });
77
185
  disposeRequestError = ctx.on("agent/request-error", async (frame, next) => {
78
- const downstream = await next();
79
- if (downstream?.kind === "retry") {
80
- pendingByAgent.delete(frame.agent);
81
- return downstream;
186
+ let settings;
187
+ let role;
188
+ try {
189
+ settings = getSettings(frame.agent);
190
+ role = resolveEffectiveDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive));
82
191
  }
192
+ catch {
193
+ const prior = attemptsByAgent.get(frame.agent);
194
+ return isRateLimit(frame.failure) && prior?.policy !== undefined ? undefined : await next();
195
+ }
196
+ const unavailable = isUnavailableRouteFailure(frame.failure, true);
197
+ if (role === undefined || (!isRateLimit(frame.failure) && !unavailable))
198
+ return await next();
83
199
  try {
84
- const settings = getSettings(frame.agent);
85
- if (!settings.runtimeRecovery.enabled || frame.signal.aborted
86
- || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step))
87
- return downstream;
88
- const preset = resolveSelectedAgentPreset(frame.agent.session);
89
- const role = resolveEffectiveDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive));
90
- const inScope = role !== undefined || controller.active(frame.agent, settings.defaultActive)
91
- || (frame.agent.session.header?.origin !== "subagent" && isDsmmRoleId(preset) && settings.roles[preset]);
92
- if (!inScope || classifyRecoveryFailure(frame.failure, settings.runtimeRecovery).kind !== "retryable")
93
- return downstream;
200
+ const policy = liveRolePolicyIdentity(frame.agent, settings, role, getSettings.admission?.(frame.agent).epoch);
201
+ const lock = policy === undefined ? undefined : roleRouteLock(frame.agent, policy);
202
+ const attempt = attemptsByAgent.get(frame.agent);
94
203
  const header = frame.agent.session.requestHeader?.();
95
- if (header === undefined || header.config.provider !== frame.provider)
96
- return downstream;
97
- const policy = rolePolicyIdentity(settings, role);
98
- const reserved = reservedByAgent.get(frame.agent);
99
- if (reserved?.turn === frame.turn && reserved.step === frame.step
100
- && reserved.policy === policy
101
- && reserved.route.provider === header.config.provider && reserved.route.model === header.config.model)
102
- return downstream;
103
- const attemptedRoutes = foldAttemptedRecoveryRoutes(recoveryEvents(frame.agent), frame.turn, frame.step);
104
- const lastAttemptedRoute = attemptedRoutes.at(-1);
105
- if (lastAttemptedRoute === undefined
106
- || lastAttemptedRoute.provider !== header.config.provider
107
- || lastAttemptedRoute.model !== header.config.model)
108
- return downstream;
109
- const route = selectFallbackRoute({
110
- failedRoute: { provider: header.config.provider, model: header.config.model },
111
- attemptedRoutes,
112
- fallbackRoutes: effectiveRoleFallbackRoutes(settings, role),
113
- maxFallbackAttempts: settings.runtimeRecovery.maxFallbackAttempts
114
- });
115
- if (route === undefined)
116
- return downstream;
117
- reservedByAgent.set(frame.agent, {
118
- turn: frame.turn, step: frame.step,
119
- route: { provider: header.config.provider, model: header.config.model }, role, policy
120
- });
121
- pendingByAgent.set(frame.agent, { turn: frame.turn, step: frame.step, route, role, policy });
204
+ if (!active || frame.signal.aborted || lock === undefined || header === undefined
205
+ || header.config.provider !== frame.provider || !sameModelRoute(header.config, lock.route)
206
+ || attempt === undefined || attempt.policy !== policy || attempt.generation !== lock.generation
207
+ || latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
208
+ || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step) || !positiveNoOutput(frame, attempt))
209
+ return undefined;
210
+ attempt.consumed = true;
211
+ const resolved = resolveRoleRuntimePolicy(settings, role);
212
+ const bounds = resolved.rateLimit;
213
+ let route = lock.route;
214
+ let switching = false;
215
+ if (unavailable) {
216
+ if (lock.startupSettled || lock.attempts !== 1)
217
+ return undefined;
218
+ switching = true;
219
+ }
220
+ else {
221
+ lock.startupSettled = true;
222
+ lock.rateLimits += 1;
223
+ switching = resolved.strategy === "rate-limit-fallback" && lock.rateLimits >= bounds.switchAfterRateLimits;
224
+ if (!switching && lock.retries >= bounds.maxRetries)
225
+ return undefined;
226
+ }
227
+ if (switching) {
228
+ if (!unavailable && lock.switches >= bounds.maxSwitches)
229
+ return undefined;
230
+ const index = lock.candidates.findIndex((candidate) => sameModelRoute(candidate, lock.route));
231
+ const candidates = lock.candidates.slice(index + 1);
232
+ if (index < 0 || candidates.length === 0)
233
+ return undefined;
234
+ const llm = frame.agent.ctx?.get?.("llm") ?? ctx.get?.("llm") ?? ctx.llm;
235
+ route = await selectInitialModelRoute(llm ?? {}, candidates, frame.signal);
236
+ }
237
+ const serverMinimum = frame.failure.providerRetryAfterMs;
238
+ if (serverMinimum !== undefined && (!Number.isSafeInteger(serverMinimum) || serverMinimum < 0))
239
+ return undefined;
240
+ const delay = unavailable ? 0 : Math.max(Math.min(bounds.maxDelayMs, bounds.initialDelayMs * 2 ** lock.retries), serverMinimum ?? 0);
241
+ if (delay > bounds.maxDelayMs || delay > bounds.maxTotalDelayMs - lock.totalDelayMs)
242
+ return undefined;
243
+ lock.totalDelayMs += delay;
244
+ const expectedGeneration = lock.generation;
245
+ if (delay > 0) {
246
+ const wait = new AbortController();
247
+ waits.add(wait);
248
+ try {
249
+ const signal = AbortSignal.any([frame.signal, wait.signal]);
250
+ await new Promise((resolve, reject) => {
251
+ const timer = setTimeout(() => { signal.removeEventListener("abort", abort); resolve(); }, delay);
252
+ const abort = () => { clearTimeout(timer); signal.removeEventListener("abort", abort); reject(new Error("dsmm retry delay aborted")); };
253
+ signal.addEventListener("abort", abort, { once: true });
254
+ if (signal.aborted)
255
+ abort();
256
+ });
257
+ }
258
+ finally {
259
+ waits.delete(wait);
260
+ }
261
+ }
262
+ const currentSettings = getSettings(frame.agent);
263
+ const currentRole = resolveEffectiveDsmmRole(frame.agent, currentSettings, controller.active(frame.agent, currentSettings.defaultActive));
264
+ if (!active || frame.signal.aborted || currentRole !== role
265
+ || liveRolePolicyIdentity(frame.agent, currentSettings, currentRole, getSettings.admission?.(frame.agent).epoch) !== policy
266
+ || roleRouteLock(frame.agent, policy) !== lock || lock.generation !== expectedGeneration
267
+ || attemptsByAgent.get(frame.agent) !== attempt || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step)
268
+ || latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
269
+ || !positiveNoOutput(frame, attempt, true)
270
+ || !sameModelRoute(frame.agent.session.requestHeader?.()?.config ?? { provider: "", model: "" }, attempt.route))
271
+ return undefined;
272
+ if (switching) {
273
+ lock.generation += 1;
274
+ if (!unavailable)
275
+ lock.switches += 1;
276
+ lock.retries = 0;
277
+ lock.rateLimits = 0;
278
+ }
279
+ else
280
+ lock.retries += 1;
281
+ pendingByAgent.set(frame.agent, { turn: frame.turn, step: frame.step, route: { ...route }, role, policy,
282
+ generation: lock.generation, failedRoute: attempt.route, attempt, manualSelectionSeq: attempt.manualSelectionSeq });
122
283
  return { kind: "retry" };
123
284
  }
124
285
  catch {
125
286
  warnSafely(ctx, RECOVERY_WARNING);
126
- return downstream;
287
+ return undefined;
127
288
  }
128
289
  }, { prepend: true });
129
290
  disposeTurnStopping = ctx.on("agent/turn-stopping", async (frame) => {
package/lib/settings.d.ts CHANGED
@@ -3,6 +3,9 @@ import type { DshAgent, DshContext } from "./dsh-types.js";
3
3
  import type { DsmmLspSettings } from "./lsp.js";
4
4
  import type { DsmmRoleId } from "./roles.js";
5
5
  import type { DsmmSkillName } from "./skills.js";
6
+ import type { DsmmRateLimitPolicy, DsmmRoutingStrategy, DsmmRuntimePolicyConfig, DsmmRuntimePolicySettings } from "./routing-policy.js";
7
+ export type { DsmmRateLimitPolicy, DsmmRoutingStrategy, DsmmRuntimePolicyConfig, DsmmRuntimePolicySettings } from "./routing-policy.js";
8
+ export { resolveRoleRuntimePolicy } from "./routing-policy.js";
6
9
  export { DSMM_SKILL_NAMES, MVP_SKILL_NAMES } from "./skills.js";
7
10
  export type { DsmmSkillName, MvpSkillName } from "./skills.js";
8
11
  export type DeepseekCalibration = "off" | "auto" | "strict";
@@ -45,6 +48,8 @@ export interface DsmmRecoveryRoute extends DsmmModelRoute {
45
48
  export interface DsmmRoleRoutingConfig {
46
49
  primary?: DsmmModelRoute;
47
50
  fallbackRoutes?: DsmmModelRoute[];
51
+ strategy?: DsmmRoutingStrategy;
52
+ rateLimit?: Partial<DsmmRateLimitPolicy>;
48
53
  }
49
54
  export type DsmmRoleRouting = Partial<Record<DsmmRoleId, DsmmRoleRoutingConfig>>;
50
55
  export interface DsmmRuntimeRecoverySettings {
@@ -86,6 +91,7 @@ export interface DsmmPluginConfig {
86
91
  skills?: Partial<Record<DsmmSkillName, boolean>>;
87
92
  roles?: Partial<Record<DsmmRoleId, boolean>>;
88
93
  roleRouting?: DsmmRoleRouting;
94
+ runtimePolicy?: DsmmRuntimePolicyConfig;
89
95
  presets?: Partial<DsmmPresetSettings>;
90
96
  workflow?: Partial<DsmmWorkflowSettings>;
91
97
  guards?: DsmmGuardConfig;
@@ -105,14 +111,34 @@ export interface DsmmSettings {
105
111
  skills: Record<DsmmSkillName, boolean>;
106
112
  roles: Record<DsmmRoleId, boolean>;
107
113
  roleRouting: DsmmRoleRouting;
114
+ runtimePolicy: DsmmRuntimePolicySettings;
108
115
  presets: DsmmPresetSettings;
109
116
  workflow: DsmmWorkflowSettings;
110
117
  guards: DsmmGuardSettings;
111
118
  runtimeRecovery: DsmmRuntimeRecoverySettings;
112
119
  lsp: DsmmLspSettings;
113
120
  }
121
+ export type DsmmProfileScope = "global-default" | "session-override" | "deployment-baseline";
122
+ export interface DsmmProfileAdmission {
123
+ settings: DsmmSettings;
124
+ profile: {
125
+ id: string;
126
+ revision: string;
127
+ } | null;
128
+ epoch: string;
129
+ scope: DsmmProfileScope;
130
+ }
114
131
  /** Runtime consumers pass their Agent so immutable profile admission is retained. */
115
- export type DsmmSettingsGetter = (agent?: DshAgent) => DsmmSettings;
132
+ export type DsmmSettingsGetter = ((agent?: DshAgent) => DsmmSettings) & {
133
+ admission?: (agent?: DshAgent) => DsmmProfileAdmission;
134
+ };
135
+ export interface DsmmResolvedRoleRuntimePolicy {
136
+ readonly strategy: DsmmRoutingStrategy;
137
+ readonly rateLimit: Readonly<DsmmRateLimitPolicy>;
138
+ readonly primary?: Readonly<DsmmModelRoute>;
139
+ readonly fallbackRoutes: readonly Readonly<DsmmModelRoute>[];
140
+ readonly fallbackSource: "role" | "global";
141
+ }
116
142
  export declare const DSMM_SETTINGS_NAMESPACE = "dsmm";
117
143
  export declare const DSMM_STATUS_COMMAND = "dsmm-status";
118
144
  export interface RegisterSettingsOptions {
package/lib/settings.js CHANGED
@@ -2,6 +2,8 @@ import Schema from "@deepseek-ai/schemastery";
2
2
  import { DEFAULT_DSMM_LSP_SETTINGS, resolveLspSettings } from "./lsp.js";
3
3
  import { DSMM_ROLE_IDS } from "./roles.js";
4
4
  import { DSMM_SKILL_NAMES } from "./skills.js";
5
+ import { DEFAULT_DSMM_RUNTIME_POLICY, normalizeRateLimitOverrides, normalizeRoutingStrategy, normalizeRuntimePolicy, resolveRoleRuntimePolicy } from "./routing-policy.js";
6
+ export { resolveRoleRuntimePolicy } from "./routing-policy.js";
5
7
  export { DSMM_SKILL_NAMES, MVP_SKILL_NAMES } from "./skills.js";
6
8
  export const DSMM_SETTINGS_NAMESPACE = "dsmm";
7
9
  export const DSMM_STATUS_COMMAND = "dsmm-status";
@@ -18,6 +20,7 @@ export const DEFAULT_DSMM_SETTINGS = {
18
20
  skills: createDefaultSkillSettings(),
19
21
  roles: createDefaultRoleSettings(),
20
22
  roleRouting: {},
23
+ runtimePolicy: DEFAULT_DSMM_RUNTIME_POLICY,
21
24
  presets: {
22
25
  materialize: false
23
26
  },
@@ -83,7 +86,9 @@ const MODEL_ROUTE_SCHEMA = Schema.object({
83
86
  // A dictionary retains unknown keys for fail-closed validation by the resolver.
84
87
  const ROLE_ROUTING_SCHEMA = Schema.dict(Schema.object({
85
88
  primary: Schema.union([Schema.const(undefined), MODEL_ROUTE_SCHEMA]),
86
- fallbackRoutes: Schema.union([Schema.const(undefined), Schema.array(MODEL_ROUTE_SCHEMA)])
89
+ fallbackRoutes: Schema.union([Schema.const(undefined), Schema.array(MODEL_ROUTE_SCHEMA)]),
90
+ strategy: Schema.any(),
91
+ rateLimit: Schema.any()
87
92
  }).required()).default({});
88
93
  // Schemastery treats null like an omitted default. Validate the untouched map
89
94
  // before object defaults can erase an explicitly malformed routing policy.
@@ -96,7 +101,9 @@ const ROLE_ROUTING_VALIDATION_SCHEMA = Schema.transform(Schema.any(), (input) =>
96
101
  normalizeRecoveryEffort(route);
97
102
  }
98
103
  }
99
- return { roleRouting: resolveRoleRouting(input.roleRouting) };
104
+ const roleRouting = resolveRoleRouting(input.roleRouting);
105
+ const runtimePolicy = normalizeRuntimePolicy(Object.hasOwn(input, "runtimePolicy") ? validatePresentRuntimePolicy(input.runtimePolicy) : undefined);
106
+ return { roleRouting, runtimePolicy };
100
107
  });
101
108
  const PRESETS_SCHEMA = Schema.object({
102
109
  materialize: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.presets.materialize),
@@ -205,6 +212,7 @@ export const DSMM_CONFIG_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SCHE
205
212
  skills: SKILLS_SCHEMA,
206
213
  roles: ROLES_SCHEMA,
207
214
  roleRouting: ROLE_ROUTING_SCHEMA,
215
+ runtimePolicy: Schema.any(),
208
216
  presets: PRESETS_SCHEMA,
209
217
  workflow: WORKFLOW_CONFIG_SCHEMA,
210
218
  guards: GUARDS_SCHEMA,
@@ -224,6 +232,7 @@ export const DSMM_SETTINGS_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SC
224
232
  skills: SKILLS_SCHEMA,
225
233
  roles: ROLES_SCHEMA,
226
234
  roleRouting: ROLE_ROUTING_SCHEMA,
235
+ runtimePolicy: Schema.any(),
227
236
  presets: PRESETS_SCHEMA,
228
237
  workflow: WORKFLOW_SCHEMA,
229
238
  guards: GUARDS_SCHEMA,
@@ -231,7 +240,7 @@ export const DSMM_SETTINGS_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SC
231
240
  lsp: LSP_SCHEMA
232
241
  })]).default({});
233
242
  export function resolveConfig(config = {}) {
234
- return {
243
+ const settings = {
235
244
  modeName: normalizeModeName(config.modeName),
236
245
  defaultActive: config.defaultActive ?? DEFAULT_DSMM_SETTINGS.defaultActive,
237
246
  promptOrder: config.promptOrder ?? DEFAULT_DSMM_SETTINGS.promptOrder,
@@ -244,12 +253,21 @@ export function resolveConfig(config = {}) {
244
253
  skills: { ...DEFAULT_DSMM_SETTINGS.skills, ...config.skills },
245
254
  roles: { ...DEFAULT_DSMM_SETTINGS.roles, ...config.roles },
246
255
  roleRouting: resolveRoleRouting(config.roleRouting),
256
+ runtimePolicy: normalizeRuntimePolicy(Object.hasOwn(config, "runtimePolicy") ? validatePresentRuntimePolicy(config.runtimePolicy) : undefined),
247
257
  presets: resolvePresetSettings(config.presets),
248
258
  workflow: resolveWorkflowSettings(config.workflow),
249
259
  guards: resolveGuardSettings(config.guards),
250
260
  runtimeRecovery: resolveRuntimeRecoverySettings(config.runtimeRecovery),
251
261
  lsp: resolveLspSettings(config.lsp)
252
262
  };
263
+ for (const role of DSMM_ROLE_IDS)
264
+ resolveRoleRuntimePolicy(settings, role);
265
+ return settings;
266
+ }
267
+ function validatePresentRuntimePolicy(value) {
268
+ if (value === undefined)
269
+ throw new TypeError("dsmm runtimePolicy must be an object when present");
270
+ return value;
253
271
  }
254
272
  function resolveMaxReasoningPresets(input, defaults) {
255
273
  const requested = new Set(input ?? defaults);
@@ -264,15 +282,19 @@ export function resolveRoleRouting(input) {
264
282
  for (const [key, value] of Object.entries(input)) {
265
283
  if (!DSMM_ROLE_IDS.includes(key))
266
284
  throw new TypeError("dsmm roleRouting contains an unknown role");
267
- if (!isRoutingRecord(value) || Object.keys(value).some((field) => field !== "primary" && field !== "fallbackRoutes")) {
268
- throw new TypeError("dsmm roleRouting role policy must contain only primary and fallbackRoutes");
285
+ if (!isRoutingRecord(value) || Object.keys(value).some((field) => !["primary", "fallbackRoutes", "strategy", "rateLimit"].includes(field))) {
286
+ throw new TypeError("dsmm roleRouting role policy must contain only primary, fallbackRoutes, strategy and rateLimit");
269
287
  }
270
288
  const policy = {};
289
+ if (Object.hasOwn(value, "strategy"))
290
+ policy.strategy = normalizeRoutingStrategy(value.strategy);
291
+ if (Object.hasOwn(value, "rateLimit"))
292
+ policy.rateLimit = normalizeRateLimitOverrides(value.rateLimit);
271
293
  if (Object.hasOwn(value, "primary"))
272
294
  policy.primary = normalizeExplicitRoute(value.primary);
273
295
  if (Object.hasOwn(value, "fallbackRoutes")) {
274
- if (!Array.isArray(value.fallbackRoutes))
275
- throw new TypeError("dsmm roleRouting fallbackRoutes must be an array");
296
+ if (!Array.isArray(value.fallbackRoutes) || value.fallbackRoutes.length > 32)
297
+ throw new TypeError("dsmm roleRouting fallbackRoutes must be an array with at most 32 entries");
276
298
  policy.fallbackRoutes = [];
277
299
  for (const entry of value.fallbackRoutes) {
278
300
  const route = normalizeExplicitRoute(entry);
package/lib/status.d.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import type { DshAgent } from "./dsh-types.js";
2
2
  import type { DsmmModelFamily } from "./model-family.js";
3
3
  import type { DsmmRoleId } from "./roles.js";
4
- import type { DeepseekCalibration, DsmmModelRoute, DsmmSettings } from "./settings.js";
4
+ import type { DeepseekCalibration, DsmmModelRoute, DsmmProfileAdmission, DsmmSettings } from "./settings.js";
5
+ import type { DsmmRateLimitPolicy, DsmmRoutingStrategy } from "./routing-policy.js";
6
+ import type { DsmmRoleRuntimeState } from "./profile-types.js";
5
7
  export declare const DSMM_STATUS_VERSION: 1;
6
8
  export interface DsmmStatusSnapshot {
7
9
  version: typeof DSMM_STATUS_VERSION;
10
+ admission?: Pick<DsmmProfileAdmission, "profile" | "epoch" | "scope">;
8
11
  mode: {
9
12
  name: string;
10
13
  active: boolean;
@@ -32,6 +35,9 @@ export interface DsmmStatusSnapshot {
32
35
  primary?: DsmmModelRoute;
33
36
  fallbackRoutes: DsmmModelRoute[];
34
37
  fallbackSource: "role" | "global" | "disabled";
38
+ strategy: DsmmRoutingStrategy;
39
+ rateLimit: DsmmRateLimitPolicy;
40
+ runtimeState?: DsmmRoleRuntimeState;
35
41
  diagnostic?: "invalid-child-descriptor";
36
42
  };
37
43
  runtimeRecovery: {
@@ -50,6 +56,8 @@ export declare function createDsmmStatusSnapshot(input: {
50
56
  agent: DshAgent;
51
57
  settings: DsmmSettings;
52
58
  modeActive: boolean;
59
+ admission?: DsmmProfileAdmission;
60
+ roleRuntimeState?: DsmmRoleRuntimeState;
53
61
  }): DsmmStatusSnapshot;
54
62
  export declare function formatDsmmStatus(snapshot: DsmmStatusSnapshot): string;
55
63
  //# sourceMappingURL=status.d.ts.map
package/lib/status.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { classifyModelFamily } from "./model-family.js";
2
2
  import { isDeepseekFlashRoute, isDeepseekV4ProRoute } from "./model-routing.js";
3
3
  import { DSMM_ROLES, isDsmmRoleId } from "./roles.js";
4
- import { effectiveRoleFallbackRoutes, persistedRoleRoute, rolePolicyIdentity } from "./role-routing.js";
4
+ import { persistedRoleRoute, liveRolePolicyIdentity, roleRouteRuntimeState } from "./role-routing.js";
5
5
  import { resolveEffectiveDsmmRole, resolveSelectedAgentPreset } from "./session-scope.js";
6
+ import { resolveRoleRuntimePolicy } from "./routing-policy.js";
6
7
  export const DSMM_STATUS_VERSION = 1;
7
8
  export function createDsmmStatusSnapshot(input) {
8
9
  const { agent, settings, modeActive } = input;
@@ -18,7 +19,10 @@ export function createDsmmStatusSnapshot(input) {
18
19
  }
19
20
  const inScope = modeActive || role !== undefined;
20
21
  const policy = role === undefined ? undefined : settings.roleRouting[role];
21
- const fallbacks = invalidDescriptor ? [] : effectiveRoleFallbackRoutes(settings, role);
22
+ const runtimePolicy = resolveRoleRuntimePolicy(settings, role);
23
+ const roleRuntimeState = input.roleRuntimeState ?? (input.admission === undefined || invalidDescriptor ? undefined
24
+ : roleRouteRuntimeState(agent, settings, role, input.admission.epoch));
25
+ const fallbacks = invalidDescriptor ? [] : runtimePolicy.fallbackRoutes;
22
26
  const selectedRoute = resolveRoute(agent);
23
27
  const family = classifyModelFamily({
24
28
  providerID: selectedRoute.provider,
@@ -30,14 +34,19 @@ export function createDsmmStatusSnapshot(input) {
30
34
  const deepseekFlash = selectedRoute.provider !== undefined && selectedRoute.model !== undefined
31
35
  && isDeepseekFlashRoute({ provider: selectedRoute.provider, model: selectedRoute.model });
32
36
  let acceptedRoleRoute;
33
- if (settings.runtimeRecovery.enabled && policy?.fallbackRoutes !== undefined) {
34
- acceptedRoleRoute = persistedRoleRoute({ agent }, policy.primary, fallbacks, rolePolicyIdentity(settings, role));
37
+ if (!invalidDescriptor && role !== undefined) {
38
+ acceptedRoleRoute = persistedRoleRoute({ agent }, policy?.primary, fallbacks, liveRolePolicyIdentity(agent, settings, role, input.admission?.epoch));
35
39
  }
36
40
  const exactRouting = policy?.primary !== undefined || acceptedRoleRoute !== undefined
37
41
  || fallbacks.some((route) => route.reasoningEffort !== undefined && route.provider === selectedRoute.provider
38
42
  && route.model === selectedRoute.model && route.reasoningEffort === selectedRoute.reasoningEffort);
39
43
  return {
40
44
  version: DSMM_STATUS_VERSION,
45
+ ...(input.admission === undefined ? {} : { admission: {
46
+ profile: input.admission.profile === null ? null : { ...input.admission.profile },
47
+ epoch: input.admission.epoch,
48
+ scope: input.admission.scope
49
+ } }),
41
50
  mode: {
42
51
  name: settings.modeName,
43
52
  active: modeActive,
@@ -65,10 +74,17 @@ export function createDsmmStatusSnapshot(input) {
65
74
  }),
66
75
  rolePolicy: {
67
76
  ...(role === undefined ? {} : { role }),
68
- applies: policy?.primary !== undefined || (settings.runtimeRecovery.enabled && policy?.fallbackRoutes !== undefined),
77
+ applies: inScope && !invalidDescriptor,
69
78
  ...(policy?.primary === undefined ? {} : { primary: { ...policy.primary } }),
70
79
  fallbackRoutes: fallbacks.map((route) => ({ ...route })),
71
- fallbackSource: !settings.runtimeRecovery.enabled ? "disabled" : policy?.fallbackRoutes === undefined ? "global" : "role",
80
+ fallbackSource: invalidDescriptor ? "disabled" : runtimePolicy.fallbackSource,
81
+ strategy: runtimePolicy.strategy,
82
+ rateLimit: { ...runtimePolicy.rateLimit },
83
+ ...(roleRuntimeState === undefined ? {} : { runtimeState: {
84
+ ...roleRuntimeState,
85
+ rateLimit: { ...roleRuntimeState.rateLimit },
86
+ ...(roleRuntimeState.route === undefined ? {} : { route: { ...roleRuntimeState.route } })
87
+ } }),
72
88
  ...(invalidDescriptor ? { diagnostic: "invalid-child-descriptor" } : {})
73
89
  },
74
90
  runtimeRecovery: {
@@ -102,9 +118,11 @@ export function formatDsmmStatus(snapshot) {
102
118
  "Deepwork status",
103
119
  `Mode: ${snapshot.mode.active ? "active" : "inactive"} (${snapshot.mode.name})`,
104
120
  `Scope: ${scope}`,
121
+ ...(snapshot.admission === undefined ? [] : [`Profile admission: ${snapshot.admission.scope}; profile=${snapshot.admission.profile?.id ?? "deployment baseline"}; epoch=${snapshot.admission.epoch}`]),
105
122
  `Workflow policy: ${snapshot.effectiveSettings.workflow.policy}`,
106
123
  `Route: ${provider}/${model} [${snapshot.route.family}]`,
107
- `Role policy: ${displayRole(snapshot.rolePolicy.role)}; primary=${snapshot.rolePolicy.primary === undefined ? "inherit" : `${snapshot.rolePolicy.primary.provider}/${snapshot.rolePolicy.primary.model}`}; fallbacks=${snapshot.rolePolicy.fallbackSource}`,
124
+ `Role policy: ${displayRole(snapshot.rolePolicy.role)}; strategy=${snapshot.rolePolicy.strategy}; primary=${snapshot.rolePolicy.primary === undefined ? "inherit" : `${snapshot.rolePolicy.primary.provider}/${snapshot.rolePolicy.primary.model}`}; fallbacks=${snapshot.rolePolicy.fallbackSource}; retries=${snapshot.rolePolicy.rateLimit.maxRetries}; threshold=${snapshot.rolePolicy.rateLimit.switchAfterRateLimits}; switches=${snapshot.rolePolicy.rateLimit.maxSwitches}`,
125
+ ...(snapshot.rolePolicy.runtimeState === undefined ? [] : [`Retry state: retries=${snapshot.rolePolicy.runtimeState.retries}; rate limits=${snapshot.rolePolicy.runtimeState.rateLimitFailures}; switches=${snapshot.rolePolicy.runtimeState.switches}; delay ms=${snapshot.rolePolicy.runtimeState.totalDelayMs}`]),
108
126
  `Reasoning: ${snapshot.calibration.mode}; policy=${policyEffort}; current=${currentReasoningEffort}; action=${snapshot.calibration.action}`,
109
127
  `Runtime recovery: ${snapshot.runtimeRecovery.enabled ? "enabled" : "disabled"}; applies=${snapshot.runtimeRecovery.applies ? "yes" : "no"}; fallbacks=${snapshot.runtimeRecovery.fallbackRouteCount}; max attempts=${snapshot.runtimeRecovery.maxFallbackAttempts}`,
110
128
  `Idle continuation: ${snapshot.runtimeRecovery.idleContinuation.enabled ? "enabled" : "disabled"}; max=${snapshot.runtimeRecovery.idleContinuation.maxContinuations}`,
@@ -168,8 +186,11 @@ function copySettings(settings) {
168
186
  roles: { ...settings.roles },
169
187
  roleRouting: Object.fromEntries(Object.entries(settings.roleRouting).map(([role, policy]) => [role, {
170
188
  ...(policy.primary === undefined ? {} : { primary: { ...policy.primary } }),
171
- ...(policy.fallbackRoutes === undefined ? {} : { fallbackRoutes: policy.fallbackRoutes.map((route) => ({ ...route })) })
189
+ ...(policy.fallbackRoutes === undefined ? {} : { fallbackRoutes: policy.fallbackRoutes.map((route) => ({ ...route })) }),
190
+ ...(policy.strategy === undefined ? {} : { strategy: policy.strategy }),
191
+ ...(policy.rateLimit === undefined ? {} : { rateLimit: { ...policy.rateLimit } })
172
192
  }])),
193
+ runtimePolicy: { strategy: settings.runtimePolicy.strategy, rateLimit: { ...settings.runtimePolicy.rateLimit } },
173
194
  presets: { ...settings.presets },
174
195
  workflow: { ...settings.workflow },
175
196
  guards: {