@dsmm/dsmm 0.0.0-stage → 0.1.0

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 (125) hide show
  1. package/LICENSE +103 -0
  2. package/README.md +67 -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 +17 -0
  29. package/docs/compatibility.md +46 -0
  30. package/docs/design.md +237 -0
  31. package/docs/lsp.md +40 -0
  32. package/docs/migration-from-ocmm.md +48 -0
  33. package/docs/model-routing.md +16 -0
  34. package/docs/releasing.md +50 -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 +67 -0
  39. package/docs/safety-guards.md +55 -0
  40. package/docs/settings-status.md +51 -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 +13 -0
  45. package/lib/dsh-events.js +2 -0
  46. package/lib/dsh-types.d.ts +308 -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 +31 -0
  51. package/lib/index.js +54 -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 +103 -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-subagents.d.ts +6 -0
  73. package/lib/role-subagents.js +54 -0
  74. package/lib/roles.d.ts +28 -0
  75. package/lib/roles.js +239 -0
  76. package/lib/runtime-recovery.d.ts +5 -0
  77. package/lib/runtime-recovery.js +149 -0
  78. package/lib/session-scope.d.ts +4 -0
  79. package/lib/session-scope.js +17 -0
  80. package/lib/settings.d.ts +112 -0
  81. package/lib/settings.js +363 -0
  82. package/lib/shell-command.d.ts +18 -0
  83. package/lib/shell-command.js +492 -0
  84. package/lib/skills.d.ts +18 -0
  85. package/lib/skills.js +64 -0
  86. package/lib/state.d.ts +13 -0
  87. package/lib/state.js +64 -0
  88. package/lib/status.d.ts +46 -0
  89. package/lib/status.js +155 -0
  90. package/package.json +124 -4
  91. package/patches/agent-presets-root.example.cordis.patch.yml +14 -0
  92. package/patches/ocmm-lsp-mcp.example.cordis.patch.yml +15 -0
  93. package/prompts/deepseek-flash.md +11 -0
  94. package/prompts/deepseek-v4-pro.md +14 -0
  95. package/prompts/deepwork.md +32 -0
  96. package/skills/brainstorming/SKILL.md +15 -0
  97. package/skills/debugging/SKILL.md +12 -0
  98. package/skills/debugging/references/logging.md +91 -0
  99. package/skills/debugging/references/methodology/00-setup.md +108 -0
  100. package/skills/debugging/references/methodology/02-investigate.md +67 -0
  101. package/skills/debugging/references/methodology/03-flaky-triage.md +69 -0
  102. package/skills/debugging/references/methodology/04-hard-reasoning-escalation.md +83 -0
  103. package/skills/debugging/references/methodology/05-escalate.md +69 -0
  104. package/skills/debugging/references/methodology/06-fix.md +123 -0
  105. package/skills/debugging/references/methodology/08-qa.md +94 -0
  106. package/skills/debugging/references/methodology/09-cleanup.md +164 -0
  107. package/skills/debugging/references/methodology/partial-runtime-evidence.md +217 -0
  108. package/skills/debugging/references/runtimes/bundled-js-binary.md +415 -0
  109. package/skills/debugging/references/runtimes/go.md +252 -0
  110. package/skills/debugging/references/runtimes/native-binary.md +484 -0
  111. package/skills/debugging/references/runtimes/node.md +260 -0
  112. package/skills/debugging/references/runtimes/python.md +248 -0
  113. package/skills/debugging/references/runtimes/rust.md +234 -0
  114. package/skills/debugging/references/scripts/dap.mjs +533 -0
  115. package/skills/debugging/references/tools/dap.md +89 -0
  116. package/skills/debugging/references/tools/ghidra.md +212 -0
  117. package/skills/debugging/references/tools/playwright-cli.md +316 -0
  118. package/skills/debugging/references/tools/pwndbg.md +263 -0
  119. package/skills/debugging/references/tools/pwntools.md +265 -0
  120. package/skills/dispatching-parallel-agents/SKILL.md +14 -0
  121. package/skills/receiving-code-review/SKILL.md +13 -0
  122. package/skills/remove-ai-slops/SKILL.md +14 -0
  123. package/skills/requesting-code-review/SKILL.md +10 -0
  124. package/skills/subagent-driven-development/SKILL.md +13 -0
  125. package/skills/writing-plans/SKILL.md +14 -0
