@dsmm/dsmm 0.1.0 → 0.1.4

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 (104) hide show
  1. package/README.md +26 -12
  2. package/agent-presets/dsmm-builder/agent.cordis.yml +25 -23
  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 +26 -24
  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 +17 -5
  27. package/docs/compatibility.md +68 -12
  28. package/docs/migration-from-ocmm.md +10 -4
  29. package/docs/model-routing.md +50 -1
  30. package/docs/profiles.md +83 -0
  31. package/docs/releasing.md +59 -18
  32. package/docs/roadmap.md +1 -1
  33. package/docs/runtime-recovery.md +10 -2
  34. package/docs/settings-status.md +16 -4
  35. package/lib/client/ProfilesSection.d.ts +11 -0
  36. package/lib/client/ProfilesSection.js +62 -0
  37. package/lib/client/controller.d.ts +77 -0
  38. package/lib/client/controller.js +198 -0
  39. package/lib/client/index.d.ts +11 -0
  40. package/lib/client/index.js +34 -0
  41. package/lib/client/locales.d.ts +56 -0
  42. package/lib/client/locales.js +48 -0
  43. package/lib/client/styles.d.ts +3 -0
  44. package/lib/client/styles.js +25 -0
  45. package/lib/client.js +1930 -0
  46. package/lib/commands.d.ts +3 -3
  47. package/lib/commands.js +4 -4
  48. package/lib/dsh-events.d.ts +8 -0
  49. package/lib/dsh-types.d.ts +8 -0
  50. package/lib/guards.d.ts +2 -2
  51. package/lib/guards.js +3 -2
  52. package/lib/index.d.ts +16 -6
  53. package/lib/index.js +77 -21
  54. package/lib/mode.d.ts +2 -2
  55. package/lib/mode.js +1 -1
  56. package/lib/model-routing.d.ts +2 -2
  57. package/lib/model-routing.js +44 -4
  58. package/lib/preset-materializer.js +2 -2
  59. package/lib/preset-registry.js +4 -2
  60. package/lib/profile-remote.d.ts +31 -0
  61. package/lib/profile-remote.js +106 -0
  62. package/lib/profile-rpc.d.ts +27 -0
  63. package/lib/profile-rpc.js +90 -0
  64. package/lib/profile-runtime.d.ts +44 -0
  65. package/lib/profile-runtime.js +159 -0
  66. package/lib/profile-store.d.ts +42 -0
  67. package/lib/profile-store.js +478 -0
  68. package/lib/profile-types.d.ts +40 -0
  69. package/lib/profile-types.js +2 -0
  70. package/lib/profiles.d.ts +26 -0
  71. package/lib/profiles.js +237 -0
  72. package/lib/prompts.d.ts +2 -2
  73. package/lib/prompts.js +4 -4
  74. package/lib/recovery-policy.js +1 -1
  75. package/lib/role-providers.d.ts +13 -0
  76. package/lib/role-providers.js +94 -0
  77. package/lib/role-routing.d.ts +15 -0
  78. package/lib/role-routing.js +147 -0
  79. package/lib/role-subagents.d.ts +2 -2
  80. package/lib/role-subagents.js +6 -4
  81. package/lib/roles.d.ts +9 -4
  82. package/lib/roles.js +54 -36
  83. package/lib/runtime-recovery.d.ts +2 -2
  84. package/lib/runtime-recovery.js +36 -17
  85. package/lib/session-metadata.d.ts +13 -0
  86. package/lib/session-metadata.js +34 -0
  87. package/lib/session-persistence.d.ts +35 -0
  88. package/lib/session-persistence.js +304 -0
  89. package/lib/session-scope.d.ts +6 -1
  90. package/lib/session-scope.js +23 -0
  91. package/lib/settings.d.ts +20 -2
  92. package/lib/settings.js +127 -39
  93. package/lib/state.d.ts +1 -0
  94. package/lib/state.js +4 -0
  95. package/lib/status.d.ts +11 -2
  96. package/lib/status.js +52 -13
  97. package/locale/en.json +6 -0
  98. package/locale/zh.json +6 -0
  99. package/package.json +67 -15
  100. package/patches/agent-presets-root.example.cordis.patch.yml +6 -10
  101. package/prompts/deepseek-v4-pro.md +1 -1
  102. package/prompts/deepwork.md +3 -3
  103. package/scripts/repair-session-log.mjs +476 -0
  104. 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
