@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,26 @@
1
+ import type { DsmmPluginConfig, DsmmSettings } from "./settings.js";
2
+ import type { ProfileErrorCode, ProfileErrorInfo } from "./profile-types.js";
3
+ export declare const MAX_PROFILE_BYTES: number;
4
+ export declare const MAX_PROFILE_COUNT = 128;
5
+ export declare const MAX_PROFILE_DIRECTORY_ENTRIES = 1024;
6
+ export declare const MAX_PROFILE_REVISIONS = 1024;
7
+ export type DsmmProfileOverlay = Pick<DsmmPluginConfig, "defaultActive" | "roleRouting" | "runtimePolicy" | "workflow" | "guards" | "runtimeRecovery" | "deepseekV4ProCalibration" | "deepseekV4ProDefaultReasoningEffort" | "deepseekV4ProMaxReasoningPresets" | "deepseekFlashCalibration" | "deepseekFlashDefaultReasoningEffort" | "deepseekFlashMaxReasoningPresets">;
8
+ export interface DsmmProfileDocument {
9
+ version: 1;
10
+ id: string;
11
+ label?: string;
12
+ settings: DsmmProfileOverlay;
13
+ }
14
+ export declare class DsmmProfileError extends Error {
15
+ readonly code: ProfileErrorCode;
16
+ readonly field?: string;
17
+ constructor(code: ProfileErrorCode, message: string, field?: string);
18
+ toInfo(): ProfileErrorInfo;
19
+ }
20
+ export declare function profileErrorInfo(error: unknown, fallback?: ProfileErrorCode): ProfileErrorInfo;
21
+ export declare function validateProfileId(id: unknown): asserts id is string;
22
+ export declare function validateProfileRevision(revision: unknown, field?: string): asserts revision is string;
23
+ export declare function parseProfileDocument(content: string, expectedId?: string): DsmmProfileDocument;
24
+ export declare function mergeProfileConfig(baseline: DsmmPluginConfig, overlay: DsmmProfileOverlay): DsmmPluginConfig;
25
+ export declare function resolveProfileSettings(baseline: DsmmPluginConfig, overlay: DsmmProfileOverlay): DsmmSettings;
26
+ //# sourceMappingURL=profiles.d.ts.map
@@ -0,0 +1,269 @@
1
+ import { getNodeValue, parseTree } from "jsonc-parser";
2
+ import { DSMM_ROLE_IDS } from "./roles.js";
3
+ import { resolveConfig } from "./settings.js";
4
+ import { normalizeRateLimitOverrides, normalizeRoutingStrategy, normalizeRuntimePolicy } from "./routing-policy.js";
5
+ export const MAX_PROFILE_BYTES = 128 * 1024;
6
+ export const MAX_PROFILE_COUNT = 128;
7
+ export const MAX_PROFILE_DIRECTORY_ENTRIES = 1024;
8
+ export const MAX_PROFILE_REVISIONS = 1024;
9
+ export class DsmmProfileError extends Error {
10
+ code;
11
+ field;
12
+ constructor(code, message, field) {
13
+ super(message);
14
+ this.name = "DsmmProfileError";
15
+ this.code = code;
16
+ this.field = field;
17
+ }
18
+ toInfo() {
19
+ return { code: this.code, message: this.message, ...(this.field === undefined ? {} : { field: this.field }) };
20
+ }
21
+ }
22
+ export function profileErrorInfo(error, fallback = "io") {
23
+ return error instanceof DsmmProfileError ? error.toInfo() : { code: fallback, message: "Deepwork profile operation failed; the previous selection and files were retained." };
24
+ }
25
+ export function validateProfileId(id) {
26
+ if (typeof id !== "string" || !/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(id) || /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])$/iu.test(id)) {
27
+ throw new DsmmProfileError("validation", "Profile ID must be 1–64 lowercase ASCII letters, digits, hyphens or underscores, and not a Windows reserved name.", "id");
28
+ }
29
+ }
30
+ export function validateProfileRevision(revision, field = "expectedRevision") {
31
+ if (typeof revision !== "string" || !/^[a-f0-9]{64}$/u.test(revision))
32
+ invalid(field, "must be a SHA256 file revision");
33
+ }
34
+ const OVERLAY_FIELDS = ["defaultActive", "roleRouting", "runtimePolicy", "workflow", "guards", "runtimeRecovery", "deepseekV4ProCalibration", "deepseekV4ProDefaultReasoningEffort", "deepseekV4ProMaxReasoningPresets", "deepseekFlashCalibration", "deepseekFlashDefaultReasoningEffort", "deepseekFlashMaxReasoningPresets"];
35
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
36
+ export function parseProfileDocument(content, expectedId) {
37
+ if (typeof content !== "string")
38
+ invalid("content", "must be JSONC text");
39
+ if (content.length > MAX_PROFILE_BYTES)
40
+ throw new DsmmProfileError("limit", "Profile files must not exceed 128 KiB.", "content");
41
+ const encoded = new TextEncoder().encode(content);
42
+ if (encoded.byteLength > MAX_PROFILE_BYTES)
43
+ throw new DsmmProfileError("limit", "Profile files must not exceed 128 KiB.", "content");
44
+ if (new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(encoded) !== content)
45
+ invalid("content", "must round-trip through UTF-8 without unpaired UTF-16 surrogates");
46
+ const errors = [];
47
+ const tree = parseTree(content.replace(/^\uFEFF/u, ""), errors, { allowTrailingComma: true, disallowComments: false, allowEmptyContent: false });
48
+ if (tree === undefined || errors.length > 0)
49
+ invalid("content", "must contain one valid JSONC document (comments and trailing commas are allowed)");
50
+ validateTree(tree, 0);
51
+ const document = record(getNodeValue(tree), "document");
52
+ keys(document, ["version", "id", "label", "settings"], "document");
53
+ if (document.version !== 1)
54
+ invalid("version", "must be 1");
55
+ validateProfileId(document.id);
56
+ if (expectedId !== undefined && document.id !== expectedId)
57
+ invalid("id", "must match the profile filename ID");
58
+ if (Object.hasOwn(document, "label"))
59
+ string(document.label, "label", 120);
60
+ const overlay = record(document.settings, "settings");
61
+ keys(overlay, OVERLAY_FIELDS, "settings", "Only runtime settings are supported; keep roles, skills, installation, providers, credentials, presets and LSP configuration in the native deployment configuration.");
62
+ optional(overlay, "defaultActive", bool, "settings");
63
+ for (const prefix of ["deepseekV4Pro", "deepseekFlash"]) {
64
+ optional(overlay, `${prefix}Calibration`, (value, field) => enumeration(value, ["off", "auto", "strict"], field), "settings");
65
+ optional(overlay, `${prefix}DefaultReasoningEffort`, (value, field) => enumeration(value, ["off", "low", "high"], field), "settings");
66
+ optional(overlay, `${prefix}MaxReasoningPresets`, roleList, "settings");
67
+ }
68
+ optional(overlay, "roleRouting", roleRouting, "settings");
69
+ optional(overlay, "runtimePolicy", runtimePolicy, "settings");
70
+ optional(overlay, "workflow", workflow, "settings");
71
+ optional(overlay, "guards", guards, "settings");
72
+ optional(overlay, "runtimeRecovery", recovery, "settings");
73
+ const result = clone(document);
74
+ // The package's existing resolver remains authoritative for semantic normalization.
75
+ try {
76
+ resolveConfig(result.settings);
77
+ }
78
+ catch {
79
+ invalid("settings", "contains an invalid Deepwork runtime policy");
80
+ }
81
+ return result;
82
+ }
83
+ export function mergeProfileConfig(baseline, overlay) {
84
+ return mergeRecords(baseline, overlay);
85
+ }
86
+ export function resolveProfileSettings(baseline, overlay) {
87
+ return resolveConfig(mergeProfileConfig(baseline, overlay));
88
+ }
89
+ function mergeRecords(baseline, overlay) {
90
+ const result = {};
91
+ for (const [key, value] of Object.entries(baseline))
92
+ result[key] = clone(value);
93
+ for (const [key, value] of Object.entries(overlay)) {
94
+ // Routes are complete values, whereas each role's policy keys merge independently.
95
+ result[key] = key !== "primary" && isRecord(value) && isRecord(result[key]) ? mergeRecords(result[key], value) : clone(value);
96
+ }
97
+ return result;
98
+ }
99
+ function clone(value) {
100
+ if (Array.isArray(value))
101
+ return value.map(clone);
102
+ return isRecord(value) ? mergeRecords({}, value) : value;
103
+ }
104
+ function validateTree(node, depth) {
105
+ if (depth > 32)
106
+ invalid("content", "exceeds the maximum JSON nesting depth");
107
+ if (node.type === "object") {
108
+ const found = new Set();
109
+ for (const property of node.children ?? []) {
110
+ const key = property.children?.[0]?.value;
111
+ if (typeof key !== "string" || FORBIDDEN_KEYS.has(key))
112
+ invalid("content", "contains an unsafe object key");
113
+ if (found.has(key))
114
+ invalid("content", "contains a duplicate object key; remove the duplicate before saving");
115
+ found.add(key);
116
+ }
117
+ }
118
+ for (const child of node.children ?? [])
119
+ validateTree(child, depth + 1);
120
+ }
121
+ function isRecord(value) {
122
+ return typeof value === "object" && value !== null && !Array.isArray(value);
123
+ }
124
+ function record(value, field) {
125
+ if (!isRecord(value))
126
+ invalid(field, "must be an object");
127
+ return value;
128
+ }
129
+ function keys(value, allowed, field, extra = "Remove unsupported fields before saving.") {
130
+ if (Object.keys(value).some((key) => !allowed.includes(key)))
131
+ invalid(field, `contains unsupported fields. ${extra}`);
132
+ }
133
+ function optional(value, key, validator, field) {
134
+ if (Object.hasOwn(value, key))
135
+ validator(value[key], `${field}.${key}`);
136
+ }
137
+ function invalid(field, message) {
138
+ throw new DsmmProfileError("validation", `${field} ${message}.`, field);
139
+ }
140
+ function bool(value, field) {
141
+ if (typeof value !== "boolean")
142
+ invalid(field, "must be true or false");
143
+ }
144
+ function string(value, field, maximum) {
145
+ if (typeof value !== "string" || value.trim() === "" || value.length > maximum || /[\u0000-\u001F\u007F]/u.test(value))
146
+ invalid(field, `must be nonempty text of at most ${maximum} characters without control characters`);
147
+ }
148
+ function enumeration(value, allowed, field) {
149
+ if (typeof value !== "string" || !allowed.includes(value))
150
+ invalid(field, `must be one of ${allowed.join(", ")}`);
151
+ }
152
+ function integer(value, field, minimum, maximum) {
153
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum || value > maximum)
154
+ invalid(field, `must be an integer from ${minimum} to ${maximum}`);
155
+ }
156
+ function array(value, field, maximum, validator) {
157
+ if (!Array.isArray(value) || value.length > maximum)
158
+ invalid(field, `must be an array with at most ${maximum} entries`);
159
+ for (const item of value)
160
+ validator(item, field);
161
+ }
162
+ function roleList(value, field) {
163
+ array(value, field, DSMM_ROLE_IDS.length, (role, path) => enumeration(role, DSMM_ROLE_IDS, path));
164
+ if (new Set(value).size !== value.length)
165
+ invalid(field, "must not contain duplicate roles");
166
+ }
167
+ function route(value, field) {
168
+ const item = record(value, field);
169
+ keys(item, ["provider", "model", "reasoningEffort"], field);
170
+ string(item.provider, `${field}.provider`, 128);
171
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/u.test(item.provider))
172
+ invalid(`${field}.provider`, "must reference a native provider ID, not a URL, credential or path");
173
+ string(item.model, `${field}.model`, 512);
174
+ if (item.model.includes("://"))
175
+ invalid(`${field}.model`, "must reference a native model ID, not a credential-bearing URL");
176
+ optional(item, "reasoningEffort", (effort, path) => string(effort, path, 64), field);
177
+ }
178
+ function routeList(value, field) {
179
+ array(value, field, 32, route);
180
+ }
181
+ function roleRouting(value, field) {
182
+ const item = record(value, field);
183
+ keys(item, DSMM_ROLE_IDS, field);
184
+ for (const [role, raw] of Object.entries(item)) {
185
+ const path = `${field}.${role}`;
186
+ const policy = record(raw, path);
187
+ keys(policy, ["primary", "fallbackRoutes", "strategy", "rateLimit"], path);
188
+ optional(policy, "primary", route, path);
189
+ optional(policy, "fallbackRoutes", routeList, path);
190
+ optional(policy, "strategy", strategy, path);
191
+ optional(policy, "rateLimit", rateLimit, path);
192
+ }
193
+ }
194
+ function strategy(value, field) {
195
+ try {
196
+ normalizeRoutingStrategy(value);
197
+ }
198
+ catch {
199
+ invalid(field, "must be startup-lock or rate-limit-fallback");
200
+ }
201
+ }
202
+ function rateLimit(value, field) {
203
+ try {
204
+ normalizeRateLimitOverrides(value);
205
+ }
206
+ catch {
207
+ invalid(field, "must contain only bounded integer retry, delay, threshold and switch fields");
208
+ }
209
+ }
210
+ function runtimePolicy(value, field) {
211
+ const item = record(value, field);
212
+ keys(item, ["strategy", "rateLimit"], field);
213
+ optional(item, "strategy", strategy, field);
214
+ optional(item, "rateLimit", rateLimit, field);
215
+ try {
216
+ normalizeRuntimePolicy(value);
217
+ }
218
+ catch {
219
+ invalid(field, "must contain a valid strategy and bounded rateLimit policy");
220
+ }
221
+ }
222
+ function workflow(value, field) {
223
+ const item = record(value, field);
224
+ keys(item, ["policy", "strictGates", "reviewCap", "finalReviewPolicy"], field);
225
+ optional(item, "policy", (policy, path) => enumeration(policy, ["risk-based", "legacy"], path), field);
226
+ optional(item, "strictGates", bool, field);
227
+ optional(item, "reviewCap", (cap, path) => integer(cap, path, 0, 10), field);
228
+ optional(item, "finalReviewPolicy", (policy, path) => enumeration(policy, ["simple-oracle-complex-reviewer", "reviewer-only", "off"], path), field);
229
+ }
230
+ function guards(value, field) {
231
+ const item = record(value, field);
232
+ keys(item, ["scope", "shellCommandSafety", "gitWriteGuard", "toolOutputTruncation", "planFormatValidation", "questionLabelHelper", "todoDisciplineHelper"], field);
233
+ optional(item, "scope", (scope, path) => enumeration(scope, ["deepwork-or-dsmm-agent", "always", "off"], path), field);
234
+ optional(item, "gitWriteGuard", (policy, path) => enumeration(policy, ["ask", "deny", "off"], path), field);
235
+ for (const key of ["shellCommandSafety", "planFormatValidation", "todoDisciplineHelper"])
236
+ optional(item, key, bool, field);
237
+ optional(item, "toolOutputTruncation", (raw, path) => {
238
+ const nested = record(raw, path);
239
+ keys(nested, ["enabled", "maxInlineBytes"], path);
240
+ optional(nested, "enabled", bool, path);
241
+ optional(nested, "maxInlineBytes", (bytes, at) => integer(bytes, at, 1, 1024 * 1024), path);
242
+ }, field);
243
+ optional(item, "questionLabelHelper", (raw, path) => {
244
+ const nested = record(raw, path);
245
+ keys(nested, ["enabled", "maxLabelChars"], path);
246
+ optional(nested, "enabled", bool, path);
247
+ optional(nested, "maxLabelChars", (chars, at) => integer(chars, at, 1, 256), path);
248
+ }, field);
249
+ }
250
+ function recovery(value, field) {
251
+ const item = record(value, field);
252
+ keys(item, ["enabled", "retryOnStatusCodes", "retryOnCodes", "fallbackRoutes", "maxFallbackAttempts", "idleContinuation"], field);
253
+ optional(item, "enabled", bool, field);
254
+ optional(item, "retryOnStatusCodes", (raw, path) => array(raw, path, 64, (status, at) => integer(status, at, 100, 599)), field);
255
+ optional(item, "retryOnCodes", (raw, path) => array(raw, path, 64, (code, at) => string(code, at, 128)), field);
256
+ optional(item, "fallbackRoutes", routeList, field);
257
+ optional(item, "maxFallbackAttempts", (attempts, path) => integer(attempts, path, 0, 10), field);
258
+ optional(item, "idleContinuation", (raw, path) => {
259
+ const nested = record(raw, path);
260
+ keys(nested, ["enabled", "maxContinuations", "prompt"], path);
261
+ optional(nested, "enabled", bool, path);
262
+ optional(nested, "maxContinuations", (count, at) => integer(count, at, 0, 10), path);
263
+ optional(nested, "prompt", (prompt, at) => {
264
+ if (typeof prompt !== "string" || prompt.trim() === "" || prompt.length > 8192 || prompt.includes("\0"))
265
+ invalid(at, "must be nonempty text of at most 8192 characters without NUL");
266
+ }, path);
267
+ }, field);
268
+ }
269
+ //# sourceMappingURL=profiles.js.map
package/lib/prompts.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { DshLlmCallConfig } from "./dsh-types.js";
2
2
  import type { DsmmSettings } from "./settings.js";