package/lib/lsp.js ADDED
@@ -0,0 +1,154 @@
1
+ export const DSMM_LSP_SERVER_NAME = "dsmm_lsp";
2
+ export const DSMM_LSP_TOOL_NAMES = [
3
+ "status",
4
+ "diagnostics",
5
+ "goto_definition",
6
+ "find_references",
7
+ "find_symbol_related",
8
+ "symbols",
9
+ "prepare_rename",
10
+ "rename",
11
+ "format"
12
+ ];
13
+ export const DEFAULT_DSMM_LSP_SETTINGS = {
14
+ enabled: false,
15
+ serverName: "dsmm_lsp",
16
+ command: "ocmm-lsp",
17
+ args: ["mcp"],
18
+ cwd: "",
19
+ env: {},
20
+ toolCallTimeoutMs: 60000,
21
+ failOnStartupError: true
22
+ };
23
+ const SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/u;
24
+ export function resolveLspSettings(input = {}) {
25
+ const serverName = input.serverName ?? DEFAULT_DSMM_LSP_SETTINGS.serverName;
26
+ validateServerName(serverName);
27
+ const command = input.command ?? DEFAULT_DSMM_LSP_SETTINGS.command;
28
+ if (typeof command !== "string" || command.trim() === "")
29
+ throw new Error("dsmm lsp command must be a non-empty string");
30
+ const args = input.args ?? DEFAULT_DSMM_LSP_SETTINGS.args;
31
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string"))
32
+ throw new Error("dsmm lsp args must be an array of strings");
33
+ const env = input.env ?? DEFAULT_DSMM_LSP_SETTINGS.env;
34
+ if (!isStringRecord(env))
35
+ throw new Error("dsmm lsp env must be a string record");
36
+ return {
37
+ enabled: input.enabled ?? DEFAULT_DSMM_LSP_SETTINGS.enabled,
38
+ serverName,
39
+ command,
40
+ args: [...args],
41
+ cwd: input.cwd ?? DEFAULT_DSMM_LSP_SETTINGS.cwd,
42
+ env: { ...env },
43
+ toolCallTimeoutMs: normalizeTimeout(input.toolCallTimeoutMs),
44
+ failOnStartupError: input.failOnStartupError ?? DEFAULT_DSMM_LSP_SETTINGS.failOnStartupError
45
+ };
46
+ }
47
+ export function toDshMcpClientConfig(input = {}) {
48
+ const settings = resolveLspSettings(input);
49
+ return {
50
+ transport: "stdio",
51
+ serverName: settings.serverName,
52
+ command: settings.command,
53
+ args: settings.args,
54
+ env: settings.env,
55
+ cwd: settings.cwd,
56
+ toolCallTimeoutMs: settings.toolCallTimeoutMs,
57
+ failOnStartupError: settings.failOnStartupError
58
+ };
59
+ }
60
+ export function publicLspToolName(rawName, serverName = DEFAULT_DSMM_LSP_SETTINGS.serverName) {
61
+ validateServerName(serverName);
62
+ return `mcp__${serverName}__${rawName}`;
63
+ }
64
+ export function renderLspMcpPatch(input = {}) {
65
+ const settings = resolveLspSettings(input);
66
+ const lines = [
67
+ "# Example only: opt-in dsmm LSP MCP bridge.",
68
+ "# Requires ocmm-lsp to be on PATH or command to be replaced with an absolute wrapper path.",
69
+ "- insert:",
70
+ " - id: dsmm-lsp-mcp",
71
+ " name: '@deepseek-ai/dsh-mcp-client'",
72
+ " config:",
73
+ " transport: stdio",
74
+ ` serverName: ${renderYamlScalar(settings.serverName)}`,
75
+ ` command: ${renderYamlScalar(settings.command)}`,
76
+ ...renderYamlStringArray(" args", settings.args),
77
+ ...renderYamlStringRecord(" env", settings.env),
78
+ ` cwd: ${renderYamlScalar(settings.cwd)}`,
79
+ ` toolCallTimeoutMs: ${settings.toolCallTimeoutMs}`,
80
+ ` failOnStartupError: ${settings.failOnStartupError}`
81
+ ];
82
+ return `${lines.join("\n")}\n`;
83
+ }
84
+ export function parseLspSmokeCommand(raw, fallback) {
85
+ const trimmed = raw?.trim();
86
+ if (trimmed === undefined || trimmed === "")
87
+ return [...fallback];
88
+ if (trimmed.startsWith("[")) {
89
+ let parsed;
90
+ try {
91
+ parsed = JSON.parse(trimmed);
92
+ }
93
+ catch (cause) {
94
+ throw new Error("dsmm lsp smoke command must be a non-empty string array when provided as JSON", { cause });
95
+ }
96
+ if (!Array.isArray(parsed) || parsed.length === 0 || parsed.some((value) => typeof value !== "string")) {
97
+ throw new Error("dsmm lsp smoke command must be a non-empty string array when provided as JSON");
98
+ }
99
+ return [...parsed];
100
+ }
101
+ return [trimmed, "mcp"];
102
+ }
103
+ function validateServerName(serverName) {
104
+ if (!SERVER_NAME_PATTERN.test(serverName))
105
+ throw new Error("dsmm lsp serverName must match /^[A-Za-z0-9_-]{1,32}$/u");
106
+ }
107
+ function normalizeTimeout(value) {
108
+ if (value === undefined || !Number.isFinite(value) || value <= 0)
109
+ return DEFAULT_DSMM_LSP_SETTINGS.toolCallTimeoutMs;
110
+ return Math.floor(value);
111
+ }
112
+ function isStringRecord(value) {
113
+ if (value === null || typeof value !== "object" || Array.isArray(value))
114
+ return false;
115
+ return Object.values(value).every((entry) => typeof entry === "string");
116
+ }
117
+ function renderYamlStringArray(key, values) {
118
+ if (values.length === 0)
119
+ return [`${key}: []`];
120
+ const itemIndent = `${key.match(/^ */u)?.[0] ?? ""} `;
121
+ return [
122
+ `${key}:`,
123
+ ...values.map((value) => `${itemIndent}- ${renderYamlScalar(value)}`)
124
+ ];
125
+ }
126
+ function renderYamlStringRecord(key, values) {
127
+ const entries = Object.entries(values).sort(([left], [right]) => left.localeCompare(right));
128
+ if (entries.length === 0)
129
+ return [`${key}: {}`];
130
+ const itemIndent = `${key.match(/^ */u)?.[0] ?? ""} `;
131
+ return [
132
+ `${key}:`,
133
+ ...entries.map(([entryKey, value]) => `${itemIndent}${renderYamlScalar(entryKey)}: ${renderYamlScalar(value)}`)
134
+ ];
135
+ }
136
+ function renderYamlScalar(value) {
137
+ if (isPlainYamlScalar(value))
138
+ return value;
139
+ return JSON.stringify(value);
140
+ }
141
+ function isPlainYamlScalar(value) {
142
+ if (value === "")
143
+ return false;
144
+ if (value !== value.trim())
145
+ return false;
146
+ if (!/^[A-Za-z0-9_./-]+$/u.test(value))
147
+ return false;
148
+ if (/^(?:true|false|null|~)$/iu.test(value))
149
+ return false;
150
+ if (/^[+-]?(?:\d+|\d*\.\d+)(?:e[+-]?\d+)?$/iu.test(value))
151
+ return false;
152
+ return !value.startsWith("---") && !value.startsWith("...");
153
+ }
154
+ //# sourceMappingURL=lsp.js.map
package/lib/mode.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { DshContext } from "./dsh-types.js";
2
+ import type { Config } from "./index.js";
3
+ import type { DsmmSettings } from "./settings.js";
4
+ import type { DeepworkModeController } from "./state.js";
5
+ export declare function registerDeepworkPrompt(readyCtx: DshContext, controller: DeepworkModeController, getSettings: () => DsmmSettings, config?: Config): void;
6
+ //# sourceMappingURL=mode.d.ts.map
package/lib/mode.js ADDED
@@ -0,0 +1,62 @@
1
+ import { symbols } from "@deepseek-ai/cordis";
2
+ import { buildDeepworkPrompt } from "./prompts.js";
3
+ import { isDsmmRoleId } from "./roles.js";
4
+ import { resolveSelectedAgentPreset } from "./session-scope.js";
5
+ import { enabledSkillNames, renderBundledSkillPrompt } from "./skills.js";
6
+ function routeFromAgent(context) {
7
+ const header = context.agent?.session.requestHeader?.();
8
+ const { provider, model } = (header === undefined ? context.agent?.options : header.config) ?? {};
9
+ return typeof provider === "string" && typeof model === "string" ? { provider, model } : undefined;
10
+ }
11
+ export function registerDeepworkPrompt(readyCtx, controller, getSettings, config = {}) {
12
+ const section = {
13
+ name: "dsmm:deepwork",
14
+ order: getSettings().promptOrder,
15
+ interpolate: false,
16
+ text(context) {
17
+ const settings = getSettings();
18
+ const preset = resolveSelectedAgentPreset(context.agent?.session);
19
+ const active = controller.active(context.agent, settings.defaultActive);
20
+ if (!active && !isDsmmRoleId(preset))
21
+ return "";
22
+ const skillPrompt = isDsmmRoleId(preset) ? "" : renderBundledSkillPrompt(enabledSkillNames(settings));
23
+ return buildDeepworkPrompt(settings, {
24
+ route: routeFromAgent(context),
25
+ selectedPreset: preset,
26
+ overrideSection: config.section,
27
+ skillPrompt
28
+ });
29
+ }
30
+ };
31
+ const installed = new WeakSet();
32
+ const install = (registry) => {
33
+ if (registry === undefined)
34
+ return;
35
+ const service = registry[symbols.original] ?? registry;
36
+ if (installed.has(service))
37
+ return;
38
+ const dispose = service.section(section);
39
+ installed.add(service);
40
+ readyCtx.effect?.(() => () => {
41
+ installed.delete(service);
42
+ if (typeof dispose === "function")
43
+ dispose();
44
+ });
45
+ };
46
+ const registry = readyCtx.get !== undefined
47
+ ? readyCtx.get("systemPrompt")
48
+ : readyCtx.systemPrompt;
49
+ install(registry);
50
+ const installForAgent = (agent) => {
51
+ const presets = readyCtx.get?.("agentPresets");
52
+ install(presets?.serviceFor(agent, "systemPrompt") ?? agent.ctx?.get?.("systemPrompt"));
53
+ };
54
+ // Creation and blank-session selection both finish mounting before these events.
55
+ readyCtx.on?.("agent/created", ({ agent }) => installForAgent(agent), { global: true });
56
+ readyCtx.on?.("agent-preset/selected", (sessionId) => {
57
+ const agent = readyCtx.get?.("agents")?.get(sessionId);
58
+ if (agent !== undefined)
59
+ installForAgent(agent);
60
+ }, { global: true });
61
+ }
62
+ //# sourceMappingURL=mode.js.map
@@ -0,0 +1,6 @@
1
+ export type DsmmModelFamily = "gpt" | "codex" | "claude" | "gemini" | "glm" | "kimi" | "deepseek" | "unknown";
2
+ export declare function classifyModelFamily(input: {
3
+ providerID?: string;
4
+ modelID?: string;
5
+ }): DsmmModelFamily;
6
+ //# sourceMappingURL=model-family.d.ts.map
@@ -0,0 +1,49 @@
1
+ const DOTTED_VENDOR_MODEL_PREFIXES = {
2
+ openai: /^(?:gpt-|o\d|chatgpt-|codex-)/,
3
+ anthropic: /^claude-/,
4
+ google: /^gemini-/,
5
+ zhipu: /^glm-/,
6
+ deepseek: /^deepseek-/
7
+ };
8
+ function stripDottedVendorModelPrefix(name) {
9
+ const parts = name.split(".");
10
+ const vendor = parts[0];
11
+ const model = parts.slice(1).join(".");
12
+ if (vendor && DOTTED_VENDOR_MODEL_PREFIXES[vendor]?.test(model))
13
+ return model;
14
+ const region = parts[0];
15
+ const regionalVendor = parts[1];
16
+ const regionalModel = parts.slice(2).join(".");
17
+ if (region
18
+ && regionalVendor
19
+ && /^(?:[a-z]{2}|[a-z]{2}-[a-z]+-\d+)$/.test(region)
20
+ && DOTTED_VENDOR_MODEL_PREFIXES[regionalVendor]?.test(regionalModel)) {
21
+ return regionalModel;
22
+ }
23
+ return name;
24
+ }
25
+ function extractModelName(fullID) {
26
+ const index = fullID.lastIndexOf("/");
27
+ return stripDottedVendorModelPrefix(index >= 0 ? fullID.slice(index + 1) : fullID);
28
+ }
29
+ export function classifyModelFamily(input) {
30
+ const providerID = input.providerID?.trim().toLowerCase() ?? "";
31
+ const modelID = input.modelID?.trim().toLowerCase() ?? "";
32
+ const name = extractModelName(modelID);
33
+ if (providerID.includes("codex") || name.includes("codex"))
34
+ return "codex";
35
+ if (name.includes("gpt"))
36
+ return "gpt";
37
+ if (providerID.includes("anthropic") || name.includes("claude"))
38
+ return "claude";
39
+ if (providerID === "google" || providerID === "google-vertex" || name.startsWith("gemini-"))
40
+ return "gemini";
41
+ if (providerID.includes("zhipu") || name.includes("glm"))
42
+ return "glm";
43
+ if (providerID.includes("moonshot") || providerID.includes("kimi") || name.includes("kimi") || /k2[-.]?p[567]/.test(name))
44
+ return "kimi";
45
+ if (providerID.includes("deepseek") || name.includes("deepseek"))
46
+ return "deepseek";
47
+ return "unknown";
48
+ }
49
+ //# sourceMappingURL=model-family.js.map
@@ -0,0 +1,11 @@
1
+ import type { DshContext, DshLlmCallConfig, DshModelReasoningInfo } from "./dsh-types.js";
2
+ import type { DeepseekDefaultReasoningEffort, DsmmSettings } from "./settings.js";
3
+ import type { DeepworkModeController } from "./state.js";
4
+ export type DeepseekReasoningEffort = DeepseekDefaultReasoningEffort | "max";
5
+ export type DeepseekModelRoute = "v4-pro" | "flash";
6
+ export declare function isDeepseekV4ProRoute(config: Pick<DshLlmCallConfig, "provider" | "model">): boolean;
7
+ export declare function isDeepseekFlashRoute(config: Pick<DshLlmCallConfig, "provider" | "model">): boolean;
8
+ export declare function desiredDeepseekEffort(settings: DsmmSettings, preset?: string, route?: DeepseekModelRoute): DeepseekReasoningEffort;
9
+ export declare function selectAdvertisedEffort(desired: DeepseekReasoningEffort, reasoning: DshModelReasoningInfo | undefined): string | undefined;
10
+ export declare function registerModelRouting(ctx: DshContext, controller: DeepworkModeController, getSettings: () => DsmmSettings): void;
11
+ //# sourceMappingURL=model-routing.d.ts.map
@@ -0,0 +1,103 @@
1
+ import { isDsmmRoleId } from "./roles.js";
2
+ import { resolveSelectedAgentPreset } from "./session-scope.js";
3
+ export function isDeepseekV4ProRoute(config) {
4
+ return config.provider.toLowerCase() === "deepseek-official" && config.model.toLowerCase() === "deepseek-v4-pro";
5
+ }
6
+ export function isDeepseekFlashRoute(config) {
7
+ return ["deepseek-official", "deepseek-account"].includes(config.provider.toLowerCase())
8
+ && config.model.toLowerCase() === "deepseek-flash";
9
+ }
10
+ export function desiredDeepseekEffort(settings, preset, route = "v4-pro") {
11
+ const maxPresets = route === "flash" ? settings.deepseekFlashMaxReasoningPresets : settings.deepseekV4ProMaxReasoningPresets;
12
+ return preset !== undefined && maxPresets.some((configuredPreset) => configuredPreset === preset)
13
+ ? "max"
14
+ : route === "flash" ? settings.deepseekFlashDefaultReasoningEffort : settings.deepseekV4ProDefaultReasoningEffort;
15
+ }
16
+ export function selectAdvertisedEffort(desired, reasoning) {
17
+ if (!reasoning)
18
+ return undefined;
19
+ const advertised = new Set(reasoning.efforts.map((effort) => effort.id));
20
+ const fallback = reasoning.defaultEffort !== undefined && advertised.has(reasoning.defaultEffort) ? reasoning.defaultEffort : undefined;
21
+ if (desired === "max") {
22
+ if (advertised.has("max"))
23
+ return "max";
24
+ if (advertised.has("high"))
25
+ return "high";
26
+ return fallback;
27
+ }
28
+ return advertised.has(desired) ? desired : fallback;
29
+ }
30
+ export function registerModelRouting(ctx, controller, getSettings) {
31
+ const installedContexts = new WeakSet();
32
+ const install = (readyCtx) => {
33
+ if (installedContexts.has(readyCtx) || readyCtx.on === undefined)
34
+ return;
35
+ installedContexts.add(readyCtx);
36
+ let dispose;
37
+ try {
38
+ dispose = readyCtx.on("agent/request", async (frame, next) => {
39
+ const downstream = await next();
40
+ const settings = getSettings();
41
+ const route = isDeepseekV4ProRoute(downstream) ? "v4-pro" : isDeepseekFlashRoute(downstream) ? "flash" : undefined;
42
+ if (route === undefined)
43
+ return downstream;
44
+ const calibration = route === "flash" ? settings.deepseekFlashCalibration : settings.deepseekV4ProCalibration;
45
+ if (calibration === "off")
46
+ return downstream;
47
+ const preset = resolveSelectedAgentPreset(frame.agent?.session);
48
+ const inScope = controller.active(frame.agent, settings.defaultActive) || isDsmmRoleId(preset);
49
+ if (!inScope)
50
+ return downstream;
51
+ if (calibration === "auto" && downstream.reasoningEffort !== undefined)
52
+ return downstream;
53
+ const desired = desiredDeepseekEffort(settings, preset, route);
54
+ let selected;
55
+ try {
56
+ const agentContext = frame.agent.ctx;
57
+ const llm = agentContext?.get?.("llm")
58
+ ?? (readyCtx.get !== undefined ? readyCtx.get("llm") : readyCtx.llm);
59
+ const modelInfo = await llm?.resolveModelInfo(downstream.provider, downstream.model, frame.signal);
60
+ selected = selectAdvertisedEffort(desired, modelInfo?.reasoning);
61
+ }
62
+ catch {
63
+ warnUnavailable(readyCtx, ctx, desired, `${downstream.provider}/${downstream.model}`);
64
+ return downstream;
65
+ }
66
+ if (selected === undefined) {
67
+ warnUnavailable(readyCtx, ctx, desired, `${downstream.provider}/${downstream.model}`);
68
+ return downstream;
69
+ }
70
+ return { ...downstream, reasoningEffort: selected };
71
+ }, { prepend: true });
72
+ }
73
+ catch (error) {
74
+ installedContexts.delete(readyCtx);
75
+ throw error;
76
+ }
77
+ readyCtx.effect?.(() => () => {
78
+ installedContexts.delete(readyCtx);
79
+ if (typeof dispose === "function")
80
+ dispose();
81
+ });
82
+ };
83
+ // Current DSH owns LLM services in Agent realms, invisible to Host injection.
84
+ if (ctx.get !== undefined) {
85
+ install(ctx);
86
+ return;
87
+ }
88
+ if (ctx.inject !== undefined) {
89
+ ctx.inject(["llm"], install);
90
+ return;
91
+ }
92
+ if (Object.prototype.hasOwnProperty.call(ctx, "llm") && Object.prototype.hasOwnProperty.call(ctx, "on"))
93
+ install(ctx);
94
+ }
95
+ function warnUnavailable(readyCtx, rootCtx, desired, modelRoute) {
96
+ try {
97
+ (readyCtx.logger ?? rootCtx.logger)?.warn(`dsmm could not select advertised reasoning effort for ${modelRoute}; desired ${desired}`);
98
+ }
99
+ catch {
100
+ // Warning emission is diagnostic-only and must not alter routing fail-open behavior.
101
+ }
102
+ }
103
+ //# sourceMappingURL=model-routing.js.map
@@ -0,0 +1,3 @@
1
+ import type { DshPreToolDecision, DshToolExecution } from "./dsh-types.js";
2
+ export declare function validatePlanMutation(exec: DshToolExecution): DshPreToolDecision | undefined;
3
+ //# sourceMappingURL=plan-validation.d.ts.map
@@ -0,0 +1,119 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isAbsolute, posix, relative, resolve, sep } from "node:path";
3
+ const GUARD_PREFIX = "[dsmm safety]";
4
+ const PLAN_PATH_PATTERN = /^(?:docs\/superpowers\/plans|\.omo\/plans)\/[^/]+\.md$/iu;
5
+ const PLAN_PATH_SUFFIX_PATTERN = /(?:^|\/)(?:docs\/superpowers\/plans|\.omo\/plans)\/[^/]+\.md$/iu;
6
+ function asRecord(value) {
7
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
8
+ }
9
+ function stringField(value, keys) {
10
+ const record = asRecord(value);
11
+ if (record === undefined)
12
+ return undefined;
13
+ for (const key of keys) {
14
+ if (typeof record[key] === "string")
15
+ return record[key];
16
+ }
17
+ return undefined;
18
+ }
19
+ function normalizedPath(path) {
20
+ return path.replace(/\\/gu, "/");
21
+ }
22
+ function hasPlanPathSuffix(path) {
23
+ return PLAN_PATH_SUFFIX_PATTERN.test(posix.normalize(normalizedPath(path)));
24
+ }
25
+ function isOutside(cwd, target) {
26
+ const targetRelative = relative(cwd, target);
27
+ return isAbsolute(targetRelative) || targetRelative === ".." || targetRelative.startsWith(`..${sep}`);
28
+ }
29
+ function malformedChecklistLine(content) {
30
+ return content.split(/\r?\n/u).find((line) => {
31
+ const token = /^\s*[-*]\s+(\[[^\]\r\n]*(?:\]|$))/u.exec(line)?.[1];
32
+ return token !== undefined && !/^\[(?: |x|X)\]$/u.test(token);
33
+ });
34
+ }
35
+ function malformedChecklistDecision(content) {
36
+ const malformed = malformedChecklistLine(content);
37
+ if (malformed === undefined)
38
+ return undefined;
39
+ return {
40
+ kind: "deny",
41
+ reason: `${GUARD_PREFIX} plan file contains a malformed checklist entry: ${malformed.trim()}`
42
+ };
43
+ }
44
+ function countMatches(content, search) {
45
+ let count = 0;
46
+ let start = 0;
47
+ while (start <= content.length - search.length) {
48
+ const match = content.indexOf(search, start);
49
+ if (match === -1)
50
+ break;
51
+ count += 1;
52
+ start = match + search.length;
53
+ }
54
+ return count;
55
+ }
56
+ function errorMessage(error) {
57
+ return error instanceof Error ? error.message : String(error);
58
+ }
59
+ function validateWrite(arguments_) {
60
+ if (typeof arguments_.content !== "string") {
61
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot validate plan write: content must be a string` };
62
+ }
63
+ return malformedChecklistDecision(arguments_.content);
64
+ }
65
+ function validateEdit(suppliedPath, target, arguments_) {
66
+ if (typeof arguments_.old_string !== "string" || arguments_.old_string === "") {
67
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot validate plan edit for ${suppliedPath}: old_string must be non-empty` };
68
+ }
69
+ if (typeof arguments_.new_string !== "string") {
70
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot validate plan edit for ${suppliedPath}: new_string must be a string` };
71
+ }
72
+ if (arguments_.replace_all !== undefined && typeof arguments_.replace_all !== "boolean") {
73
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot validate plan edit for ${suppliedPath}: replace_all must be boolean` };
74
+ }
75
+ let current;
76
+ try {
77
+ current = readFileSync(target, "utf8");
78
+ }
79
+ catch (error) {
80
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot read plan edit target ${suppliedPath}: ${errorMessage(error)}` };
81
+ }
82
+ const matchCount = countMatches(current, arguments_.old_string);
83
+ let finalDocument;
84
+ if (arguments_.replace_all === true) {
85
+ if (matchCount === 0) {
86
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot reconstruct plan edit for ${suppliedPath}: old_string was not found` };
87
+ }
88
+ finalDocument = current.split(arguments_.old_string).join(arguments_.new_string);
89
+ }
90
+ else {
91
+ if (matchCount !== 1) {
92
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot reconstruct plan edit for ${suppliedPath}: expected exactly one old_string match, found ${String(matchCount)}` };
93
+ }
94
+ const match = current.indexOf(arguments_.old_string);
95
+ finalDocument = `${current.slice(0, match)}${arguments_.new_string}${current.slice(match + arguments_.old_string.length)}`;
96
+ }
97
+ return malformedChecklistDecision(finalDocument);
98
+ }
99
+ export function validatePlanMutation(exec) {
100
+ const name = exec.name.toLowerCase();
101
+ if (name !== "write" && name !== "edit")
102
+ return undefined;
103
+ const arguments_ = asRecord(exec.arguments);
104
+ const suppliedPath = stringField(arguments_, ["file_path", "path"]);
105
+ if (arguments_ === undefined || suppliedPath === undefined)
106
+ return undefined;
107
+ const cwd = resolve(exec.agent?.session.header?.cwd ?? process.cwd());
108
+ const target = resolve(cwd, suppliedPath);
109
+ if (isOutside(cwd, target)) {
110
+ if (!hasPlanPathSuffix(suppliedPath))
111
+ return undefined;
112
+ return { kind: "deny", reason: `${GUARD_PREFIX} cannot validate plan target outside session cwd: ${suppliedPath}` };
113
+ }
114
+ const targetRelative = normalizedPath(relative(cwd, target));
115
+ if (!PLAN_PATH_PATTERN.test(targetRelative))
116
+ return undefined;
117
+ return name === "write" ? validateWrite(arguments_) : validateEdit(suppliedPath, target, arguments_);
118
+ }
119
+ //# sourceMappingURL=plan-validation.js.map
@@ -0,0 +1,36 @@
1
+ import type { DsmmRoleId } from "./roles.js";
2
+ import type { DsmmSettings } from "./settings.js";
3
+ export declare const DSMM_MANAGED_PRESET_MARKER = ".dsmm-managed-preset";
4
+ export declare const DSMM_MANAGED_PRESET_MARKER_VERSION = 1;
5
+ interface PresetFilesystem {
6
+ lstatSync(path: string): PresetFileStatus;
7
+ mkdirSync(path: string, options?: {
8
+ recursive?: boolean;
9
+ }): void;
10
+ readFileSync(path: string, encoding: "utf8"): string;
11
+ readdirSync(path: string): string[];
12
+ realpathSync(path: string): string;
13
+ renameSync(from: string, to: string): void;
14
+ rmSync(path: string, options: {
15
+ recursive: boolean;
16
+ force: boolean;
17
+ }): void;
18
+ writeFileSync(path: string, data: string, encoding: "utf8"): void;
19
+ }
20
+ export interface RolePresetMaterializerOptions {
21
+ root: string;
22
+ settings: DsmmSettings;
23
+ /** Test-only narrow filesystem seam for fault and link judgement coverage. */
24
+ filesystem?: Partial<PresetFilesystem>;
25
+ }
26
+ interface PresetFileStatus {
27
+ isSymbolicLink(): boolean;
28
+ isDirectory(): boolean;
29
+ isFile(): boolean;
30
+ }
31
+ export declare function renderManagedPresetMarker(role: DsmmRoleId): string;
32
+ export declare function resolveManagedPresetRoot(settings: DsmmSettings, env?: NodeJS.ProcessEnv): string | undefined;
33
+ export declare function materializeRolePresets(options: RolePresetMaterializerOptions): void;
34
+ export declare function reconcileRolePresets({ root, settings, filesystem: filesystemOverride }: RolePresetMaterializerOptions): void;
35
+ export {};
36
+ //# sourceMappingURL=preset-materializer.d.ts.map