@@ -1,4 +1,9 @@
1
- import type { DshSession, DshSessionEvent } from "./dsh-types.js";
1
+ import type { DshAgent, DshSession, DshSessionEvent } from "./dsh-types.js";
2
+ import type { DsmmRoleId } from "./roles.js";
3
+ import type { DsmmSettings } from "./settings.js";
2
4
  export declare function sessionEvents(session: DshSession | undefined): readonly DshSessionEvent[];
3
5
  export declare function resolveSelectedAgentPreset(session: DshSession | undefined): string | undefined;
6
+ export declare function childOwnedSessionEvents(session: DshSession): readonly DshSessionEvent[];
7
+ /** Parent preset/persona inheritance is deliberately not delegated role authority. */
8
+ export declare function resolveEffectiveDsmmRole(agent: DshAgent, settings: DsmmSettings, modeActive: boolean): DsmmRoleId | undefined;
4
9
  //# sourceMappingURL=session-scope.d.ts.map
@@ -1,3 +1,6 @@
1
+ import { foldSubagentDescriptor } from "@deepseek-ai/dsh-subagent";
2
+ import { isDsmmRoleId } from "./roles.js";
3
+ import { roleFromProviderName } from "./role-providers.js";
1
4
  export function sessionEvents(session) {
2
5
  return session?.snapshotEvents?.() ?? session?.events ?? [];
3
6
  }
@@ -14,4 +17,24 @@ export function resolveSelectedAgentPreset(session) {
14
17
  }
15
18
  return typeof session?.header?.agentPreset === "string" ? session.header.agentPreset : undefined;
16
19
  }
20
+ export function childOwnedSessionEvents(session) {
21
+ const inherited = session.inheritedEventCount ?? 0;
22
+ if (!Number.isSafeInteger(inherited) || inherited < 0)
23
+ throw new TypeError("dsmm cannot classify an invalid inherited event boundary");
24
+ return sessionEvents(session).slice(inherited);
25
+ }
26
+ /** Parent preset/persona inheritance is deliberately not delegated role authority. */
27
+ export function resolveEffectiveDsmmRole(agent, settings, modeActive) {
28
+ let role;
29
+ if (agent.session.header?.origin === "subagent") {
30
+ const own = childOwnedSessionEvents(agent.session);
31
+ const descriptor = foldSubagentDescriptor(own);
32
+ role = descriptor?.mode === "one-shot" ? roleFromProviderName(descriptor.provider) : undefined;
33
+ }
34
+ else {
35
+ const preset = resolveSelectedAgentPreset(agent.session);
36
+ role = isDsmmRoleId(preset) ? preset : modeActive ? "dsmm-orchestrator" : undefined;
37
+ }
38
+ return role !== undefined && settings.roles[role] ? role : undefined;
39
+ }
17
40
  //# sourceMappingURL=session-scope.js.map
package/lib/settings.d.ts CHANGED
@@ -1,5 +1,5 @@
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";
@@ -35,10 +35,18 @@ export interface DsmmGuardSettings {
35
35
  };
36
36
  todoDisciplineHelper: boolean;
37
37
  }