3
- export declare const BASE_DEEPWORK_PROMPT = "<dsmm-deepwork-mode>\n\nDEEPWORK MODE ENABLED!\n\nUse this workflow only while the `{{modeName}}` mode is active OR a DSMM-managed preset is selected. This is an opt-in boundary: outside both conditions, do not apply dsmm-specific gates, intent routing, or tool-discipline requirements. The default mode name is `deepwork` unless configured.\n\n## Intent routing\n\nDetermine whether the user requests an explanation, diagnosis, implementation, or open-ended design. State the outcome and evidence in the user's language; classify aloud only when it helps the user.\n\n## Workflow gates\n\n- A clear implementation request authorizes its stated scope. Do not require design reapproval or a separate approval loop for equivalent implementation decisions.\n- For complex business or behavior implementation, default to planner \u2192 plan-critic \u2192 implementation. Skip this sequence only for a bounded, simple, low-risk change or an explicit permitted user request. A task having multiple steps alone is not the criterion.\n- Escalate choices that change scope or acceptance, weaken safety/data guarantees, change a public API/protocol or permissions, or cause an irreversible effect. Preserve explicit user configuration.\n- Request implementation review when risk, uncertainty, or user requirements warrant it; reviewer is primary-lane self-review, while an Oracle is an externally configured cross-check. Do not run fixed review loops or manufacture an Oracle model.\n- For completed implementation, gather evidence from tests, diagnostics, and real surfaces before declaring done.\n- Keep scope exact. Do not add unrelated refactors, speculative abstractions, or surprise features.\n- The bundled workflow skill set is available in this mode: `brainstorming`, `writing-plans`, `subagent-driven-development`, `dispatching-parallel-agents`, `requesting-code-review`, `receiving-code-review`, and `remove-ai-slops`.\n- `workflow.policy=risk-based` uses the rules above. Explicit `workflow.policy=legacy` retains the configured `strictGates`, `reviewCap`, and `finalReviewPolicy` gates. Do not apply any DSMM policy outside active `{{modeName}}` mode or DSMM-managed preset scope.\n\n## Tool discipline\n\nUse repository tools for repository-specific claims. Prefer narrow reads and searches before broad exploration. Use external documentation for library, API, CLI, or cloud-service details.\n\n- Use the shell dialect available in the current DSH runtime. Keep commands short and inspectable; resolve exact paths before destructive actions and do not string-build cross-shell deletes.\n- No autonomous Git writes: implementing or fixing does not authorize a commit, and a commit does not authorize pushing, tagging, rebasing, or releasing.\n- Child tasks inherit the host's authority and depth limits. Delegate only through actually available DSH tools; preset files alone do not prove that a role is callable.\n\n- DSMM safety guards may enforce shell dialect, git-write approval, output-size, plan-format, question-label, and todo-discipline policy inside this mode; treat `[dsmm safety]` messages as binding policy feedback.\n\n</dsmm-deepwork-mode>";
4
- export declare const DEEPSEEK_V4_PRO_OVERLAY = "<dsmm-deepseek-v4-pro-calibration>\n\nDeepSeek V4 Pro calibration is active.\n\n- Treat complex coding, architecture, migration, debugging, and review tasks as deliberate reasoning tasks.\n- First classify the task and identify the evidence needed.\n- Use tools before making repository-specific or API-specific claims.\n- Runtime reasoning effort is enforced by `agent/request`, not this prompt.\n- In `auto` calibration, explicit upstream reasoning effort is preserved; `strict` overrides it with computed policy.\n- Only adapter-advertised reasoning efforts are emitted; `max` is selected only for configured DSMM presets.\n- Keep final answers concise and do not expose private chain-of-thought.\n- When tool calls are enabled through the provider, preserve the provider-required reasoning/tool-call continuity.\n\n</dsmm-deepseek-v4-pro-calibration>";
3
+ export declare const BASE_DEEPWORK_PROMPT = "<dsmm-deepwork-mode>\n\nDEEPWORK MODE ENABLED!\n\nUse this workflow only while the `{{modeName}}` mode is active OR a DW-managed preset is selected. This is an opt-in boundary: outside both conditions, do not apply Deepwork-specific gates, intent routing, or tool-discipline requirements. The default mode name is `deepwork` unless configured.\n\n## Intent routing\n\nDetermine whether the user requests an explanation, diagnosis, implementation, or open-ended design. State the outcome and evidence in the user's language; classify aloud only when it helps the user.\n\n## Workflow gates\n\n- A clear implementation request authorizes its stated scope. Do not require design reapproval or a separate approval loop for equivalent implementation decisions.\n- For complex business or behavior implementation, default to planner \u2192 plan-critic \u2192 implementation. Skip this sequence only for a bounded, simple, low-risk change or an explicit permitted user request. A task having multiple steps alone is not the criterion.\n- Escalate choices that change scope or acceptance, weaken safety/data guarantees, change a public API/protocol or permissions, or cause an irreversible effect. Preserve explicit user configuration.\n- Request implementation review when risk, uncertainty, or user requirements warrant it; reviewer is primary-lane self-review, while an Oracle is an externally configured cross-check. Do not run fixed review loops or manufacture an Oracle model.\n- For completed implementation, gather evidence from tests, diagnostics, and real surfaces before declaring done.\n- Keep scope exact. Do not add unrelated refactors, speculative abstractions, or surprise features.\n- The bundled workflow skill set is available in this mode: `brainstorming`, `writing-plans`, `subagent-driven-development`, `dispatching-parallel-agents`, `requesting-code-review`, `receiving-code-review`, and `remove-ai-slops`.\n- `workflow.policy=risk-based` uses the rules above. Explicit `workflow.policy=legacy` retains the configured `strictGates`, `reviewCap`, and `finalReviewPolicy` gates. Do not apply any Deepwork policy outside active `{{modeName}}` mode or DW-managed preset scope.\n\n## Tool discipline\n\nUse repository tools for repository-specific claims. Prefer narrow reads and searches before broad exploration. Use external documentation for library, API, CLI, or cloud-service details.\n\n- Use the shell dialect available in the current DSH runtime. Keep commands short and inspectable; resolve exact paths before destructive actions and do not string-build cross-shell deletes.\n- No autonomous Git writes: implementing or fixing does not authorize a commit, and a commit does not authorize pushing, tagging, rebasing, or releasing.\n- Child tasks inherit the host's authority and depth limits. Delegate only through actually available DSH tools; preset files alone do not prove that a role is callable.\n\n- Deepwork safety guards may enforce shell dialect, git-write approval, output-size, plan-format, question-label, and todo-discipline policy inside this mode; treat `[dsmm safety]` messages as binding policy feedback.\n\n</dsmm-deepwork-mode>";
4
+ export declare const DEEPSEEK_V4_PRO_OVERLAY = "<dsmm-deepseek-v4-pro-calibration>\n\nDeepSeek V4 Pro calibration is active.\n\n- Treat complex coding, architecture, migration, debugging, and review tasks as deliberate reasoning tasks.\n- First classify the task and identify the evidence needed.\n- Use tools before making repository-specific or API-specific claims.\n- Runtime reasoning effort is enforced by `agent/request`, not this prompt.\n- In `auto` calibration, explicit upstream reasoning effort is preserved; `strict` overrides it with computed policy.\n- Only adapter-advertised reasoning efforts are emitted; `max` is selected only for configured DW presets.\n- Keep final answers concise and do not expose private chain-of-thought.\n- When tool calls are enabled through the provider, preserve the provider-required reasoning/tool-call continuity.\n\n</dsmm-deepseek-v4-pro-calibration>";
5
5
  export declare const DEEPSEEK_FLASH_OVERLAY = "<dsmm-deepseek-flash-calibration>\n\nDeepSeek-V41-Flash applies only to the verified deepseek-official/deepseek-flash or deepseek-account/deepseek-flash routes. The host catalog and explicit user model choice are authoritative.\n\n- Keep work outcome-first and avoid procedural review or approval loops.\n- Runtime reasoning effort is chosen by the adapter only from the resolved model's advertised efforts. If the catalog advertises no reasoning efforts, leave the request unchanged.\n- Auto preserves explicit upstream effort; strict overrides it only with an advertised effort.\n- Do not assume max, high, temperature, or another model's capabilities. Do not claim model heterogeneity when all child roles use the same route.\n- Maintain tool-call continuity required by the provider and never reveal private reasoning.\n\n</dsmm-deepseek-flash-calibration>";
