@dsmm/dsmm 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +24 -13
  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 +64 -11
  28. package/docs/model-routing.md +10 -6
  29. package/docs/profiles.md +83 -0
  30. package/docs/releasing.md +58 -19
  31. package/docs/settings-status.md +13 -5
  32. package/lib/client/ProfilesSection.d.ts +11 -0
  33. package/lib/client/ProfilesSection.js +62 -0
  34. package/lib/client/controller.d.ts +77 -0
  35. package/lib/client/controller.js +198 -0
  36. package/lib/client/index.d.ts +11 -0
  37. package/lib/client/index.js +34 -0
  38. package/lib/client/locales.d.ts +56 -0
  39. package/lib/client/locales.js +48 -0
  40. package/lib/client/styles.d.ts +3 -0
  41. package/lib/client/styles.js +25 -0
  42. package/lib/client.js +1930 -0
  43. package/lib/commands.d.ts +3 -3
  44. package/lib/commands.js +4 -4
  45. package/lib/dsh-types.d.ts +4 -0
  46. package/lib/guards.d.ts +2 -2
  47. package/lib/guards.js +3 -2
  48. package/lib/index.d.ts +12 -4
  49. package/lib/index.js +72 -20
  50. package/lib/mode.d.ts +2 -2
  51. package/lib/mode.js +1 -1
  52. package/lib/model-routing.d.ts +2 -2
  53. package/lib/model-routing.js +17 -2
  54. package/lib/preset-registry.js +5 -3
  55. package/lib/profile-remote.d.ts +31 -0
  56. package/lib/profile-remote.js +106 -0
  57. package/lib/profile-rpc.d.ts +27 -0
  58. package/lib/profile-rpc.js +90 -0
  59. package/lib/profile-runtime.d.ts +44 -0
  60. package/lib/profile-runtime.js +159 -0
  61. package/lib/profile-store.d.ts +42 -0
  62. package/lib/profile-store.js +478 -0
  63. package/lib/profile-types.d.ts +40 -0
  64. package/lib/profile-types.js +2 -0
  65. package/lib/profiles.d.ts +26 -0
  66. package/lib/profiles.js +237 -0
  67. package/lib/prompts.d.ts +2 -2
  68. package/lib/prompts.js +4 -4
  69. package/lib/role-providers.d.ts +2 -2
  70. package/lib/role-providers.js +39 -6
  71. package/lib/role-routing.d.ts +2 -2
  72. package/lib/role-routing.js +4 -1
  73. package/lib/role-subagents.d.ts +2 -2
  74. package/lib/role-subagents.js +6 -4
  75. package/lib/roles.d.ts +4 -0
  76. package/lib/roles.js +43 -27
  77. package/lib/runtime-recovery.d.ts +2 -2
  78. package/lib/runtime-recovery.js +3 -3
  79. package/lib/session-metadata.d.ts +13 -0
  80. package/lib/session-metadata.js +34 -0
  81. package/lib/session-persistence.d.ts +35 -0
  82. package/lib/session-persistence.js +304 -0
  83. package/lib/settings.d.ts +8 -1
  84. package/lib/settings.js +4 -0
  85. package/lib/state.d.ts +1 -0
  86. package/lib/state.js +4 -0
  87. package/lib/status.js +6 -5
  88. package/locale/en.json +6 -0
  89. package/locale/zh.json +6 -0
  90. package/package.json +62 -15
  91. package/patches/agent-presets-root.example.cordis.patch.yml +6 -10
  92. package/prompts/deepseek-v4-pro.md +1 -1
  93. package/prompts/deepwork.md +3 -3
  94. package/scripts/repair-session-log.mjs +476 -0
  95. package/scripts/session-repair-native-verifier.mjs +367 -0
