@dsmm/dsmm 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +103 -0
  2. package/README.md +70 -2
  3. package/agent-presets/dsmm-builder/agent.cordis.yml +210 -0
  4. package/agent-presets/dsmm-builder/preset.yml +3 -0
  5. package/agent-presets/dsmm-clarifier/agent.cordis.yml +34 -0
  6. package/agent-presets/dsmm-clarifier/preset.yml +3 -0
  7. package/agent-presets/dsmm-code-search/agent.cordis.yml +34 -0
  8. package/agent-presets/dsmm-code-search/preset.yml +3 -0
  9. package/agent-presets/dsmm-creative/agent.cordis.yml +31 -0
  10. package/agent-presets/dsmm-creative/preset.yml +3 -0
  11. package/agent-presets/dsmm-doc-search/agent.cordis.yml +34 -0
  12. package/agent-presets/dsmm-doc-search/preset.yml +3 -0
  13. package/agent-presets/dsmm-media-reader/agent.cordis.yml +34 -0
  14. package/agent-presets/dsmm-media-reader/preset.yml +3 -0
  15. package/agent-presets/dsmm-oracle/agent.cordis.yml +31 -0
  16. package/agent-presets/dsmm-oracle/preset.yml +3 -0
  17. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +31 -0
  18. package/agent-presets/dsmm-oracle-2nd/preset.yml +3 -0
  19. package/agent-presets/dsmm-orchestrator/agent.cordis.yml +215 -0
  20. package/agent-presets/dsmm-orchestrator/preset.yml +3 -0
  21. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +33 -0
  22. package/agent-presets/dsmm-plan-critic/preset.yml +3 -0
  23. package/agent-presets/dsmm-planner/agent.cordis.yml +33 -0
  24. package/agent-presets/dsmm-planner/preset.yml +3 -0
  25. package/agent-presets/dsmm-reviewer/agent.cordis.yml +33 -0
  26. package/agent-presets/dsmm-reviewer/preset.yml +3 -0
  27. package/cordis.patch.yml +8 -0
  28. package/docs/agent-presets.md +19 -0
  29. package/docs/compatibility.md +49 -0
  30. package/docs/design.md +237 -0
  31. package/docs/lsp.md +40 -0
  32. package/docs/migration-from-ocmm.md +54 -0
  33. package/docs/model-routing.md +61 -0
  34. package/docs/releasing.md +52 -0
  35. package/docs/research/deepseek-v4-pro.md +74 -0
  36. package/docs/research/oh-dsh.md +96 -0
  37. package/docs/roadmap.md +207 -0
  38. package/docs/runtime-recovery.md +75 -0
  39. package/docs/safety-guards.md +55 -0
  40. package/docs/settings-status.md +55 -0
  41. package/docs/skill-sync.md +20 -0
  42. package/lib/commands.d.ts +13 -0
  43. package/lib/commands.js +55 -0
  44. package/lib/dsh-events.d.ts +21 -0
  45. package/lib/dsh-events.js +2 -0
  46. package/lib/dsh-types.d.ts +312 -0
  47. package/lib/dsh-types.js +2 -0
  48. package/lib/guards.d.ts +10 -0
  49. package/lib/guards.js +252 -0
  50. package/lib/index.d.ts +33 -0
  51. package/lib/index.js +58 -0
  52. package/lib/lsp.d.ts +30 -0
  53. package/lib/lsp.js +154 -0
  54. package/lib/mode.d.ts +6 -0
  55. package/lib/mode.js +62 -0
  56. package/lib/model-family.d.ts +6 -0
  57. package/lib/model-family.js +49 -0
  58. package/lib/model-routing.d.ts +11 -0
  59. package/lib/model-routing.js +128 -0
  60. package/lib/plan-validation.d.ts +3 -0
  61. package/lib/plan-validation.js +119 -0
  62. package/lib/preset-materializer.d.ts +36 -0
  63. package/lib/preset-materializer.js +258 -0
  64. package/lib/preset-registry.d.ts +5 -0
  65. package/lib/preset-registry.js +126 -0
  66. package/lib/preset-skills.d.ts +12 -0
  67. package/lib/preset-skills.js +28 -0
  68. package/lib/prompts.d.ts +13 -0
  69. package/lib/prompts.js +82 -0
  70. package/lib/recovery-policy.d.ts +25 -0
  71. package/lib/recovery-policy.js +252 -0
  72. package/lib/role-providers.d.ts +13 -0
  73. package/lib/role-providers.js +61 -0
  74. package/lib/role-routing.d.ts +15 -0
  75. package/lib/role-routing.js +144 -0
  76. package/lib/role-subagents.d.ts +6 -0
  77. package/lib/role-subagents.js +54 -0
  78. package/lib/roles.d.ts +29 -0
  79. package/lib/roles.js +241 -0
  80. package/lib/runtime-recovery.d.ts +5 -0
  81. package/lib/runtime-recovery.js +168 -0
  82. package/lib/session-scope.d.ts +9 -0
  83. package/lib/session-scope.js +40 -0
  84. package/lib/settings.d.ts +123 -0
  85. package/lib/settings.js +447 -0
  86. package/lib/shell-command.d.ts +18 -0
  87. package/lib/shell-command.js +492 -0
  88. package/lib/skills.d.ts +18 -0
  89. package/lib/skills.js +64 -0
  90. package/lib/state.d.ts +13 -0
  91. package/lib/state.js +64 -0
  92. package/lib/status.d.ts +55 -0
  93. package/lib/status.js +193 -0
  94. package/package.json +129 -4
  95. package/patches/agent-presets-root.example.cordis.patch.yml +14 -0
  96. package/patches/ocmm-lsp-mcp.example.cordis.patch.yml +15 -0
  97. package/prompts/deepseek-flash.md +11 -0
  98. package/prompts/deepseek-v4-pro.md +14 -0
  99. package/prompts/deepwork.md +32 -0
  100. package/skills/brainstorming/SKILL.md +15 -0
  101. package/skills/debugging/SKILL.md +12 -0
  102. package/skills/debugging/references/logging.md +91 -0
  103. package/skills/debugging/references/methodology/00-setup.md +108 -0
  104. package/skills/debugging/references/methodology/02-investigate.md +67 -0
  105. package/skills/debugging/references/methodology/03-flaky-triage.md +69 -0
  106. package/skills/debugging/references/methodology/04-hard-reasoning-escalation.md +83 -0
  107. package/skills/debugging/references/methodology/05-escalate.md +69 -0
  108. package/skills/debugging/references/methodology/06-fix.md +123 -0
  109. package/skills/debugging/references/methodology/08-qa.md +94 -0
  110. package/skills/debugging/references/methodology/09-cleanup.md +164 -0
  111. package/skills/debugging/references/methodology/partial-runtime-evidence.md +217 -0
  112. package/skills/debugging/references/runtimes/bundled-js-binary.md +415 -0
  113. package/skills/debugging/references/runtimes/go.md +252 -0
  114. package/skills/debugging/references/runtimes/native-binary.md +484 -0
  115. package/skills/debugging/references/runtimes/node.md +260 -0
  116. package/skills/debugging/references/runtimes/python.md +248 -0
  117. package/skills/debugging/references/runtimes/rust.md +234 -0
  118. package/skills/debugging/references/scripts/dap.mjs +533 -0
  119. package/skills/debugging/references/tools/dap.md +89 -0
  120. package/skills/debugging/references/tools/ghidra.md +212 -0
  121. package/skills/debugging/references/tools/playwright-cli.md +316 -0
  122. package/skills/debugging/references/tools/pwndbg.md +263 -0
  123. package/skills/debugging/references/tools/pwntools.md +265 -0
  124. package/skills/dispatching-parallel-agents/SKILL.md +14 -0
  125. package/skills/receiving-code-review/SKILL.md +13 -0
  126. package/skills/remove-ai-slops/SKILL.md +14 -0
  127. package/skills/requesting-code-review/SKILL.md +10 -0
  128. package/skills/subagent-driven-development/SKILL.md +13 -0
  129. package/skills/writing-plans/SKILL.md +14 -0
