@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
@@ -1,8 +1,8 @@
1
1
  import type { DshAgent, DshContext } from "./dsh-types.js";
2
- import type { LoadedProfileSelection } from "./profile-store.js";
3
- import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSelectionState, ProfileSnapshot } from "./profile-types.js";
2
+ import type { LoadedProfileSelection, LoadedSessionProfileSelection, SessionProfileCommit } from "./profile-store.js";
3
+ import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSelectionState, ProfileSnapshot, SessionProfileSelectRequest, SessionProfileSnapshot } from "./profile-types.js";
4
4
  import type { DsmmProfileDocument } from "./profiles.js";
5
- import type { DsmmSettings, DsmmSettingsGetter } from "./settings.js";
5
+ import type { DsmmProfileAdmission, DsmmSettings, DsmmSettingsGetter } from "./settings.js";
6
6
  export interface DsmmProfileRuntimeStore {
7
7
  loadSelection(): Promise<LoadedProfileSelection>;
8
8
  describe(): Promise<ProfileSnapshot>;
@@ -12,12 +12,19 @@ export interface DsmmProfileRuntimeStore {
12
12
  selection: ProfileSelectionState;
13
13
  prepared: T;
14
14
  }>;
15
+ loadSessionSelection(sessionId: string): Promise<LoadedSessionProfileSelection>;
16
+ selectSession<T>(request: SessionProfileSelectRequest, epoch: string, validateCandidate: (document: DsmmProfileDocument | null) => T | Promise<T>, commit: SessionProfileCommit<T>): Promise<{
17
+ selection: LoadedSessionProfileSelection;
18
+ prepared: T;
19
+ }>;
15
20
  }
16
21
  export interface DsmmProfileRuntimeOptions {
17
22
  /** Trusted test/integration seam, never a wire-supplied path or callback. */
18
23
  validateCandidate?: (settings: DsmmSettings) => void | Promise<void>;
19
24
  }