6
6
  export interface DeepworkPromptOptions {
7
7
  route?: Pick<DshLlmCallConfig, "provider" | "model">;
package/lib/prompts.js CHANGED
@@ -3,7 +3,7 @@ export const BASE_DEEPWORK_PROMPT = `<dsmm-deepwork-mode>
3
3
 
4
4
  DEEPWORK MODE ENABLED!
5
5
 
6
- Use this workflow only while the \`{{modeName}}\` mode is active OR a DSMM-managed preset is selected. This is an opt-in boundary: outside both conditions, do not apply dsmm-specific gates, intent routing, or tool-discipline requirements. The default mode name is \`deepwork\` unless configured.
6
+ Use this workflow only while the \`{{modeName}}\` mode is active OR a DW-managed preset is selected. This is an opt-in boundary: outside both conditions, do not apply Deepwork-specific gates, intent routing, or tool-discipline requirements. The default mode name is \`deepwork\` unless configured.
7
7
 
8
8
  ## Intent routing
9
9
 
@@ -18,7 +18,7 @@ Determine whether the user requests an explanation, diagnosis, implementation, o
18
18
  - For completed implementation, gather evidence from tests, diagnostics, and real surfaces before declaring done.
19
19
  - Keep scope exact. Do not add unrelated refactors, speculative abstractions, or surprise features.
20
20
  - The bundled workflow skill set is available in this mode: \`brainstorming\`, \`writing-plans\`, \`subagent-driven-development\`, \`dispatching-parallel-agents\`, \`requesting-code-review\`, \`receiving-code-review\`, and \`remove-ai-slops\`.
21
- - \`workflow.policy=risk-based\` uses the rules above. Explicit \`workflow.policy=legacy\` retains the configured \`strictGates\`, \`reviewCap\`, and \`finalReviewPolicy\` gates. Do not apply any DSMM policy outside active \`{{modeName}}\` mode or DSMM-managed preset scope.
21
+ - \`workflow.policy=risk-based\` uses the rules above. Explicit \`workflow.policy=legacy\` retains the configured \`strictGates\`, \`reviewCap\`, and \`finalReviewPolicy\` gates. Do not apply any Deepwork policy outside active \`{{modeName}}\` mode or DW-managed preset scope.
22
22
 
23
23
  ## Tool discipline
24
24
 
@@ -28,7 +28,7 @@ Use repository tools for repository-specific claims. Prefer narrow reads and sea
28
28
  - No autonomous Git writes: implementing or fixing does not authorize a commit, and a commit does not authorize pushing, tagging, rebasing, or releasing.
29
29
  - Child tasks inherit the host's authority and depth limits. Delegate only through actually available DSH tools; preset files alone do not prove that a role is callable.
30
30
 
31
- - DSMM safety guards may enforce shell dialect, git-write approval, output-size, plan-format, question-label, and todo-discipline policy inside this mode; treat \`[dsmm safety]\` messages as binding policy feedback.
31
+ - Deepwork safety guards may enforce shell dialect, git-write approval, output-size, plan-format, question-label, and todo-discipline policy inside this mode; treat \`[dsmm safety]\` messages as binding policy feedback.
32
32
 
33
33
  </dsmm-deepwork-mode>`;
34
34
  export const DEEPSEEK_V4_PRO_OVERLAY = `<dsmm-deepseek-v4-pro-calibration>
@@ -40,7 +40,7 @@ DeepSeek V4 Pro calibration is active.
40
40
  - Use tools before making repository-specific or API-specific claims.
41
41
  - Runtime reasoning effort is enforced by \`agent/request\`, not this prompt.
42
42
  - In \`auto\` calibration, explicit upstream reasoning effort is preserved; \`strict\` overrides it with computed policy.
43
- - Only adapter-advertised reasoning efforts are emitted; \`max\` is selected only for configured DSMM presets.
43
+ - Only adapter-advertised reasoning efforts are emitted; \`max\` is selected only for configured DW presets.
44
44
  - Keep final answers concise and do not expose private chain-of-thought.
45
45
  - When tool calls are enabled through the provider, preserve the provider-required reasoning/tool-call continuity.
46
46
 
@@ -1,7 +1,7 @@
1
1
  import type { SubagentProvider } from "@deepseek-ai/dsh-subagent";
2
2
  import type { DshContext } from "./dsh-types.js";
3
3
  import type { DsmmRoleId } from "./roles.js";
4
- import type { DsmmSettings } from "./settings.js";
4
+ import type { DsmmSettingsGetter } from "./settings.js";
5
5
  export interface DsmmSubagentRegistry {
6
6
  getProvider(name: string): SubagentProvider | undefined;
7
7
  registerProvider(provider: SubagentProvider): () => void;
@@ -9,5 +9,5 @@ export interface DsmmSubagentRegistry {
9
9
  export declare function roleProviderName(role: DsmmRoleId): string;
10
10
  export declare function roleFromProviderName(provider: string): DsmmRoleId | undefined;
11
11
  /** Only the native outer start owns descriptors, capability admission and returned runs. */
12
- export declare function registerRoleProviders(ctx: DshContext, getSettings: () => DsmmSettings): void;
12
+ export declare function registerRoleProviders(ctx: DshContext, getSettings: DsmmSettingsGetter, getDeploymentSettings?: DsmmSettingsGetter): void;
13
13
  //# sourceMappingURL=role-providers.d.ts.map
@@ -1,4 +1,8 @@
1
+ import { parentAgentOptionsForDelegation } from "@deepseek-ai/dsh-subagent";
2
+ import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
1
3
  import { DSMM_ROLE_IDS } from "./roles.js";
4
+ import { resolveRoleRuntimePolicy } from "./routing-policy.js";
5
+ import { selectInitialModelRoute } from "./role-routing.js";
2
6
  export function roleProviderName(role) {
3
7
  return `dsmm-role-${role.slice("dsmm-".length)}`;
4
8
  }
@@ -12,7 +16,7 @@ function supportedSpawn(provider) {
12
16
  && Object.keys(SPAWN_CAPABILITIES).every((key) => provider.capabilities?.[key] === true);
13
17
  }
14
18
  /** Only the native outer start owns descriptors, capability admission and returned runs. */
15
- export function registerRoleProviders(ctx, getSettings) {
19
+ export function registerRoleProviders(ctx, getSettings, getDeploymentSettings = getSettings) {
16
20
  const installed = new WeakSet();
17
21
  const install = (readyCtx) => {
18
22
  const registry = readyCtx.get?.("subagents")
@@ -22,20 +26,59 @@ export function registerRoleProviders(ctx, getSettings) {
22
26
  const disposers = [];
23
27
  installed.add(registry);
24
28
  try {
25
- const settings = getSettings();
29
+ const settings = getDeploymentSettings();
26
30
  for (const role of DSMM_ROLE_IDS) {
27
31
  if (role === "dsmm-orchestrator" || !settings.roles[role])
28
32
  continue;
29
33
  let active = true;
30
34
  const dispose = registry.registerProvider({
31
35
  name: roleProviderName(role), capabilities: SPAWN_CAPABILITIES, inheritsParentContext: false,
32
- start(request) {
36
+ async start(request) {
33
37
  if (!active)
34
- return Promise.reject(new Error("dsmm role provider is disposed"));
38
+ throw new Error("dsmm role provider is disposed");
35
39
  const spawn = registry.getProvider("spawn");
36
40
  if (!supportedSpawn(spawn))
37
- return Promise.reject(new Error("dsmm role provider requires the supported native spawn capabilities"));
38
- return spawn.start(request);
41
+ throw new Error("dsmm role provider requires the supported native spawn capabilities");
42
+ const parentSettings = getSettings(request.parent);
43
+ if (!parentSettings.roles[role])
44
+ throw new Error("dsmm role provider is disabled by deployment configuration");
45
+ const primary = parentSettings.roleRouting[role]?.primary;
46
+ const agentOptions = primary === undefined ? request.agentOptions : {
47
+ ...primary,
48
+ reasoningEffort: primary.reasoningEffort === undefined ? undefined : ReasoningEffortId(primary.reasoningEffort),
49
+ ...request.agentOptions
50
+ };
51
+ if (primary !== undefined && request.agentOptions?.reasoningEffort === undefined
52
+ && ((request.agentOptions?.provider !== undefined && request.agentOptions.provider !== primary.provider)
53
+ || (request.agentOptions?.model !== undefined && request.agentOptions.model !== primary.model))) {
54
+ agentOptions.reasoningEffort = undefined;
55
+ }
56
+ const parentOptions = parentAgentOptionsForDelegation(request.parent);
57
+ const provider = agentOptions?.provider ?? parentOptions.provider;
58
+ const model = agentOptions?.model ?? parentOptions.model;
59
+ if (provider === undefined || model === undefined)
60
+ throw new Error("dsmm role delegation requires an effective provider and model");
61
+ const routeChanged = provider !== parentOptions.provider || model !== parentOptions.model;
62
+ const reasoningEffort = agentOptions?.reasoningEffort
63
+ ?? (primary === undefined && !routeChanged ? parentOptions.reasoningEffort : undefined);
64
+ const llm = request.parent.ctx.get("llm");
65
+ if (llm?.resolveCallConfig === undefined)
66
+ throw new Error("dsmm role delegation requires the parent Agent native LLM service");
67
+ const explicitRoute = request.agentOptions?.provider !== undefined || request.agentOptions?.model !== undefined;
68
+ const candidates = [{ provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) },
69
+ ...explicitRoute ? [] : resolveRoleRuntimePolicy(parentSettings, role).fallbackRoutes.map((route) => ({ ...route,
70
+ ...(request.agentOptions?.reasoningEffort === undefined ? {} : { reasoningEffort: request.agentOptions.reasoningEffort }) }))];
71
+ const selected = await selectInitialModelRoute(llm, candidates, request.signal);
72
+ request.signal.throwIfAborted();
73
+ if (!active || registry.getProvider("spawn") !== spawn)
74
+ throw new Error("dsmm role spawn provider changed during route validation; retry delegation");
75
+ // Preserve the native descriptor, authority filters and lifecycle;
76
+ // this alias owns only profile-derived route defaults and preflight.
77
+ const changed = selected.provider !== provider || selected.model !== model;
78
+ return spawn.start(primary === undefined && !changed ? request : { ...request, agentOptions: {
79
+ ...agentOptions, ...selected,
80
+ reasoningEffort: selected.reasoningEffort === undefined ? undefined : ReasoningEffortId(selected.reasoningEffort)
81
+ } });
39
82
  }
40
83
  });
41
84
  disposers.push(() => { active = false; dispose(); });
@@ -1,10 +1,44 @@
1
- import type { AgentRequestFrame, DshLlmCallConfig } from "./dsh-types.js";
1
+ import type { AgentRequestFrame, DshAgent, DshContext, DshLlmCallConfig, DshLlmRuntime } from "./dsh-types.js";
2
2
  import type { DsmmRoleId } from "./roles.js";
3
3
  import type { DsmmModelRoute, DsmmSettings } from "./settings.js";
4
+ import type { DsmmRoleRuntimeState } from "./profile-types.js";
4
5
  export declare const DSMM_ROLE_POLICY_EVENT = "dsmm/role-policy";
5
- export declare function rolePolicyIdentity(settings: DsmmSettings, role: DsmmRoleId | undefined): string | undefined;
6
+ export interface RoleRouteLock {
7
+ identity: string;
8
+ route: DsmmModelRoute;
9
+ candidates: readonly DsmmModelRoute[];
10
+ generation: number;
11
+ attempts: number;
12
+ startupSettled: boolean;
13
+ retries: number;
14
+ rateLimits: number;
15
+ switches: number;
16
+ totalDelayMs: number;
17
+ manualSelectionSeq?: number;
18
+ }
19
+ export interface NativeModelSelectionIntent {
20
+ seq: number;
21
+ route: DsmmModelRoute;
22
+ }
23
+ /** Native user selection is authority; inherited headers/default configs are not. */
24
+ export declare function latestNativeModelSelection(agent: DshAgent): NativeModelSelectionIntent | undefined;
25
+ export declare function sameExactModelRoute(left: Pick<DsmmModelRoute, "provider" | "model" | "reasoningEffort">, right: DsmmModelRoute): boolean;
26
+ /** Consumed user intent stays explicit on cold resume and profile re-admission. */
27
+ export declare function nativeModelSelectionWasAccepted(agent: DshAgent, intent: NativeModelSelectionIntent): boolean;
28
+ /** Only native, machine-routable absence authorizes initial candidate admission. */
29
+ export declare function isUnavailableRouteFailure(error: unknown, nativeRequestFailure?: boolean): boolean;
30
+ export declare function orderedModelRoutes(candidates: readonly DsmmModelRoute[]): DsmmModelRoute[];
31
+ /** Exact metadata preparation, never a completion or advisory catalog health check. */
32
+ export declare function selectInitialModelRoute(llm: DshLlmRuntime, candidates: readonly DsmmModelRoute[], signal?: AbortSignal): Promise<DsmmModelRoute>;
33
+ export declare function roleRouteLock(agent: DshAgent, identity: string): RoleRouteLock | undefined;
34
+ export declare function pinRoleRoute(agent: DshAgent, identity: string, route: DsmmModelRoute, candidates: readonly DsmmModelRoute[]): RoleRouteLock;
35
+ export declare function clearRoleRouteLock(agent: DshAgent): void;
36
+ export declare function roleRouteRuntimeState(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): DsmmRoleRuntimeState;
37
+ export declare function rolePolicyIdentity(settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): string | undefined;
38
+ /** Durable profile choice is not permission to retain a former process's route lock. */
39
+ export declare function liveRolePolicyIdentity(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): string | undefined;
6
40
  /** Native custom events are model-hidden log facts, retained across surface compaction. */
7
- export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined): Promise<string | undefined>;
41
+ export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined, ctx?: DshContext, epoch?: string): Promise<string | undefined>;
8
42
  export declare function recordAdmittedRecoveryRoute(frame: AgentRequestFrame, route: DsmmModelRoute): void;
9
43
  export declare function takeAdmittedRecoveryRoute(frame: AgentRequestFrame): DsmmModelRoute | undefined;
10
44
  export declare function effectiveRoleFallbackRoutes(settings: DsmmSettings, role: DsmmRoleId | undefined): readonly DsmmModelRoute[];