@dsmm/dsmm 0.1.1 → 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 (108) hide show
  1. package/README.md +26 -15
  2. package/agent-presets/dsmm-builder/agent.cordis.yml +14 -12
  3. package/agent-presets/dsmm-builder/preset.yml +1 -1
  4. package/agent-presets/dsmm-clarifier/agent.cordis.yml +4 -2
  5. package/agent-presets/dsmm-clarifier/preset.yml +1 -1
  6. package/agent-presets/dsmm-code-search/agent.cordis.yml +4 -2
  7. package/agent-presets/dsmm-code-search/preset.yml +1 -1
  8. package/agent-presets/dsmm-creative/agent.cordis.yml +3 -1
  9. package/agent-presets/dsmm-creative/preset.yml +1 -1
  10. package/agent-presets/dsmm-doc-search/agent.cordis.yml +4 -2
  11. package/agent-presets/dsmm-doc-search/preset.yml +1 -1
  12. package/agent-presets/dsmm-media-reader/agent.cordis.yml +4 -2
  13. package/agent-presets/dsmm-media-reader/preset.yml +1 -1
  14. package/agent-presets/dsmm-oracle/agent.cordis.yml +3 -1
  15. package/agent-presets/dsmm-oracle/preset.yml +1 -1
  16. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +3 -1
  17. package/agent-presets/dsmm-oracle-2nd/preset.yml +1 -1
  18. package/agent-presets/dsmm-orchestrator/agent.cordis.yml +15 -13
  19. package/agent-presets/dsmm-orchestrator/preset.yml +2 -2
  20. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +4 -2
  21. package/agent-presets/dsmm-plan-critic/preset.yml +1 -1
  22. package/agent-presets/dsmm-planner/agent.cordis.yml +4 -2
  23. package/agent-presets/dsmm-planner/preset.yml +1 -1
  24. package/agent-presets/dsmm-reviewer/agent.cordis.yml +4 -2
  25. package/agent-presets/dsmm-reviewer/preset.yml +1 -1
  26. package/docs/agent-presets.md +15 -5
  27. package/docs/compatibility.md +66 -11
  28. package/docs/migration-from-ocmm.md +8 -0
  29. package/docs/model-routing.md +25 -7
  30. package/docs/profiles.md +95 -0
  31. package/docs/releasing.md +66 -19
  32. package/docs/runtime-recovery.md +39 -14
  33. package/docs/settings-status.md +13 -5
  34. package/lib/client/ProfilesSection.d.ts +11 -0
  35. package/lib/client/ProfilesSection.js +66 -0
  36. package/lib/client/SessionProfiles.d.ts +19 -0
  37. package/lib/client/SessionProfiles.js +24 -0
  38. package/lib/client/StructuredEditor.d.ts +11 -0
  39. package/lib/client/StructuredEditor.js +74 -0
  40. package/lib/client/controller.d.ts +115 -0
  41. package/lib/client/controller.js +340 -0
  42. package/lib/client/index.d.ts +13 -0
  43. package/lib/client/index.js +54 -0
  44. package/lib/client/locales.d.ts +145 -0
  45. package/lib/client/locales.js +91 -0
  46. package/lib/client/session-labels.d.ts +8 -0
  47. package/lib/client/session-labels.js +13 -0
  48. package/lib/client/structured.d.ts +18 -0
  49. package/lib/client/structured.js +98 -0
  50. package/lib/client/styles.d.ts +3 -0
  51. package/lib/client/styles.js +36 -0
  52. package/lib/client.js +2825 -0
  53. package/lib/commands.d.ts +3 -3
  54. package/lib/commands.js +5 -4
  55. package/lib/dsh-types.d.ts +20 -0
  56. package/lib/guards.d.ts +2 -2
  57. package/lib/guards.js +3 -2
  58. package/lib/index.d.ts +12 -4
  59. package/lib/index.js +98 -20
  60. package/lib/mode.d.ts +2 -2
  61. package/lib/mode.js +1 -1
  62. package/lib/model-routing.d.ts +2 -2
  63. package/lib/model-routing.js +100 -15
  64. package/lib/preset-registry.js +5 -3
  65. package/lib/profile-remote.d.ts +37 -0
  66. package/lib/profile-remote.js +219 -0
  67. package/lib/profile-rpc.d.ts +35 -0
  68. package/lib/profile-rpc.js +187 -0
  69. package/lib/profile-runtime.d.ts +63 -0
  70. package/lib/profile-runtime.js +310 -0
  71. package/lib/profile-store.d.ts +60 -0
  72. package/lib/profile-store.js +588 -0
  73. package/lib/profile-types.d.ts +80 -0
  74. package/lib/profile-types.js +2 -0
  75. package/lib/profiles.d.ts +26 -0
  76. package/lib/profiles.js +269 -0
  77. package/lib/prompts.d.ts +2 -2
  78. package/lib/prompts.js +4 -4
  79. package/lib/role-providers.d.ts +2 -2
  80. package/lib/role-providers.js +49 -6
  81. package/lib/role-routing.d.ts +37 -3
  82. package/lib/role-routing.js +110 -35
  83. package/lib/role-subagents.d.ts +2 -2
  84. package/lib/role-subagents.js +6 -4
  85. package/lib/roles.d.ts +4 -0
  86. package/lib/roles.js +43 -27
  87. package/lib/routing-policy.d.ts +32 -0
  88. package/lib/routing-policy.js +92 -0
  89. package/lib/runtime-recovery.d.ts +2 -2
  90. package/lib/runtime-recovery.js +215 -54
  91. package/lib/session-metadata.d.ts +13 -0
  92. package/lib/session-metadata.js +34 -0
  93. package/lib/session-persistence.d.ts +35 -0
  94. package/lib/session-persistence.js +304 -0
  95. package/lib/settings.d.ts +34 -1
  96. package/lib/settings.js +33 -7
  97. package/lib/state.d.ts +1 -0
  98. package/lib/state.js +4 -0
  99. package/lib/status.d.ts +9 -1
  100. package/lib/status.js +34 -12
  101. package/locale/en.json +6 -0
  102. package/locale/zh.json +6 -0
  103. package/package.json +66 -15
  104. package/patches/agent-presets-root.example.cordis.patch.yml +6 -10
  105. package/prompts/deepseek-v4-pro.md +1 -1
  106. package/prompts/deepwork.md +3 -3
  107. package/scripts/repair-session-log.mjs +476 -0
  108. package/scripts/session-repair-native-verifier.mjs +367 -0