package/lib/roles.js ADDED
@@ -0,0 +1,241 @@
1
+ import { DSMM_SKILL_NAMES } from "./skills.js";
2
+ import { roleProviderName } from "./role-providers.js";
3
+ export const DSMM_ROLE_IDS = [
4
+ "dsmm-orchestrator",
5
+ "dsmm-planner",
6
+ "dsmm-plan-critic",
7
+ "dsmm-builder",
8
+ "dsmm-reviewer",
9
+ "dsmm-oracle",
10
+ "dsmm-oracle-2nd",
11
+ "dsmm-creative",
12
+ "dsmm-code-search",
13
+ "dsmm-doc-search",
14
+ "dsmm-clarifier",
15
+ "dsmm-media-reader"
16
+ ];
17
+ export const DSMM_ROLES = [
18
+ {
19
+ id: "dsmm-orchestrator",
20
+ name: "DSMM Orchestrator",
21
+ description: "Coordinates deepwork sessions and routes work to focused dsmm role presets.",
22
+ order: 10,
23
+ enabledByDefault: true,
24
+ persona: `You are dsmm-orchestrator, a dsh-native coordinator for deepwork sessions.
25
+ For complex behavior implementation, default to planner → plan-critic → implementation; for simple bounded low-risk work, proceed directly. A clear implementation request authorizes its stated scope without repeated design approval.
26
+ Delegate bounded work only through callable role-specific DSH tools: dsmm-planner, dsmm-plan-critic, dsmm-builder, dsmm-reviewer, dsmm-oracle, dsmm-oracle-2nd, dsmm-creative, dsmm-code-search, dsmm-doc-search, dsmm-clarifier and dsmm-media-reader.
27
+ Reviewer is primary-lane self-review; use Oracle only for a useful external cross-check when a different model was explicitly selected. Review when risk warrants it, not in a fixed loop.
28
+ Keep scope explicit, preserve user constraints, and do not claim a preset is active unless the host selected it. Implementing does not authorize Git writes.`
29
+ },
30
+ {
31
+ id: "dsmm-planner",
32
+ name: "DSMM Planner",
33
+ description: "Turns approved scope into ordered implementation steps with verification gates.",
34
+ order: 20,
35
+ enabledByDefault: true,
36
+ access: "read-only",
37
+ persona: `You are dsmm-planner, a dsh-native planning specialist.
38
+ Inspect evidence and convert approved complex work into an outcome-oriented plan with dependencies, interfaces, risks and verification. Do not implement or modify files. Flag decisions that change scope, safety or public APIs. Git writes need specific authorization.`
39
+ },
40
+ {
41
+ id: "dsmm-plan-critic",
42
+ name: "DSMM Plan Critic",
43
+ description: "Checks implementation plans for ambiguity, missing evidence, and unsafe sequencing.",
44
+ order: 30,
45
+ enabledByDefault: true,
46
+ access: "read-only",
47
+ persona: `You are dsmm-plan-critic, a dsh-native plan review specialist.
48
+ Inspect the plan and evidence for material blockers in outcome coverage, dependencies, tests, safety and scope. Return concrete blockers or a concise pass with residual risks; do not require a fixed format or repeated reviews after editorial changes. Read only; do not implement or perform Git writes.`
49
+ },
50
+ {
51
+ id: "dsmm-builder",
52
+ name: "DSMM Builder",
53
+ description: "Implements one bounded approved outcome and verifies the changed surface.",
54
+ order: 35,
55
+ enabledByDefault: true,
56
+ access: "write",
57
+ persona: `You are dsmm-builder, a bounded implementation worker. Respect assigned file ownership and other workers' changes. Implement only the approved outcome, verify the affected surface, and report changes, evidence and risks. Escalate changes to public APIs, permissions, safety, data guarantees or irreversible behavior. Never stage, commit, push, tag, rebase or release without specific authorization.`
58
+ },
59
+ {
60
+ id: "dsmm-reviewer",
61
+ name: "DSMM Reviewer",
62
+ description: "Reviews completed changes against requirements, tests, and regression risk.",
63
+ order: 40,
64
+ enabledByDefault: true,
65
+ access: "read-only",
66
+ persona: `You are dsmm-reviewer, a dsh-native implementation reviewer.
67
+ Read the current implementation diff and new files against requirements, conventions and verification. Prioritize actionable correctness and regression findings. This is primary-model or primary-lane self-review, not external Oracle review. Do not modify files or perform Git writes.`
68
+ },
69
+ {
70
+ id: "dsmm-oracle",
71
+ name: "DSMM Oracle",
72
+ description: "First-priority external-model implementation cross-check when explicitly configured.",
73
+ order: 42,
74
+ enabledByDefault: true,
75
+ access: "read-only",
76
+ persona: `You are dsmm-oracle, first-priority implementation cross-check. Read only; inspect the current diff, evidence and requirements for concrete defects. Your role is externally heterogeneous only when the caller selects a different available model; do not claim model independence when inheriting the parent's route. Do not implement or perform Git writes.`
77
+ },
78
+ {
79
+ id: "dsmm-oracle-2nd",
80
+ name: "DSMM Oracle 2nd",
81
+ description: "Second-priority external-model implementation cross-check for an additional evidence need.",
82
+ order: 44,
83
+ enabledByDefault: true,
84
+ access: "read-only",
85
+ persona: `You are dsmm-oracle-2nd, second-priority implementation cross-check, not a higher-capability rank. Read only; report concrete defects in the current diff and evidence. An external model must be explicitly selected; the role label alone is no proof of independence. Do not implement or perform Git writes.`
86
+ },
87
+ {
88
+ id: "dsmm-creative",
89
+ name: "DSMM Creative",
90
+ description: "Explores unconventional but coherent approaches and explicit trade-offs.",
91
+ order: 46,
92
+ enabledByDefault: true,
93
+ access: "read-only",
94
+ persona: `You are dsmm-creative. Explore distinct coherent approaches, state trade-offs, constraints and a grounded recommendation. Remain read-only unless a separate implementation assignment authorizes changes. Do not perform Git writes.`
95
+ },
96
+ {
97
+ id: "dsmm-code-search",
98
+ name: "DSMM Code Search",
99
+ description: "Finds local codebase facts, symbols, patterns, and relevant implementation context.",
100
+ order: 50,
101
+ enabledByDefault: true,
102
+ access: "read-only",
103
+ persona: `You are dsmm-code-search, a dsh-native codebase research specialist.
104
+ Search local project context for exact files, symbols, references, and conventions needed by the caller.
105
+ Summarize findings with paths and evidence; do not modify files.`
106
+ },
107
+ {
108
+ id: "dsmm-doc-search",
109
+ name: "DSMM Doc Search",
110
+ description: "Finds current external documentation and examples for library or API questions.",
111
+ order: 60,
112
+ enabledByDefault: true,
113
+ access: "read-only",
114
+ persona: `You are dsmm-doc-search, a dsh-native documentation research specialist.
115
+ Find current documentation and real examples for libraries, APIs, CLIs, and services relevant to the task.
116
+ Cite source locations, separate facts from assumptions, and avoid guessing when documentation is unavailable.`
117
+ },
118
+ {
119
+ id: "dsmm-clarifier",
120
+ name: "DSMM Clarifier",
121
+ description: "Reduces ambiguous requests to the few decisions needed before planning or implementation.",
122
+ order: 70,
123
+ enabledByDefault: true,
124
+ access: "read-only",
125
+ persona: `You are dsmm-clarifier, a dsh-native requirements clarification specialist.
126
+ Identify ambiguity in purpose, constraints, success criteria, and scope boundaries.
127
+ Ask at most three material questions, prefer concrete choices, and propose safe defaults when evidence is strong.`
128
+ },
129
+ {
130
+ id: "dsmm-media-reader",
131
+ name: "DSMM Media Reader",
132
+ description: "Extracts implementation-relevant information from images, PDFs, and visual artifacts.",
133
+ order: 80,
134
+ enabledByDefault: true,
135
+ access: "read-only",
136
+ persona: `You are dsmm-media-reader, a dsh-native visual and document analysis specialist.
137
+ Extract text, structure, UI details, diagrams, and implementation-relevant facts from provided media.
138
+ Report uncertainty clearly and avoid inventing details that are not visible.`
139
+ }
140
+ ];
141
+ export function isDsmmRoleId(value) {
142
+ return typeof value === "string" && DSMM_ROLE_IDS.includes(value);
143
+ }
144
+ export function renderAgentCordis(role, skills = DSMM_SKILL_NAMES, enabledRoles = DSMM_ROLE_IDS, roleRouting = {}) {
145
+ return rolePluginRows(role, skills, enabledRoles, roleRouting).map(renderPluginRow).join("");
146
+ }
147
+ /** The native PresetDefinition and the static YAML mirror use this same inventory. */
148
+ export function rolePluginRows(role, skills = DSMM_SKILL_NAMES, enabledRoles = DSMM_ROLE_IDS, roleRouting = {}) {
149
+ const rows = [
150
+ { id: "persona", name: "@deepseek-ai/dsh-persona", config: { text: role.persona } },
151
+ { id: "agent-instructions", name: "@deepseek-ai/dsh-agent-instructions" },
152
+ { id: "tool-fs", name: "@deepseek-ai/dsh-tool-fs" },
153
+ { id: "tool-fs-search", name: "@deepseek-ai/dsh-tool-fs-search", config: { sampleOverCapGlobResults: false } },
154
+ { id: "tool-web", name: "@deepseek-ai/dsh-tool-web", config: { fetch: true } },
155
+ { id: "skill-filesystem", name: "@deepseek-ai/dsh-skill-filesystem" },
156
+ { id: "tool-skill", name: "@deepseek-ai/dsh-tool-skill" },
157
+ { id: "dsmm-preset-skills", name: "@dsmm/dsmm/preset-skills", config: { skills: DSMM_SKILL_NAMES.filter((name) => skills.includes(name)) } }
158
+ ];
159
+ if (role.access !== "read-only") {
160
+ rows.push({ id: "tool-bash", name: "@deepseek-ai/dsh-tool-bash", disabled: process.platform === "win32" });
161
+ rows.push({ id: "tool-pwsh", name: "@deepseek-ai/dsh-tool-pwsh", disabled: process.platform !== "win32" });
162
+ rows.push({ id: "tool-jobs", name: "@deepseek-ai/dsh-tool-jobs" });
163
+ }
164
+ if (role.id === "dsmm-orchestrator" || role.id === "dsmm-builder")
165
+ rows.push(...roleSubagentPluginRows(enabledRoles, roleRouting));
166
+ return rows;
167
+ }
168
+ /** DSH's spawn provider joins the parent's preset; persona/filter give each child its own role. */
169
+ export function roleSubagentPluginRows(enabledRoles = DSMM_ROLE_IDS, roleRouting = {}) {
170
+ return DSMM_ROLES.filter((role) => role.id !== "dsmm-orchestrator" && enabledRoles.includes(role.id)).map((role) => ({
171
+ id: `subagent-${role.id}`,
172
+ name: "@deepseek-ai/dsh-tool-subagent",
173
+ config: roleSubagentConfig(role, [], roleRouting[role.id]?.primary)
174
+ }));
175
+ }
176
+ export function roleSubagentConfig(role, availableTools = [], primary) {
177
+ const readOnlyTools = ["read", "glob", "grep"];
178
+ if (role.id === "dsmm-doc-search" || role.id === "dsmm-media-reader") {
179
+ readOnlyTools.push("web_search", "web_fetch");
180
+ }
181
+ // read_image is conditional on the DSH attachment store; an unknown name
182
+ // would make DSH's native toolFilter reject the child at startup.
183
+ if (role.id === "dsmm-media-reader" && availableTools.includes("read_image"))
184
+ readOnlyTools.push("read_image");
185
+ return {
186
+ provider: roleProviderName(role.id),
187
+ ...(primary === undefined ? {} : { agentOptions: { ...primary } }),
188
+ toolName: role.id.replace(/-/gu, "_"),
189
+ // A standing preset with modelSelectionSettings=true re-registers tools in
190
+ // each child Agent's own scope. DSH restrictions filter inherited tools,
191
+ // not same-scope registrations, so that would bypass readonly filters.
192
+ modelSelectionSettings: false,
193
+ backgroundMode: "one-shot",
194
+ enableRunInBackground: false,
195
+ persona: role.persona,
196
+ ...(role.access === "read-only" ? { toolFilter: { allow: readOnlyTools } } : {})
197
+ };
198
+ }
199
+ export function renderPresetMetadata(role) {
200
+ return `id: ${role.id}
201
+ name: ${quoteYamlString(role.name)}
202
+ description: ${quoteYamlString(role.description)}
203
+ `;
204
+ }
205
+ function indentBlock(value, spaces) {
206
+ const prefix = " ".repeat(spaces);
207
+ return value.split(/\r?\n/u).map((line) => `${prefix}${line}`).join("\n");
208
+ }
209
+ function renderPluginRow(row) {
210
+ let output = `- id: ${row.id}\n name: ${quoteYamlString(row.name)}\n`;
211
+ if (row.disabled !== undefined) {
212
+ output += ` disabled: !!js process.platform ${row.id === "tool-bash" ? "===" : "!=="} 'win32'\n`;
213
+ }
214
+ if (row.config === undefined)
215
+ return output;
216
+ output += " config:\n";
217
+ for (const [key, value] of Object.entries(row.config)) {
218
+ if (typeof value === "string" && value.includes("\n"))
219
+ output += ` ${key}: |-\n${indentBlock(value, 6)}\n`;
220
+ else if (typeof value === "string")
221
+ output += ` ${key}: ${quoteYamlString(value)}\n`;
222
+ else if (Array.isArray(value))
223
+ output += value.length === 0 ? ` ${key}: []\n` : ` ${key}:\n${value.map((item) => ` - ${quoteYamlString(String(item))}\n`).join("")}`;
224
+ else if (typeof value === "object" && value !== null) {
225
+ output += ` ${key}:\n`;
226
+ for (const [nestedKey, nestedValue] of Object.entries(value)) {
227
+ if (Array.isArray(nestedValue))
228
+ output += nestedValue.length === 0 ? ` ${nestedKey}: []\n` : ` ${nestedKey}:\n${nestedValue.map((item) => ` - ${quoteYamlString(String(item))}\n`).join("")}`;
229
+ else
230
+ output += ` ${nestedKey}: ${typeof nestedValue === "string" ? quoteYamlString(nestedValue) : String(nestedValue)}\n`;
231
+ }
232
+ }
233
+ else
234
+ output += ` ${key}: ${String(value)}\n`;
235
+ }
236
+ return output;
237
+ }
238
+ function quoteYamlString(value) {
239
+ return `'${value.replace(/'/gu, "''")}'`;
240
+ }
241
+ //# sourceMappingURL=roles.js.map
@@ -0,0 +1,5 @@
1
+ import type { DshContext } from "./dsh-types.js";
2
+ import type { DsmmSettings } from "./settings.js";
3
+ import type { DeepworkModeController } from "./state.js";
4
+ export declare function registerRuntimeRecovery(ctx: DshContext, controller: DeepworkModeController, getSettings: () => DsmmSettings): void;
5
+ //# sourceMappingURL=runtime-recovery.d.ts.map
@@ -0,0 +1,168 @@
1
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
2
+ import { classifyRecoveryFailure, foldAttemptedRecoveryRoutes, foldDurableRecoveryWork, isCurrentRecoveryStep, selectFallbackRoute } from "./recovery-policy.js";
3
+ import { isDsmmRoleId } from "./roles.js";
4
+ import { applyModelRoute, effectiveRoleFallbackRoutes, recordAdmittedRecoveryRoute, rolePolicyIdentity, sameModelRoute } from "./role-routing.js";
5
+ import { childOwnedSessionEvents, resolveEffectiveDsmmRole, resolveSelectedAgentPreset, sessionEvents } from "./session-scope.js";
6
+ const installedContexts = new WeakSet();
7
+ const RECOVERY_WARNING = "dsmm runtime recovery could not evaluate fallback; preserving the host request-error decision";
8
+ const CONTINUATION_WARNING = "dsmm runtime recovery continuation steering failed for turn";
9
+ function warnSafely(ctx, message) {
10
+ try {
11
+ ctx.logger?.warn(message);
12
+ }
13
+ catch { }
14
+ }
15
+ function recoveryEvents(agent) {
16
+ return agent.session.header?.origin === "subagent" ? childOwnedSessionEvents(agent.session) : sessionEvents(agent.session);
17
+ }
18
+ export function registerRuntimeRecovery(ctx, controller, getSettings) {
19
+ if (installedContexts.has(ctx) || ctx.on === undefined)
20
+ return;
21
+ installedContexts.add(ctx);
22
+ let pendingByAgent = new WeakMap();
23
+ let reservedByAgent = new WeakMap();
24
+ let continuationsByAgent = new WeakMap();
25
+ let disposeRequest;
26
+ let disposeRequestError;
27
+ let disposeTurnStopping;
28
+ const reset = () => {
29
+ const request = disposeRequest;
30
+ const requestError = disposeRequestError;
31
+ const turnStopping = disposeTurnStopping;
32
+ disposeRequest = undefined;
33
+ disposeRequestError = undefined;
34
+ disposeTurnStopping = undefined;
35
+ pendingByAgent = new WeakMap();
36
+ reservedByAgent = new WeakMap();
37
+ continuationsByAgent = new WeakMap();
38
+ installedContexts.delete(ctx);
39
+ if (typeof turnStopping === "function")
40
+ turnStopping();
41
+ if (typeof requestError === "function")
42
+ requestError();
43
+ if (typeof request === "function")
44
+ request();
45
+ };
46
+ try {
47
+ disposeRequest = ctx.on("agent/request", async (frame, next) => {
48
+ const downstream = await next();
49
+ const pending = pendingByAgent.get(frame.agent);
50
+ if (pending === undefined)
51
+ return downstream;
52
+ if (frame.signal.aborted || !isCurrentRecoveryStep(recoveryEvents(frame.agent), pending.turn, pending.step)) {
53
+ pendingByAgent.delete(frame.agent);
54
+ return downstream;
55
+ }
56
+ if (pending.turn !== frame.turn || pending.step !== frame.step)
57
+ return downstream;
58
+ if (pending.policy !== undefined) {
59
+ const settings = getSettings();
60
+ const role = resolveEffectiveDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive));
61
+ if (role !== pending.role || rolePolicyIdentity(settings, role) !== pending.policy) {
62
+ pendingByAgent.delete(frame.agent);
63
+ reservedByAgent.delete(frame.agent);
64
+ return downstream;
65
+ }
66
+ }
67
+ const reserved = reservedByAgent.get(frame.agent);
68
+ const accepted = frame.agent.session.requestHeader?.()?.config;
69
+ if (reserved !== undefined && accepted !== undefined && !sameModelRoute(accepted, reserved.route) && !sameModelRoute(accepted, pending.route)) {
70
+ pendingByAgent.delete(frame.agent);
71
+ return downstream;
72
+ }
73
+ pendingByAgent.delete(frame.agent);
74
+ recordAdmittedRecoveryRoute(frame, pending.route);
75
+ return applyModelRoute(downstream, pending.route);
76
+ }, { prepend: true });
77
+ disposeRequestError = ctx.on("agent/request-error", async (frame, next) => {
78
+ const downstream = await next();
79
+ if (downstream?.kind === "retry") {
80
+ pendingByAgent.delete(frame.agent);
81
+ return downstream;
82
+ }
83
+ try {
84
+ const settings = getSettings();
85
+ if (!settings.runtimeRecovery.enabled || frame.signal.aborted
86
+ || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step))
87
+ return downstream;
88
+ const preset = resolveSelectedAgentPreset(frame.agent.session);
89
+ const role = resolveEffectiveDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive));
90
+ const inScope = role !== undefined || controller.active(frame.agent, settings.defaultActive)
91
+ || (frame.agent.session.header?.origin !== "subagent" && isDsmmRoleId(preset) && settings.roles[preset]);
92
+ if (!inScope || classifyRecoveryFailure(frame.failure, settings.runtimeRecovery).kind !== "retryable")
93
+ return downstream;
94
+ const header = frame.agent.session.requestHeader?.();
95
+ if (header === undefined || header.config.provider !== frame.provider)
96
+ return downstream;
97
+ const policy = rolePolicyIdentity(settings, role);
98
+ const reserved = reservedByAgent.get(frame.agent);
99
+ if (reserved?.turn === frame.turn && reserved.step === frame.step
100
+ && reserved.policy === policy
101
+ && reserved.route.provider === header.config.provider && reserved.route.model === header.config.model)
102
+ return downstream;
103
+ const attemptedRoutes = foldAttemptedRecoveryRoutes(recoveryEvents(frame.agent), frame.turn, frame.step);
104
+ const lastAttemptedRoute = attemptedRoutes.at(-1);
105
+ if (lastAttemptedRoute === undefined
106
+ || lastAttemptedRoute.provider !== header.config.provider
107
+ || lastAttemptedRoute.model !== header.config.model)
108
+ return downstream;
109
+ const route = selectFallbackRoute({
110
+ failedRoute: { provider: header.config.provider, model: header.config.model },
111
+ attemptedRoutes,
112
+ fallbackRoutes: effectiveRoleFallbackRoutes(settings, role),
113
+ maxFallbackAttempts: settings.runtimeRecovery.maxFallbackAttempts
114
+ });
115
+ if (route === undefined)
116
+ return downstream;
117
+ reservedByAgent.set(frame.agent, {
118
+ turn: frame.turn, step: frame.step,
119
+ route: { provider: header.config.provider, model: header.config.model }, role, policy
120
+ });
121
+ pendingByAgent.set(frame.agent, { turn: frame.turn, step: frame.step, route, role, policy });
122
+ return { kind: "retry" };
123
+ }
124
+ catch {
125
+ warnSafely(ctx, RECOVERY_WARNING);
126
+ return downstream;
127
+ }
128
+ }, { prepend: true });
129
+ disposeTurnStopping = ctx.on("agent/turn-stopping", async (frame) => {
130
+ try {
131
+ const settings = getSettings();
132
+ const continuation = settings.runtimeRecovery.idleContinuation;
133
+ if (!settings.runtimeRecovery.enabled || !continuation.enabled || frame.signal.aborted)
134
+ return;
135
+ const preset = resolveSelectedAgentPreset(frame.agent.session);
136
+ const inScope = controller.active(frame.agent, settings.defaultActive) || isDsmmRoleId(preset);
137
+ if (!inScope || typeof frame.agent.steer !== "function")
138
+ return;
139
+ const work = foldDurableRecoveryWork(sessionEvents(frame.agent.session));
140
+ if (!work.incompleteTodo && !work.activeGoal)
141
+ return;
142
+ const cap = continuation.maxContinuations;
143
+ if (cap <= 0)
144
+ return;
145
+ const previous = continuationsByAgent.get(frame.agent);
146
+ const count = previous?.turn === frame.turn ? previous.count : 0;
147
+ if (count >= cap)
148
+ return;
149
+ continuationsByAgent.set(frame.agent, { turn: frame.turn, count: count + 1 });
150
+ await frame.agent.steer(createUserMessage({
151
+ content: [{ type: "text", text: continuation.prompt }],
152
+ source: { kind: "user" }
153
+ }));
154
+ }
155
+ catch {
156
+ warnSafely(ctx, `${CONTINUATION_WARNING} ${frame.turn}`);
157
+ }
158
+ });
159
+ ctx.effect?.(() => () => {
160
+ reset();
161
+ });
162
+ }
163
+ catch (error) {
164
+ reset();
165
+ throw error;
166
+ }
167
+ }
168
+ //# sourceMappingURL=runtime-recovery.js.map
@@ -0,0 +1,9 @@
1
+ import type { DshAgent, DshSession, DshSessionEvent } from "./dsh-types.js";
2
+ import type { DsmmRoleId } from "./roles.js";
3
+ import type { DsmmSettings } from "./settings.js";
4
+ export declare function sessionEvents(session: DshSession | undefined): readonly DshSessionEvent[];
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;
9
+ //# sourceMappingURL=session-scope.d.ts.map
@@ -0,0 +1,40 @@
1
+ import { foldSubagentDescriptor } from "@deepseek-ai/dsh-subagent";
2
+ import { isDsmmRoleId } from "./roles.js";
3
+ import { roleFromProviderName } from "./role-providers.js";
4
+ export function sessionEvents(session) {
5
+ return session?.snapshotEvents?.() ?? session?.events ?? [];
6
+ }
7
+ export function resolveSelectedAgentPreset(session) {
8
+ const events = sessionEvents(session);
9
+ for (let index = events.length - 1; index >= 0; index -= 1) {
10
+ const event = events[index];
11
+ if (event?.type !== "agent-preset/selected")
12
+ continue;
13
+ const data = event.data;
14
+ if (typeof data === "object" && data !== null && "agentPreset" in data && typeof data.agentPreset === "string") {
15
+ return data.agentPreset;
16
+ }
17
+ }
18
+ return typeof session?.header?.agentPreset === "string" ? session.header.agentPreset : undefined;
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
+ }
40
+ //# sourceMappingURL=session-scope.js.map
@@ -0,0 +1,123 @@
1
+ import Schema from "@deepseek-ai/schemastery";
2
+ import type { DshContext } from "./dsh-types.js";
3
+ import type { DsmmLspSettings } from "./lsp.js";
4
+ import type { DsmmRoleId } from "./roles.js";
5
+ import type { DsmmSkillName } from "./skills.js";
6
+ export { DSMM_SKILL_NAMES, MVP_SKILL_NAMES } from "./skills.js";
7
+ export type { DsmmSkillName, MvpSkillName } from "./skills.js";
8
+ export type DeepseekCalibration = "off" | "auto" | "strict";
9
+ export type DeepseekDefaultReasoningEffort = "off" | "low" | "high";
10
+ export type DsmmFinalReviewPolicy = "simple-oracle-complex-reviewer" | "reviewer-only" | "off";
11
+ export type DsmmGuardScope = "deepwork-or-dsmm-agent" | "always" | "off";
12
+ export type DsmmGitWritePolicy = "ask" | "deny" | "off";
13
+ export interface DsmmWorkflowSettings {
14
+ policy: "risk-based" | "legacy";
15
+ strictGates: boolean;
16
+ reviewCap: number;
17
+ finalReviewPolicy: DsmmFinalReviewPolicy;
18
+ }
19
+ export interface DsmmPresetSettings {
20
+ materialize: boolean;
21
+ root?: string;
22
+ }
23
+ export interface DsmmGuardSettings {
24
+ scope: DsmmGuardScope;
25
+ shellCommandSafety: boolean;
26
+ gitWriteGuard: DsmmGitWritePolicy;
27
+ toolOutputTruncation: {
28
+ enabled: boolean;
29
+ maxInlineBytes: number;
30
+ };
31
+ planFormatValidation: boolean;
32
+ questionLabelHelper: {
33
+ enabled: boolean;
34
+ maxLabelChars: number;
35
+ };
36
+ todoDisciplineHelper: boolean;
37
+ }
38
+ export interface DsmmModelRoute {
39
+ provider: string;
40
+ model: string;
41
+ reasoningEffort?: string;
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>>;
50
+ export interface DsmmRuntimeRecoverySettings {
51
+ enabled: boolean;
52
+ retryOnStatusCodes: number[];
53
+ retryOnCodes: string[];
54
+ fallbackRoutes: DsmmRecoveryRoute[];
55
+ maxFallbackAttempts: number;
56
+ idleContinuation: {
57
+ enabled: boolean;
58
+ maxContinuations: number;
59
+ prompt: string;
60
+ };
61
+ }
62
+ type DsmmGuardConfig = Partial<Omit<DsmmGuardSettings, "toolOutputTruncation" | "questionLabelHelper">> & {
63
+ toolOutputTruncation?: Partial<DsmmGuardSettings["toolOutputTruncation"]>;
64
+ questionLabelHelper?: Partial<DsmmGuardSettings["questionLabelHelper"]>;
65
+ };
66
+ type DsmmRuntimeRecoveryConfig = Partial<Omit<DsmmRuntimeRecoverySettings, "fallbackRoutes" | "idleContinuation">> & {
67
+ fallbackRoutes?: Array<Partial<DsmmRecoveryRoute>>;
68
+ idleContinuation?: Partial<DsmmRuntimeRecoverySettings["idleContinuation"]>;
69
+ };
70
+ export interface DsmmPluginConfig {
71
+ modeName?: string;
72
+ section?: string;
73
+ deepseekV4ProCalibration?: DeepseekCalibration;
74
+ deepseekV4ProDefaultReasoningEffort?: DeepseekDefaultReasoningEffort;
75
+ deepseekV4ProMaxReasoningPresets?: DsmmRoleId[];
76
+ deepseekFlashCalibration?: DeepseekCalibration;
77
+ deepseekFlashDefaultReasoningEffort?: DeepseekDefaultReasoningEffort;
78
+ deepseekFlashMaxReasoningPresets?: DsmmRoleId[];
79
+ defaultActive?: boolean;
80
+ promptOrder?: number;
81
+ skills?: Partial<Record<DsmmSkillName, boolean>>;
82
+ roles?: Partial<Record<DsmmRoleId, boolean>>;
83
+ roleRouting?: DsmmRoleRouting;
84
+ presets?: Partial<DsmmPresetSettings>;
85
+ workflow?: Partial<DsmmWorkflowSettings>;
86
+ guards?: DsmmGuardConfig;
87
+ runtimeRecovery?: DsmmRuntimeRecoveryConfig;
88
+ lsp?: Partial<DsmmLspSettings>;
89
+ }
90
+ export interface DsmmSettings {
91
+ modeName: string;
92
+ defaultActive: boolean;
93
+ promptOrder: number;
94
+ deepseekV4ProCalibration: DeepseekCalibration;
95
+ deepseekV4ProDefaultReasoningEffort: DeepseekDefaultReasoningEffort;
96
+ deepseekV4ProMaxReasoningPresets: DsmmRoleId[];
97
+ deepseekFlashCalibration: DeepseekCalibration;
98
+ deepseekFlashDefaultReasoningEffort: DeepseekDefaultReasoningEffort;
99
+ deepseekFlashMaxReasoningPresets: DsmmRoleId[];
100
+ skills: Record<DsmmSkillName, boolean>;
101
+ roles: Record<DsmmRoleId, boolean>;
102
+ roleRouting: DsmmRoleRouting;
103
+ presets: DsmmPresetSettings;
104
+ workflow: DsmmWorkflowSettings;
105
+ guards: DsmmGuardSettings;
106
+ runtimeRecovery: DsmmRuntimeRecoverySettings;
107
+ lsp: DsmmLspSettings;
108
+ }
109
+ export declare const DSMM_SETTINGS_NAMESPACE = "dsmm";
110
+ export declare const DSMM_STATUS_COMMAND = "dsmm-status";
111
+ export interface RegisterSettingsOptions {
112
+ onChange?: (settings: DsmmSettings) => void;
113
+ install?: (readyCtx: DshContext, getSettings: () => DsmmSettings) => void;
114
+ }
115
+ export declare const DEFAULT_DSMM_SETTINGS: DsmmSettings;
116
+ export declare const DSMM_CONFIG_SCHEMA: Schema<DsmmPluginConfig>;
117
+ export declare const DSMM_SETTINGS_SCHEMA: Schema<DsmmSettings>;
118
+ export declare function resolveConfig(config?: DsmmPluginConfig): DsmmSettings;
119
+ export declare function resolveRoleRouting(input: DsmmRoleRouting | undefined): DsmmRoleRouting;
120
+ export declare function isRoleEnabled(settings: DsmmSettings, role: DsmmRoleId): boolean;
121
+ export declare function resolveGuardSettings(config: DsmmPluginConfig["guards"]): DsmmGuardSettings;
122
+ export declare function registerSettings(ctx: DshContext, config?: DsmmPluginConfig, options?: RegisterSettingsOptions): () => DsmmSettings;
123
+ //# sourceMappingURL=settings.d.ts.map