@dsmm/dsmm 0.1.4 → 0.1.6

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 (52) hide show
  1. package/README.md +13 -12
  2. package/docs/compatibility.md +8 -6
  3. package/docs/migration-from-ocmm.md +8 -0
  4. package/docs/model-routing.md +22 -6
  5. package/docs/profiles.md +23 -9
  6. package/docs/releasing.md +27 -15
  7. package/docs/runtime-recovery.md +41 -14
  8. package/docs/settings-status.md +10 -8
  9. package/lib/client/ProfilesSection.js +7 -3
  10. package/lib/client/SessionProfiles.d.ts +19 -0
  11. package/lib/client/SessionProfiles.js +55 -0
  12. package/lib/client/StructuredEditor.d.ts +11 -0
  13. package/lib/client/StructuredEditor.js +74 -0
  14. package/lib/client/controller.d.ts +68 -1
  15. package/lib/client/controller.js +282 -11
  16. package/lib/client/index.d.ts +3 -1
  17. package/lib/client/index.js +47 -0
  18. package/lib/client/locales.d.ts +109 -0
  19. package/lib/client/locales.js +56 -2
  20. package/lib/client/session-labels.d.ts +8 -0
  21. package/lib/client/session-labels.js +13 -0
  22. package/lib/client/structured.d.ts +18 -0
  23. package/lib/client/structured.js +98 -0
  24. package/lib/client/styles.d.ts +1 -1
  25. package/lib/client/styles.js +14 -1
  26. package/lib/client.js +1215 -74
  27. package/lib/commands.js +1 -0
  28. package/lib/dsh-types.d.ts +16 -0
  29. package/lib/index.js +27 -1
  30. package/lib/model-routing.js +109 -23
  31. package/lib/profile-remote.d.ts +7 -1
  32. package/lib/profile-remote.js +117 -2
  33. package/lib/profile-rpc.d.ts +9 -1
  34. package/lib/profile-rpc.js +99 -2
  35. package/lib/profile-runtime.d.ts +25 -5
  36. package/lib/profile-runtime.js +193 -31
  37. package/lib/profile-store.d.ts +19 -1
  38. package/lib/profile-store.js +120 -10
  39. package/lib/profile-types.d.ts +43 -1
  40. package/lib/profiles.d.ts +1 -1
  41. package/lib/profiles.js +34 -2
  42. package/lib/role-providers.js +12 -2
  43. package/lib/role-routing.d.ts +37 -3
  44. package/lib/role-routing.js +107 -35
  45. package/lib/routing-policy.d.ts +32 -0
  46. package/lib/routing-policy.js +92 -0
  47. package/lib/runtime-recovery.js +216 -52
  48. package/lib/settings.d.ts +27 -1
  49. package/lib/settings.js +29 -7
  50. package/lib/status.d.ts +10 -2
  51. package/lib/status.js +36 -10
  52. package/package.json +8 -1