38
- export interface DsmmRecoveryRoute {
38
+ export interface DsmmModelRoute {
39
39
  provider: string;
40
40
  model: string;
41
+ reasoningEffort?: string;
41
42
  }
43
+ export interface DsmmRecoveryRoute extends DsmmModelRoute {
44
+ }
45
+ export interface DsmmRoleRoutingConfig {
46
+ primary?: DsmmModelRoute;
47
+ fallbackRoutes?: DsmmModelRoute[];
48
+ }
49
+ export type DsmmRoleRouting = Partial<Record<DsmmRoleId, DsmmRoleRoutingConfig>>;
42
50
  export interface DsmmRuntimeRecoverySettings {
43
51
  enabled: boolean;
44
52
  retryOnStatusCodes: number[];
@@ -60,6 +68,11 @@ type DsmmRuntimeRecoveryConfig = Partial<Omit<DsmmRuntimeRecoverySettings, "fall
60
68
  idleContinuation?: Partial<DsmmRuntimeRecoverySettings["idleContinuation"]>;
61
69
  };
62
70
  export interface DsmmPluginConfig {
71
+ /** Startup-only native storage binding; never a runtime-profile field. */
72
+ sessionPersistence?: {
73
+ root: string;
74
+ compression?: "zstd" | "none";
75
+ };
63
76
  modeName?: string;
64
77
  section?: string;
65
78
  deepseekV4ProCalibration?: DeepseekCalibration;
@@ -72,6 +85,7 @@ export interface DsmmPluginConfig {
72
85
  promptOrder?: number;
73
86
  skills?: Partial<Record<DsmmSkillName, boolean>>;
74
87
  roles?: Partial<Record<DsmmRoleId, boolean>>;
88
+ roleRouting?: DsmmRoleRouting;
75
89
  presets?: Partial<DsmmPresetSettings>;
76
90
  workflow?: Partial<DsmmWorkflowSettings>;
77
91
  guards?: DsmmGuardConfig;
@@ -90,12 +104,15 @@ export interface DsmmSettings {
90
104
  deepseekFlashMaxReasoningPresets: DsmmRoleId[];
91
105
  skills: Record<DsmmSkillName, boolean>;
92
106
  roles: Record<DsmmRoleId, boolean>;
107
+ roleRouting: DsmmRoleRouting;
93
108
  presets: DsmmPresetSettings;
94
109
  workflow: DsmmWorkflowSettings;
95
110
  guards: DsmmGuardSettings;
96
111
  runtimeRecovery: DsmmRuntimeRecoverySettings;
97
112
  lsp: DsmmLspSettings;
98
113
  }
114
+ /** Runtime consumers pass their Agent so immutable profile admission is retained. */
115
+ export type DsmmSettingsGetter = (agent?: DshAgent) => DsmmSettings;
99
116
  export declare const DSMM_SETTINGS_NAMESPACE = "dsmm";
100
117
  export declare const DSMM_STATUS_COMMAND = "dsmm-status";
101
118
  export interface RegisterSettingsOptions {
@@ -106,6 +123,7 @@ export declare const DEFAULT_DSMM_SETTINGS: DsmmSettings;
106
123
  export declare const DSMM_CONFIG_SCHEMA: Schema<DsmmPluginConfig>;
107
124
  export declare const DSMM_SETTINGS_SCHEMA: Schema<DsmmSettings>;
108
125
  export declare function resolveConfig(config?: DsmmPluginConfig): DsmmSettings;
126
+ export declare function resolveRoleRouting(input: DsmmRoleRouting | undefined): DsmmRoleRouting;
109
127
  export declare function isRoleEnabled(settings: DsmmSettings, role: DsmmRoleId): boolean;
110
128
  export declare function resolveGuardSettings(config: DsmmPluginConfig["guards"]): DsmmGuardSettings;
111
129
  export declare function registerSettings(ctx: DshContext, config?: DsmmPluginConfig, options?: RegisterSettingsOptions): () => DsmmSettings;
package/lib/settings.js CHANGED
@@ -17,6 +17,7 @@ export const DEFAULT_DSMM_SETTINGS = {
17
17
  deepseekFlashMaxReasoningPresets: ["dsmm-plan-critic", "dsmm-reviewer"],
18
18
  skills: createDefaultSkillSettings(),
19
19
  roles: createDefaultRoleSettings(),
20
+ roleRouting: {},
20
21
  presets: {
21
22
  materialize: false
22
23
  },
@@ -74,6 +75,29 @@ const SKILLS_SCHEMA = Schema.object({
74
75
  "remove-ai-slops": Schema.boolean().default(DEFAULT_DSMM_SETTINGS.skills["remove-ai-slops"])
75
76
  });
76
77
  const ROLES_SCHEMA = Schema.object(Object.fromEntries(DSMM_ROLE_IDS.map((id) => [id, Schema.boolean().default(DEFAULT_DSMM_SETTINGS.roles[id])])));
78
+ const MODEL_ROUTE_SCHEMA = Schema.object({
79
+ provider: Schema.string().required(),
80
+ model: Schema.string().required(),
81
+ reasoningEffort: Schema.string()
82
+ });
83
+ // A dictionary retains unknown keys for fail-closed validation by the resolver.
84
+ const ROLE_ROUTING_SCHEMA = Schema.dict(Schema.object({
85
+ primary: Schema.union([Schema.const(undefined), MODEL_ROUTE_SCHEMA]),
86
+ fallbackRoutes: Schema.union([Schema.const(undefined), Schema.array(MODEL_ROUTE_SCHEMA)])
87
+ }).required()).default({});
88
+ // Schemastery treats null like an omitted default. Validate the untouched map
89
+ // before object defaults can erase an explicitly malformed routing policy.
90
+ const ROLE_ROUTING_VALIDATION_SCHEMA = Schema.transform(Schema.any(), (input) => {
91
+ if (!isRoutingRecord(input))
92
+ return input;
93
+ if (isRoutingRecord(input.runtimeRecovery) && Array.isArray(input.runtimeRecovery.fallbackRoutes)) {
94
+ for (const route of input.runtimeRecovery.fallbackRoutes) {
95
+ if (isRoutingRecord(route))
96
+ normalizeRecoveryEffort(route);
97
+ }
98
+ }
99
+ return { roleRouting: resolveRoleRouting(input.roleRouting) };
100
+ });
77
101
  const PRESETS_SCHEMA = Schema.object({
78
102
  materialize: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.presets.materialize),
79
103
  root: Schema.string()
@@ -135,7 +159,8 @@ const RUNTIME_RECOVERY_SCHEMA = Schema.object({
135
159
  retryOnCodes: Schema.array(String).default([...DEFAULT_DSMM_SETTINGS.runtimeRecovery.retryOnCodes]),
136
160
  fallbackRoutes: Schema.array(Schema.object({
137
161
  provider: Schema.string(),
138
- model: Schema.string()
162
+ model: Schema.string(),
163
+ reasoningEffort: Schema.string()
139
164
  })).default(DEFAULT_DSMM_SETTINGS.runtimeRecovery.fallbackRoutes.map((route) => ({ ...route }))),
140
165
  maxFallbackAttempts: Schema.number().default(DEFAULT_DSMM_SETTINGS.runtimeRecovery.maxFallbackAttempts),
141
166
  idleContinuation: RUNTIME_RECOVERY_IDLE_CONTINUATION_SCHEMA
@@ -162,43 +187,49 @@ const LSP_SCHEMA = Schema.object({
162
187
  toolCallTimeoutMs: Schema.number().default(DEFAULT_DSMM_SETTINGS.lsp.toolCallTimeoutMs),
163
188
  failOnStartupError: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.lsp.failOnStartupError)
164
189
  });
165
- export const DSMM_CONFIG_SCHEMA = Schema.object({
166
- modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
167
- section: Schema.string(),
168
- defaultActive: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.defaultActive),
169
- promptOrder: Schema.number().default(DEFAULT_DSMM_SETTINGS.promptOrder),
170
- deepseekV4ProCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
171
- deepseekV4ProDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
172
- deepseekV4ProMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
173
- deepseekFlashCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
174
- deepseekFlashDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
175
- deepseekFlashMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
176
- skills: SKILLS_SCHEMA,
177
- roles: ROLES_SCHEMA,
178
- presets: PRESETS_SCHEMA,
179
- workflow: WORKFLOW_CONFIG_SCHEMA,
180
- guards: GUARDS_SCHEMA,
181
- runtimeRecovery: RUNTIME_RECOVERY_SCHEMA,
182
- lsp: LSP_SCHEMA
183
- });
184
- export const DSMM_SETTINGS_SCHEMA = Schema.object({
185
- modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
186
- defaultActive: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.defaultActive),
187
- promptOrder: Schema.number().default(DEFAULT_DSMM_SETTINGS.promptOrder),
188
- deepseekV4ProCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
189
- deepseekV4ProDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
190
- deepseekV4ProMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
191
- deepseekFlashCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
192
- deepseekFlashDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
193
- deepseekFlashMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
194
- skills: SKILLS_SCHEMA,
195
- roles: ROLES_SCHEMA,
196
- presets: PRESETS_SCHEMA,
197
- workflow: WORKFLOW_SCHEMA,
198
- guards: GUARDS_SCHEMA,
199
- runtimeRecovery: RUNTIME_RECOVERY_SCHEMA,
200
- lsp: LSP_SCHEMA
201
- });
190
+ export const DSMM_CONFIG_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SCHEMA, Schema.object({
191
+ sessionPersistence: Schema.union([Schema.const(undefined), Schema.object({
192
+ root: Schema.string().required(),
193
+ compression: Schema.union([Schema.const("zstd"), Schema.const("none")])
194
+ })]),
195
+ modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
196
+ section: Schema.string(),
197
+ defaultActive: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.defaultActive),
198
+ promptOrder: Schema.number().default(DEFAULT_DSMM_SETTINGS.promptOrder),
199
+ deepseekV4ProCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
200
+ deepseekV4ProDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
201
+ deepseekV4ProMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
202
+ deepseekFlashCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
203
+ deepseekFlashDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
204
+ deepseekFlashMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
205
+ skills: SKILLS_SCHEMA,
206
+ roles: ROLES_SCHEMA,
207
+ roleRouting: ROLE_ROUTING_SCHEMA,
208
+ presets: PRESETS_SCHEMA,
209
+ workflow: WORKFLOW_CONFIG_SCHEMA,
210
+ guards: GUARDS_SCHEMA,
211
+ runtimeRecovery: RUNTIME_RECOVERY_SCHEMA,
212
+ lsp: LSP_SCHEMA
213
+ })]).default({});
214
+ export const DSMM_SETTINGS_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SCHEMA, Schema.object({
215
+ modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
216
+ defaultActive: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.defaultActive),
217
+ promptOrder: Schema.number().default(DEFAULT_DSMM_SETTINGS.promptOrder),
218
+ deepseekV4ProCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
219
+ deepseekV4ProDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
220
+ deepseekV4ProMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
221
+ deepseekFlashCalibration: DEEPSEEK_CALIBRATION_SCHEMA,
222
+ deepseekFlashDefaultReasoningEffort: DEEPSEEK_DEFAULT_REASONING_EFFORT_SCHEMA,
223
+ deepseekFlashMaxReasoningPresets: DEEPSEEK_MAX_REASONING_PRESETS_SCHEMA,
224
+ skills: SKILLS_SCHEMA,
225
+ roles: ROLES_SCHEMA,
226
+ roleRouting: ROLE_ROUTING_SCHEMA,
227
+ presets: PRESETS_SCHEMA,
228
+ workflow: WORKFLOW_SCHEMA,
229
+ guards: GUARDS_SCHEMA,
230
+ runtimeRecovery: RUNTIME_RECOVERY_SCHEMA,
231
+ lsp: LSP_SCHEMA
232
+ })]).default({});
202
233
  export function resolveConfig(config = {}) {
203
234
  return {
204
235
  modeName: normalizeModeName(config.modeName),
@@ -212,6 +243,7 @@ export function resolveConfig(config = {}) {
212
243
  deepseekFlashMaxReasoningPresets: resolveMaxReasoningPresets(config.deepseekFlashMaxReasoningPresets, DEFAULT_DSMM_SETTINGS.deepseekFlashMaxReasoningPresets),
213
244
  skills: { ...DEFAULT_DSMM_SETTINGS.skills, ...config.skills },
214
245
  roles: { ...DEFAULT_DSMM_SETTINGS.roles, ...config.roles },
246
+ roleRouting: resolveRoleRouting(config.roleRouting),
215
247
  presets: resolvePresetSettings(config.presets),
216
248
  workflow: resolveWorkflowSettings(config.workflow),
217
249
  guards: resolveGuardSettings(config.guards),
@@ -223,6 +255,53 @@ function resolveMaxReasoningPresets(input, defaults) {
223
255
  const requested = new Set(input ?? defaults);
224
256
  return DSMM_ROLE_IDS.filter((id) => requested.has(id));
225
257
  }
258
+ export function resolveRoleRouting(input) {
259
+ if (input === undefined)
260
+ return {};
261
+ if (!isRoutingRecord(input))
262
+ throw new TypeError("dsmm roleRouting must be an object");
263
+ const result = {};
264
+ for (const [key, value] of Object.entries(input)) {
265
+ if (!DSMM_ROLE_IDS.includes(key))
266
+ 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");
269
+ }
270
+ const policy = {};
271
+ if (Object.hasOwn(value, "primary"))
272
+ policy.primary = normalizeExplicitRoute(value.primary);
273
+ if (Object.hasOwn(value, "fallbackRoutes")) {
274
+ if (!Array.isArray(value.fallbackRoutes))
275
+ throw new TypeError("dsmm roleRouting fallbackRoutes must be an array");
276
+ policy.fallbackRoutes = [];
277
+ for (const entry of value.fallbackRoutes) {
278
+ const route = normalizeExplicitRoute(entry);
279
+ if (!policy.fallbackRoutes.some((existing) => existing.provider === route.provider && existing.model === route.model))
280
+ policy.fallbackRoutes.push(route);
281
+ }
282
+ }
283
+ result[key] = policy;
284
+ }
285
+ return result;
286
+ }
287
+ function isRoutingRecord(value) {
288
+ return typeof value === "object" && value !== null && !Array.isArray(value);
289
+ }
290
+ function normalizeExplicitRoute(value) {
291
+ if (!isRoutingRecord(value) || Object.keys(value).some((field) => !["provider", "model", "reasoningEffort"].includes(field))) {
292
+ throw new TypeError("dsmm explicit model route must contain provider, model and optional reasoningEffort");
293
+ }
294
+ if (typeof value.provider !== "string" || value.provider.trim() === "" || typeof value.model !== "string" || value.model.trim() === "") {
295
+ throw new TypeError("dsmm explicit model route requires nonempty provider and model");
296
+ }
297
+ if (Object.hasOwn(value, "reasoningEffort") && (typeof value.reasoningEffort !== "string" || value.reasoningEffort.trim() === "")) {
298
+ throw new TypeError("dsmm explicit model route reasoningEffort must be nonempty");
299
+ }
300
+ return {
301
+ provider: value.provider.trim(), model: value.model.trim(),
302
+ ...(typeof value.reasoningEffort === "string" ? { reasoningEffort: value.reasoningEffort.trim() } : {})
303
+ };
304
+ }
226
305
  export function isRoleEnabled(settings, role) {
227
306
  return settings.roles[role];
228
307
  }
@@ -292,14 +371,23 @@ function normalizeRetryCodes(input, defaults) {
292
371
  function normalizeRecoveryRoutes(input, defaults) {
293
372
  const normalized = [];
294
373
  for (const route of input ?? defaults) {
374
+ const reasoningEffort = normalizeRecoveryEffort(route);
295
375
  const provider = route.provider?.trim() ?? "";
296
376
  const model = route.model?.trim() ?? "";
297
377
  if (provider === "" || model === "" || normalized.some((candidate) => candidate.provider === provider && candidate.model === model))
298
378
  continue;
299
- normalized.push({ provider, model });
379
+ normalized.push({ provider, model, ...(reasoningEffort ? { reasoningEffort } : {}) });
300
380
  }
301
381
  return normalized;
302
382
  }
383
+ function normalizeRecoveryEffort(route) {
384
+ if (!Object.hasOwn(route, "reasoningEffort"))
385
+ return undefined;
386
+ const value = route.reasoningEffort;
387
+ if (typeof value !== "string" || value.trim() === "")
388
+ throw new TypeError("dsmm recovery route reasoningEffort must be nonempty");
389
+ return value.trim();
390
+ }
303
391
  function normalizeBoundedInteger(value, defaultValue) {
304
392
  if (value === undefined || !Number.isFinite(value))
305
393
  return defaultValue;
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
  }