package/lib/roles.js CHANGED
@@ -17,11 +17,12 @@ export const DSMM_ROLE_IDS = [
17
17
  export const DSMM_ROLES = [
18
18
  {
19
19
  id: "dsmm-orchestrator",
20
- name: "DSMM Orchestrator",
21
- description: "Coordinates deepwork sessions and routes work to focused dsmm role presets.",
20
+ name: "DW Orchestrator",
21
+ description: "Coordinates Deepwork sessions and routes work to focused DW roles.",
22
22
  order: 10,
23
+ mode: "primary",
23
24
  enabledByDefault: true,
24
- persona: `You are dsmm-orchestrator, a dsh-native coordinator for deepwork sessions.
25
+ persona: `You are DW Orchestrator (role ID: dsmm-orchestrator), a dsh-native coordinator for deepwork sessions.
25
26
  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
27
  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
28
  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.
@@ -29,111 +30,122 @@ Keep scope explicit, preserve user constraints, and do not claim a preset is act
29
30
  },
30
31
  {
31
32
  id: "dsmm-planner",
32
- name: "DSMM Planner",
33
+ name: "DW Planner",
33
34
  description: "Turns approved scope into ordered implementation steps with verification gates.",
34
35
  order: 20,
36
+ mode: "all",
35
37
  enabledByDefault: true,
36
38
  access: "read-only",
37
- persona: `You are dsmm-planner, a dsh-native planning specialist.
39
+ persona: `You are DW Planner (role ID: dsmm-planner), a dsh-native planning specialist.
38
40
  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
41
  },
40
42
  {
41
43
  id: "dsmm-plan-critic",
42
- name: "DSMM Plan Critic",
44
+ name: "DW Plan Critic",
43
45
  description: "Checks implementation plans for ambiguity, missing evidence, and unsafe sequencing.",
44
46
  order: 30,
47
+ mode: "subagent",
45
48
  enabledByDefault: true,
46
49
  access: "read-only",
47
- persona: `You are dsmm-plan-critic, a dsh-native plan review specialist.
50
+ persona: `You are DW Plan Critic (role ID: dsmm-plan-critic), a dsh-native plan review specialist.
48
51
  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
52
  },
50
53
  {
51
54
  id: "dsmm-builder",
52
- name: "DSMM Builder",
55
+ name: "DW Builder",
53
56
  description: "Implements one bounded approved outcome and verifies the changed surface.",
54
57
  order: 35,
58
+ mode: "primary",
55
59
  enabledByDefault: true,
56
60
  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.`
61
+ persona: `You are DW Builder (role ID: 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
62
  },
59
63
  {
60
64
  id: "dsmm-reviewer",
61
- name: "DSMM Reviewer",
65
+ name: "DW Reviewer",
62
66
  description: "Reviews completed changes against requirements, tests, and regression risk.",
63
67
  order: 40,
68
+ mode: "subagent",
64
69
  enabledByDefault: true,
65
70
  access: "read-only",
66
- persona: `You are dsmm-reviewer, a dsh-native implementation reviewer.
71
+ persona: `You are DW Reviewer (role ID: dsmm-reviewer), a dsh-native implementation reviewer.
67
72
  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
73
  },
69
74
  {
70
75
  id: "dsmm-oracle",
71
- name: "DSMM Oracle",
76
+ name: "DW Oracle",
72
77
  description: "First-priority external-model implementation cross-check when explicitly configured.",
73
78
  order: 42,
79
+ mode: "subagent",
74
80
  enabledByDefault: true,
75
81
  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.`
82
+ persona: `You are DW Oracle (role ID: 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
83
  },
78
84
  {
79
85
  id: "dsmm-oracle-2nd",
80
- name: "DSMM Oracle 2nd",
86
+ name: "DW Oracle 2nd",
81
87
  description: "Second-priority external-model implementation cross-check for an additional evidence need.",
82
88
  order: 44,
89
+ mode: "subagent",
83
90
  enabledByDefault: true,
84
91
  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.`
92
+ persona: `You are DW Oracle 2nd (role ID: 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
93
  },
87
94
  {
88
95
  id: "dsmm-creative",
89
- name: "DSMM Creative",
96
+ name: "DW Creative",
90
97
  description: "Explores unconventional but coherent approaches and explicit trade-offs.",
91
98
  order: 46,
99
+ mode: "subagent",
92
100
  enabledByDefault: true,
93
101
  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.`
102
+ persona: `You are DW Creative (role ID: 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
103
  },
96
104
  {
97
105
  id: "dsmm-code-search",
98
- name: "DSMM Code Search",
106
+ name: "DW Code Search",
99
107
  description: "Finds local codebase facts, symbols, patterns, and relevant implementation context.",
100
108
  order: 50,
109
+ mode: "subagent",
101
110
  enabledByDefault: true,
102
111
  access: "read-only",
103
- persona: `You are dsmm-code-search, a dsh-native codebase research specialist.
112
+ persona: `You are DW Code Search (role ID: dsmm-code-search), a dsh-native codebase research specialist.
104
113
  Search local project context for exact files, symbols, references, and conventions needed by the caller.
105
114
  Summarize findings with paths and evidence; do not modify files.`
106
115
  },
107
116
  {
108
117
  id: "dsmm-doc-search",
109
- name: "DSMM Doc Search",
118
+ name: "DW Doc Search",
110
119
  description: "Finds current external documentation and examples for library or API questions.",
111
120
  order: 60,
121
+ mode: "subagent",
112
122
  enabledByDefault: true,
113
123
  access: "read-only",
114
- persona: `You are dsmm-doc-search, a dsh-native documentation research specialist.
124
+ persona: `You are DW Doc Search (role ID: dsmm-doc-search), a dsh-native documentation research specialist.
115
125
  Find current documentation and real examples for libraries, APIs, CLIs, and services relevant to the task.
116
126
  Cite source locations, separate facts from assumptions, and avoid guessing when documentation is unavailable.`
117
127
  },
118
128
  {
119
129
  id: "dsmm-clarifier",
120
- name: "DSMM Clarifier",
130
+ name: "DW Clarifier",
121
131
  description: "Reduces ambiguous requests to the few decisions needed before planning or implementation.",
122
132
  order: 70,
133
+ mode: "subagent",
123
134
  enabledByDefault: true,
124
135
  access: "read-only",
125
- persona: `You are dsmm-clarifier, a dsh-native requirements clarification specialist.
136
+ persona: `You are DW Clarifier (role ID: dsmm-clarifier), a dsh-native requirements clarification specialist.
126
137
  Identify ambiguity in purpose, constraints, success criteria, and scope boundaries.
127
138
  Ask at most three material questions, prefer concrete choices, and propose safe defaults when evidence is strong.`
128
139
  },
129
140
  {
130
141
  id: "dsmm-media-reader",
131
- name: "DSMM Media Reader",
142
+ name: "DW Media Reader",
132
143
  description: "Extracts implementation-relevant information from images, PDFs, and visual artifacts.",
133
144
  order: 80,
145
+ mode: "subagent",
134
146
  enabledByDefault: true,
135
147
  access: "read-only",
136
- persona: `You are dsmm-media-reader, a dsh-native visual and document analysis specialist.
148
+ persona: `You are DW Media Reader (role ID: dsmm-media-reader), a dsh-native visual and document analysis specialist.
137
149
  Extract text, structure, UI details, diagrams, and implementation-relevant facts from provided media.
138
150
  Report uncertainty clearly and avoid inventing details that are not visible.`
139
151
  }
@@ -141,14 +153,18 @@ Report uncertainty clearly and avoid inventing details that are not visible.`
141
153
  export function isDsmmRoleId(value) {
142
154
  return typeof value === "string" && DSMM_ROLE_IDS.includes(value);
143
155
  }
156
+ /** Root exposure is separate from whether a role is enabled for delegation. */
157
+ export function isRootRole(role) {
158
+ return role.mode === "primary" || role.mode === "all";
159
+ }
144
160
  export function renderAgentCordis(role, skills = DSMM_SKILL_NAMES, enabledRoles = DSMM_ROLE_IDS, roleRouting = {}) {
145
161
  return rolePluginRows(role, skills, enabledRoles, roleRouting).map(renderPluginRow).join("");
146
162
  }
147
163
  /** The native PresetDefinition and the static YAML mirror use this same inventory. */
148
164
  export function rolePluginRows(role, skills = DSMM_SKILL_NAMES, enabledRoles = DSMM_ROLE_IDS, roleRouting = {}) {
149
165
  const rows = [
150
- { id: "persona", name: "@deepseek-ai/dsh-persona", config: { text: role.persona } },
151
- { id: "agent-instructions", name: "@deepseek-ai/dsh-agent-instructions" },
166
+ { id: "persona", name: "@deepseek-ai/dsh-persona", config: { prefix: role.persona } },
167
+ { id: "agent-instructions", name: "@deepseek-ai/dsh-agent-instructions", config: { maxBytes: 65536 } },
152
168
  { id: "tool-fs", name: "@deepseek-ai/dsh-tool-fs" },
153
169
  { id: "tool-fs-search", name: "@deepseek-ai/dsh-tool-fs-search", config: { sampleOverCapGlobResults: false } },
154
170
  { id: "tool-web", name: "@deepseek-ai/dsh-tool-web", config: { fetch: true } },
@@ -1,5 +1,5 @@
1
1
  import type { DshContext } from "./dsh-types.js";
2
- import type { DsmmSettings } from "./settings.js";
2
+ import type { DsmmSettingsGetter } from "./settings.js";
3
3
  import type { DeepworkModeController } from "./state.js";
4
- export declare function registerRuntimeRecovery(ctx: DshContext, controller: DeepworkModeController, getSettings: () => DsmmSettings): void;
4
+ export declare function registerRuntimeRecovery(ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter): void;
5
5
  //# sourceMappingURL=runtime-recovery.d.ts.map
@@ -56,7 +56,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings) {
56
56
  if (pending.turn !== frame.turn || pending.step !== frame.step)
57
57
  return downstream;
58
58
  if (pending.policy !== undefined) {
59
- const settings = getSettings();
59
+ const settings = getSettings(frame.agent);
60
60
  const role = resolveEffectiveDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive));
61
61
  if (role !== pending.role || rolePolicyIdentity(settings, role) !== pending.policy) {
62
62
  pendingByAgent.delete(frame.agent);
@@ -81,7 +81,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings) {
81
81
  return downstream;
82
82
  }
83
83
  try {
84
- const settings = getSettings();
84
+ const settings = getSettings(frame.agent);
85
85
  if (!settings.runtimeRecovery.enabled || frame.signal.aborted
86
86
  || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step))
87
87
  return downstream;
@@ -128,7 +128,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings) {
128
128
  }, { prepend: true });
129
129
  disposeTurnStopping = ctx.on("agent/turn-stopping", async (frame) => {
130
130
  try {
131
- const settings = getSettings();
131
+ const settings = getSettings(frame.agent);
132
132
  const continuation = settings.runtimeRecovery.idleContinuation;
133
133
  if (!settings.runtimeRecovery.enabled || !continuation.enabled || frame.signal.aborted)
134
134
  return;
@@ -0,0 +1,13 @@
1
+ import type { DshContext } from "./dsh-types.js";
2
+ export declare const DSMM_PERSISTENCE_COMPATIBILITY: unique symbol;
3
+ /** An ephemeral Host without persistence is safe; a durable Host must use the compatible provider. */
4
+ export declare function assertDsmmMetadataPersistence(ctx: DshContext | undefined): void;
5
+ /** Only these audited, model-hidden records are safe for a stock reader to skip. */
6
+ export declare function annotateDsmmEvent<T extends {
7
+ type: string;
8
+ data?: unknown;
9
+ ignorable?: unknown;
10
+ }>(event: T): T & {
11
+ ignorable?: true;
12
+ };
13
+ //# sourceMappingURL=session-metadata.d.ts.map
@@ -0,0 +1,34 @@
1
+ import { isDsmmRoleId } from "./roles.js";
2
+ export const DSMM_PERSISTENCE_COMPATIBILITY = Symbol.for("dsmm.sessionPersistence.ignorable.v1");
3
+ /** An ephemeral Host without persistence is safe; a durable Host must use the compatible provider. */
4
+ export function assertDsmmMetadataPersistence(ctx) {
5
+ const persistence = ctx?.get?.("sessionPersistence");
6
+ if (persistence !== undefined && (typeof persistence !== "object" || persistence === null
7
+ || persistence[DSMM_PERSISTENCE_COMPATIBILITY] !== true)) {
8
+ throw new Error("Deepwork requires @dsmm/dsmm/session-persistence for durable session metadata; no unsafe event was appended");
9
+ }
10
+ }
11
+ /** Only these audited, model-hidden records are safe for a stock reader to skip. */
12
+ export function annotateDsmmEvent(event) {
13
+ if (event.type !== "deepwork/mode" && event.type !== "dsmm/role-policy")
14
+ return event;
15
+ const envelope = event;
16
+ const allowedKeys = ["type", "seq", "time", "data", "ignorable"];
17
+ const validEnvelope = Reflect.ownKeys(event).every((key) => typeof key === "string" && allowedKeys.includes(key))
18
+ && ["type", "seq", "time", "data"].every((key) => Object.hasOwn(event, key))
19
+ && Number.isSafeInteger(envelope.seq) && envelope.seq >= 0 && !Object.is(envelope.seq, -0)
20
+ && Number.isSafeInteger(envelope.time);
21
+ const data = event.data;
22
+ const record = typeof data === "object" && data !== null && !Array.isArray(data)
23
+ && (Object.getPrototypeOf(data) === Object.prototype || Object.getPrototypeOf(data) === null)
24
+ ? data : undefined;
25
+ const valid = record !== undefined && (event.type === "deepwork/mode"
26
+ ? Reflect.ownKeys(record).length === 1 && typeof record.active === "boolean"
27
+ : Reflect.ownKeys(record).length === 3 && record.version === 1 && isDsmmRoleId(record.role)
28
+ && (record.policy === null || typeof record.policy === "string" && /^[a-f0-9]{64}$/u.test(record.policy)));
29
+ if (!validEnvelope || !valid || event.ignorable !== undefined && event.ignorable !== true) {
30
+ throw new TypeError("invalid Deepwork session metadata; refusing to mark it ignorable");
31
+ }
32
+ return event.ignorable === true ? event : { ...event, ignorable: true };
33
+ }
34
+ //# sourceMappingURL=session-metadata.js.map
@@ -0,0 +1,35 @@
1
+ import { Context, Service } from "@deepseek-ai/cordis";
2
+ import type { SessionHeader, SessionId } from "@deepseek-ai/dsh-session";
3
+ import { SessionPersistence } from "@deepseek-ai/dsh-session-persistence";
4
+ import type { SessionAccess, SessionHandle, SessionPersistenceCreateOptions, SessionPersistenceListOptions, SessionPersistenceOpenOptions, SessionPersistenceStatOptions } from "@deepseek-ai/dsh-session-persistence";
5
+ import type { Config } from "@deepseek-ai/dsh-session-persistence-jsonl";
6
+ export { DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
7
+ export type { Config } from "@deepseek-ai/dsh-session-persistence-jsonl";
8
+ /**
9
+ * Drop-in native JSONL persistence companion for audited DSMM metadata.
10
+ * A separate root Context is intentional: a child service-isolation scope still
11
+ * shares the host event bus and would persist every live event twice.
12
+ */
13
+ export default class DsmmSessionPersistence extends SessionPersistence {
14
+ readonly config: Config;
15
+ static Config: import("@deepseek-ai/schemastery").default<Config>;
16
+ readonly name = "dsmm-session-persistence";
17
+ private readonly inner;
18
+ private readonly ready;
19
+ private readonly handles;
20
+ private readonly writers;
21
+ private readonly acquisitions;
22
+ private readonly closeFailures;
23
+ private disposed;
24
+ constructor(ctx: Context, config: Config);
25
+ [Service.init](): Promise<void>;
26
+ create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle>;
27
+ open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle>;
28
+ flush(): Promise<void>;
29
+ stat(id: SessionId, options?: SessionPersistenceStatOptions): Promise<import("@deepseek-ai/dsh-session-persistence").SessionPersistenceSnapshot | undefined>;
30
+ list(options?: SessionPersistenceListOptions): Promise<readonly import("@deepseek-ai/dsh-session-persistence").SessionPersistenceSnapshot[]>;
31
+ private acquire;
32
+ private warn;
33
+ private assertActive;
34
+ }
35
+ //# sourceMappingURL=session-persistence.d.ts.map
@@ -0,0 +1,304 @@
1
+ import { Context, Service } from "@deepseek-ai/cordis";
2
+ import { SessionHandleClosedError, SessionPersistence, SessionReadOnlyError, materializeAppendBatch } from "@deepseek-ai/dsh-session-persistence";
3
+ import JsonlSessionPersistence from "@deepseek-ai/dsh-session-persistence-jsonl";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { annotateDsmmEvent, DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
6
+ export { DSMM_PERSISTENCE_COMPATIBILITY } from "./session-metadata.js";
7
+ /** Host-owned live routing; the native handle remains the sole storage/lock owner. */
8
+ class DsmmSessionHandle {
9
+ native;
10
+ cursor;
11
+ warn;
12
+ released;
13
+ chain = Promise.resolve();
14
+ closing;
15
+ buffered = [];
16
+ timer;
17
+ paused = false;
18
+ failure;
19
+ routingFailure;
20
+ constructor(native, cursor, warn, released) {
21
+ this.native = native;
22
+ this.cursor = cursor;
23
+ this.warn = warn;
24
+ this.released = released;
25
+ }
26
+ get id() { return this.native.id; }
27
+ get header() { return this.native.header; }
28
+ get access() { return this.native.access; }
29
+ get inheritedEventCount() { return this.native.inheritedEventCount; }
30
+ async read(offset, length, options) {
31
+ this.assertOpen("read");
32
+ return this.native.read(offset, length, options);
33
+ }
34
+ async append(events, options) {
35
+ this.assertOpen("append");
36
+ options?.signal?.throwIfAborted();
37
+ const batch = materializeAppendBatch(events).map(annotateDsmmEvent);
38
+ await this.enqueue(async () => {
39
+ options?.signal?.throwIfAborted();
40
+ if (this.access !== "write")
41
+ throw new SessionReadOnlyError(this.id, "append");
42
+ if (this.paused)
43
+ throw this.failure;
44
+ // Live records preceding this explicit batch must commit first. Later live
45
+ // records cannot overtake a direct append waiting on the mutation chain.
46
+ await this.drain(batch[0]?.seq ?? Number.POSITIVE_INFINITY, options?.signal);
47
+ await this.native.append(batch, options);
48
+ this.cursor += batch.length;
49
+ this.scheduleDrain();
50
+ });
51
+ }
52
+ async flush(options) {
53
+ this.assertOpen("flush");
54
+ await this.enqueue(async () => {
55
+ options?.signal?.throwIfAborted();
56
+ if (this.access !== "write")
57
+ throw new SessionReadOnlyError(this.id, "flush");
58
+ this.paused = false;
59
+ await this.drain(Number.POSITIVE_INFINITY, options?.signal);
60
+ await this.native.flush(options);
61
+ });
62
+ }
63
+ enqueueLive(event) {
64
+ if (this.closing !== undefined)
65
+ return;
66
+ let owned;
67
+ try {
68
+ owned = annotateDsmmEvent(materializeAppendBatch([event])[0]);
69
+ }
70
+ catch (error) {
71
+ this.routingFailure ??= error;
72
+ this.cancelTimer();
73
+ this.warn(this.id, error);
74
+ return;
75
+ }
76
+ this.buffered.push(owned);
77
+ this.scheduleDrain();
78
+ }
79
+ scheduleDrain() {
80
+ if (this.buffered.length === 0 || this.timer !== undefined || this.paused
81
+ || this.routingFailure !== undefined || this.closing !== undefined)
82
+ return;
83
+ this.timer = setTimeout(() => {
84
+ this.timer = undefined;
85
+ const last = this.buffered.at(-1);
86
+ if (last === undefined)
87
+ return;
88
+ // Fence this queued operation to the prefix accepted now. Events published
89
+ // after a later direct append is queued belong behind that append.
90
+ const beforeSeq = last.seq + 1;
91
+ void this.enqueue(async () => {
92
+ if (!this.paused) {
93
+ await this.drain(beforeSeq);
94
+ this.scheduleDrain();
95
+ }
96
+ }).catch((error) => this.warn(this.id, error));
97
+ }, 200);
98
+ }
99
+ close() {
100
+ return this.closing ??= this.enqueue(async () => {
101
+ this.cancelTimer();
102
+ const errors = [];
103
+ try {
104
+ this.paused = false;
105
+ await this.drain();
106
+ if (this.access === "write")
107
+ await this.native.flush();
108
+ }
109
+ catch (error) {
110
+ errors.push(error);
111
+ }
112
+ try {
113
+ await this.native.close();
114
+ }
115
+ catch (error) {
116
+ errors.push(error);
117
+ }
118
+ const failure = errors.length > 1 ? new AggregateError(errors, `session "${this.id}": close failed`)
119
+ : errors[0];
120
+ this.released(this, failure);
121
+ if (errors.length > 0)
122
+ throw failure;
123
+ });
124
+ }
125
+ [Symbol.asyncDispose]() { return this.close(); }
126
+ enqueue(operation) {
127
+ const next = this.chain.then(operation);
128
+ // The caller observes rejection; this recovery only keeps later barriers usable.
129
+ this.chain = next.then(() => undefined, () => undefined);
130
+ return next;
131
+ }
132
+ async drain(beforeSeq = Number.POSITIVE_INFINITY, signal) {
133
+ this.cancelTimer();
134
+ if (this.routingFailure !== undefined)
135
+ throw this.routingFailure;
136
+ while (this.buffered.length > 0 && this.buffered[0].seq < beforeSeq) {
137
+ signal?.throwIfAborted();
138
+ const count = this.buffered.findIndex((event) => event.seq >= beforeSeq);
139
+ const batch = this.buffered.slice(0, count < 0 ? undefined : count);
140
+ try {
141
+ // An explicitly appended event may subsequently be published by the live
142
+ // store. Coalesce only byte-equivalent logical events, never conflicts.
143
+ let duplicateCount = 0;
144
+ while (duplicateCount < batch.length && batch[duplicateCount].seq < this.cursor)
145
+ duplicateCount++;
146
+ if (duplicateCount > 0) {
147
+ const existing = await this.native.read(batch[0].seq, duplicateCount, { signal });
148
+ if (!isDeepStrictEqual(existing.events, batch.slice(0, duplicateCount))) {
149
+ throw new Error(`session "${this.id}": live event conflicts with the persisted prefix`);
150
+ }
151
+ }
152
+ const fresh = batch.slice(duplicateCount);
153
+ await this.native.append(fresh, { signal });
154
+ this.cursor += fresh.length;
155
+ this.buffered.splice(0, batch.length);
156
+ this.failure = undefined;
157
+ }
158
+ catch (error) {
159
+ this.cancelTimer();
160
+ this.paused = true;
161
+ this.failure = error;
162
+ throw error;
163
+ }
164
+ }
165
+ }
166
+ cancelTimer() {
167
+ if (this.timer !== undefined)
168
+ clearTimeout(this.timer);
169
+ this.timer = undefined;
170
+ }
171
+ assertOpen(operation) {
172
+ if (this.closing !== undefined)
173
+ throw new SessionHandleClosedError(this.id, operation);
174
+ }
175
+ }
176
+ /**
177
+ * Drop-in native JSONL persistence companion for audited DSMM metadata.
178
+ * A separate root Context is intentional: a child service-isolation scope still
179
+ * shares the host event bus and would persist every live event twice.
180
+ */
181
+ export default class DsmmSessionPersistence extends SessionPersistence {
182
+ config;
183
+ static Config = JsonlSessionPersistence.Config;
184
+ name = "dsmm-session-persistence";
185
+ inner = new Context();
186
+ ready;
187
+ handles = new Set();
188
+ writers = new Map();
189
+ acquisitions = new Set();
190
+ closeFailures = new Map();
191
+ disposed = false;
192
+ constructor(ctx, config) {
193
+ super(ctx);
194
+ this.config = config;
195
+ Object.defineProperty(this, DSMM_PERSISTENCE_COMPATIBILITY, {
196
+ value: true, writable: false, configurable: false, enumerable: false
197
+ });
198
+ const nativeFiber = this.inner.plugin(JsonlSessionPersistence, config);
199
+ this.ready = nativeFiber.await().then(() => this.inner.sessionPersistence);
200
+ ctx.on("session/event", (session, event) => this.writers.get(session.id)?.enqueueLive(event));
201
+ ctx.on("session/flush", (session) => this.writers.get(session.id)?.flush());
202
+ ctx.on("session/disposed", (session) => {
203
+ const writer = this.writers.get(session.id);
204
+ if (writer !== undefined)
205
+ void writer.close().catch((error) => this.warn(session.id, error));
206
+ });
207
+ // One outer disposer enforces the ownership boundary: drain/close every
208
+ // adapter handle before disposing the still-live native storage Context.
209
+ ctx.effect(() => async () => {
210
+ this.disposed = true;
211
+ await Promise.allSettled([...this.acquisitions]);
212
+ const errors = [...this.closeFailures.values()];
213
+ for (const handle of [...this.handles]) {
214
+ try {
215
+ await handle.close();
216
+ }
217
+ catch (error) {
218
+ errors.push(error);
219
+ }
220
+ }
221
+ try {
222
+ await this.inner.fiber.dispose();
223
+ }
224
+ catch (error) {
225
+ errors.push(error);
226
+ }
227
+ if (errors.length > 0)
228
+ throw new AggregateError(errors, `${this.name} dispose failed`);
229
+ }, "dsmm-session-persistence ordered shutdown");
230
+ }
231
+ async [Service.init]() { await this.ready; }
232
+ create(header, options) {
233
+ return this.acquire(async (native) => native.create(header, options), false);
234
+ }
235
+ open(id, access, options) {
236
+ return this.acquire(async (native) => native.open(id, access, options), access === "write");
237
+ }
238
+ async flush() {
239
+ this.assertActive();
240
+ const errors = [];
241
+ for (const handle of [...this.writers.values()]) {
242
+ try {
243
+ await handle.flush();
244
+ }
245
+ catch (error) {
246
+ if (!(error instanceof SessionHandleClosedError))
247
+ errors.push(error);
248
+ }
249
+ }
250
+ if (errors.length > 0)
251
+ throw new AggregateError(errors, `${this.name} flush failed`);
252
+ }
253
+ async stat(id, options) {
254
+ this.assertActive();
255
+ return (await this.ready).stat(id, options);
256
+ }
257
+ async list(options) {
258
+ this.assertActive();
259
+ return (await this.ready).list(options);
260
+ }
261
+ acquire(factory, existing) {
262
+ this.assertActive();
263
+ const operation = (async () => {
264
+ const native = await factory(await this.ready);
265
+ let cursor = 0;
266
+ try {
267
+ if (existing)
268
+ cursor = (await native.read()).events.length;
269
+ }
270
+ catch (error) {
271
+ try {
272
+ await native.close();
273
+ }
274
+ catch (closeError) {
275
+ throw new AggregateError([error, closeError], `session "${native.id}": open failed`);
276
+ }
277
+ throw error;
278
+ }
279
+ const handle = new DsmmSessionHandle(native, cursor, (id, error) => this.warn(id, error), (closed, error) => {
280
+ this.handles.delete(closed);
281
+ if (this.writers.get(closed.id) === closed)
282
+ this.writers.delete(closed.id);
283
+ if (error !== undefined)
284
+ this.closeFailures.set(closed.id, error);
285
+ });
286
+ this.handles.add(handle);
287
+ if (handle.access === "write")
288
+ this.writers.set(handle.id, handle);
289
+ return handle;
290
+ })();
291
+ this.acquisitions.add(operation);
292
+ void operation.then(() => this.acquisitions.delete(operation), () => this.acquisitions.delete(operation));
293
+ return operation;
294
+ }
295
+ warn(id, error) {
296
+ const errorClass = error instanceof Error && /^[A-Za-z][A-Za-z0-9]*Error$/u.test(error.name) ? error.name : "Error";
297
+ this.ctx.logger.warn("Deepwork session persistence failed", { sessionId: id, errorClass });
298
+ }
299
+ assertActive() {
300
+ if (this.disposed)
301
+ throw new Error("Deepwork session persistence is disposed");
302
+ }
303
+ }
304
+ //# sourceMappingURL=session-persistence.js.map
package/lib/settings.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import Schema from "@deepseek-ai/schemastery";
2
- import type { DshContext } from "./dsh-types.js";
2
+ import type { DshAgent, DshContext } from "./dsh-types.js";
3
3
  import type { DsmmLspSettings } from "./lsp.js";
4
4
  import type { DsmmRoleId } from "./roles.js";
5
5
  import type { DsmmSkillName } from "./skills.js";
@@ -68,6 +68,11 @@ type DsmmRuntimeRecoveryConfig = Partial<Omit<DsmmRuntimeRecoverySettings, "fall
68
68
  idleContinuation?: Partial<DsmmRuntimeRecoverySettings["idleContinuation"]>;
69
69
  };
70
70
  export interface DsmmPluginConfig {
71
+ /** Startup-only native storage binding; never a runtime-profile field. */
72
+ sessionPersistence?: {
73
+ root: string;
74
+ compression?: "zstd" | "none";
75
+ };
71
76
  modeName?: string;
72
77
  section?: string;
73
78
  deepseekV4ProCalibration?: DeepseekCalibration;
@@ -106,6 +111,8 @@ export interface DsmmSettings {
106
111
  runtimeRecovery: DsmmRuntimeRecoverySettings;
107
112
  lsp: DsmmLspSettings;
108
113
  }
114
+ /** Runtime consumers pass their Agent so immutable profile admission is retained. */
115
+ export type DsmmSettingsGetter = (agent?: DshAgent) => DsmmSettings;
109
116
  export declare const DSMM_SETTINGS_NAMESPACE = "dsmm";
110
117
  export declare const DSMM_STATUS_COMMAND = "dsmm-status";
111
118
  export interface RegisterSettingsOptions {
package/lib/settings.js CHANGED
@@ -188,6 +188,10 @@ const LSP_SCHEMA = Schema.object({
188
188
  failOnStartupError: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.lsp.failOnStartupError)
189
189
  });
190
190
  export const DSMM_CONFIG_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SCHEMA, Schema.object({
191
+ sessionPersistence: Schema.union([Schema.const(undefined), Schema.object({
192
+ root: Schema.string().required(),
193
+ compression: Schema.union([Schema.const("zstd"), Schema.const("none")])
194
+ })]),
191
195
  modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
192
196
  section: Schema.string(),
193
197
  defaultActive: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.defaultActive),
package/lib/state.d.ts CHANGED
@@ -4,6 +4,7 @@ export type DeepworkSelectionOutcome = "committed" | "pending" | "unchanged";
4
4
  export declare function isDeepworkActive(events?: readonly DshSessionEvent[], defaultActive?: boolean): boolean;
5
5
  export declare function hasOpenTurn(events?: readonly DshSessionEvent[]): boolean;
6
6
  export declare class DeepworkModeController {
7
+ private readonly ctx;
7
8
  private readonly pending;
8
9
  constructor(ctx: DshContext);
9
10
  active(agent: DshAgent | undefined, defaultActive: boolean): boolean;