package/lib/commands.js CHANGED
@@ -27,6 +27,7 @@ function handleDsmmStatusCommand(controller, getSettings, invocation) {
27
27
  const snapshot = createDsmmStatusSnapshot({
28
28
  agent: invocation.agent,
29
29
  settings,
30
+ admission: getSettings.admission?.(invocation.agent),
30
31
  modeActive: controller.active(invocation.agent, settings.defaultActive)
31
32
  });
32
33
  return {
@@ -18,6 +18,7 @@ export interface DshSessionHeader {
18
18
  origin?: string;
19
19
  }
20
20
  export interface DshSession {
21
+ readonly id?: string;
21
22
  inheritedEventCount?: number;
22
23
  events?: readonly DshSessionEvent[];
23
24
  snapshotEvents?(): readonly DshSessionEvent[];
@@ -32,6 +33,9 @@ export interface DshAgent {
32
33
  id?: string;
33
34
  ctx?: DshContext;
34
35
  session: DshSession;
36
+ readonly status?: "idle" | "running";
37
+ /** Public native reservation: throws synchronously unless truly idle. */
38
+ runMaintenance?<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
35
39
  options?: {
36
40
  provider?: string;
37
41
  model?: string;
@@ -40,6 +44,17 @@ export interface DshAgent {
40
44
  steer?(message: unknown): unknown | Promise<unknown>;
41
45
  inject?(message: unknown): unknown | Promise<unknown>;
42
46
  }
47
+ export interface DshAgentsRegistry {
48
+ get(id: string): DshAgent | undefined;
49
+ list(): DshAgent[];
50
+ roots(): DshAgent[];
51
+ isOwnedBy(id: string, owner: DshAgent): boolean;
52
+ }
53
+ export interface DshAgentCreatedFrame {
54
+ agent: DshAgent;
55
+ source: "startup" | "resume" | "clear" | "compact";
56
+ signal?: AbortSignal;
57
+ }
43
58
  export interface DshLlmCallConfig {
44
59
  provider: string;
45
60
  model: string;
@@ -283,6 +298,7 @@ export interface PreStepDecision {
283
298
  [key: string]: unknown;
284
299
  }
285
300
  export interface DshContext {
301
+ agents?: DshAgentsRegistry;
286
302
  subagents?: import("./role-providers.js").DsmmSubagentRegistry;
287
303
  settings?: DshSettingsRegistry;
288
304
  systemPrompt?: DshSystemPromptRegistry;
package/lib/index.js CHANGED
@@ -13,6 +13,8 @@ import { DSMM_CONFIG_SCHEMA, registerSettings } from "./settings.js";
13
13
  import { DeepworkModeController } from "./state.js";
14
14
  import DsmmSessionPersistence from "./session-persistence.js";
15
15
  import { isAbsolute } from "node:path";
16
+ import { createHash, randomUUID } from "node:crypto";
17
+ import { DsmmProfileError } from "./profiles.js";
16
18
  export const name = "dsmm";
17
19
  export const inject = ["profileContext"];
18
20
  export const Config = DSMM_CONFIG_SCHEMA;
@@ -55,7 +57,30 @@ function applyRuntime(ctx, config) {
55
57
  const controller = new DeepworkModeController(ctx);
56
58
  let runtime;
57
59
  let profileInitialization;
58
- const getBoundSettings = (agent) => runtime?.getSettings(agent) ?? getSettings();
60
+ let requiresNativeProfiles = ctx.get !== undefined;
61
+ const requireProfileAdmission = () => {
62
+ if (requiresNativeProfiles && runtime === undefined) {
63
+ throw new DsmmProfileError("unavailable", "Native Deepwork profile admission is not ready. No provider request or tool work is allowed.");
64
+ }
65
+ };
66
+ const getBoundSettings = (agent) => {
67
+ requireProfileAdmission();
68
+ return runtime?.getSettings(agent) ?? getSettings();
69
+ };
70
+ const deploymentAdmissions = new WeakMap();
71
+ getBoundSettings.admission = (agent) => {
72
+ requireProfileAdmission();
73
+ const nativeAdmission = runtime?.getSettings.admission?.(agent);
74
+ if (nativeAdmission !== undefined)
75
+ return nativeAdmission;
76
+ const settings = getSettings();
77
+ let admission = deploymentAdmissions.get(settings);
78
+ if (admission === undefined) {
79
+ admission = Object.freeze({ settings, profile: null, scope: "deployment-baseline", epoch: createHash("sha256").update(randomUUID()).digest("hex") });
80
+ deploymentAdmissions.set(settings, admission);
81
+ }
82
+ return admission;
83
+ };
59
84
  const getSettings = registerSettings(ctx, config, {
60
85
  install(readyCtx, getReadySettings) {
61
86
  const install = (installCtx, settingsGetter) => {
@@ -81,6 +106,7 @@ function applyRuntime(ctx, config) {
81
106
  install(readyCtx, getReadySettings);
82
107
  return;
83
108
  }
109
+ requiresNativeProfiles = true;
84
110
  const installProfiles = async (profileCtx) => {
85
111
  runtime = await createProfileRuntime(profileCtx, getReadySettings());
86
112
  profileCtx.provide?.("dsmmProfileRuntime", runtime);
@@ -1,6 +1,8 @@
1
1
  import { isDsmmRoleId } from "./roles.js";
2
- import { applyModelRoute, effectiveRoleFallbackRoutes, establishRolePolicy, persistedRoleRoute, sameModelRoute, takeAdmittedRecoveryRoute } from "./role-routing.js";
2
+ import { applyModelRoute, clearRoleRouteLock, effectiveRoleFallbackRoutes, establishRolePolicy, latestNativeModelSelection, nativeModelSelectionWasAccepted, orderedModelRoutes, persistedRoleRoute, pinRoleRoute, roleRouteLock, selectInitialModelRoute, sameExactModelRoute, sameModelRoute, takeAdmittedRecoveryRoute } from "./role-routing.js";
3
3
  import { resolveEffectiveDsmmRole, resolveSelectedAgentPreset } from "./session-scope.js";
4
+ import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
5
+ import { isCurrentRecoveryStep } from "./recovery-policy.js";
4
6
  export function isDeepseekV4ProRoute(config) {
5
7
  return config.provider.toLowerCase() === "deepseek-official" && config.model.toLowerCase() === "deepseek-v4-pro";
6
8
  }
@@ -39,41 +41,105 @@ export function registerModelRouting(ctx, controller, getSettings) {
39
41
  if (installedContexts.has(readyCtx) || readyCtx.on === undefined)
40
42
  return;
41
43
  installedContexts.add(readyCtx);
44
+ const lockedAgents = new Set();
45
+ const assembledSelections = new WeakMap();
42
46
  let dispose;
47
+ let disposeAgent;
48
+ let disposeAssembly;
43
49
  try {
50
+ disposeAssembly = readyCtx.on("system-prompt/assemble", async (_assembly, context, next) => {
51
+ if (context.agent !== undefined && context.signal !== undefined) {
52
+ assembledSelections.set(context.agent, { signal: context.signal, intent: latestNativeModelSelection(context.agent) });
53
+ }
54
+ return next();
55
+ }, { prepend: true });
44
56
  dispose = readyCtx.on("agent/request", async (frame, next) => {
45
57
  let downstream = await next();
58
+ if (frame.signal.aborted)
59
+ return downstream;
46
60
  const settings = getSettings(frame.agent);
61
+ const ordinaryRoot = frame.agent.session.header?.origin !== "subagent";
47
62
  const admitted = takeAdmittedRecoveryRoute(frame);
48
63
  const active = controller.active(frame.agent, settings.defaultActive);
49
64
  const role = resolveEffectiveDsmmRole(frame.agent, settings, active);
50
65
  const policy = role === undefined ? undefined : settings.roleRouting[role];
51
66
  const primary = policy?.primary;
52
- const identity = await establishRolePolicy(frame, settings, role, readyCtx);
53
- if (admitted !== undefined) {
54
- downstream = applyModelRoute(downstream, admitted);
55
- if (admitted.reasoningEffort !== undefined || primary !== undefined
56
- || (role !== undefined && settings.roleRouting[role]?.fallbackRoutes !== undefined))
57
- return downstream;
58
- }
67
+ const epoch = getSettings.admission?.(frame.agent).epoch;
68
+ const identity = await establishRolePolicy(frame, settings, role, readyCtx, epoch);
59
69
  const fallbacks = effectiveRoleFallbackRoutes(settings, role);
60
- if (primary !== undefined && role !== undefined && frame.agent.session.header?.origin === "subagent"
70
+ const liveAlias = primary !== undefined && role !== undefined && frame.agent.session.header?.origin === "subagent"
61
71
  && (frame.agent.session.inheritedEventCount ?? 0) === 0
62
- && hasLiveRuntimeOwner(readyCtx, frame.agent)) {
63
- // A trusted one-shot alias already preflighted its merged native
64
- // options. Its first accepted route, not the profile default, starts
65
- // this live child's durable host/recovery ownership. Cold unowned or
66
- // parent-seeded fork children resolve the current primary below.
67
- const accepted = persistedRoleRoute(frame, undefined, fallbacks, identity);
68
- return accepted === undefined ? downstream : applyModelRoute(downstream, accepted);
69
- }
70
- if (primary !== undefined)
71
- return applyModelRoute(downstream, persistedRoleRoute(frame, primary, fallbacks, identity) ?? primary);
72
- if (settings.runtimeRecovery.enabled && policy?.fallbackRoutes !== undefined) {
73
- const accepted = persistedRoleRoute(frame, undefined, fallbacks, identity);
74
- if (accepted !== undefined)
75
- return applyModelRoute(downstream, accepted);
72
+ && hasLiveRuntimeOwner(readyCtx, frame.agent);
73
+ const currentStep = isCurrentRecoveryStep(frame.agent.session.header?.origin === "subagent" ? childOwnedSessionEvents(frame.agent.session) : sessionEvents(frame.agent.session), frame.turn, frame.step);
74
+ if (role !== undefined && identity !== undefined && currentStep) {
75
+ let lock = roleRouteLock(frame.agent, identity);
76
+ const exactPolicy = primary !== undefined || policy?.fallbackRoutes !== undefined || fallbacks.length > 0;
77
+ const captured = assembledSelections.get(frame.agent);
78
+ const manual = captured?.signal === frame.signal ? captured.intent : undefined;
79
+ if (ordinaryRoot) {
80
+ const selected = { provider: downstream.provider, model: downstream.model,
81
+ ...(downstream.reasoningEffort === undefined ? {} : { reasoningEffort: downstream.reasoningEffort }) };
82
+ if (lock === undefined || !sameExactModelRoute(lock.route, selected) || lock.manualSelectionSeq !== manual?.seq) {
83
+ const generation = (lock?.generation ?? -1) + 1;
84
+ lock = pinRoleRoute(frame.agent, identity, selected, [selected]);
85
+ lock.manualSelectionSeq = manual?.seq;
86
+ lock.generation = generation;
87
+ lockedAgents.add(frame.agent);
88
+ }
89
+ return downstream;
90
+ }
91
+ if (manual !== undefined && lock?.manualSelectionSeq !== manual.seq
92
+ && (sameExactModelRoute(downstream, manual.route) || nativeModelSelectionWasAccepted(frame.agent, manual))) {
93
+ const llm = frame.agent.ctx?.get?.("llm")
94
+ ?? (readyCtx.get !== undefined ? readyCtx.get("llm") : readyCtx.llm);
95
+ if (llm?.resolveCallConfig === undefined)
96
+ throw new Error("dsmm explicit model selection requires the native LLM service");
97
+ await llm.resolveCallConfig(applyModelRoute(downstream, manual.route), frame.signal);
98
+ frame.signal.throwIfAborted();
99
+ const generation = (lock?.generation ?? -1) + 1;
100
+ lock = pinRoleRoute(frame.agent, identity, manual.route, [manual.route, ...fallbacks]);
101
+ lock.manualSelectionSeq = manual.seq;
102
+ lock.generation = generation;
103
+ lockedAgents.add(frame.agent);
104
+ }
105
+ if (lock?.manualSelectionSeq !== undefined) {
106
+ // An unchanged explicit intent must not undo a policy-authorized
107
+ // fallback; a fresh native selection event re-admits above.
108
+ return applyModelRoute(downstream, lock.route);
109
+ }
110
+ if (admitted !== undefined)
111
+ return applyModelRoute(downstream, admitted);
112
+ const accepted = persistedRoleRoute(frame, liveAlias ? undefined : primary, fallbacks, identity);
113
+ if (lock !== undefined && accepted !== undefined && !sameModelRoute(accepted, lock.route)) {
114
+ // An explicit already-committed native route change remains host-owned;
115
+ // DSMM's pending current-frame route still has precedence above.
116
+ lock.route = { ...accepted };
117
+ lock.generation += 1;
118
+ lock.startupSettled = true;
119
+ lock.retries = 0;
120
+ lock.rateLimits = 0;
121
+ }
122
+ if (lock === undefined) {
123
+ const inherited = { provider: downstream.provider, model: downstream.model,
124
+ ...(downstream.reasoningEffort === undefined ? {} : { reasoningEffort: downstream.reasoningEffort }) };
125
+ const candidates = orderedModelRoutes([liveAlias ? inherited : primary ?? inherited, ...fallbacks]);
126
+ const persisted = accepted;
127
+ const llm = frame.agent.ctx?.get?.("llm")
128
+ ?? (readyCtx.get !== undefined ? readyCtx.get("llm") : readyCtx.llm);
129
+ const selected = persisted ?? (exactPolicy ? await selectInitialModelRoute(llm ?? {}, candidates, frame.signal) : inherited);
130
+ frame.signal.throwIfAborted();
131
+ lock = pinRoleRoute(frame.agent, identity, selected, candidates);
132
+ if (persisted !== undefined)
133
+ lock.startupSettled = true;
134
+ lockedAgents.add(frame.agent);
135
+ }
136
+ downstream = applyModelRoute(downstream, lock.route);
137
+ if (exactPolicy || lock.attempts > 0)
138
+ return downstream;
76
139
  }
140
+ // Ordinary roots belong to the native model tab, including its exact effort.
141
+ if (ordinaryRoot)
142
+ return downstream;
77
143
  // Named fallback efforts are native policy IDs, never legacy calibration inputs.
78
144
  if (fallbacks.some((fallback) => fallback.reasoningEffort !== undefined
79
145
  && sameModelRoute(fallback, downstream) && fallback.reasoningEffort === downstream.reasoningEffort))
@@ -107,15 +173,35 @@ export function registerModelRouting(ctx, controller, getSettings) {
107
173
  warnUnavailable(readyCtx, ctx, desired, `${downstream.provider}/${downstream.model}`);
108
174
  return downstream;
109
175
  }
176
+ if (identity !== undefined) {
177
+ const lock = roleRouteLock(frame.agent, identity);
178
+ if (lock !== undefined)
179
+ lock.route = { ...lock.route, reasoningEffort: selected };
180
+ }
110
181
  return { ...downstream, reasoningEffort: selected };
111
182
  }, { prepend: true });
183
+ disposeAgent = readyCtx.on("agent/disposed", ({ agent }) => {
184
+ lockedAgents.delete(agent);
185
+ clearRoleRouteLock(agent);
186
+ }, { global: true });
112
187
  }
113
188
  catch (error) {
114
189
  installedContexts.delete(readyCtx);
190
+ if (typeof dispose === "function")
191
+ dispose();
192
+ if (typeof disposeAssembly === "function")
193
+ disposeAssembly();
115
194
  throw error;
116
195
  }
117
196
  readyCtx.effect?.(() => () => {
197
+ for (const agent of lockedAgents)
198
+ clearRoleRouteLock(agent);
199
+ lockedAgents.clear();
118
200
  installedContexts.delete(readyCtx);
201
+ if (typeof disposeAgent === "function")
202
+ disposeAgent();
203
+ if (typeof disposeAssembly === "function")
204
+ disposeAssembly();
119
205
  if (typeof dispose === "function")
120
206
  dispose();
121
207
  });
@@ -1,11 +1,13 @@
1
1
  import type { RemoteResult, TypertRemoteContribution } from "@deepseek-ai/dsh-typert-protocol";
2
2
  import type { TypertContribution } from "@deepseek-ai/dsh-typert-registry";
3
- import type { ProfileErrorInfo, ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSnapshot } from "./profile-types.js";
3
+ import type { ProfileErrorInfo, ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSnapshot, SessionProfileSelectRequest, SessionProfileSnapshot } from "./profile-types.js";
4
4
  export interface DsmmProfilesRemote {
5
5
  describe(): Promise<RemoteResult<ProfileSnapshot>>;
6
6
  read(id: string): Promise<RemoteResult<ProfileReadResult>>;
7
7
  save(request: ProfileSaveRequest): Promise<RemoteResult<ProfileReadResult>>;
8
8
  select(request: ProfileSelectRequest): Promise<RemoteResult<ProfileSnapshot>>;
9
+ describeSession(sessionId: string): Promise<RemoteResult<SessionProfileSnapshot>>;
10
+ selectSession(sessionId: string, request: SessionProfileSelectRequest): Promise<RemoteResult<SessionProfileSnapshot>>;
9
11
  }
10
12
  declare module "@deepseek-ai/dsh-typert-protocol/types" {
11
13
  interface TypertRemoteMap {
@@ -13,6 +15,8 @@ declare module "@deepseek-ai/dsh-typert-protocol/types" {
13
15
  "dsmmProfiles/read": DsmmProfilesRemote["read"];
14
16
  "dsmmProfiles/save": DsmmProfilesRemote["save"];
15
17
  "dsmmProfiles/select": DsmmProfilesRemote["select"];
18
+ "dsmmProfiles/describeSession": DsmmProfilesRemote["describeSession"];
19
+ "dsmmProfiles/selectSession": DsmmProfilesRemote["selectSession"];
16
20
  }
17
21
  interface TypertRemoteNamespaceMap {
18
22
  dsmmProfiles: DsmmProfilesRemote;
@@ -24,6 +28,8 @@ declare module "@deepseek-ai/dsh-typert-protocol/types" {
24
28
  }
25
29
  /** Shared wire grammar for native codec validation and local form feedback. */
26
30
  export declare function isProfileId(value: unknown): value is string;
31
+ /** Opaque native identities are never interpreted as paths. */
32
+ export declare function isNativeSessionId(value: unknown): value is string;
27
33
  /** Explicit strict Host contract; no SRC fallback or browser-supplied authority. */
28
34
  export declare const TYPERT_REMOTE: TypertRemoteContribution;
29
35
  export declare const TYPERT_HOST: TypertContribution;
@@ -1,6 +1,8 @@
1
- const errorCodes = new Set(["validation", "conflict", "not-found", "lock-timeout", "unsafe-path", "io", "activation", "corrupt-selection", "limit"]);
1
+ import { DSMM_RATE_LIMIT_BOUNDS, normalizeRateLimitOverrides, normalizeRateLimitPolicy, normalizeRoutingStrategy } from "./routing-policy.js";
2
+ const errorCodes = new Set(["validation", "conflict", "not-found", "lock-timeout", "unsafe-path", "io", "activation", "corrupt-selection", "limit", "busy", "maintenance", "disposed", "not-owned", "unavailable", "cancelled"]);
2
3
  const idPattern = /^[a-z0-9][a-z0-9_-]{0,63}$/u;
3
4
  const revisionPattern = /^[a-f0-9]{64}$/u;
5
+ const rolePattern = /^dsmm-(?:orchestrator|planner|plan-critic|builder|reviewer|oracle|oracle-2nd|creative|code-search|doc-search|clarifier|media-reader)$/u;
4
6
  /** Shared wire grammar for native codec validation and local form feedback. */
5
7
  export function isProfileId(value) {
6
8
  return typeof value === "string" && idPattern.test(value)
@@ -25,6 +27,39 @@ function revision(value) {
25
27
  return result;
26
28
  }
27
29
  function selectionRevision(value) { return value === "absent" ? value : revision(value); }
30
+ /** Opaque native identities are never interpreted as paths. */
31
+ export function isNativeSessionId(value) {
32
+ return typeof value === "string" && value.length > 0 && value.length <= 256
33
+ && !/[\u0000-\u001f\u007f]/u.test(value)
34
+ && new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(new TextEncoder().encode(value)) === value;
35
+ }
36
+ function sessionId(value) {
37
+ if (!isNativeSessionId(value))
38
+ fail("sessionId");
39
+ return value;
40
+ }
41
+ function boolean(value, field) {
42
+ if (typeof value !== "boolean")
43
+ fail(field);
44
+ return value;
45
+ }
46
+ function integer(value, field, maximum = Number.MAX_SAFE_INTEGER) {
47
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > maximum)
48
+ fail(field);
49
+ return value;
50
+ }
51
+ function routeText(value, field, maximum) {
52
+ const result = text(value, field, maximum);
53
+ if (result.trim() === "" || /[\u0000-\u001f\u007f]/u.test(result)
54
+ || new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(new TextEncoder().encode(result)) !== result)
55
+ fail(field);
56
+ return result;
57
+ }
58
+ function role(value) {
59
+ if (typeof value !== "string" || !rolePattern.test(value))
60
+ fail("role");
61
+ return value;
62
+ }
28
63
  function object(value, required, optional = []) {
29
64
  if (value === null || typeof value !== "object" || Array.isArray(value))
30
65
  fail("object");
@@ -55,7 +90,7 @@ function content(value) {
55
90
  return result;
56
91
  }
57
92
  function snapshot(value) {
58
- const item = object(value, ["profiles", "selectedId", "appliedRevision", "selectionRevision"], ["selectionError"]);
93
+ const item = object(value, ["profiles", "selectedId", "appliedRevision", "selectionRevision"], ["selectionError", "roles", "editorDefaults"]);
59
94
  if (!Array.isArray(item.profiles) || item.profiles.length > 128)
60
95
  fail("profiles");
61
96
  return {
@@ -67,6 +102,70 @@ function snapshot(value) {
67
102
  appliedRevision: item.appliedRevision === null ? null : revision(item.appliedRevision),
68
103
  selectionRevision: item.selectionRevision === "unavailable" && Object.hasOwn(item, "selectionError") ? "unavailable" : selectionRevision(item.selectionRevision),
69
104
  ...optional(item, "selectionError", errorInfo),
105
+ ...optional(item, "roles", (input) => {
106
+ if (!Array.isArray(input) || input.length > 12)
107
+ fail("roles");
108
+ const result = input.map((value) => {
109
+ const row = object(value, ["id", "label", "enabled"], ["runtimePolicy"]);
110
+ return { id: role(row.id), label: text(row.label, "label", 120), enabled: boolean(row.enabled, "enabled"), ...optional(row, "runtimePolicy", (input) => {
111
+ const policy = object(input, [], ["strategy", "rateLimit"]);
112
+ return { ...optional(policy, "strategy", normalizeRoutingStrategy), ...optional(policy, "rateLimit", normalizeRateLimitOverrides) };
113
+ }) };
114
+ });
115
+ if (new Set(result.map((row) => row.id)).size !== result.length)
116
+ fail("roles");
117
+ return result;
118
+ }),
119
+ ...optional(item, "editorDefaults", runtimePolicy),
120
+ };
121
+ }
122
+ function rateLimit(value) {
123
+ const item = object(value, Object.keys(DSMM_RATE_LIMIT_BOUNDS));
124
+ return normalizeRateLimitPolicy(item);
125
+ }
126
+ function runtimePolicy(value) {
127
+ const item = object(value, ["strategy", "rateLimit"]);
128
+ return { strategy: normalizeRoutingStrategy(item.strategy), rateLimit: rateLimit(item.rateLimit) };
129
+ }
130
+ function rolePolicy(value) {
131
+ const item = object(value, ["strategy", "rateLimit", "retries", "rateLimitFailures", "switches", "totalDelayMs"], ["role", "route"]);
132
+ return {
133
+ ...runtimePolicy({ strategy: item.strategy, rateLimit: item.rateLimit }),
134
+ retries: integer(item.retries, "retries", 10),
135
+ rateLimitFailures: integer(item.rateLimitFailures, "rateLimitFailures"),
136
+ switches: integer(item.switches, "switches", 10),
137
+ totalDelayMs: integer(item.totalDelayMs, "totalDelayMs", 120000),
138
+ ...optional(item, "role", role),
139
+ ...optional(item, "route", modelRoute),
140
+ };
141
+ }
142
+ function modelRoute(value) {
143
+ const route = object(value, ["provider", "model"], ["reasoningEffort"]);
144
+ const provider = routeText(route.provider, "provider", 128);
145
+ const model = routeText(route.model, "model", 512);
146
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/u.test(provider) || model.includes("://"))
147
+ fail("route");
148
+ return { provider, model, ...optional(route, "reasoningEffort", (input) => routeText(input, "reasoningEffort", 64)) };
149
+ }
150
+ function selectionState(value) {
151
+ const item = object(value, ["selectedId", "appliedRevision", "selectionRevision"]);
152
+ return { selectedId: item.selectedId === null ? null : id(item.selectedId), appliedRevision: item.appliedRevision === null ? null : revision(item.appliedRevision), selectionRevision: selectionRevision(item.selectionRevision) };
153
+ }
154
+ function sessionSnapshot(value) {
155
+ const item = object(value, ["sessionId", "globalDefault", "selection", "scope", "admissionEpoch", "switchAllowed"], ["admittedSelection", "switchUnavailableReason", "rolePolicy", "profileModel"]);
156
+ if (typeof item.scope !== "string" || !["global-default", "session-override", "deployment-baseline"].includes(item.scope))
157
+ fail("scope");
158
+ return {
159
+ sessionId: sessionId(item.sessionId), globalDefault: selectionState(item.globalDefault), selection: selectionState(item.selection),
160
+ scope: item.scope, admissionEpoch: revision(item.admissionEpoch), switchAllowed: boolean(item.switchAllowed, "switchAllowed"),
161
+ ...optional(item, "admittedSelection", selectionState),
162
+ ...optional(item, "switchUnavailableReason", (input) => {
163
+ if (typeof input !== "string" || !["busy", "maintenance", "disposed", "not-owned", "unavailable"].includes(input))
164
+ fail("switchUnavailableReason");
165
+ return input;
166
+ }),
167
+ ...optional(item, "rolePolicy", rolePolicy),
168
+ ...optional(item, "profileModel", modelRoute),
70
169
  };
71
170
  }
72
171
  function saveRequest(value) {
@@ -82,6 +181,11 @@ function selectRequest(value) {
82
181
  fail("expectedRevision");
83
182
  return result;
84
183
  }
184
+ function sessionSelectRequest(value) {
185
+ const item = object(value, ["sessionId", "id", "expectedSelectionRevision", "expectedAdmissionEpoch"], ["expectedRevision"]);
186
+ const { sessionId: inputSessionId, expectedAdmissionEpoch, ...profileRequest } = item;
187
+ return { ...selectRequest(profileRequest), sessionId: sessionId(inputSessionId), expectedAdmissionEpoch: revision(expectedAdmissionEpoch) };
188
+ }
85
189
  function codec(symbol, parse) {
86
190
  return { mode: "strict", typeSymbol: `@dsmm/dsmm#${symbol}`, create: () => ({ parse }) };
87
191
  }
@@ -96,6 +200,17 @@ export const TYPERT_REMOTE = {
96
200
  descriptor("read", codec("ProfileReadResult", readResult), { name: "id", codec: codec("ProfileId", id) }),
97
201
  descriptor("save", codec("ProfileReadResult", readResult), { name: "request", codec: codec("ProfileSaveRequest", saveRequest) }),
98
202
  descriptor("select", codec("ProfileSnapshot", snapshot), { name: "request", codec: codec("ProfileSelectRequest", selectRequest) }),
203
+ {
204
+ ...descriptor("describeSession", codec("SessionProfileSnapshot", sessionSnapshot)),
205
+ parameters: [{ name: "sessionId", wire: "sessionId", source: "json", codec: codec("NativeSessionId", sessionId) }],
206
+ },
207
+ {
208
+ ...descriptor("selectSession", codec("SessionProfileSnapshot", sessionSnapshot)),
209
+ parameters: [
210
+ { name: "sessionId", wire: "sessionId", source: "json", codec: codec("NativeSessionId", sessionId) },
211
+ { name: "request", wire: "request", source: "json", codec: codec("SessionProfileSelectRequest", sessionSelectRequest) },
212
+ ],
213
+ },
99
214
  ],
100
215
  };
101
216
  export const TYPERT_HOST = {
@@ -1,21 +1,29 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
3
- import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSnapshot } from "./profile-types.js";
3
+ import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSnapshot, SessionProfileSelectRequest, SessionProfileSnapshot } from "./profile-types.js";
4
+ import type { DshAgent } from "./dsh-types.js";
4
5
  export interface ProfilesBackend {
5
6
  describe(): Promise<ProfileSnapshot>;
6
7
  read(id: string): Promise<ProfileReadResult>;
7
8
  save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
8
9
  select(request: ProfileSelectRequest): Promise<ProfileSnapshot>;
10
+ getSession(agent: DshAgent): Promise<SessionProfileSnapshot>;
11
+ selectSession(request: SessionProfileSelectRequest, capturedAgent: DshAgent, signal?: AbortSignal, assertAuthority?: () => void): Promise<SessionProfileSnapshot>;
9
12
  }
10
13
  /** Business service addressed only by native Typert Gateway invocations. */
11
14
  export declare class DsmmProfilesHost extends TypertRemoteService {
12
15
  readonly backend: ProfilesBackend;
16
+ private readonly lifetime;
13
17
  constructor(ctx: Context, backend: ProfilesBackend);
14
18
  private invoke;
15
19
  describe(): Promise<ProfileSnapshot>;
16
20
  read(id: string): Promise<ProfileReadResult>;
17
21
  save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
18
22
  select(request: ProfileSelectRequest): Promise<ProfileSnapshot>;
23
+ /** Native Connection's exact operator is authority, not a claimed Peer ID. */
24
+ private invokeSession;
25
+ describeSession(sessionId: string): Promise<SessionProfileSnapshot>;
26
+ selectSession(sessionId: string, request: SessionProfileSelectRequest): Promise<SessionProfileSnapshot>;
19
27
  }
20
28
  declare module "@deepseek-ai/cordis" {
21
29
  interface Context {
@@ -32,9 +32,11 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
32
32
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
33
  done = true;
34
34
  };
35
- import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
35
+ import { symbols } from "@deepseek-ai/cordis";
36
+ import { Remote, RemoteError, TypertRemoteService, remoteErrorOf } from "@deepseek-ai/dsh-typert-protocol";
37
+ import { SessionId } from "@deepseek-ai/dsh-session";
36
38
  import { TYPERT_HOST } from "./profile-remote.js";
37
- import { profileErrorInfo } from "./profiles.js";
39
+ import { DsmmProfileError, profileErrorInfo } from "./profiles.js";
38
40
  /** Business service addressed only by native Typert Gateway invocations. */
39
41
  let DsmmProfilesHost = (() => {
40
42
  let _classSuper = TypertRemoteService;
@@ -43,6 +45,8 @@ let DsmmProfilesHost = (() => {
43
45
  let _read_decorators;
44
46
  let _save_decorators;
45
47
  let _select_decorators;
48
+ let _describeSession_decorators;
49
+ let _selectSession_decorators;
46
50
  return class DsmmProfilesHost extends _classSuper {
47
51
  static {
48
52
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
@@ -50,16 +54,22 @@ let DsmmProfilesHost = (() => {
50
54
  _read_decorators = [Remote];
51
55
  _save_decorators = [Remote];
52
56
  _select_decorators = [Remote];
57
+ _describeSession_decorators = [Remote];
58
+ _selectSession_decorators = [Remote];
53
59
  __esDecorate(this, null, _describe_decorators, { kind: "method", name: "describe", static: false, private: false, access: { has: obj => "describe" in obj, get: obj => obj.describe }, metadata: _metadata }, null, _instanceExtraInitializers);
54
60
  __esDecorate(this, null, _read_decorators, { kind: "method", name: "read", static: false, private: false, access: { has: obj => "read" in obj, get: obj => obj.read }, metadata: _metadata }, null, _instanceExtraInitializers);
55
61
  __esDecorate(this, null, _save_decorators, { kind: "method", name: "save", static: false, private: false, access: { has: obj => "save" in obj, get: obj => obj.save }, metadata: _metadata }, null, _instanceExtraInitializers);
56
62
  __esDecorate(this, null, _select_decorators, { kind: "method", name: "select", static: false, private: false, access: { has: obj => "select" in obj, get: obj => obj.select }, metadata: _metadata }, null, _instanceExtraInitializers);
63
+ __esDecorate(this, null, _describeSession_decorators, { kind: "method", name: "describeSession", static: false, private: false, access: { has: obj => "describeSession" in obj, get: obj => obj.describeSession }, metadata: _metadata }, null, _instanceExtraInitializers);
64
+ __esDecorate(this, null, _selectSession_decorators, { kind: "method", name: "selectSession", static: false, private: false, access: { has: obj => "selectSession" in obj, get: obj => obj.selectSession }, metadata: _metadata }, null, _instanceExtraInitializers);
57
65
  if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
58
66
  }
59
67
  backend = __runInitializers(this, _instanceExtraInitializers);
68
+ lifetime = new AbortController();
60
69
  constructor(ctx, backend) {
61
70
  super(ctx, "dsmmProfiles");
62
71
  this.backend = backend;
72
+ ctx.effect(() => () => this.lifetime.abort(), "dsmmProfiles: cancel scoped operations");
63
73
  }
64
74
  async invoke(operation) {
65
75
  const invocation = this.ctx.invocation;
@@ -78,6 +88,93 @@ let DsmmProfilesHost = (() => {
78
88
  read(id) { return this.invoke(() => this.backend.read(id)); }
79
89
  save(request) { return this.invoke(() => this.backend.save(request)); }
80
90
  select(request) { return this.invoke(() => this.backend.select(request)); }
91
+ /** Native Connection's exact operator is authority, not a claimed Peer ID. */
92
+ async invokeSession(sessionId, operation, readOnly = false) {
93
+ return this.invoke(async () => {
94
+ const invocation = this.ctx.invocation;
95
+ const connection = this.ctx.get("connection");
96
+ if (connection === undefined || connection.operator !== invocation.peer) {
97
+ throw new DsmmProfileError("not-owned", "The native Host operator must own this session profile operation.");
98
+ }
99
+ // Cordis rebinds Service projections for each accessing Context. Its
100
+ // public original symbol identifies the exact native authority owner.
101
+ const connectionOwner = Reflect.get(connection, symbols.original) ?? connection;
102
+ const signal = AbortSignal.any([invocation.signal, this.lifetime.signal]);
103
+ const checkAuthority = () => {
104
+ if (signal.aborted)
105
+ throw new DsmmProfileError("cancelled", "The session profile operation was cancelled; no late selection is allowed.");
106
+ const currentConnection = this.ctx.get("connection");
107
+ const currentOwner = currentConnection === undefined ? undefined : Reflect.get(currentConnection, symbols.original) ?? currentConnection;
108
+ if (currentOwner !== connectionOwner || currentConnection?.operator !== invocation.peer) {
109
+ throw new DsmmProfileError("not-owned", "The native Host operator connection is no longer active.");
110
+ }
111
+ const agents = this.ctx.get("agents");
112
+ if (agents === undefined || typeof agents.get !== "function" || typeof agents.roots !== "function" || typeof agents.list !== "function" || typeof agents.isOwnedBy !== "function") {
113
+ throw new DsmmProfileError("unavailable", "Native session authority is unavailable.");
114
+ }
115
+ return agents;
116
+ };
117
+ let agents = checkAuthority();
118
+ let captured = agents.get(sessionId);
119
+ if (captured === undefined) {
120
+ // Gateway lookups run before invocation authentication. Resolve here,
121
+ // after full strict JSON decoding and operator admission, so invalid or
122
+ // unauthorized calls cannot cold-resume a native session as a side effect.
123
+ const controller = this.ctx.get("sessionController");
124
+ if (controller === undefined || typeof controller.resolveAgent !== "function") {
125
+ throw new DsmmProfileError("unavailable", "The native ordinary-session resume service is unavailable.");
126
+ }
127
+ let found;
128
+ try {
129
+ found = await controller.resolveAgent(SessionId(sessionId));
130
+ }
131
+ catch {
132
+ checkAuthority();
133
+ throw new DsmmProfileError("unavailable", "The native session could not be safely resumed.", "sessionId");
134
+ }
135
+ agents = checkAuthority();
136
+ if ("error" in found) {
137
+ const code = remoteErrorOf(found.error)?.code;
138
+ if (code === "session/not-found")
139
+ throw new DsmmProfileError("not-found", "The native session was not found.", "sessionId");
140
+ if (code === "session/agent-busy")
141
+ throw new DsmmProfileError("not-owned", "Subagent-owned sessions cannot select a root profile.", "sessionId");
142
+ if (code === "session/writer-held")
143
+ throw new DsmmProfileError("busy", "The native session is owned by another active writer.", "sessionId");
144
+ throw new DsmmProfileError("unavailable", "The native session could not be safely resumed.", "sessionId");
145
+ }
146
+ captured = found.agent;
147
+ }
148
+ const agent = captured;
149
+ const checkCaptured = () => {
150
+ const current = checkAuthority();
151
+ if (agent.id !== sessionId || agent.session.id !== sessionId || current.get(sessionId) !== agent
152
+ || agent.session.header?.origin === "subagent" || !current.roots().includes(agent)
153
+ || current.list().some((owner) => owner !== agent && current.isOwnedBy(sessionId, owner))) {
154
+ throw new DsmmProfileError("not-owned", "Only an exact live ordinary root session can select a profile.", "sessionId");
155
+ }
156
+ };
157
+ checkCaptured();
158
+ const result = await operation(agent, signal, checkCaptured);
159
+ // Mutation owns its final pre-commit fence in native maintenance. A
160
+ // successful durable commit must not be relabeled as a failed write if
161
+ // a queued wake/disposal wins immediately after maintenance releases.
162
+ if (readOnly)
163
+ checkCaptured();
164
+ return result;
165
+ });
166
+ }
167
+ describeSession(sessionId) {
168
+ return this.invokeSession(sessionId, (agent) => this.backend.getSession(agent), true);
169
+ }
170
+ selectSession(sessionId, request) {
171
+ // The redundant stable identity is a fence, never an authority assertion.
172
+ // Check it before any native resume or profile-store operation.
173
+ if (request.sessionId !== sessionId) {
174
+ return this.invoke(async () => { throw new DsmmProfileError("validation", "The requested session identities must match.", "sessionId"); });
175
+ }
176
+ return this.invokeSession(sessionId, (agent, signal, assertAuthority) => this.backend.selectSession(request, agent, signal, assertAuthority));
177
+ }
81
178
  };
82
179
  })();
83
180
  export { DsmmProfilesHost };