@@ -0,0 +1,304 @@
1
+ import { Context, Service } from "@deepseek-ai/cordis";
2
+ import { SessionHandleClosedError, SessionPersistence, SessionReadOnlyError, materializeAppendBatch } from "@deepseek-ai/dsh-session-persistence";
3
+ import JsonlSessionPersistence from "@deepseek-ai/dsh-session-persistence-jsonl";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { annotateDsmmEvent, DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
6
+ export { DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
7
+ /** Host-owned live routing; the native handle remains the sole storage/lock owner. */
8
+ class DsmmSessionHandle {
9
+ native;
10
+ cursor;
11
+ warn;
12
+ released;
13
+ chain = Promise.resolve();
14
+ closing;
15
+ buffered = [];
16
+ timer;
17
+ paused = false;
18
+ failure;
19
+ routingFailure;
20
+ constructor(native, cursor, warn, released) {
21
+ this.native = native;
22
+ this.cursor = cursor;
23
+ this.warn = warn;
24
+ this.released = released;
25
+ }
26
+ get id() { return this.native.id; }
27
+ get header() { return this.native.header; }
28
+ get access() { return this.native.access; }
29
+ get inheritedEventCount() { return this.native.inheritedEventCount; }
30
+ async read(offset, length, options) {
31
+ this.assertOpen("read");
32
+ return this.native.read(offset, length, options);
33
+ }
34
+ async append(events, options) {
35
+ this.assertOpen("append");
36
+ options?.signal?.throwIfAborted();
37
+ const batch = materializeAppendBatch(events).map(annotateDsmmEvent);
38
+ await this.enqueue(async () => {
39
+ options?.signal?.throwIfAborted();
40
+ if (this.access !== "write")
41
+ throw new SessionReadOnlyError(this.id, "append");
42
+ if (this.paused)
43
+ throw this.failure;
44
+ // Live records preceding this explicit batch must commit first. Later live
45
+ // records cannot overtake a direct append waiting on the mutation chain.
46
+ await this.drain(batch[0]?.seq ?? Number.POSITIVE_INFINITY, options?.signal);
47
+ await this.native.append(batch, options);
48
+ this.cursor += batch.length;
49
+ this.scheduleDrain();
50
+ });
51
+ }
52
+ async flush(options) {
53
+ this.assertOpen("flush");
54
+ await this.enqueue(async () => {
55
+ options?.signal?.throwIfAborted();
56
+ if (this.access !== "write")
57
+ throw new SessionReadOnlyError(this.id, "flush");
58
+ this.paused = false;
59
+ await this.drain(Number.POSITIVE_INFINITY, options?.signal);
60
+ await this.native.flush(options);
61
+ });
62
+ }
63
+ enqueueLive(event) {
64
+ if (this.closing !== undefined)
65
+ return;
66
+ let owned;
67
+ try {
68
+ owned = annotateDsmmEvent(materializeAppendBatch([event])[0]);
69
+ }
70
+ catch (error) {
71
+ this.routingFailure ??= error;
72
+ this.cancelTimer();
73
+ this.warn(this.id, error);
74
+ return;
75
+ }
76
+ this.buffered.push(owned);
77
+ this.scheduleDrain();
78
+ }
79
+ scheduleDrain() {
80
+ if (this.buffered.length === 0 || this.timer !== undefined || this.paused
81
+ || this.routingFailure !== undefined || this.closing !== undefined)
82
+ return;
83
+ this.timer = setTimeout(() => {
84
+ this.timer = undefined;
85
+ const last = this.buffered.at(-1);
86
+ if (last === undefined)
87
+ return;
88
+ // Fence this queued operation to the prefix accepted now. Events published
89
+ // after a later direct append is queued belong behind that append.
90
+ const beforeSeq = last.seq + 1;
91
+ void this.enqueue(async () => {
92
+ if (!this.paused) {
93
+ await this.drain(beforeSeq);
94
+ this.scheduleDrain();
95
+ }
96
+ }).catch((error) => this.warn(this.id, error));
97
+ }, 200);
98
+ }
99
+ close() {
100
+ return this.closing ??= this.enqueue(async () => {
101
+ this.cancelTimer();
102
+ const errors = [];
103
+ try {
104
+ this.paused = false;
105
+ await this.drain();
106
+ if (this.access === "write")
107
+ await this.native.flush();
108
+ }
109
+ catch (error) {
110
+ errors.push(error);
111
+ }
112
+ try {
113
+ await this.native.close();
114
+ }
115
+ catch (error) {
116
+ errors.push(error);
117
+ }
118
+ const failure = errors.length > 1 ? new AggregateError(errors, `session "${this.id}": close failed`)
119
+ : errors[0];
120
+ this.released(this, failure);
121
+ if (errors.length > 0)
122
+ throw failure;
123
+ });
124
+ }
125
+ [Symbol.asyncDispose]() { return this.close(); }
126
+ enqueue(operation) {
127
+ const next = this.chain.then(operation);
128
+ // The caller observes rejection; this recovery only keeps later barriers usable.
129
+ this.chain = next.then(() => undefined, () => undefined);
130
+ return next;
131
+ }
132
+ async drain(beforeSeq = Number.POSITIVE_INFINITY, signal) {
133
+ this.cancelTimer();
134
+ if (this.routingFailure !== undefined)
135
+ throw this.routingFailure;
136
+ while (this.buffered.length > 0 && this.buffered[0].seq < beforeSeq) {
137
+ signal?.throwIfAborted();
138
+ const count = this.buffered.findIndex((event) => event.seq >= beforeSeq);
139
+ const batch = this.buffered.slice(0, count < 0 ? undefined : count);
140
+ try {
141
+ // An explicitly appended event may subsequently be published by the live
142
+ // store. Coalesce only byte-equivalent logical events, never conflicts.
143
+ let duplicateCount = 0;
144
+ while (duplicateCount < batch.length && batch[duplicateCount].seq < this.cursor)
145
+ duplicateCount++;
146
+ if (duplicateCount > 0) {
147
+ const existing = await this.native.read(batch[0].seq, duplicateCount, { signal });
148
+ if (!isDeepStrictEqual(existing.events, batch.slice(0, duplicateCount))) {
149
+ throw new Error(`session "${this.id}": live event conflicts with the persisted prefix`);
150
+ }
151
+ }
152
+ const fresh = batch.slice(duplicateCount);
153
+ await this.native.append(fresh, { signal });
154
+ this.cursor += fresh.length;
155
+ this.buffered.splice(0, batch.length);
156
+ this.failure = undefined;
157
+ }
158
+ catch (error) {
159
+ this.cancelTimer();
160
+ this.paused = true;
161
+ this.failure = error;
162
+ throw error;
163
+ }
164
+ }
165
+ }
166
+ cancelTimer() {
167
+ if (this.timer !== undefined)
168
+ clearTimeout(this.timer);
169
+ this.timer = undefined;
170
+ }
171
+ assertOpen(operation) {
172
+ if (this.closing !== undefined)
173
+ throw new SessionHandleClosedError(this.id, operation);
174
+ }
175
+ }
176
+ /**
177
+ * Drop-in native JSONL persistence companion for audited DSMM metadata.
178
+ * A separate root Context is intentional: a child service-isolation scope still
179
+ * shares the host event bus and would persist every live event twice.
180
+ */
181
+ export default class DsmmSessionPersistence extends SessionPersistence {
182
+ config;
183
+ static Config = JsonlSessionPersistence.Config;
184
+ name = "dsmm-session-persistence";
185
+ inner = new Context();
186
+ ready;
187
+ handles = new Set();
188
+ writers = new Map();
189
+ acquisitions = new Set();
190
+ closeFailures = new Map();
191
+ disposed = false;
192
+ constructor(ctx, config) {
193
+ super(ctx);
194
+ this.config = config;
195
+ Object.defineProperty(this, DSMM_PERSISTENCE_COMPATIBILITY, {
196
+ value: true, writable: false, configurable: false, enumerable: false
197
+ });
198
+ const nativeFiber = this.inner.plugin(JsonlSessionPersistence, config);
199
+ this.ready = nativeFiber.await().then(() => this.inner.sessionPersistence);
200
+ ctx.on("session/event", (session, event) => this.writers.get(session.id)?.enqueueLive(event));
201
+ ctx.on("session/flush", (session) => this.writers.get(session.id)?.flush());
202
+ ctx.on("session/disposed", (session) => {
203
+ const writer = this.writers.get(session.id);
204
+ if (writer !== undefined)
205
+ void writer.close().catch((error) => this.warn(session.id, error));
206
+ });
207
+ // One outer disposer enforces the ownership boundary: drain/close every
208
+ // adapter handle before disposing the still-live native storage Context.
209
+ ctx.effect(() => async () => {
210
+ this.disposed = true;
211
+ await Promise.allSettled([...this.acquisitions]);
212
+ const errors = [...this.closeFailures.values()];
213
+ for (const handle of [...this.handles]) {
214
+ try {
215
+ await handle.close();
216
+ }
217
+ catch (error) {
218
+ errors.push(error);
219
+ }
220
+ }
221
+ try {
222
+ await this.inner.fiber.dispose();
223
+ }
224
+ catch (error) {
225
+ errors.push(error);
226
+ }
227
+ if (errors.length > 0)
228
+ throw new AggregateError(errors, `${this.name} dispose failed`);
229
+ }, "dsmm-session-persistence ordered shutdown");
230
+ }
231
+ async [Service.init]() { await this.ready; }
232
+ create(header, options) {
233
+ return this.acquire(async (native) => native.create(header, options), false);
234
+ }
235
+ open(id, access, options) {
236
+ return this.acquire(async (native) => native.open(id, access, options), access === "write");
237
+ }
238
+ async flush() {
239
+ this.assertActive();
240
+ const errors = [];
241
+ for (const handle of [...this.writers.values()]) {
242
+ try {
243
+ await handle.flush();
244
+ }
245
+ catch (error) {
246
+ if (!(error instanceof SessionHandleClosedError))
247
+ errors.push(error);
248
+ }
249
+ }
250
+ if (errors.length > 0)
251
+ throw new AggregateError(errors, `${this.name} flush failed`);
252
+ }
253
+ async stat(id, options) {
254
+ this.assertActive();
255
+ return (await this.ready).stat(id, options);
256
+ }
257
+ async list(options) {
258
+ this.assertActive();
259
+ return (await this.ready).list(options);
260
+ }
261
+ acquire(factory, existing) {
262
+ this.assertActive();
263
+ const operation = (async () => {
264
+ const native = await factory(await this.ready);
265
+ let cursor = 0;
266
+ try {
267
+ if (existing)
268
+ cursor = (await native.read()).events.length;
269
+ }
270
+ catch (error) {
271
+ try {
272
+ await native.close();
273
+ }
274
+ catch (closeError) {
275
+ throw new AggregateError([error, closeError], `session "${native.id}": open failed`);
276
+ }
277
+ throw error;
278
+ }
279
+ const handle = new DsmmSessionHandle(native, cursor, (id, error) => this.warn(id, error), (closed, error) => {
280
+ this.handles.delete(closed);
281
+ if (this.writers.get(closed.id) === closed)
282
+ this.writers.delete(closed.id);
283
+ if (error !== undefined)
284
+ this.closeFailures.set(closed.id, error);
285
+ });
286
+ this.handles.add(handle);
287
+ if (handle.access === "write")
288
+ this.writers.set(handle.id, handle);
289
+ return handle;
290
+ })();
291
+ this.acquisitions.add(operation);
292
+ void operation.then(() => this.acquisitions.delete(operation), () => this.acquisitions.delete(operation));
293
+ return operation;
294
+ }
295
+ warn(id, error) {
296
+ const errorClass = error instanceof Error && /^[A-Za-z][A-Za-z0-9]*Error$/u.test(error.name) ? error.name : "Error";
297
+ this.ctx.logger.warn("Deepwork session persistence failed", { sessionId: id, errorClass });
298
+ }
299
+ assertActive() {
300
+ if (this.disposed)
301
+ throw new Error("Deepwork session persistence is disposed");
302
+ }
303
+ }
304
+ //# sourceMappingURL=session-persistence.js.map
package/lib/settings.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import Schema from "@deepseek-ai/schemastery";
2
- import type { DshContext } from "./dsh-types.js";
2
+ 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 {
@@ -68,6 +73,11 @@ type DsmmRuntimeRecoveryConfig = Partial<Omit<DsmmRuntimeRecoverySettings, "fall
68
73
  idleContinuation?: Partial<DsmmRuntimeRecoverySettings["idleContinuation"]>;
69
74
  };
70
75
  export interface DsmmPluginConfig {
76
+ /** Startup-only native storage binding; never a runtime-profile field. */
77
+ sessionPersistence?: {
78
+ root: string;
79
+ compression?: "zstd" | "none";
80
+ };
71
81
  modeName?: string;
72
82
  section?: string;
73
83
  deepseekV4ProCalibration?: DeepseekCalibration;
@@ -81,6 +91,7 @@ export interface DsmmPluginConfig {
81
91
  skills?: Partial<Record<DsmmSkillName, boolean>>;
82
92
  roles?: Partial<Record<DsmmRoleId, boolean>>;
83
93
  roleRouting?: DsmmRoleRouting;
94
+ runtimePolicy?: DsmmRuntimePolicyConfig;
84
95
  presets?: Partial<DsmmPresetSettings>;
85
96
  workflow?: Partial<DsmmWorkflowSettings>;
86
97
  guards?: DsmmGuardConfig;
@@ -100,12 +111,34 @@ export interface DsmmSettings {
100
111
  skills: Record<DsmmSkillName, boolean>;
101
112
  roles: Record<DsmmRoleId, boolean>;
102
113
  roleRouting: DsmmRoleRouting;
114
+ runtimePolicy: DsmmRuntimePolicySettings;
103
115
  presets: DsmmPresetSettings;
104
116
  workflow: DsmmWorkflowSettings;
105
117
  guards: DsmmGuardSettings;
106
118
  runtimeRecovery: DsmmRuntimeRecoverySettings;
107
119
  lsp: DsmmLspSettings;
108
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
+ }
131
+ /** Runtime consumers pass their Agent so immutable profile admission is retained. */
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
+ }
109
142
  export declare const DSMM_SETTINGS_NAMESPACE = "dsmm";
110
143
  export declare const DSMM_STATUS_COMMAND = "dsmm-status";
111
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),
@@ -188,6 +195,10 @@ const LSP_SCHEMA = Schema.object({
188
195
  failOnStartupError: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.lsp.failOnStartupError)
189
196
  });
190
197
  export const DSMM_CONFIG_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SCHEMA, Schema.object({
198
+ sessionPersistence: Schema.union([Schema.const(undefined), Schema.object({
199
+ root: Schema.string().required(),
200
+ compression: Schema.union([Schema.const("zstd"), Schema.const("none")])
201
+ })]),
191
202
  modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
192
203
  section: Schema.string(),
193
204
  defaultActive: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.defaultActive),
@@ -201,6 +212,7 @@ export const DSMM_CONFIG_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SCHE
201
212
  skills: SKILLS_SCHEMA,
202
213
  roles: ROLES_SCHEMA,
203
214
  roleRouting: ROLE_ROUTING_SCHEMA,
215
+ runtimePolicy: Schema.any(),
204
216
  presets: PRESETS_SCHEMA,
205
217
  workflow: WORKFLOW_CONFIG_SCHEMA,
206
218
  guards: GUARDS_SCHEMA,
@@ -220,6 +232,7 @@ export const DSMM_SETTINGS_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SC
220
232
  skills: SKILLS_SCHEMA,
221
233
  roles: ROLES_SCHEMA,
222
234
  roleRouting: ROLE_ROUTING_SCHEMA,
235
+ runtimePolicy: Schema.any(),
223
236
  presets: PRESETS_SCHEMA,
224
237
  workflow: WORKFLOW_SCHEMA,
225
238
  guards: GUARDS_SCHEMA,
@@ -227,7 +240,7 @@ export const DSMM_SETTINGS_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SC
227
240
  lsp: LSP_SCHEMA
228
241
  })]).default({});