20
- /** Selection admits new roots only; live children inherit exact runtime ownership. */
25
+ interface AdmittedProfile extends ProfileSelectionState, DsmmProfileAdmission {
26
+ }
27
+ /** Global defaults admit new roots; scoped idle switches replace one root's epoch. */
21
28
  export declare class DsmmProfileRuntime {
22
29
  private readonly ctx;
23
30
  private readonly store;
@@ -26,19 +33,32 @@ export declare class DsmmProfileRuntime {
26
33
  private current;
27
34
  private readonly baseline;
28
35
  private readonly bound;
36
+ private readonly admitting;
37
+ private readonly disposedAgents;
38
+ private readonly switching;
39
+ private disposed;
29
40
  private selectionQueue;
30
41
  constructor(ctx: DshContext, baseline: DsmmSettings, store: DsmmProfileRuntimeStore, options?: DsmmProfileRuntimeOptions);
31
42
  initialize(): Promise<void>;
32
- admission(agent: DshAgent): ProfileSelectionState;
43
+ admission(agent?: DshAgent): AdmittedProfile;
44
+ getSession(agent: DshAgent): Promise<SessionProfileSnapshot>;
45
+ /** The fourth argument is trusted native caller authority, never wire data. */
46
+ selectSession(request: SessionProfileSelectRequest, agent: DshAgent, signal?: AbortSignal, assertAuthority?: () => void): Promise<SessionProfileSnapshot>;
33
47
  describe(): Promise<ProfileSnapshot>;
34
48
  read(id: string): Promise<ProfileReadResult>;
35
49
  save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
36
50
  select(request: ProfileSelectRequest): Promise<ProfileSnapshot>;
37
51
  private prepare;
52
+ private profileAdmission;
53
+ private declaredProfileModel;
38
54
  private agents;
39
55
  private bind;
56
+ private owner;
57
+ private assertRoot;
58
+ private admit;
40
59
  private validate;
41
60
  }
42
61
  /** No guessed home fallback: native deployment context owns this directory. */
43
62
  export declare function createProfileRuntime(ctx: DshContext, baseline: DsmmSettings): Promise<DsmmProfileRuntime>;
63
+ export {};
44
64
  //# sourceMappingURL=profile-runtime.d.ts.map
@@ -1,7 +1,12 @@
1
1
  import { join } from "node:path";
2
- import { ProfileStore } from "./profile-store.js";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { ProfileStore, validateSessionProfileId } from "./profile-store.js";
3
4
  import { DsmmProfileError, resolveProfileSettings } from "./profiles.js";
4
5
  import { DSMM_ROLES, isRootRole } from "./roles.js";
6
+ import { roleRouteRuntimeState, selectInitialModelRoute } from "./role-routing.js";
7
+ import { resolveEffectiveDsmmRole, sessionEvents } from "./session-scope.js";
8
+ import { isDeepworkActive } from "./state.js";
9
+ import { resolveRoleRuntimePolicy } from "./settings.js";
5
10
  function immutableSettings(settings) {
6
11
  const copy = structuredClone(settings);
7
12
  const freeze = (value) => {
@@ -14,7 +19,7 @@ function immutableSettings(settings) {
14
19
  freeze(copy);
15
20
  return copy;
16
21
  }
17
- /** Selection admits new roots only; live children inherit exact runtime ownership. */
22
+ /** Global defaults admit new roots; scoped idle switches replace one root's epoch. */
18
23
  export class DsmmProfileRuntime {
19
24
  ctx;
20
25
  store;
@@ -23,28 +28,110 @@ export class DsmmProfileRuntime {
23
28
  current;
24
29
  baseline;
25
30
  bound = new WeakMap();
31
+ admitting = new WeakSet();
32
+ disposedAgents = new WeakSet();
33
+ switching = new WeakSet();
34
+ disposed = false;
26
35
  selectionQueue = Promise.resolve();
27
36
  constructor(ctx, baseline, store, options = {}) {
28
37
  this.ctx = ctx;
29
38
  this.store = store;
30
39
  this.options = options;
31
40
  this.baseline = immutableSettings(baseline);
32
- this.current = { selectedId: null, appliedRevision: null, selectionRevision: "absent", settings: this.baseline };
41
+ this.current = this.prepare(null, { selectedId: null, appliedRevision: null, selectionRevision: "absent" });
42
+ this.getSettings.admission = (agent) => this.admission(agent);
33
43
  }
34
44
  async initialize() {
35
45
  const selection = await this.store.loadSelection();
36
- // Cold resumes are new runtime Agents: the pinned current selection is the
37
- // startup authority, not an assertion that a previous process still lives.
38
46
  this.current = this.prepare(selection.document, selection);
39
- this.ctx.on?.("agent/created", ({ agent }) => { this.bind(agent); }, { global: true, prepend: true });
47
+ this.ctx.on?.("agent/created", async ({ agent, signal }) => {
48
+ // Factory initialization already owns native maintenance: never whenIdle
49
+ // or reserve maintenance from inside this serial creation listener.
50
+ await this.admit(agent, signal);
51
+ }, { global: true, prepend: true });
52
+ this.ctx.on?.("agent/disposed", ({ agent }) => { this.disposedAgents.add(agent); }, { global: true });
53
+ this.ctx.effect?.(() => () => { this.disposed = true; });
40
54
  // Installation into an already-running host treats those Agents as admitted
41
55
  // now, while all later profile switches continue to preserve their snapshot.
42
56
  for (const agent of this.agents()?.list() ?? [])
43
- this.bind(agent);
57
+ await this.admit(agent);
58
+ }
59
+ admission(agent) { return agent === undefined ? this.current : this.bind(agent); }
60
+ async getSession(agent) {
61
+ this.assertRoot(agent);
62
+ const admitted = this.bind(agent);
63
+ const disk = await this.store.loadSessionSelection(agent.id);
64
+ this.assertRoot(agent);
65
+ if (this.bind(agent) !== admitted)
66
+ throw new DsmmProfileError("conflict", "The session admission changed while reading. Refresh before selecting again.");
67
+ if ((disk.admissionEpoch === null && admitted.scope !== "global-default") || (disk.admissionEpoch !== null && (disk.admissionEpoch !== admitted.epoch || disk.selectedId !== admitted.selectedId || disk.appliedRevision !== admitted.appliedRevision))) {
68
+ throw new DsmmProfileError("conflict", "The session choice changed outside this Host. Its admitted policy was retained; refresh or resume explicitly.");
69
+ }
70
+ const reason = this.switching.has(agent) ? "maintenance" : agent.status === "running" ? "busy" : agent.runMaintenance === undefined ? "unavailable" : undefined;
71
+ const role = resolveEffectiveDsmmRole(agent, admitted.settings, isDeepworkActive(sessionEvents(agent.session), admitted.settings.defaultActive));
72
+ const profileModel = this.declaredProfileModel(admitted.settings, role);
73
+ return { sessionId: agent.id, globalDefault: selectionState(this.current), selection: selectionState(disk), admittedSelection: selectionState(admitted), scope: admitted.scope,
74
+ rolePolicy: roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch),
75
+ ...(profileModel === undefined ? {} : { profileModel }),
76
+ admissionEpoch: admitted.epoch, switchAllowed: reason === undefined, ...(reason === undefined ? {} : { switchUnavailableReason: reason }) };
44
77
  }
45
- admission(agent) {
46
- const { selectedId, appliedRevision, selectionRevision } = this.bind(agent);
47
- return { selectedId, appliedRevision, selectionRevision };
78
+ /** The fourth argument is trusted native caller authority, never wire data. */
79
+ selectSession(request, agent, signal, assertAuthority) {
80
+ this.assertRoot(agent);
81
+ if (request.sessionId !== agent.id)
82
+ throw new DsmmProfileError("not-owned", "The native session does not match the captured Agent.");
83
+ const admitted = this.bind(agent);
84
+ const assertCurrent = (maintenanceSignal) => {
85
+ this.assertRoot(agent);
86
+ if (signal?.aborted || maintenanceSignal?.aborted)
87
+ throw new DsmmProfileError("cancelled", "Session profile selection was cancelled; the previous admission was retained.");
88
+ if (this.bind(agent) !== admitted || admitted.epoch !== request.expectedAdmissionEpoch)
89
+ throw new DsmmProfileError("conflict", "The session admission changed. Refresh before selecting again.");
90
+ assertAuthority?.();
91
+ };
92
+ assertCurrent();
93
+ if (agent.status === "running")
94
+ throw new DsmmProfileError("busy", "The session is running. Wait for its current activity before selecting a profile.");
95
+ if (agent.runMaintenance === undefined)
96
+ throw new DsmmProfileError("unavailable", "Native idle maintenance is unavailable; no session selection was committed.");
97
+ let operation;
98
+ try {
99
+ operation = agent.runMaintenance(async (maintenanceSignal) => {
100
+ this.switching.add(agent);
101
+ try {
102
+ assertCurrent(maintenanceSignal);
103
+ const epoch = newEpoch();
104
+ let profileModel;
105
+ const result = await this.store.selectSession(request, epoch, async (document) => {
106
+ const prepared = immutableSettings(resolveProfileSettings(this.baseline, document?.settings ?? {}));
107
+ await this.validate(prepared, agent, maintenanceSignal);
108
+ const role = resolveEffectiveDsmmRole(agent, prepared, isDeepworkActive(sessionEvents(agent.session), prepared.defaultActive));
109
+ profileModel = this.declaredProfileModel(prepared, role);
110
+ assertCurrent(maintenanceSignal);
111
+ return prepared;
112
+ }, {
113
+ assertCurrent: () => assertCurrent(maintenanceSignal),
114
+ committed: (selection, settings) => {
115
+ this.bound.set(agent, this.profileAdmission(selection, settings, epoch, request.id === null ? "deployment-baseline" : "session-override"));
116
+ }
117
+ });
118
+ // A committed selection remains a successful transaction even if a
119
+ // queued wake or disposal wins immediately when maintenance releases.
120
+ return { sessionId: request.sessionId, globalDefault: selectionState(this.current), selection: selectionState(result.selection), admittedSelection: selectionState(result.selection),
121
+ ...(profileModel === undefined ? {} : { profileModel }),
122
+ scope: request.id === null ? "deployment-baseline" : "session-override", admissionEpoch: epoch, switchAllowed: true };
123
+ }
124
+ finally {
125
+ this.switching.delete(agent);
126
+ }
127
+ });
128
+ }
129
+ catch (error) {
130
+ if (error instanceof DsmmProfileError)
131
+ throw error;
132
+ throw new DsmmProfileError("maintenance", "Another activity owns the session's idle maintenance phase. No selection was queued or committed.");
133
+ }
134
+ return operation;
48
135
  }
49
136
  async describe() {
50
137
  const persisted = await this.store.describe();
@@ -54,6 +141,14 @@ export class DsmmProfileRuntime {
54
141
  || persisted.selectionRevision !== current.selectionRevision;
55
142
  return {
56
143
  ...persisted,
144
+ roles: DSMM_ROLES.map((role) => {
145
+ const configured = this.baseline.roleRouting[role.id];
146
+ const runtimePolicy = { ...(configured?.strategy === undefined ? {} : { strategy: configured.strategy }),
147
+ ...(configured?.rateLimit === undefined ? {} : { rateLimit: structuredClone(configured.rateLimit) }) };
148
+ return { id: role.id, label: role.name, enabled: this.baseline.roles[role.id],
149
+ ...(Object.keys(runtimePolicy).length === 0 ? {} : { runtimePolicy }) };
150
+ }),
151
+ editorDefaults: structuredClone(this.baseline.runtimePolicy),
57
152
  selectedId: current.selectedId,
58
153
  appliedRevision: current.appliedRevision,
59
154
  // Keep the disk revision for CAS, but never label its unvalidated policy
@@ -77,31 +172,87 @@ export class DsmmProfileRuntime {
77
172
  });
78
173
  // There is no await between successful durable commit and publication of
79
174
  // the complete settings value. Draft saves never reach this assignment.
80
- this.current = { ...result.selection, settings: result.prepared };
175
+ this.current = this.profileAdmission(result.selection, result.prepared, newEpoch(), "global-default");
81
176
  return this.describe();
82
177
  });
83
178
  this.selectionQueue = operation.catch(() => undefined);
84
179
  return operation;
85
180
  }
86
- prepare(document, selection) {
87
- return { selectedId: selection.selectedId, appliedRevision: selection.appliedRevision, selectionRevision: selection.selectionRevision,
88
- settings: immutableSettings(resolveProfileSettings(this.baseline, document?.settings ?? {})) };
181
+ prepare(document, selection, epoch = newEpoch(), scope = "global-default") {
182
+ return this.profileAdmission(selection, immutableSettings(resolveProfileSettings(this.baseline, document?.settings ?? {})), epoch, scope);
183
+ }
184
+ profileAdmission(selection, settings, epoch, scope) {
185
+ return Object.freeze({ ...selectionState(selection), settings, epoch, scope, profile: selection.selectedId === null || selection.appliedRevision === null ? null : Object.freeze({ id: selection.selectedId, revision: selection.appliedRevision }) });
186
+ }
187
+ declaredProfileModel(settings, role) {
188
+ const primary = role === undefined ? undefined : settings.roleRouting[role]?.primary;
189
+ return primary === undefined ? undefined : { provider: primary.provider, model: primary.model,
190
+ ...(primary.reasoningEffort === undefined ? {} : { reasoningEffort: primary.reasoningEffort }) };
89
191
  }
90
192
  agents() { return this.ctx.get?.("agents"); }
91
193
  bind(agent) {
92
194
  const existing = this.bound.get(agent);
93
195
  if (existing !== undefined)
94
196
  return existing;
95
- const agents = this.agents();
197
+ if (this.admitting.has(agent))
198
+ throw new DsmmProfileError("activation", "The session's profile admission has not completed.");
199
+ if (agent.id !== undefined && this.agents()?.get !== undefined) {
200
+ // Native enter() precedes serial created admission. An early RPC or
201
+ // extension (including unpublished setup) cannot make a native root skip
202
+ // its persisted sidecar by eagerly creating a default binding.
203
+ throw new DsmmProfileError("activation", "The native session has not completed its awaited profile admission.");
204
+ }
96
205
  // The native factory enters the exact child/owner pair before announcing
97
206
  // creation. Durable lineage and inherited persona never establish ownership.
98
- const parent = agent.id === undefined ? undefined
99
- : agents?.list().find((candidate) => candidate !== agent && agents.isOwnedBy(agent.id, candidate));
207
+ const parent = this.owner(agent);
100
208
  const admitted = parent === undefined ? this.current : this.bind(parent);
101
209
  this.bound.set(agent, admitted);
102
210
  return admitted;
103
211
  }
104
- async validate(settings) {
212
+ owner(agent) {
213
+ const agents = this.agents();
214
+ return agent.id === undefined ? undefined : agents?.list().find((candidate) => candidate !== agent && agents.isOwnedBy(agent.id, candidate));
215
+ }
216
+ assertRoot(agent) {
217
+ if (this.disposed || this.disposedAgents.has(agent))
218
+ throw new DsmmProfileError("disposed", "The session or profile service was disposed; no selection was committed.");
219
+ validateSessionProfileId(agent.id);
220
+ const agents = this.agents();
221
+ if (agents?.get === undefined)
222
+ throw new DsmmProfileError("unavailable", "Native live Agent lookup is unavailable; no session selection was committed.");
223
+ if (agents.get(agent.id) !== agent || this.owner(agent) !== undefined || agent.session.header?.origin === "subagent") {
224
+ throw new DsmmProfileError("not-owned", "Session profile selection requires the exact live ordinary root Agent.");
225
+ }
226
+ }
227
+ async admit(agent, signal) {
228
+ if (this.bound.has(agent))
229
+ return;
230
+ const parent = this.owner(agent);
231
+ if (parent !== undefined) {
232
+ this.bound.set(agent, this.bind(parent));
233
+ return;
234
+ }
235
+ if (agent.id === undefined) {
236
+ this.bind(agent);
237
+ return;
238
+ }
239
+ this.admitting.add(agent);
240
+ try {
241
+ signal?.throwIfAborted();
242
+ const selection = await this.store.loadSessionSelection(agent.id);
243
+ signal?.throwIfAborted();
244
+ if (this.disposed || this.disposedAgents.has(agent))
245
+ throw new DsmmProfileError("disposed", "The session was disposed during profile admission.");
246
+ const registry = this.agents();
247
+ if (registry?.get !== undefined && registry.get(agent.id) !== agent)
248
+ throw new DsmmProfileError("not-owned", "The live session changed during profile admission.");
249
+ this.bound.set(agent, selection.admissionEpoch === null ? this.current : this.prepare(selection.document, selection, selection.admissionEpoch, selection.selectedId === null ? "deployment-baseline" : "session-override"));
250
+ }
251
+ finally {
252
+ this.admitting.delete(agent);
253
+ }
254
+ }
255
+ async validate(settings, agent, signal) {
105
256
  if (this.options.validateCandidate !== undefined) {
106
257
  await this.options.validateCandidate(settings);
107
258
  return;
@@ -119,27 +270,34 @@ export class DsmmProfileRuntime {
119
270
  }
120
271
  }
121
272
  }
122
- const routes = [];
123
- for (const [role, policy] of Object.entries(settings.roleRouting)) {
124
- if (!settings.roles[role])
273
+ const nativeAgent = agent ?? (this.agents()?.list() ?? []).find((candidate) => candidate.ctx?.get?.("llm")?.resolveCallConfig !== undefined);
274
+ const inherited = nativeAgent?.options;
275
+ const inheritedRoute = inherited?.provider === undefined || inherited.model === undefined ? undefined
276
+ : { provider: inherited.provider, model: inherited.model, ...(inherited.reasoningEffort === undefined ? {} : { reasoningEffort: inherited.reasoningEffort }) };
277
+ const chains = [];
278
+ for (const role of DSMM_ROLES) {
279
+ if (!settings.roles[role.id])
280
+ continue;
281
+ const policy = resolveRoleRuntimePolicy(settings, role.id);
282
+ // No explicit primary inherits native routing. Dormant fallbacks alone
283
+ // cannot make a usable inherited route fail profile Apply. If that exact
284
+ // route is unavailable here, native request preflight remains authority.
285
+ if (policy.primary === undefined && inheritedRoute === undefined)
125
286
  continue;
126
- if (policy.primary !== undefined)
127
- routes.push({ route: policy.primary, field: `settings.roleRouting.${role}.primary` });
128
- for (const [index, route] of (policy.fallbackRoutes ?? []).entries())
129
- routes.push({ route, field: `settings.roleRouting.${role}.fallbackRoutes.${index}` });
287
+ const routes = [policy.primary ?? inheritedRoute, ...policy.fallbackRoutes];
288
+ if (routes.length > 0)
289
+ chains.push({ routes, field: `settings.roleRouting.${role.id}.${policy.primary === undefined ? "fallbackRoutes" : "primary"}` });
130
290
  }
131
- for (const [index, route] of settings.runtimeRecovery.fallbackRoutes.entries())
132
- routes.push({ route, field: `settings.runtimeRecovery.fallbackRoutes.${index}` });
133
- if (routes.length === 0)
291
+ if (chains.length === 0)
134
292
  return;
135
- const llm = (this.agents()?.list() ?? []).map((agent) => agent.ctx?.get?.("llm")).find((service) => service?.resolveCallConfig !== undefined)
293
+ const llm = nativeAgent?.ctx?.get?.("llm")
136
294
  ?? this.ctx.get?.("llm") ?? (this.ctx.get === undefined ? this.ctx.llm : undefined);
137
295
  if (llm?.resolveCallConfig === undefined) {
138
296
  throw new DsmmProfileError("activation", "Open a chat so its native model service can validate configured routes before applying this profile.");
139
297
  }
140
- for (const { route, field } of routes) {
298
+ for (const { routes, field } of chains) {
141
299
  try {
142
- await llm.resolveCallConfig({ ...route });
300
+ await selectInitialModelRoute(llm, routes, signal);
143
301
  }
144
302
  catch {
145
303
  throw new DsmmProfileError("activation", "The configured provider, model or exact reasoning effort is unavailable in the native model catalog.", field);
@@ -147,6 +305,10 @@ export class DsmmProfileRuntime {
147
305
  }
148
306
  }
149
307
  }
308
+ function newEpoch() { return createHash("sha256").update(randomUUID()).digest("hex"); }
309
+ function selectionState(selection) {
310
+ return { selectedId: selection.selectedId, appliedRevision: selection.appliedRevision, selectionRevision: selection.selectionRevision };
311
+ }
150
312
  /** No guessed home fallback: native deployment context owns this directory. */
151
313
  export async function createProfileRuntime(ctx, baseline) {
152
314
  const profile = ctx.get?.("profileContext");
@@ -1,4 +1,4 @@
1
- import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSelectionState, ProfileSnapshot } from "./profile-types.js";
1
+ import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSelectionState, ProfileSnapshot, SessionProfileSelectRequest } from "./profile-types.js";
2
2
  import type { DsmmProfileDocument } from "./profiles.js";
3
3
  export type SaveProfileRequest = ProfileSaveRequest;
4
4
  export type SelectProfileRequest = ProfileSelectRequest;
@@ -6,6 +6,17 @@ export interface LoadedProfileSelection extends ProfileSelectionState {
6
6
  document: DsmmProfileDocument | null;
7
7
  content: string | null;
8
8
  }
9
+ export interface LoadedSessionProfileSelection extends LoadedProfileSelection {
10
+ sessionId: string;
11
+ admissionEpoch: string | null;
12
+ }
13
+ export declare const MAX_SESSION_PROFILE_CHOICES = 1024;
14
+ export interface SessionProfileCommit<T> {
15
+ /** Trusted native liveness/cancellation fence; invoked immediately before rename. */
16
+ assertCurrent(): void;
17
+ /** Synchronous publication after durable commit. Must not throw or await. */
18
+ committed(selection: LoadedSessionProfileSelection, prepared: T): void;
19
+ }
9
20
  export interface ProfileStoreOptions {
10
21
  lockTimeoutMs?: number;
11
22
  lockPollMs?: number;
@@ -24,6 +35,11 @@ export declare class ProfileStore {
24
35
  read(id: string): Promise<ProfileReadResult>;
25
36
  save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
26
37
  loadSelection(): Promise<LoadedProfileSelection>;
38
+ loadSessionSelection(sessionId: string): Promise<LoadedSessionProfileSelection>;
39
+ selectSession<T>(request: SessionProfileSelectRequest, epoch: string, validateCandidate: (document: DsmmProfileDocument | null) => T | Promise<T>, commit: SessionProfileCommit<T>): Promise<{
40
+ selection: LoadedSessionProfileSelection;
41
+ prepared: T;
42
+ }>;
27
43
  select<T = undefined>(request: ProfileSelectRequest, validateCandidate?: (document: DsmmProfileDocument | null) => T | Promise<T>): Promise<{
28
44
  selection: LoadedProfileSelection;
29
45
  prepared: T;
@@ -33,10 +49,12 @@ export declare class ProfileStore {
33
49
  private draftName;
34
50
  private draft;
35
51
  private selection;
52
+ private sessionSelection;
36
53
  private assertSelectionRevision;
37
54
  private publishRevision;
38
55
  private atomicReplace;
39
56
  private validateRoot;
40
57
  private locked;
41
58
  }
59
+ export declare function validateSessionProfileId(id: unknown): asserts id is string;
42
60
  //# sourceMappingURL=profile-store.d.ts.map
@@ -4,6 +4,7 @@ import { basename, dirname, isAbsolute, join, parse, resolve } from "node:path";
4
4
  import { parseTree } from "jsonc-parser";
5
5
  import { ABSENT_PROFILE_SELECTION_REVISION } from "./profile-types.js";
6
6
  import { DsmmProfileError, MAX_PROFILE_BYTES, MAX_PROFILE_COUNT, MAX_PROFILE_DIRECTORY_ENTRIES, MAX_PROFILE_REVISIONS, parseProfileDocument, profileErrorInfo, validateProfileId, validateProfileRevision } from "./profiles.js";
7
+ export const MAX_SESSION_PROFILE_CHOICES = 1024;
7
8
  /** This directory is supplied by the Host, never by a remote method parameter. */
8
9
  export class ProfileStore {
9
10
  profileDir;
@@ -77,16 +78,62 @@ export class ProfileStore {
77
78
  async loadSelection() {
78
79
  return this.locked(() => this.selection());
79
80
  }
81
+ async loadSessionSelection(sessionId) {
82
+ validateSessionProfileId(sessionId);
83
+ return this.locked(() => this.sessionSelection(sessionId));
84
+ }
85
+ async selectSession(request, epoch, validateCandidate, commit) {
86
+ validateSessionProfileId(request.sessionId);
87
+ validateSelectionRequest(request);
88
+ validateProfileRevision(epoch, "admissionEpoch");
89
+ return this.locked(async (assertLock) => {
90
+ commit.assertCurrent();
91
+ if (this.sessionSelection(request.sessionId).selectionRevision !== request.expectedSelectionRevision)
92
+ conflict("The session profile changed. Refresh before selecting again.");
93
+ const draft = request.id === null ? undefined : this.draft(request.id, this.inventory());
94
+ if (draft !== undefined && draft.revision !== request.expectedRevision)
95
+ conflict("The profile changed before selection. Reload and select its latest revision.");
96
+ let prepared;
97
+ try {
98
+ prepared = await validateCandidate(draft === undefined ? null : structuredClone(draft.document));
99
+ }
100
+ catch (error) {
101
+ if (error instanceof DsmmProfileError)
102
+ throw error;
103
+ throw new DsmmProfileError("activation", "The candidate profile could not be activated; the previous session selection was retained.");
104
+ }
105
+ const directory = join(this.profileDir, ".sessions");
106
+ const target = join(directory, `${sessionChoiceKey(request.sessionId)}.json`);
107
+ const fence = (temporary) => {
108
+ commit.assertCurrent();
109
+ if (this.sessionSelection(request.sessionId, temporary).selectionRevision !== request.expectedSelectionRevision)
110
+ conflict("The session selection was edited externally. Refresh before selecting again.");
111
+ if (draft !== undefined && this.draft(request.id, this.inventory()).revision !== draft.revision)
112
+ conflict("The draft changed during activation. Reload and select again.");
113
+ validateDirectories(directory, false);
114
+ // The one exclusive atomic staging file is not a session choice.
115
+ const entries = boundedEntries(directory, MAX_SESSION_PROFILE_CHOICES + (temporary === undefined ? 0 : 1))
116
+ .filter((name) => temporary === undefined || name !== basename(temporary));
117
+ if (status(target) === undefined && entries.length >= MAX_SESSION_PROFILE_CHOICES)
118
+ throw new DsmmProfileError("limit", "The session profile choice inventory is full; no selection was committed.");
119
+ };
120
+ assertLock();
121
+ commit.assertCurrent();
122
+ validateDirectories(directory, true);
123
+ fence();
124
+ if (draft !== undefined)
125
+ this.publishRevision(draft, assertLock);
126
+ const pointer = { version: 1, sessionId: request.sessionId, id: request.id, revision: draft?.revision ?? null, epoch };
127
+ const bytes = Buffer.from(`${JSON.stringify(pointer)}\n`, "utf8");
128
+ const selection = { sessionId: request.sessionId, admissionEpoch: epoch,
129
+ selectedId: request.id, appliedRevision: draft?.revision ?? null, selectionRevision: digest(bytes), document: draft?.document ?? null, content: draft?.content ?? null };
130
+ this.atomicReplace(target, bytes, fence, assertLock);
131
+ commit.committed(selection, prepared);
132
+ return { selection, prepared };
133
+ });
134
+ }
80
135
  async select(request, validateCandidate) {
81
- if (request.id !== null) {
82
- validateProfileId(request.id);
83
- validateProfileRevision(request.expectedRevision);
84
- }
85
- else if (request.expectedRevision !== undefined) {
86
- throw new DsmmProfileError("validation", "Baseline selection must not include a draft revision.", "expectedRevision");
87
- }
88
- if (request.expectedSelectionRevision !== ABSENT_PROFILE_SELECTION_REVISION)
89
- validateProfileRevision(request.expectedSelectionRevision, "expectedSelectionRevision");
136
+ validateSelectionRequest(request);
90
137
  return this.locked(async (assertLock) => {
91
138
  const current = this.selection();
92
139
  if (current.selectionRevision !== request.expectedSelectionRevision)
@@ -178,6 +225,39 @@ export class ProfileStore {
178
225
  throw new DsmmProfileError("corrupt-selection", "The selected profile pointer or immutable revision is missing or invalid. Repair it explicitly; the baseline was not silently selected.");
179
226
  }
180
227
  }
228
+ sessionSelection(sessionId, temporary) {
229
+ this.validateRoot(false);
230
+ const absent = { sessionId, admissionEpoch: null, selectedId: null, appliedRevision: null,
231
+ selectionRevision: ABSENT_PROFILE_SELECTION_REVISION, document: null, content: null };
232
+ const directory = join(this.profileDir, ".sessions");
233
+ if (status(directory) === undefined)
234
+ return absent;
235
+ validateDirectories(directory, false);
236
+ const entries = boundedEntries(directory, MAX_SESSION_PROFILE_CHOICES + (temporary === undefined ? 0 : 1))
237
+ .filter((name) => temporary === undefined || name !== basename(temporary));
238
+ if (entries.length > MAX_SESSION_PROFILE_CHOICES)
239
+ throw new DsmmProfileError("limit", "The session profile choice inventory exceeds its supported limit.");
240
+ const path = join(directory, `${sessionChoiceKey(sessionId)}.json`);
241
+ if (status(path) === undefined)
242
+ return absent;
243
+ try {
244
+ const file = regularFile(path, 2048);
245
+ const pointer = parseSessionSelectionPointer(file.content, sessionId);
246
+ if (pointer.id === null)
247
+ return { ...absent, admissionEpoch: pointer.epoch, selectionRevision: file.revision };
248
+ validateDirectories(join(this.profileDir, ".revisions"), false);
249
+ const immutable = regularFile(join(this.profileDir, ".revisions", `${pointer.revision}.jsonc`), MAX_PROFILE_BYTES);
250
+ if (immutable.revision !== pointer.revision)
251
+ throw new DsmmProfileError("corrupt-selection", "The session's immutable profile revision failed SHA256 verification.");
252
+ return { sessionId, admissionEpoch: pointer.epoch, selectedId: pointer.id, appliedRevision: pointer.revision,
253
+ selectionRevision: file.revision, document: parseProfileDocument(immutable.content, pointer.id), content: immutable.content };
254
+ }
255
+ catch (error) {
256
+ if (error instanceof DsmmProfileError && error.code === "unsafe-path")
257
+ throw error;
258
+ throw new DsmmProfileError("corrupt-selection", "The session profile choice or immutable revision is missing or invalid. Repair it explicitly; no global or baseline fallback was admitted.");
259
+ }
260
+ }
181
261
  assertSelectionRevision(expected) {
182
262
  if (this.selection().selectionRevision !== expected)
183
263
  conflict("The selection was edited externally. Refresh before selecting again.");
@@ -231,7 +311,7 @@ export class ProfileStore {
231
311
  this.validateRoot(false);
232
312
  if (status(target) !== undefined)
233
313
  assertRegular(status(target));
234
- beforeRename();
314
+ beforeRename(temporary);
235
315
  assertLock();
236
316
  this.rename(temporary, target);
237
317
  created = false;
@@ -469,6 +549,36 @@ function parseSelectionPointer(content) {
469
549
  validateProfileRevision(record.revision, "revision");
470
550
  return { version: 1, id: record.id, revision: record.revision };
471
551
  }
552
+ export function validateSessionProfileId(id) {
553
+ if (typeof id !== "string" || id.length < 1 || id.length > 256 || /[\u0000-\u001f\u007f]/u.test(id) || Buffer.from(id, "utf8").toString("utf8") !== id) {
554
+ throw new DsmmProfileError("validation", "A bounded native session ID is required.", "sessionId");
555
+ }
556
+ }
557
+ function sessionChoiceKey(sessionId) { return digest(Buffer.from(sessionId, "utf8")); }
558
+ function validateSelectionRequest(request) {
559
+ if (request.id !== null) {
560
+ validateProfileId(request.id);
561
+ validateProfileRevision(request.expectedRevision);
562
+ }
563
+ else if (request.expectedRevision !== undefined) {
564
+ throw new DsmmProfileError("validation", "Baseline selection must not include a draft revision.", "expectedRevision");
565
+ }
566
+ if (request.expectedSelectionRevision !== ABSENT_PROFILE_SELECTION_REVISION)
567
+ validateProfileRevision(request.expectedSelectionRevision, "expectedSelectionRevision");
568
+ }
569
+ function parseSessionSelectionPointer(content, sessionId) {
570
+ const errors = [];
571
+ const tree = parseTree(content, errors, { disallowComments: true, allowTrailingComma: false, allowEmptyContent: false });
572
+ if (tree?.type !== "object" || errors.length > 0 || tree.children?.length !== 5)
573
+ throw new DsmmProfileError("corrupt-selection", "The session choice must contain exactly five unique fields in valid JSON.");
574
+ const record = JSON.parse(content);
575
+ if (Object.keys(record).length !== 5 || !["version", "sessionId", "id", "revision", "epoch"].every((key) => Object.hasOwn(record, key)) || record.version !== 1 || record.sessionId !== sessionId) {
576
+ throw new DsmmProfileError("corrupt-selection", "The session choice identity, shape or version is invalid.");
577
+ }
578
+ validateProfileRevision(record.epoch, "admissionEpoch");
579
+ const selection = parseSelectionPointer(JSON.stringify({ version: record.version, id: record.id, revision: record.revision }));
580
+ return { ...selection, sessionId, epoch: record.epoch };
581
+ }
472
582
  function conflict(message) {
473
583
  throw new DsmmProfileError("conflict", message);
474
584
  }
@@ -1,5 +1,8 @@
1
1
  /** Wire-only profile data: safe to import from the native browser client. */
2
- export type ProfileErrorCode = "validation" | "conflict" | "not-found" | "lock-timeout" | "unsafe-path" | "io" | "activation" | "corrupt-selection" | "limit";
2
+ import type { DsmmRoleId } from "./roles.js";
3
+ import type { DsmmModelRoute, DsmmProfileScope } from "./settings.js";
4
+ import type { DsmmRateLimitPolicy, DsmmRoutingStrategy, DsmmRuntimePolicyConfig, DsmmRuntimePolicySettings } from "./routing-policy.js";
5
+ export type ProfileErrorCode = "validation" | "conflict" | "not-found" | "lock-timeout" | "unsafe-path" | "io" | "activation" | "corrupt-selection" | "limit" | "busy" | "maintenance" | "disposed" | "not-owned" | "unavailable" | "cancelled";
3
6
  export interface ProfileErrorInfo {
4
7
  code: ProfileErrorCode;
5
8
  message: string;
@@ -19,6 +22,9 @@ export interface ProfileSelectionState {
19
22
  export interface ProfileSnapshot extends ProfileSelectionState {
20
23
  profiles: ProfileSummary[];
21
24
  selectionError?: ProfileErrorInfo;
25
+ /** Native deployment role inventory; excludes provider accounts and auth data. */
26
+ roles?: ProfileRoleMetadata[];
27
+ editorDefaults?: DsmmRuntimePolicySettings;
22
28
  }
23
29
  export interface ProfileReadResult {
24
30
  id: string;
@@ -36,5 +42,41 @@ export interface ProfileSelectRequest {
36
42
  expectedRevision?: string;
37
43
  expectedSelectionRevision: string;
38
44
  }
45
+ export interface ProfileRoleMetadata {
46
+ id: DsmmRoleId;
47
+ label: string;
48
+ enabled: boolean;
49
+ /** Explicit deployment overrides inherited by a profile's omitted role fields. */
50
+ runtimePolicy?: DsmmRuntimePolicyConfig;
51
+ }
52
+ export interface DsmmRoleRuntimeState {
53
+ role?: DsmmRoleId;
54
+ strategy: DsmmRoutingStrategy;
55
+ rateLimit: DsmmRateLimitPolicy;
56
+ route?: DsmmModelRoute;
57
+ retries: number;
58
+ rateLimitFailures: number;
59
+ switches: number;
60
+ totalDelayMs: number;
61
+ }
62
+ export interface SessionProfileSnapshot {
63
+ sessionId: string;
64
+ globalDefault: ProfileSelectionState;
65
+ /** Current sidecar state: the authority for session-selection CAS. */
66
+ selection: ProfileSelectionState;
67
+ /** Exact live admission, for display only; may differ from the future global default. */
68
+ admittedSelection?: ProfileSelectionState;
69
+ scope: DsmmProfileScope;
70
+ admissionEpoch: string;
71
+ switchAllowed: boolean;
72
+ switchUnavailableReason?: "busy" | "maintenance" | "disposed" | "not-owned" | "unavailable";
73
+ rolePolicy?: DsmmRoleRuntimeState;
74
+ /** Declared profile primary for the current ordinary root role, not an applied native selection. */
75
+ profileModel?: DsmmModelRoute;
76
+ }
77
+ export interface SessionProfileSelectRequest extends ProfileSelectRequest {
78
+ sessionId: string;
79
+ expectedAdmissionEpoch: string;
80
+ }
39
81
  export declare const ABSENT_PROFILE_SELECTION_REVISION = "absent";
40
82
  //# sourceMappingURL=profile-types.d.ts.map