@dsmm/dsmm 0.3.39 → 0.3.41

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.
@@ -95,8 +95,6 @@ export class NativeAdmission {
95
95
  nativeToolExecution = new AsyncLocalStorage();
96
96
  observedCallRuns = new Map();
97
97
  callSubscribers = new Set();
98
- admissionRoutes = new WeakMap();
99
- admissionRouteFailures = new WeakMap();
100
98
  setupSelectionCursors = new WeakMap();
101
99
  ready = false;
102
100
  scopes = new Map();
@@ -141,37 +139,15 @@ export class NativeAdmission {
141
139
  else
142
140
  await this.created(frame.agent, frame.source, frame.signal);
143
141
  }, { global: true, prepend: true });
144
- ctx.on("agent/status", ({ agent, status }) => { if (status === "running")
145
- this.installCachedAdmissionRouteSafely(agent); }, { global: true });
146
- ctx.on("agent/inbox/claimed", ({ agent }) => { this.installCachedAdmissionRouteSafely(agent); }, { global: true });
147
142
  ctx.on("session/event", (session, event) => {
148
143
  if (event.type === "request/header")
149
144
  this.observeCallRequestHeader(session, event.data.header.config);
150
- if (event.type !== "model/selection")
151
- return;
152
- const agent = this.ctx.agents.get(session.id), cache = agent === undefined ? undefined : this.admissionRoutes.get(agent);
153
- if (agent === undefined || agent.session !== session || cache?.candidate?.restoresConfiguredPrimary !== true)
154
- return;
155
- queueMicrotask(() => {
156
- try {
157
- if (this.lifetime.signal.aborted || this.agentLifetimes.get(agent)?.signal.aborted || this.selecting.has(agent)
158
- || this.admissionRoutes.get(agent) !== cache)
159
- return;
160
- this.installCachedAdmissionRouteSafely(agent, cache);
161
- }
162
- catch (error) {
163
- if (this.admissionRoutes.get(agent) === cache)
164
- this.admissionRouteFailures.set(agent, { cache, error });
165
- }
166
- });
167
145
  }, { global: true });
168
146
  ctx.on("agent/disposed", ({ agent }) => {
169
147
  void this.retireAgent(agent).catch(() => { });
170
148
  this.retireObservedParent(agent);
171
149
  this.live.delete(agent);
172
150
  this.candidates.delete(agent);
173
- this.admissionRoutes.delete(agent);
174
- this.admissionRouteFailures.delete(agent);
175
151
  this.agents.delete(agent);
176
152
  for (const activation of this.activations)
177
153
  if (activation.childId === agent.id)
@@ -251,7 +227,6 @@ export class NativeAdmission {
251
227
  }
252
228
  }));
253
229
  }
254
- /** Bind asynchronous metadata preparation; later lifecycle callbacks only install its immutable result. */
255
230
  bindAdmissionModelSelection(hook) {
256
231
  this.admissionModelSelection = hook;
257
232
  }
@@ -593,25 +568,6 @@ export class NativeAdmission {
593
568
  if (subscriber.parent === parent)
594
569
  subscriber.notify();
595
570
  }
596
- installCachedAdmissionRoute(agent, expected) {
597
- const cache = expected ?? this.admissionRoutes.get(agent), live = this.live.get(agent);
598
- if (cache === undefined || cache !== this.admissionRoutes.get(agent) || live === undefined || this.failedInstallations.has(agent)
599
- || !this.isReady || this.ctx.agents.get(agent.id) !== agent || this.agentLifetimes.get(agent)?.signal.aborted)
600
- return undefined;
601
- return cache.candidate?.install(live.admission);
602
- }
603
- installCachedAdmissionRouteSafely(agent, expected) {
604
- const cache = expected ?? this.admissionRoutes.get(agent);
605
- if (cache?.candidate?.restoresConfiguredPrimary !== true || this.admissionRouteFailures.get(agent)?.cache === cache)
606
- return;
607
- try {
608
- this.installCachedAdmissionRoute(agent, cache);
609
- }
610
- catch (error) {
611
- if (this.admissionRoutes.get(agent) === cache)
612
- this.admissionRouteFailures.set(agent, { cache, error });
613
- }
614
- }
615
571
  get isReady() {
616
572
  const current = this.ctx.get("dsmmNativeAdmission");
617
573
  return this.ready && !this.lifetime.signal.aborted && current !== undefined && original(current) === original(this);
@@ -674,10 +630,6 @@ export class NativeAdmission {
674
630
  throw new SubagentError("Session configuration maintenance is in progress", "UNAUTHORIZED");
675
631
  if (!this.isReady || !live || this.ctx.agents.get(agent.id) !== agent)
676
632
  throw new SubagentError("No trusted live admission; create a new session", "UNAUTHORIZED");
677
- const routeFailure = this.admissionRouteFailures.get(agent);
678
- if (routeFailure !== undefined && routeFailure.cache === this.admissionRoutes.get(agent)) {
679
- throw new SubagentError("Configured model selection installation failed; create a new session", "UNAUTHORIZED");
680
- }
681
633
  if (this.ctx.get("sessions")?.get(agent.id) !== agent.session || agent.session.id !== agent.id || agent.session.header.id !== agent.id
682
634
  || scopeOf(agent.ctx) !== agent || original(agent.ctx.get("agents")) !== original(this.ctx.agents)
683
635
  || live.dependencies && this.dependencies(agent).some((value, index) => value !== live.dependencies[index])
@@ -766,8 +718,6 @@ export class NativeAdmission {
766
718
  }
767
719
  let prepared = false, committed = false;
768
720
  let publication;
769
- const previousRouteCache = this.admissionRoutes.get(agent), previousRouteFailure = this.admissionRouteFailures.get(agent);
770
- let installedRouteCache, routeInstallation;
771
721
  let providers = new Map();
772
722
  const assertCurrent = () => {
773
723
  assertAuthority();
@@ -802,21 +752,7 @@ export class NativeAdmission {
802
752
  }));
803
753
  });