229
242
  export function resolveConfig(config = {}) {
230
- return {
243
+ const settings = {
231
244
  modeName: normalizeModeName(config.modeName),
232
245
  defaultActive: config.defaultActive ?? DEFAULT_DSMM_SETTINGS.defaultActive,
233
246
  promptOrder: config.promptOrder ?? DEFAULT_DSMM_SETTINGS.promptOrder,
@@ -240,12 +253,21 @@ export function resolveConfig(config = {}) {
240
253
  skills: { ...DEFAULT_DSMM_SETTINGS.skills, ...config.skills },
241
254
  roles: { ...DEFAULT_DSMM_SETTINGS.roles, ...config.roles },
242
255
  roleRouting: resolveRoleRouting(config.roleRouting),
256
+ runtimePolicy: normalizeRuntimePolicy(Object.hasOwn(config, "runtimePolicy") ? validatePresentRuntimePolicy(config.runtimePolicy) : undefined),
243
257
  presets: resolvePresetSettings(config.presets),
244
258
  workflow: resolveWorkflowSettings(config.workflow),
245
259
  guards: resolveGuardSettings(config.guards),
246
260
  runtimeRecovery: resolveRuntimeRecoverySettings(config.runtimeRecovery),
247
261
  lsp: resolveLspSettings(config.lsp)
248
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;
249
271
  }
250
272
  function resolveMaxReasoningPresets(input, defaults) {
251
273
  const requested = new Set(input ?? defaults);
@@ -260,15 +282,19 @@ export function resolveRoleRouting(input) {
260
282
  for (const [key, value] of Object.entries(input)) {
261
283
  if (!DSMM_ROLE_IDS.includes(key))
262
284
  throw new TypeError("dsmm roleRouting contains an unknown role");
263
- if (!isRoutingRecord(value) || Object.keys(value).some((field) => field !== "primary" && field !== "fallbackRoutes")) {
264
- 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");
265
287
  }
266
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);
267
293
  if (Object.hasOwn(value, "primary"))
268
294
  policy.primary = normalizeExplicitRoute(value.primary);
269
295
  if (Object.hasOwn(value, "fallbackRoutes")) {
270
- if (!Array.isArray(value.fallbackRoutes))
271
- 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");
272
298
  policy.fallbackRoutes = [];
273
299
  for (const entry of value.fallbackRoutes) {
274
300
  const route = normalizeExplicitRoute(entry);
package/lib/state.d.ts CHANGED
@@ -4,6 +4,7 @@ export type DeepworkSelectionOutcome = "committed" | "pending" | "unchanged";
4
4
  export declare function isDeepworkActive(events?: readonly DshSessionEvent[], defaultActive?: boolean): boolean;
5
5
  export declare function hasOpenTurn(events?: readonly DshSessionEvent[]): boolean;
6
6
  export declare class DeepworkModeController {
7
+ private readonly ctx;
7
8
  private readonly pending;
8
9
  constructor(ctx: DshContext);
9
10
  active(agent: DshAgent | undefined, defaultActive: boolean): boolean;
package/lib/state.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { sessionEvents } from "./session-scope.js";
2
+ import { assertDsmmMetadataPersistence } from "./session-metadata.js";
2
3
  export const DEEPWORK_MODE_EVENT = "deepwork/mode";
3
4
  function activeFromEvent(event) {
4
5
  if (event.type !== DEEPWORK_MODE_EVENT)
@@ -25,8 +26,10 @@ export function hasOpenTurn(events = []) {
25
26
  return open;
26
27
  }
27
28
  export class DeepworkModeController {
29
+ ctx;
28
30
  pending = new WeakMap();
29
31
  constructor(ctx) {
32
+ this.ctx = ctx;
30
33
  ctx.on?.("agent/pre-step", async (frame, next) => {
31
34
  const decision = await next();
32
35
  const intent = this.pending.get(frame.agent.session);
@@ -57,6 +60,7 @@ export class DeepworkModeController {
57
60
  return "committed";
58
61
  }
59
62
  async commit(session, active) {
63
+ assertDsmmMetadataPersistence(this.ctx);
60
64
  await session.append(DEEPWORK_MODE_EVENT, { active });
61
65
  this.pending.delete(session);
62
66
  }
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