804
754
  assertCurrent();
805
- const candidate = await this.admissionModelSelection?.(agent, { settings: admission.settings, epoch: admission.epoch,
806
- admission, signal: preparationSignal, assertCurrent });
807
- assertCurrent();
808
755
  prepared = true;
809
- installedRouteCache = Object.freeze({ candidate });
810
- this.admissionRoutes.set(agent, installedRouteCache);
811
- this.admissionRouteFailures.delete(agent);
812
- try {
813
- routeInstallation = candidate?.install(admission);
814
- }
815
- catch (error) {
816
- if (candidate?.preflightFailure !== error)
817
- this.failedInstallations.add(agent);
818
- throw error;
819
- }
820
756
  await install(admission);
821
757
  assertCurrent();
822
758
  this.installing.run({ agent, admission }, describe);
@@ -826,38 +762,16 @@ export class NativeAdmission {
826
762
  close: async () => {
827
763
  try {
828
764
  if (prepared && !committed) {
829
- const errors = [];
830
- const canRestore = this.ctx.agents.get(agent.id) === agent && !this.lifetime.signal.aborted;
831
- if (canRestore) {
765
+ if (this.ctx.agents.get(agent.id) === agent && !this.lifetime.signal.aborted)
832
766
  try {
833
767
  await install(previous.admission);
834
768
  }
835
769
  catch (error) {
836
- errors.push(error);
770
+ this.failedInstallations.add(agent);
771
+ const refusal = new DsmmProfileError("activation", "Session configuration restoration failed. Execution is disabled; create a new session.");
772
+ refusal.cause = error;
773
+ throw refusal;
837
774
  }
838
- try {
839
- routeInstallation?.rollback();
840
- }
841
- catch (error) {
842
- errors.push(error);
843
- }
844
- }
845
- if (installedRouteCache !== undefined && this.admissionRoutes.get(agent) === installedRouteCache) {
846
- if (previousRouteCache === undefined)
847
- this.admissionRoutes.delete(agent);
848
- else
849
- this.admissionRoutes.set(agent, previousRouteCache);
850
- if (previousRouteFailure !== undefined && previousRouteFailure.cache === previousRouteCache)
851
- this.admissionRouteFailures.set(agent, previousRouteFailure);
852
- else
853
- this.admissionRouteFailures.delete(agent);
854
- }
855
- if (errors.length > 0) {
856
- this.failedInstallations.add(agent);
857
- const refusal = new DsmmProfileError("activation", "Session configuration restoration failed. Execution is disabled; create a new session.");
858
- refusal.cause = errors.length === 1 ? errors[0] : new AggregateError(errors, "Session configuration restoration failed");
859
- throw refusal;
860
- }
861
775
  }
862
776
  }
863
777
  finally {
@@ -1110,8 +1024,6 @@ export class NativeAdmission {
1110
1024
  this.scopes.delete(agent);
1111
1025
  this.live.delete(agent);
1112
1026
  this.candidates.delete(agent);
1113
- this.admissionRoutes.delete(agent);
1114
- this.admissionRouteFailures.delete(agent);
1115
1027
  this.agents.delete(agent);
1116
1028
  this.profiles.release(agent);
1117
1029
  this.policy.release(agent);
@@ -1279,15 +1191,10 @@ export class NativeAdmission {
1279
1191
  this.check(pending);
1280
1192
  if (continuationProvider && this.ctx.get("subagents").getProvider(continuationProvider.name) !== continuationProvider)
1281
1193
  throw new SubagentError("Role provider changed", "UNAUTHORIZED");
1282
- const routeCandidate = await this.admissionModelSelection?.(agent, {
1194
+ await this.admissionModelSelection?.(agent, {
1283
1195
  settings: admission.settings, epoch: admission.epoch, admission, signal, assertCurrent: check,
1284
1196
  });
1285
1197
  check();
1286
- const routeCache = Object.freeze({ candidate: routeCandidate });
1287
- this.admissionRoutes.set(agent, routeCache);
1288
- this.admissionRouteFailures.delete(agent);
1289
- routeCandidate?.install(admission);
1290
- check();
1291
1198
  this.profiles.publish(agent, admission);
1292
1199
  const published = this.profiles.admission(agent);
1293
1200
  this.live.set(agent, Object.freeze({ admission: published, preset, scopeParent: scopeParentOf(agent), parent, owner, creatorId: agent.session.header.parentSession,
@@ -1300,8 +1207,6 @@ export class NativeAdmission {
1300
1207
  }
1301
1208
  catch (error) {
1302
1209
  this.failedInstallations.add(agent);
1303
- this.admissionRoutes.delete(agent);
1304
- this.admissionRouteFailures.delete(agent);
1305
1210
  this.policy.release(agent);
1306
1211
  await scope.fiber.dispose();
1307
1212
  throw error;
@@ -208,7 +208,7 @@ export class DsmmProfileRuntime {
208
208
  const profileModel = role === undefined ? undefined : admitted.settings.roleRouting[role]?.primary;
209
209
  const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
210
210
  return { sessionId: agent.id, globalDefault: this.observedSelection(this.current), selection: selectionState(disk), admittedSelection: this.observedSelection(admitted), scope: admitted.scope,
211
- rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), deepwork,
211
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted)), deepwork,
212
212
  modules: projectDsmmModules(this.baseline, admitted.deployment, admitted, false, this.options.getMountedPermission), configuration: deploymentAdmissionView(admitted),
213
213
  warnings: structuredClone(admitted.warnings ?? []), roles: structuredClone(admitted.roleAvailability ?? []), subagentRuntime: this.runtimeView(),
214
214
  ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }), admissionEpoch: admitted.epoch,
@@ -247,7 +247,7 @@ export class DsmmProfileRuntime {
247
247
  const deepwork = this.mode.describe(agent, admitted.settings.defaultActive);
248
248
  const { profileModel: _previous, selectModelUnavailableReason: _modelReason, toggleModeUnavailableReason: _modeReason, applyOverlayUnavailableReason: _overlayReason, ...snapshot } = before;
249
249
  return { ...snapshot, deepwork, ...this.sessionActions(agent, admitted, deepwork, profileModel !== undefined),
250
- rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted.epoch)), ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }) };
250
+ rolePolicy: structuredClone(roleRouteRuntimeState(agent, admitted.settings, role, admitted)), ...(profileModel === undefined ? {} : { profileModel: structuredClone(profileModel) }) };
251
251
  });
252
252
  }
253
253
  catch (error) {
@@ -3,6 +3,7 @@ import type { DsmmSettingsGetter } from "./settings.js";
3
3
  import type { DeepworkModeController } from "./state.js";
4
4
  import type { DsmmEffortSource } from "./host-llm.js";
5
5
  import { resolveAdmittedDsmmRole } from "./role-policy.js";
6
+ import { type NativeModelSelectionIntent } from "./role-routing.js";
6
7
  /** Shared by selection, recovery and the native prepared-call owner. */
7
8
  export interface DsmmRequestRoutingDecision {
8
9
  readonly frame: AgentRequestFrame;
@@ -21,7 +22,7 @@ declare const results: WeakMap<AgentRequestFrame, {
21
22
  }>;
22
23
  export declare function currentRequestRouting(agent: DshAgent): DsmmRequestRoutingDecision | undefined;
23
24
  export declare function preparedRequestRouting(frame: AgentRequestFrame): ReturnType<typeof results.get>;
24
- export declare function captureRequestRouting(frame: AgentRequestFrame, ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, assertOwner: () => void): DsmmRequestRoutingDecision;
25
+ export declare function captureRequestRouting(frame: AgentRequestFrame, ctx: DshContext, controller: DeepworkModeController, getSettings: DsmmSettingsGetter, manual: NativeModelSelectionIntent | undefined, assertOwner: () => void): DsmmRequestRoutingDecision;
25
26
  export declare function captureRequestRoute(frame: AgentRequestFrame, decision: DsmmRequestRoutingDecision, effortSource?: DsmmEffortSource): void;
26
27
  export {};
27
28
  //# sourceMappingURL=request-routing.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { resolveAdmittedDsmmRole } from "./role-policy.js";
2
- import { liveRolePolicyIdentity, roleRouteLock } from "./role-routing.js";
2
+ import { liveRolePolicyIdentity, roleRouteLock, usesConfiguredRootRoute } from "./role-routing.js";
3
3
  import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
4
4
  import { isCurrentRecoveryStep } from "./recovery-policy.js";
5
5
  const decisions = new WeakMap();
@@ -7,7 +7,7 @@ const routeAssertions = new WeakMap();
7
7
  const results = new WeakMap();
8
8
  export function currentRequestRouting(agent) { return decisions.get(agent); }
9
9
  export function preparedRequestRouting(frame) { return results.get(frame); }
10
- export function captureRequestRouting(frame, ctx, controller, getSettings, assertOwner) {
10
+ export function captureRequestRouting(frame, ctx, controller, getSettings, manual, assertOwner) {
11
11
  const settings = getSettings(frame.agent), admission = getSettings.admission?.(frame.agent);
12
12
  const role = settings.modules.deepwork.enabled
13
13
  ? resolveAdmittedDsmmRole(frame.agent, settings, controller.active(frame.agent, settings.defaultActive)) : undefined;
@@ -19,8 +19,7 @@ export function captureRequestRouting(frame, ctx, controller, getSettings, asser
19
19
  const events = () => captured.agent.session.header?.origin === "subagent" ? childOwnedSessionEvents(captured.agent.session) : sessionEvents(captured.agent.session);
20
20
  const currentStep = isCurrentRecoveryStep(events(), captured.turn, captured.step);
21
21
  const decision = Object.freeze({ frame: captured, settings, admission, role, policy,
22
- configuredRoot: captured.agent.session.header?.origin !== "subagent" && admission !== undefined
23
- && admission.settings === settings && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined,
22
+ configuredRoot: usesConfiguredRootRoute(captured.agent, settings, admission, role, manual),
24
23
  assertPolicyCurrent() {
25
24
  assertOwner();
26
25
  captured.signal.throwIfAborted();
@@ -1,12 +1,8 @@
1
- import type { AgentRequestFrame, DshAgent, DshAgentModel, DshContext, DshLlmCallConfig, DshLlmRuntime } from "./dsh-types.js";
1
+ import type { AgentRequestFrame, DshAgent, DshAgentModel, DshContext, DshLlmCallConfig, DshLlmRuntime, DshModelSelection } from "./dsh-types.js";
2
2
  import type { DsmmRoleId } from "./roles.js";
3
- import type { DsmmModelRoute, DsmmSettings } from "./settings.js";
3
+ import type { DsmmModelRoute, DsmmProfileAdmission, DsmmSettings } from "./settings.js";
4
4
  import type { DsmmRoleRuntimeState } from "./profile-types.js";
5
5
  import type { DsmmLlmRouteResolver } from "./role-llm.js";
6
- export interface RolePolicyState {
7
- readonly fields: unknown;
8
- readonly identity: string;
9
- }
10
6
  export declare const DSMM_ROLE_POLICY_EVENT = "dsmm/role-policy";
11
7
  export interface RoleRouteLock {
12
8
  identity: string;
@@ -21,6 +17,7 @@ export interface RoleRouteLock {
21
17
  switches: number;
22
18
  totalDelayMs: number;
23
19
  manualSelectionSeq?: number;
20
+ nativeBaseline?: DshModelSelection;
24
21
  effortSource?: "native" | "dsmm-config";
25
22
  }
26
23
  export interface NativeModelSelectionIntent {
@@ -61,12 +58,13 @@ export declare function pinRoleRoute(agent: DshAgent, identity: string, route: D
61
58
  }): RoleRouteLock;
62
59
  export declare function clearRoleRouteLock(agent: DshAgent): void;
63
60
  export declare function currentRoleRouteLock(agent: DshAgent): RoleRouteLock | undefined;
64
- export declare function currentRolePolicyState(agent: DshAgent): RolePolicyState | undefined;
65
- export declare function restoreRolePolicyAndLock(agent: DshAgent, installedPolicy: RolePolicyState, installedLock: RoleRouteLock, previousPolicy: RolePolicyState | undefined, previousLock: RoleRouteLock | undefined): boolean;
66
- export declare function roleRouteRuntimeState(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): DsmmRoleRuntimeState;
61
+ export declare function usesConfiguredRootRoute(agent: DshAgent, settings: DsmmSettings, admission: DsmmProfileAdmission | undefined, role: DsmmRoleId | undefined, manual: NativeModelSelectionIntent | undefined): boolean;
62
+ export declare function observedRootModel(agent: DshAgent, manual: NativeModelSelectionIntent | undefined): DsmmModelRoute | undefined;
63
+ export declare function roleRouteRuntimeState(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, admission?: DsmmProfileAdmission): DsmmRoleRuntimeState;
67
64
  export declare function liveRolePolicyIdentity(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): string | undefined;
65
+ export declare function hasRecordedRolePolicy(agent: DshAgent): boolean;
68
66
  /** Native custom events are model-hidden log facts, retained across surface compaction. */
69
- export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined, _ctx?: DshContext, epoch?: string): Promise<string | undefined>;
67
+ export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined, _ctx?: DshContext, epoch?: string, ownsRoute?: boolean): Promise<string | undefined>;
70
68
  export declare function recordAdmittedRecoveryRoute(frame: AgentRequestFrame, route: DsmmModelRoute): void;
71
69
  export declare function takeAdmittedRecoveryRoute(frame: AgentRequestFrame): DsmmModelRoute | undefined;
72
70
  export declare function effectiveRoleFallbackRoutes(settings: DsmmSettings, role: DsmmRoleId | undefined): readonly DsmmModelRoute[];
@@ -196,26 +196,35 @@ export function pinRoleRoute(agent, identity, route, candidates, projection) {
196
196
  }
197
197
  export function clearRoleRouteLock(agent) { routeLocks.delete(agent); }
198
198
  export function currentRoleRouteLock(agent) { return routeLocks.get(agent); }
199
- export function currentRolePolicyState(agent) { return agentPolicies.get(agent); }
200
- export function restoreRolePolicyAndLock(agent, installedPolicy, installedLock, previousPolicy, previousLock) {
201
- if (agentPolicies.get(agent) !== installedPolicy || routeLocks.get(agent) !== installedLock)
202
- return false;
203
- if (previousPolicy === undefined)
204
- agentPolicies.delete(agent);
205
- else
206
- agentPolicies.set(agent, previousPolicy);
207
- if (previousLock === undefined)
208
- routeLocks.delete(agent);
209
- else
210
- routeLocks.set(agent, previousLock);
211
- return true;
212
- }
213
- export function roleRouteRuntimeState(agent, settings, role, epoch) {
199
+ export function usesConfiguredRootRoute(agent, settings, admission, role, manual) {
200
+ return agent.session.header?.origin !== "subagent" && admission?.scope === "global-default" && admission.settings === settings
201
+ && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined && manual === undefined;
202
+ }
203
+ export function observedRootModel(agent, manual) {
204
+ const header = agent.session.requestHeader?.();
205
+ if (manual !== undefined && !sessionEvents(agent.session).some(event => event.type === "request/header" && Number(event.seq) > manual.seq))
206
+ return manual.route;
207
+ if (header !== undefined) {
208
+ const config = header.config;
209
+ if (typeof config?.provider !== "string" || typeof config.model !== "string")
210
+ return undefined;
211
+ return { provider: config.provider, model: config.model,
212
+ ...(typeof config.reasoningEffort === "string" ? { reasoningEffort: config.reasoningEffort } : {}) };
213
+ }
214
+ const current = hostModelSelection(agent)?.current();
215
+ return current === undefined ? undefined : { ...current };
216
+ }
217
+ export function roleRouteRuntimeState(agent, settings, role, admission) {
214
218
  const resolved = resolveRoleRuntimePolicy(settings, role);
215
- const identity = liveRolePolicyIdentity(agent, settings, role, epoch);
216
- const lock = identity === undefined ? undefined : roleRouteLock(agent, identity);
217
- return { ...(role === undefined ? {} : { role }), strategy: agent.session.header?.origin === "subagent" || epoch !== undefined && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined ? resolved.strategy : "startup-lock", rateLimit: { ...resolved.rateLimit },
218
- ...(lock === undefined ? {} : { route: { ...lock.route } }), retries: lock?.retries ?? 0,
219
+ const policy = agentPolicies.get(agent);
220
+ const current = policy !== undefined && policy.fields.role === role && policy.fields.epoch === admission?.epoch ? roleRouteLock(agent, policy.identity) : undefined;
221
+ const child = agent.session.header?.origin === "subagent";
222
+ const manual = child ? undefined : latestNativeModelSelection(agent);
223
+ const lock = !child && manual?.seq !== current?.manualSelectionSeq ? undefined : current;
224
+ const configured = usesConfiguredRootRoute(agent, settings, admission, role, manual);
225
+ const route = child || configured ? lock?.route : observedRootModel(agent, manual) ?? lock?.route;
226
+ return { ...(role === undefined ? {} : { role }), strategy: child || configured ? resolved.strategy : "startup-lock", rateLimit: { ...resolved.rateLimit },
227
+ ...(route === undefined ? {} : { route: { ...route } }), retries: lock?.retries ?? 0,
219
228
  rateLimitFailures: lock?.rateLimits ?? 0, switches: lock?.switches ?? 0, totalDelayMs: lock?.totalDelayMs ?? 0 };
220
229
  }
221
230
  export function liveRolePolicyIdentity(agent, settings, role, epoch) {
@@ -263,10 +272,21 @@ function readPolicyMarker(event) {
263
272
  }
264
273
  return { role: data.role, policy: data.policy };
265
274
  }
275
+ export function hasRecordedRolePolicy(agent) {
276
+ const events = policyEvents({ agent });
277
+ for (let index = events.length - 1; index >= 0; index--) {
278
+ const event = events[index];
279
+ if (isPresetBoundary({ agent }, event))
280
+ return false;
281
+ if (event.type === DSMM_ROLE_POLICY_EVENT)
282
+ return readPolicyMarker(event)?.policy != null;
283
+ }
284
+ return false;
285
+ }
266
286
  /** Native custom events are model-hidden log facts, retained across surface compaction. */
267
- export async function establishRolePolicy(frame, settings, role, _ctx, epoch) {
287
+ export async function establishRolePolicy(frame, settings, role, _ctx, epoch, ownsRoute) {
268
288
  const identity = liveRolePolicyIdentity(frame.agent, settings, role, epoch);
269
- const declared = role !== undefined && (Object.keys(settings.roleRouting[role] ?? {}).length > 0 || settings.runtimeRecovery.fallbackRoutes.length > 0);
289
+ const declared = ownsRoute ?? (role !== undefined && (Object.keys(settings.roleRouting[role] ?? {}).length > 0 || settings.runtimeRecovery.fallbackRoutes.length > 0));
270
290
  if (frame.signal.aborted)
271
291
  return identity;
272
292
  let latest;
@@ -48,7 +48,7 @@ export function roleInvocationObservation(invocation, label, mode, getSettings,
48
48
  const actual = latestOwnRoleRoute(child);
49
49
  if (actual.status === "known")
50
50
  return { view: { ...view, route: actual.route }, routeKind: "actual" };
51
- const route = roleRouteRuntimeState(child, getSettings(child), invocation.target, getSettings.admission?.(child).epoch).route;
51
+ const route = roleRouteRuntimeState(child, getSettings(child), invocation.target, getSettings.admission?.(child)).route;
52
52
  return { view: route === undefined ? view : { ...view, route: { ...route } }, routeKind: "initial" };
53
53
  }
54
54
  function latestOwnRoleRoute(child) {
@@ -184,7 +184,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings, bindReques
184
184
  pendingByAgent.delete(frame.agent);
185
185
  throw new Error("DSMM retry routing capture changed");
186
186
  }
187
- if (!decision?.configuredRoot && latestNativeModelSelection(frame.agent)?.seq !== pending.manualSelectionSeq) {
187
+ if (latestNativeModelSelection(frame.agent)?.seq !== pending.manualSelectionSeq) {
188
188
  pendingByAgent.delete(frame.agent);
189
189
  throw new Error("dsmm retry was superseded by an explicit native model selection");
190
190
  }
@@ -254,7 +254,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings, bindReques
254
254
  if (!active || frame.signal.aborted || lock === undefined || headerRoute === undefined
255
255
  || headerRoute.provider !== frame.provider || !sameModelRoute(headerRoute, lock.route) || headerRoute.reasoningEffort !== lock.route.reasoningEffort
256
256
  || attempt === undefined || attempt.policy !== policy || attempt.generation !== lock.generation
257
- || !decision?.configuredRoot && latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
257
+ || latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
258
258
  || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step) || !positiveNoOutput(frame, attempt))
259
259
  return undefined;
260
260
  const expectedGeneration = lock.generation;
@@ -346,7 +346,7 @@ export function registerRuntimeRecovery(ctx, controller, getSettings, bindReques
346
346
  || liveRolePolicyIdentity(frame.agent, currentSettings, currentRole, getSettings.admission?.(frame.agent).epoch) !== policy
347
347
  || roleRouteLock(frame.agent, policy) !== lock || lock.generation !== expectedGeneration
348
348
  || attemptsByAgent.get(frame.agent) !== attempt || !isCurrentRecoveryStep(recoveryEvents(frame.agent), frame.turn, frame.step)
349
- || !decision?.configuredRoot && latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
349
+ || latestNativeModelSelection(frame.agent)?.seq !== attempt.manualSelectionSeq
350
350
  || !positiveNoOutput(frame, attempt, true)
351
351
  || !sameExactModelRoute(modelRouteFromHeader(frame.agent.session.requestHeader?.()), attempt.route))
352
352
  return undefined;
package/lib/status.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { classifyModelFamily } from "./model-family.js";
2
2
  import { DSMM_ROLES, isDsmmRoleId } from "./roles.js";
3
- import { roleRouteRuntimeState } from "./role-routing.js";
3
+ import { latestNativeModelSelection, observedRootModel, roleRouteRuntimeState, usesConfiguredRootRoute } from "./role-routing.js";
4
4
  import { resolveSelectedAgentPreset } from "./session-scope.js";
5
5
  import { resolveAdmittedDsmmRole as resolveEffectiveDsmmRole } from "./role-policy.js";
6
6
  import { resolveRoleRuntimePolicy } from "./routing-policy.js";
@@ -20,14 +20,14 @@ export function createDsmmStatusSnapshot(input) {
20
20
  invalidDescriptor = true;
21
21
  }
22
22
  const inScope = modeActive || role !== undefined;
23
- const nativeRoot = ordinaryRoot && !(input.admission?.settings === settings
24
- && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined && !invalidDescriptor);
23
+ const manual = ordinaryRoot ? latestNativeModelSelection(agent) : undefined;
24
+ const nativeRoot = ordinaryRoot && !usesConfiguredRootRoute(agent, settings, input.admission, role, manual);
25
25
  const policy = nativeRoot || role === undefined ? undefined : settings.roleRouting[role];
26
26
  const runtimePolicy = resolveRoleRuntimePolicy(settings, role);
27
27
  const roleRuntimeState = input.roleRuntimeState ?? (input.admission === undefined || invalidDescriptor ? undefined
28
- : roleRouteRuntimeState(agent, settings, role, input.admission.epoch));
28
+ : roleRouteRuntimeState(agent, settings, role, input.admission));
29
29
  const fallbacks = nativeRoot || invalidDescriptor ? [] : runtimePolicy.fallbackRoutes;
30
- const selectedRoute = resolveRoute(agent, !ordinaryRoot || nativeRoot);
30
+ const selectedRoute = (ordinaryRoot && nativeRoot ? observedRootModel(agent, manual) : undefined) ?? resolveRoute(agent, !ordinaryRoot || nativeRoot);
31
31
  const family = classifyModelFamily({
32
32
  providerID: selectedRoute.provider,
33
33
  modelID: selectedRoute.model
@@ -1,3 +1,5 @@
1
+ import { symbols } from "@deepseek-ai/cordis";
2
+ import { hostModelSelection, latestModelSelectionSeq } from "./role-routing.js";
1
3
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
2
4
  import { createDsmmStatusSnapshot, formatDsmmStatus } from "./status.js";
3
5
  import { handleDsmmStatusCommand, parseDeepworkCommandInput } from "./commands.js";
@@ -183,6 +185,7 @@ async function manageGlobal(deps, authority) {
183
185
  return success(`Saved Global ${field.path.join(".")}=${after}; desired revision is ${saved.revision}.${saved.refreshRequired ? " Refresh is required before another edit." : ""}`);
184
186
  }
185
187
  async function manageProfiles(deps, invocation, authority) {
188
+ const choiceCursor = latestModelSelectionSeq(invocation.agent);
186
189
  const operation = await authority.select("Named profiles", [
187
190
  { id: "browse", label: "Browse", description: "Show saved profile IDs, diagnostics and revisions" },
188
191
  { id: "future", label: "Select future default", description: "Set or clear the default for new sessions" },
@@ -212,9 +215,22 @@ async function manageProfiles(deps, invocation, authority) {
212
215
  ...(revision === undefined ? {} : { expectedRevision: revision }) }, () => authority.assertCurrent());
213
216
  return success(`Future named-profile default is ${selected.selectedId ?? "deployment baseline"}; current sessions were not changed.${selected.refreshRequired ? " The commit succeeded, but refresh is required before another profile action." : ""}`);
214
217
  }
218
+ const chooseModel = id === null ? undefined : captureProfileModelChoice(invocation.agent, choiceCursor);
215
219
  const session = await deps.profiles.getSession(invocation.agent);
216
220
  authority.assertCurrent();
217
- const message = `Apply ${id ?? "deployment baseline"} to live root session ${session.sessionId}; admission ${session.admissionEpoch}; selection revision ${session.selection.selectionRevision}${revision === undefined ? "" : `; profile revision ${revision}`}.`;
221
+ let useModel = false;
222
+ if (chooseModel !== undefined) {
223
+ const action = await authority.select(`Apply ${id} to this session`, [
224
+ { id: "apply-only", label: "Apply profile only", description: "Keep the current session model" },
225
+ { id: "apply-model", label: "Apply and use profile model", description: "Select the admitted profile’s model for this session" }
226
+ ]);
227
+ if (action === undefined)
228
+ return error("Session profile action cancelled; no maintenance was started.");
229
+ useModel = action === "apply-model";
230
+ }
231
+ const modelNotice = useModel ? " Also select the admitted profile’s model for this session."
232
+ : chooseModel === undefined && id !== null ? " Keep the current model. Use /model to select a model on this Host." : " Keep the current model.";
233
+ const message = `Apply ${id ?? "deployment baseline"} to live root session ${session.sessionId}; admission ${session.admissionEpoch}; selection revision ${session.selection.selectionRevision}${revision === undefined ? "" : `; profile revision ${revision}`}.${modelNotice}`;
218
234
  if (await authority.confirm("Confirm session profile", message, "Apply") !== true)
219
235
  return error("Session profile action cancelled; no maintenance was started.");
220
236
  authority.assertCurrent();
@@ -222,7 +238,54 @@ async function manageProfiles(deps, invocation, authority) {
222
238
  expectedSelectionRevision: session.selection.selectionRevision, expectedAdmissionEpoch: session.admissionEpoch,
223
239
  ...(revision === undefined ? {} : { expectedRevision: revision }) }, invocation.agent, authority.signal, () => authority.assertCurrent());
224
240
  const refreshRequired = selected.refreshRequired === true || selected.selection.refreshRequired === true;
225
- return success(`Session ${selected.sessionId} now admits ${selected.admittedSelection?.selectedId ?? "deployment baseline"}; admission epoch ${selected.admissionEpoch}.${refreshRequired ? " The commit succeeded, but refresh is required before another profile action." : ""}`);
241
+ const applied = `Applied ${id ?? "deployment baseline"} to session ${session.sessionId}; admission epoch ${selected.admissionEpoch}.`;
242
+ if (refreshRequired)
243
+ return success(`${applied} Refresh is required before another profile action.${useModel ? " The profile model was not selected." : ""}`);
244
+ if (!useModel || chooseModel === undefined)
245
+ return success(`${applied}${id !== null && chooseModel === undefined ? " Use /model to change the session model." : ""}`);
246
+ if (selected.sessionId !== session.sessionId || selected.canSelectModel !== true || selected.profileModel === undefined) {
247
+ return success(`${applied} The profile model is unavailable; use /model to choose a session model.`);
248
+ }
249
+ try {
250
+ const outcome = await chooseModel(selected.profileModel, authority, selected.admissionEpoch);
251
+ return success(`${applied} ${outcome}`);
252
+ }
253
+ catch {
254
+ return success(`${applied} Model selection was not confirmed; check /model.`);
255
+ }
256
+ }
257
+ function captureProfileModelChoice(agent, cursor) {
258
+ const selector = hostModelSelection(agent);
259
+ const llm = agent.ctx?.get?.("llm");
260
+ if (selector === undefined || typeof llm?.resolveCallConfig !== "function" || (!agent.session.snapshotEvents && !agent.session.events))
261
+ return undefined;
262
+ const resolve = llm.resolveCallConfig.bind(llm);
263
+ const current = selector.current();
264
+ const before = current === undefined ? undefined : { ...current };
265
+ const llmOwner = Reflect.get(llm, symbols.original) ?? llm;
266
+ return async ({ provider, model, reasoningEffort }, authority, epoch) => {
267
+ const choiceUnchanged = () => {
268
+ authority.assertApplied(epoch);
269
+ const liveLlm = agent.ctx?.get?.("llm");
270
+ if (hostModelSelection(agent) !== selector || !liveLlm || (Reflect.get(liveLlm, symbols.original) ?? liveLlm) !== llmOwner) {
271
+ throw new Error("The session model service changed.");
272
+ }
273
+ const now = selector.current();
274
+ return latestModelSelectionSeq(agent) === cursor && before?.provider === now?.provider && before?.model === now?.model && before?.reasoningEffort === now?.reasoningEffort;
275
+ };
276
+ const newerChoice = "Kept the newer session model choice.";
277
+ if (!choiceUnchanged())
278
+ return newerChoice;
279
+ const route = { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) };
280
+ const resolved = await resolve({ ...route }, authority.signal);
281
+ if (!choiceUnchanged())
282
+ return newerChoice;
283
+ if (resolved.provider !== provider || resolved.model !== model || (reasoningEffort !== undefined && resolved.reasoningEffort !== reasoningEffort)) {
284
+ return "The Host could not resolve the exact profile model and effort; use /model to choose a session model.";
285
+ }
286
+ selector.select(route);
287
+ return `Selected ${provider}/${model} for this session.`;
288
+ };
226
289
  }
227
290
  async function chooseProfile(authority, inventory) {
228
291
  const available = inventory.profiles.filter(profile => profile.error === undefined && typeof profile.revision === "string");
@@ -1,6 +1,7 @@
1
1
  import { symbols } from "@deepseek-ai/cordis";
2
2
  import { createDeepworkCommandDefinition, createDsmmStatusCommandDefinition } from "./commands.js";
3
3
  import { DSMM_LOCALES } from "./settings.js";
4
+ import { validateAdmissionEpoch } from "./profiles.js";
4
5
  import { createDsmmManagementCommandDefinition, DIALOG_TIMEOUT_MS, DSMM_TUI_CONTRIBUTIONS } from "./tui-actions.js";
5
6
  const INHERIT = "inherit";
6
7
  const ACTION_TIMEOUT_MS = 120_000;
@@ -277,7 +278,7 @@ class DsmmTuiAdapter {
277
278
  const signal = invocation.signal === undefined
278
279
  ? AbortSignal.any([local.signal, deadline.signal])
279
280
  : AbortSignal.any([local.signal, deadline.signal, invocation.signal]);
280
- const assertCurrent = () => {
281
+ const assertOwner = () => {
281
282
  if (signal.aborted || this.disposed)
282
283
  throw abortError();
283
284
  if (this.mediated !== mounted || !this.currentHost(mounted.owner, mounted.generationId)
@@ -286,17 +287,17 @@ class DsmmTuiAdapter {
286
287
  const currentAgents = softGet(this.ctx, "agents");
287
288
  if (currentAgents === undefined || original(currentAgents) !== agentsOwner || currentAgents.get(id) !== agent)
288
289
  throw new Error("The exact live Agent changed.");
289
- if (admission !== undefined) {
290
- const current = this.options.getSettings.admission?.(agent);
291
- if (current !== admission || current?.epoch !== admission.epoch)
292
- throw new Error("The DSMM admission changed.");
293
- }
294
290
  if (dialogsOwner !== undefined) {
295
291
  const currentDialogs = softGet(this.ctx, "tuiDialogs");
296
292
  if (currentDialogs === undefined || original(currentDialogs) !== dialogsOwner)
297
293
  throw new Error("The managed dialog owner changed.");
298
294
  }
299
295
  };
296
+ const assertCurrent = () => {
297
+ assertOwner();
298
+ if (admission !== undefined && this.options.getSettings.admission?.(agent) !== admission)
299
+ throw new Error("The DSMM admission changed.");
300
+ };
300
301
  const checked = async (operation) => {
301
302
  assertCurrent();
302
303
  const result = await operation();
@@ -308,7 +309,18 @@ class DsmmTuiAdapter {
308
309
  signal,
309
310
  agent,
310
311
  assertCurrent,
311
- select: (title, options) => checked(() => dialogs.select({ title, options, signal, timeoutMs: DIALOG_TIMEOUT_MS })),
312
+ assertApplied: epoch => {
313
+ assertOwner();
314
+ validateAdmissionEpoch(epoch);
315
+ if (admission === undefined || epoch === admission.epoch || this.options.getSettings.admission?.(agent)?.epoch !== epoch) {
316
+ throw new Error("The applied session admission is no longer current.");
317
+ }
318
+ },
319
+ select: (title, options) => checked(async () => {
320
+ const offered = options.map(option => option.id);
321
+ const answer = await dialogs.select({ title, options, signal, timeoutMs: DIALOG_TIMEOUT_MS });
322
+ return answer !== undefined && offered.includes(answer) ? answer : undefined;
323
+ }),
312
324
  confirm: (title, message, confirmLabel) => checked(() => dialogs.confirm({ title, message,
313
325
  ...(confirmLabel === undefined ? {} : { confirmLabel }), cancelLabel: "Cancel", signal, timeoutMs: DIALOG_TIMEOUT_MS })),
314
326
  input: (title, placeholder) => checked(() => dialogs.input({ title, ...(placeholder === undefined ? {} : { placeholder }), signal, timeoutMs: DIALOG_TIMEOUT_MS })),
@@ -88,6 +88,7 @@ export interface DsmmTuiActionAuthority {
88
88
  readonly signal: AbortSignal;
89
89
  readonly agent: DshCommandInvocation["agent"];
90
90
  assertCurrent(): void;
91
+ assertApplied(epoch: string): void;
91
92
  select(title: string, options: readonly TuiDialogOption[]): Promise<string | undefined>;
92
93
  confirm(title: string, message: string, confirmLabel?: string): Promise<boolean>;
93
94
  input(title: string, placeholder?: string): Promise<string | undefined>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsmm/dsmm",
3
- "version": "0.3.39",
3
+ "version": "0.3.41",
4
4
  "description": "Native Deepwork roles, routing, profiles, and permission controls for DeepSeek Harness.",
5
5
  "author": "Hugefiver",
6
6
  "license": "LicenseRef-AAAPL",