@dsmm/dsmm 0.1.4 → 0.1.5
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.
- package/README.md +12 -12
- package/docs/compatibility.md +8 -6
- package/docs/migration-from-ocmm.md +8 -0
- package/docs/model-routing.md +19 -5
- package/docs/profiles.md +21 -9
- package/docs/releasing.md +23 -15
- package/docs/runtime-recovery.md +39 -14
- package/docs/settings-status.md +7 -7
- package/lib/client/ProfilesSection.js +7 -3
- package/lib/client/SessionProfiles.d.ts +19 -0
- package/lib/client/SessionProfiles.js +24 -0
- package/lib/client/StructuredEditor.d.ts +11 -0
- package/lib/client/StructuredEditor.js +74 -0
- package/lib/client/controller.d.ts +38 -0
- package/lib/client/controller.js +153 -11
- package/lib/client/index.d.ts +2 -0
- package/lib/client/index.js +20 -0
- package/lib/client/locales.d.ts +89 -0
- package/lib/client/locales.js +45 -2
- package/lib/client/session-labels.d.ts +8 -0
- package/lib/client/session-labels.js +13 -0
- package/lib/client/structured.d.ts +18 -0
- package/lib/client/structured.js +98 -0
- package/lib/client/styles.d.ts +1 -1
- package/lib/client/styles.js +12 -1
- package/lib/client.js +969 -74
- package/lib/commands.js +1 -0
- package/lib/dsh-types.d.ts +16 -0
- package/lib/index.js +27 -1
- package/lib/model-routing.js +93 -23
- package/lib/profile-remote.d.ts +7 -1
- package/lib/profile-remote.js +115 -2
- package/lib/profile-rpc.d.ts +9 -1
- package/lib/profile-rpc.js +99 -2
- package/lib/profile-runtime.d.ts +24 -5
- package/lib/profile-runtime.js +182 -31
- package/lib/profile-store.d.ts +19 -1
- package/lib/profile-store.js +120 -10
- package/lib/profile-types.d.ts +41 -1
- package/lib/profiles.d.ts +1 -1
- package/lib/profiles.js +34 -2
- package/lib/role-providers.js +12 -2
- package/lib/role-routing.d.ts +37 -3
- package/lib/role-routing.js +107 -35
- package/lib/routing-policy.d.ts +32 -0
- package/lib/routing-policy.js +92 -0
- package/lib/runtime-recovery.js +213 -52
- package/lib/settings.d.ts +27 -1
- package/lib/settings.js +29 -7
- package/lib/status.d.ts +9 -1
- package/lib/status.js +29 -8
- package/package.json +5 -1
package/lib/profiles.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getNodeValue, parseTree } from "jsonc-parser";
|
|
2
2
|
import { DSMM_ROLE_IDS } from "./roles.js";
|
|
3
3
|
import { resolveConfig } from "./settings.js";
|
|
4
|
+
import { normalizeRateLimitOverrides, normalizeRoutingStrategy, normalizeRuntimePolicy } from "./routing-policy.js";
|
|
4
5
|
export const MAX_PROFILE_BYTES = 128 * 1024;
|
|
5
6
|
export const MAX_PROFILE_COUNT = 128;
|
|
6
7
|
export const MAX_PROFILE_DIRECTORY_ENTRIES = 1024;
|
|
@@ -30,7 +31,7 @@ export function validateProfileRevision(revision, field = "expectedRevision") {
|
|
|
30
31
|
if (typeof revision !== "string" || !/^[a-f0-9]{64}$/u.test(revision))
|
|
31
32
|
invalid(field, "must be a SHA256 file revision");
|
|
32
33
|
}
|
|
33
|
-
const OVERLAY_FIELDS = ["defaultActive", "roleRouting", "workflow", "guards", "runtimeRecovery", "deepseekV4ProCalibration", "deepseekV4ProDefaultReasoningEffort", "deepseekV4ProMaxReasoningPresets", "deepseekFlashCalibration", "deepseekFlashDefaultReasoningEffort", "deepseekFlashMaxReasoningPresets"];
|
|
34
|
+
const OVERLAY_FIELDS = ["defaultActive", "roleRouting", "runtimePolicy", "workflow", "guards", "runtimeRecovery", "deepseekV4ProCalibration", "deepseekV4ProDefaultReasoningEffort", "deepseekV4ProMaxReasoningPresets", "deepseekFlashCalibration", "deepseekFlashDefaultReasoningEffort", "deepseekFlashMaxReasoningPresets"];
|
|
34
35
|
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
35
36
|
export function parseProfileDocument(content, expectedId) {
|
|
36
37
|
if (typeof content !== "string")
|
|
@@ -65,6 +66,7 @@ export function parseProfileDocument(content, expectedId) {
|
|
|
65
66
|
optional(overlay, `${prefix}MaxReasoningPresets`, roleList, "settings");
|
|
66
67
|
}
|
|
67
68
|
optional(overlay, "roleRouting", roleRouting, "settings");
|
|
69
|
+
optional(overlay, "runtimePolicy", runtimePolicy, "settings");
|
|
68
70
|
optional(overlay, "workflow", workflow, "settings");
|
|
69
71
|
optional(overlay, "guards", guards, "settings");
|
|
70
72
|
optional(overlay, "runtimeRecovery", recovery, "settings");
|
|
@@ -182,9 +184,39 @@ function roleRouting(value, field) {
|
|
|
182
184
|
for (const [role, raw] of Object.entries(item)) {
|
|
183
185
|
const path = `${field}.${role}`;
|
|
184
186
|
const policy = record(raw, path);
|
|
185
|
-
keys(policy, ["primary", "fallbackRoutes"], path);
|
|
187
|
+
keys(policy, ["primary", "fallbackRoutes", "strategy", "rateLimit"], path);
|
|
186
188
|
optional(policy, "primary", route, path);
|
|
187
189
|
optional(policy, "fallbackRoutes", routeList, path);
|
|
190
|
+
optional(policy, "strategy", strategy, path);
|
|
191
|
+
optional(policy, "rateLimit", rateLimit, path);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function strategy(value, field) {
|
|
195
|
+
try {
|
|
196
|
+
normalizeRoutingStrategy(value);
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
invalid(field, "must be startup-lock or rate-limit-fallback");
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function rateLimit(value, field) {
|
|
203
|
+
try {
|
|
204
|
+
normalizeRateLimitOverrides(value);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
invalid(field, "must contain only bounded integer retry, delay, threshold and switch fields");
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function runtimePolicy(value, field) {
|
|
211
|
+
const item = record(value, field);
|
|
212
|
+
keys(item, ["strategy", "rateLimit"], field);
|
|
213
|
+
optional(item, "strategy", strategy, field);
|
|
214
|
+
optional(item, "rateLimit", rateLimit, field);
|
|
215
|
+
try {
|
|
216
|
+
normalizeRuntimePolicy(value);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
invalid(field, "must contain a valid strategy and bounded rateLimit policy");
|
|
188
220
|
}
|
|
189
221
|
}
|
|
190
222
|
function workflow(value, field) {
|
package/lib/role-providers.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { parentAgentOptionsForDelegation } from "@deepseek-ai/dsh-subagent";
|
|
2
2
|
import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
|
|
3
3
|
import { DSMM_ROLE_IDS } from "./roles.js";
|
|
4
|
+
import { resolveRoleRuntimePolicy } from "./routing-policy.js";
|
|
5
|
+
import { selectInitialModelRoute } from "./role-routing.js";
|
|
4
6
|
export function roleProviderName(role) {
|
|
5
7
|
return `dsmm-role-${role.slice("dsmm-".length)}`;
|
|
6
8
|
}
|
|
@@ -62,13 +64,21 @@ export function registerRoleProviders(ctx, getSettings, getDeploymentSettings =
|
|
|
62
64
|
const llm = request.parent.ctx.get("llm");
|
|
63
65
|
if (llm?.resolveCallConfig === undefined)
|
|
64
66
|
throw new Error("dsmm role delegation requires the parent Agent native LLM service");
|
|
65
|
-
|
|
67
|
+
const explicitRoute = request.agentOptions?.provider !== undefined || request.agentOptions?.model !== undefined;
|
|
68
|
+
const candidates = [{ provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) },
|
|
69
|
+
...explicitRoute ? [] : resolveRoleRuntimePolicy(parentSettings, role).fallbackRoutes.map((route) => ({ ...route,
|
|
70
|
+
...(request.agentOptions?.reasoningEffort === undefined ? {} : { reasoningEffort: request.agentOptions.reasoningEffort }) }))];
|
|
71
|
+
const selected = await selectInitialModelRoute(llm, candidates, request.signal);
|
|
66
72
|
request.signal.throwIfAborted();
|
|
67
73
|
if (!active || registry.getProvider("spawn") !== spawn)
|
|
68
74
|
throw new Error("dsmm role spawn provider changed during route validation; retry delegation");
|
|
69
75
|
// Preserve the native descriptor, authority filters and lifecycle;
|
|
70
76
|
// this alias owns only profile-derived route defaults and preflight.
|
|
71
|
-
|
|
77
|
+
const changed = selected.provider !== provider || selected.model !== model;
|
|
78
|
+
return spawn.start(primary === undefined && !changed ? request : { ...request, agentOptions: {
|
|
79
|
+
...agentOptions, ...selected,
|
|
80
|
+
reasoningEffort: selected.reasoningEffort === undefined ? undefined : ReasoningEffortId(selected.reasoningEffort)
|
|
81
|
+
} });
|
|
72
82
|
}
|
|
73
83
|
});
|
|
74
84
|
disposers.push(() => { active = false; dispose(); });
|
package/lib/role-routing.d.ts
CHANGED
|
@@ -1,10 +1,44 @@
|
|
|
1
|
-
import type { AgentRequestFrame, DshContext, DshLlmCallConfig } from "./dsh-types.js";
|
|
1
|
+
import type { AgentRequestFrame, DshAgent, DshContext, DshLlmCallConfig, DshLlmRuntime } from "./dsh-types.js";
|
|
2
2
|
import type { DsmmRoleId } from "./roles.js";
|
|
3
3
|
import type { DsmmModelRoute, DsmmSettings } from "./settings.js";
|
|
4
|
+
import type { DsmmRoleRuntimeState } from "./profile-types.js";
|
|
4
5
|
export declare const DSMM_ROLE_POLICY_EVENT = "dsmm/role-policy";
|
|
5
|
-
export
|
|
6
|
+
export interface RoleRouteLock {
|
|
7
|
+
identity: string;
|
|
8
|
+
route: DsmmModelRoute;
|
|
9
|
+
candidates: readonly DsmmModelRoute[];
|
|
10
|
+
generation: number;
|
|
11
|
+
attempts: number;
|
|
12
|
+
startupSettled: boolean;
|
|
13
|
+
retries: number;
|
|
14
|
+
rateLimits: number;
|
|
15
|
+
switches: number;
|
|
16
|
+
totalDelayMs: number;
|
|
17
|
+
manualSelectionSeq?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface NativeModelSelectionIntent {
|
|
20
|
+
seq: number;
|
|
21
|
+
route: DsmmModelRoute;
|
|
22
|
+
}
|
|
23
|
+
/** Native user selection is authority; inherited headers/default configs are not. */
|
|
24
|
+
export declare function latestNativeModelSelection(agent: DshAgent): NativeModelSelectionIntent | undefined;
|
|
25
|
+
export declare function sameExactModelRoute(left: Pick<DsmmModelRoute, "provider" | "model" | "reasoningEffort">, right: DsmmModelRoute): boolean;
|
|
26
|
+
/** Consumed user intent stays explicit on cold resume and profile re-admission. */
|
|
27
|
+
export declare function nativeModelSelectionWasAccepted(agent: DshAgent, intent: NativeModelSelectionIntent): boolean;
|
|
28
|
+
/** Only native, machine-routable absence authorizes initial candidate admission. */
|
|
29
|
+
export declare function isUnavailableRouteFailure(error: unknown, nativeRequestFailure?: boolean): boolean;
|
|
30
|
+
export declare function orderedModelRoutes(candidates: readonly DsmmModelRoute[]): DsmmModelRoute[];
|
|
31
|
+
/** Exact metadata preparation, never a completion or advisory catalog health check. */
|
|
32
|
+
export declare function selectInitialModelRoute(llm: DshLlmRuntime, candidates: readonly DsmmModelRoute[], signal?: AbortSignal): Promise<DsmmModelRoute>;
|
|
33
|
+
export declare function roleRouteLock(agent: DshAgent, identity: string): RoleRouteLock | undefined;
|
|
34
|
+
export declare function pinRoleRoute(agent: DshAgent, identity: string, route: DsmmModelRoute, candidates: readonly DsmmModelRoute[]): RoleRouteLock;
|
|
35
|
+
export declare function clearRoleRouteLock(agent: DshAgent): void;
|
|
36
|
+
export declare function roleRouteRuntimeState(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): DsmmRoleRuntimeState;
|
|
37
|
+
export declare function rolePolicyIdentity(settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): string | undefined;
|
|
38
|
+
/** Durable profile choice is not permission to retain a former process's route lock. */
|
|
39
|
+
export declare function liveRolePolicyIdentity(agent: DshAgent, settings: DsmmSettings, role: DsmmRoleId | undefined, epoch?: string): string | undefined;
|
|
6
40
|
/** Native custom events are model-hidden log facts, retained across surface compaction. */
|
|
7
|
-
export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined, ctx?: DshContext): Promise<string | undefined>;
|
|
41
|
+
export declare function establishRolePolicy(frame: AgentRequestFrame, settings: DsmmSettings, role: DsmmRoleId | undefined, ctx?: DshContext, epoch?: string): Promise<string | undefined>;
|
|
8
42
|
export declare function recordAdmittedRecoveryRoute(frame: AgentRequestFrame, route: DsmmModelRoute): void;
|
|
9
43
|
export declare function takeAdmittedRecoveryRoute(frame: AgentRequestFrame): DsmmModelRoute | undefined;
|
|
10
44
|
export declare function effectiveRoleFallbackRoutes(settings: DsmmSettings, role: DsmmRoleId | undefined): readonly DsmmModelRoute[];
|
package/lib/role-routing.js
CHANGED
|
@@ -1,23 +1,111 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { LlmError } from "@deepseek-ai/dsh-llm";
|
|
2
3
|
import { assertDsmmMetadataPersistence } from "./session-metadata.js";
|
|
3
4
|
import { isDsmmRoleId } from "./roles.js";
|
|
4
5
|
import { isCurrentRecoveryStep } from "./recovery-policy.js";
|
|
5
6
|
import { childOwnedSessionEvents, sessionEvents } from "./session-scope.js";
|
|
7
|
+
import { resolveRoleRuntimePolicy } from "./routing-policy.js";
|
|
6
8
|
const admittedRecoveryRoutes = new WeakMap();
|
|
9
|
+
const routeLocks = new WeakMap();
|
|
10
|
+
const agentEntries = new WeakMap();
|
|
7
11
|
export const DSMM_ROLE_POLICY_EVENT = "dsmm/role-policy";
|
|
8
|
-
|
|
12
|
+
/** Native user selection is authority; inherited headers/default configs are not. */
|
|
13
|
+
export function latestNativeModelSelection(agent) {
|
|
14
|
+
let selected;
|
|
15
|
+
for (const event of policyEvents({ agent })) {
|
|
16
|
+
if (event.type !== "model/selection" || !("seq" in event) || !Number.isSafeInteger(event.seq)
|
|
17
|
+
|| typeof event.seq !== "number" || event.seq < 0 || !isRecord(event.data))
|
|
18
|
+
continue;
|
|
19
|
+
const { provider, model, reasoningEffort } = event.data;
|
|
20
|
+
if (typeof provider !== "string" || provider.trim() === "" || typeof model !== "string" || model.trim() === ""
|
|
21
|
+
|| (reasoningEffort !== undefined && (typeof reasoningEffort !== "string" || reasoningEffort.trim() === "")))
|
|
22
|
+
continue;
|
|
23
|
+
selected = { seq: event.seq, route: { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) } };
|
|
24
|
+
}
|
|
25
|
+
return selected;
|
|
26
|
+
}
|
|
27
|
+
export function sameExactModelRoute(left, right) {
|
|
28
|
+
return sameModelRoute(left, right) && left.reasoningEffort === right.reasoningEffort;
|
|
29
|
+
}
|
|
30
|
+
/** Consumed user intent stays explicit on cold resume and profile re-admission. */
|
|
31
|
+
export function nativeModelSelectionWasAccepted(agent, intent) {
|
|
32
|
+
return policyEvents({ agent }).some((event) => event.type === "request/header" && "seq" in event
|
|
33
|
+
&& typeof event.seq === "number" && event.seq > intent.seq && isRecord(event.data)
|
|
34
|
+
&& isRecord(event.data.header) && isRecord(event.data.header.config)
|
|
35
|
+
&& sameExactModelRoute(event.data.header.config, intent.route));
|
|
36
|
+
}
|
|
37
|
+
/** Only native, machine-routable absence authorizes initial candidate admission. */
|
|
38
|
+
export function isUnavailableRouteFailure(error, nativeRequestFailure = false) {
|
|
39
|
+
return isRecord(error) && (error.status === undefined || error.status === 503)
|
|
40
|
+
&& (error.code === "NO_ADAPTER" || (error.code === "UNKNOWN_MODEL" && (nativeRequestFailure || error instanceof LlmError)));
|
|
41
|
+
}
|
|
42
|
+
export function orderedModelRoutes(candidates) {
|
|
43
|
+
const routes = [];
|
|
44
|
+
for (const route of candidates)
|
|
45
|
+
if (!routes.some((previous) => sameModelRoute(previous, route)))
|
|
46
|
+
routes.push(canonicalRoute(route));
|
|
47
|
+
return routes;
|
|
48
|
+
}
|
|
49
|
+
/** Exact metadata preparation, never a completion or advisory catalog health check. */
|
|
50
|
+
export async function selectInitialModelRoute(llm, candidates, signal) {
|
|
51
|
+
if (llm.resolveCallConfig === undefined)
|
|
52
|
+
throw new Error("dsmm route admission requires the Agent native LLM service");
|
|
53
|
+
let unavailable;
|
|
54
|
+
for (const route of orderedModelRoutes(candidates)) {
|
|
55
|
+
signal?.throwIfAborted();
|
|
56
|
+
try {
|
|
57
|
+
await llm.resolveCallConfig({ ...route }, signal);
|
|
58
|
+
signal?.throwIfAborted();
|
|
59
|
+
return { ...route };
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
signal?.throwIfAborted();
|
|
63
|
+
if (!isUnavailableRouteFailure(error))
|
|
64
|
+
throw error;
|
|
65
|
+
unavailable = error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
throw unavailable ?? new Error("dsmm route admission has no configured candidate");
|
|
69
|
+
}
|
|
70
|
+
export function roleRouteLock(agent, identity) {
|
|
71
|
+
const lock = routeLocks.get(agent);
|
|
72
|
+
return lock?.identity === identity ? lock : undefined;
|
|
73
|
+
}
|
|
74
|
+
export function pinRoleRoute(agent, identity, route, candidates) {
|
|
75
|
+
const lock = { identity, route: canonicalRoute(route), candidates: orderedModelRoutes(candidates), generation: 0,
|
|
76
|
+
attempts: 0, startupSettled: false, retries: 0, rateLimits: 0, switches: 0, totalDelayMs: 0 };
|
|
77
|
+
routeLocks.set(agent, lock);
|
|
78
|
+
return lock;
|
|
79
|
+
}
|
|
80
|
+
export function clearRoleRouteLock(agent) { routeLocks.delete(agent); }
|
|
81
|
+
export function roleRouteRuntimeState(agent, settings, role, epoch) {
|
|
82
|
+
const resolved = resolveRoleRuntimePolicy(settings, role);
|
|
83
|
+
const identity = liveRolePolicyIdentity(agent, settings, role, epoch);
|
|
84
|
+
const lock = identity === undefined ? undefined : roleRouteLock(agent, identity);
|
|
85
|
+
return { ...(role === undefined ? {} : { role }), strategy: resolved.strategy, rateLimit: { ...resolved.rateLimit },
|
|
86
|
+
...(lock === undefined ? {} : { route: { ...lock.route } }), retries: lock?.retries ?? 0,
|
|
87
|
+
rateLimitFailures: lock?.rateLimits ?? 0, switches: lock?.switches ?? 0, totalDelayMs: lock?.totalDelayMs ?? 0 };
|
|
88
|
+
}
|
|
89
|
+
export function rolePolicyIdentity(settings, role, epoch) {
|
|
9
90
|
if (role === undefined)
|
|
10
91
|
return undefined;
|
|
11
92
|
const policy = settings.roleRouting[role];
|
|
12
|
-
|
|
13
|
-
return undefined;
|
|
93
|
+
const resolved = resolveRoleRuntimePolicy(settings, role);
|
|
14
94
|
return createHash("sha256").update(JSON.stringify({
|
|
15
|
-
version:
|
|
16
|
-
fallbackSource:
|
|
17
|
-
|
|
18
|
-
enabled: settings.runtimeRecovery.enabled
|
|
95
|
+
version: 2, role, epoch: epoch ?? null, primary: policy?.primary === undefined ? null : canonicalRoute(policy.primary),
|
|
96
|
+
fallbackSource: resolved.fallbackSource, fallbackRoutes: resolved.fallbackRoutes.map(canonicalRoute),
|
|
97
|
+
strategy: resolved.strategy, rateLimit: resolved.rateLimit
|
|
19
98
|
})).digest("hex");
|
|
20
99
|
}
|
|
100
|
+
/** Durable profile choice is not permission to retain a former process's route lock. */
|
|
101
|
+
export function liveRolePolicyIdentity(agent, settings, role, epoch) {
|
|
102
|
+
let entry = agentEntries.get(agent);
|
|
103
|
+
if (entry === undefined) {
|
|
104
|
+
entry = randomUUID();
|
|
105
|
+
agentEntries.set(agent, entry);
|
|
106
|
+
}
|
|
107
|
+
return rolePolicyIdentity(settings, role, `${epoch ?? "unscoped"}:${entry}`);
|
|
108
|
+
}
|
|
21
109
|
function canonicalRoute(route) {
|
|
22
110
|
return { provider: route.provider, model: route.model, ...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }) };
|
|
23
111
|
}
|
|
@@ -42,8 +130,9 @@ function readPolicyMarker(event) {
|
|
|
42
130
|
return { role: data.role, policy: data.policy };
|
|
43
131
|
}
|
|
44
132
|
/** Native custom events are model-hidden log facts, retained across surface compaction. */
|
|
45
|
-
export async function establishRolePolicy(frame, settings, role, ctx) {
|
|
46
|
-
const identity =
|
|
133
|
+
export async function establishRolePolicy(frame, settings, role, ctx, epoch) {
|
|
134
|
+
const identity = liveRolePolicyIdentity(frame.agent, settings, role, epoch);
|
|
135
|
+
const declared = role !== undefined && (Object.keys(settings.roleRouting[role] ?? {}).length > 0 || settings.runtimeRecovery.fallbackRoutes.length > 0);
|
|
47
136
|
if (frame.signal.aborted)
|
|
48
137
|
return identity;
|
|
49
138
|
let latest;
|
|
@@ -56,12 +145,12 @@ export async function establishRolePolicy(frame, settings, role, ctx) {
|
|
|
56
145
|
}
|
|
57
146
|
if (frame.signal.aborted || !isCurrentRecoveryStep(events, frame.turn, frame.step))
|
|
58
147
|
return identity;
|
|
59
|
-
if (identity === undefined || role === undefined) {
|
|
148
|
+
if (identity === undefined || role === undefined || !declared) {
|
|
60
149
|
if (latest !== undefined && latest.policy !== null) {
|
|
61
150
|
assertDsmmMetadataPersistence(ctx ?? frame.agent.ctx);
|
|
62
151
|
await frame.agent.session.append(DSMM_ROLE_POLICY_EVENT, { version: 1, role: latest.role, policy: null });
|
|
63
152
|
}
|
|
64
|
-
return
|
|
153
|
+
return identity;
|
|
65
154
|
}
|
|
66
155
|
if (latest?.role !== role || latest.policy !== identity) {
|
|
67
156
|
assertDsmmMetadataPersistence(ctx ?? frame.agent.ctx);
|
|
@@ -78,10 +167,7 @@ export function takeAdmittedRecoveryRoute(frame) {
|
|
|
78
167
|
return route;
|
|
79
168
|
}
|
|
80
169
|
export function effectiveRoleFallbackRoutes(settings, role) {
|
|
81
|
-
|
|
82
|
-
return [];
|
|
83
|
-
return role === undefined ? settings.runtimeRecovery.fallbackRoutes
|
|
84
|
-
: settings.roleRouting[role]?.fallbackRoutes ?? settings.runtimeRecovery.fallbackRoutes;
|
|
170
|
+
return resolveRoleRuntimePolicy(settings, role).fallbackRoutes;
|
|
85
171
|
}
|
|
86
172
|
export function applyModelRoute(config, route) {
|
|
87
173
|
const { reasoningEffort: _inheritedEffort, ...preserved } = config;
|
|
@@ -94,16 +180,10 @@ export function sameModelRoute(left, right) {
|
|
|
94
180
|
export function persistedRoleRoute(frame, primary, fallbacks = [], identity) {
|
|
95
181
|
const events = policyEvents(frame);
|
|
96
182
|
let matchingPolicy = false;
|
|
97
|
-
let sawPrimary = false;
|
|
98
|
-
let initial;
|
|
99
|
-
let sawChange = false;
|
|
100
183
|
let selected;
|
|
101
184
|
for (const event of events) {
|
|
102
185
|
if (isPresetBoundary(frame, event) || event.type === DSMM_ROLE_POLICY_EVENT) {
|
|
103
186
|
matchingPolicy = event.type === DSMM_ROLE_POLICY_EVENT && identity !== undefined && readPolicyMarker(event)?.policy === identity;
|
|
104
|
-
sawPrimary = false;
|
|
105
|
-
initial = undefined;
|
|
106
|
-
sawChange = false;
|
|
107
187
|
selected = undefined;
|
|
108
188
|
continue;
|
|
109
189
|
}
|
|
@@ -119,22 +199,14 @@ export function persistedRoleRoute(frame, primary, fallbacks = [], identity) {
|
|
|
119
199
|
if (typeof config?.provider !== "string" || config.provider.trim() === ""
|
|
120
200
|
|| typeof config.model !== "string" || config.model.trim() === "")
|
|
121
201
|
continue;
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
sawPrimary = true;
|
|
127
|
-
else if (primary === undefined ? sawChange : sawPrimary)
|
|
128
|
-
selected = {
|
|
129
|
-
provider: config.provider, model: config.model,
|
|
130
|
-
...(typeof config.reasoningEffort === "string" && !adapterDefaultEffort(header) ? { reasoningEffort: config.reasoningEffort } : {})
|
|
131
|
-
};
|
|
132
|
-
if (primary !== undefined && sameModelRoute(config, primary))
|
|
133
|
-
selected = undefined;
|
|
202
|
+
selected = {
|
|
203
|
+
provider: config.provider, model: config.model,
|
|
204
|
+
...(typeof config.reasoningEffort === "string" && !adapterDefaultEffort(header) ? { reasoningEffort: config.reasoningEffort } : {})
|
|
205
|
+
};
|
|
134
206
|
}
|
|
135
207
|
// A configured fallback remains exact after its adapter/default header is
|
|
136
208
|
// persisted. A later non-chain durable host route remains host-owned instead.
|
|
137
|
-
return selected === undefined ? undefined : fallbacks.find((route) => sameModelRoute(route, selected)) ?? selected;
|
|
209
|
+
return selected === undefined ? undefined : [primary, ...fallbacks].find((route) => route !== undefined && sameModelRoute(route, selected)) ?? selected;
|
|
138
210
|
}
|
|
139
211
|
function isRecord(value) {
|
|
140
212
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Browser-safe route policy grammar shared by settings, profiles and native UI. */
|
|
2
|
+
import type { DsmmRoleId } from "./roles.js";
|
|
3
|
+
import type { DsmmResolvedRoleRuntimePolicy, DsmmSettings } from "./settings.js";
|
|
4
|
+
export type DsmmRoutingStrategy = "startup-lock" | "rate-limit-fallback";
|
|
5
|
+
export interface DsmmRateLimitPolicy {
|
|
6
|
+
/** Same-route requests after the first attempt. */
|
|
7
|
+
maxRetries: number;
|
|
8
|
+
initialDelayMs: number;
|
|
9
|
+
maxDelayMs: number;
|
|
10
|
+
maxTotalDelayMs: number;
|
|
11
|
+
/** Distinct failed native attempts, including the first attempt. */
|
|
12
|
+
switchAfterRateLimits: number;
|
|
13
|
+
maxSwitches: number;
|
|
14
|
+
}
|
|
15
|
+
export interface DsmmRuntimePolicyConfig {
|
|
16
|
+
strategy?: DsmmRoutingStrategy;
|
|
17
|
+
rateLimit?: Partial<DsmmRateLimitPolicy>;
|
|
18
|
+
}
|
|
19
|
+
export interface DsmmRuntimePolicySettings {
|
|
20
|
+
strategy: DsmmRoutingStrategy;
|
|
21
|
+
rateLimit: DsmmRateLimitPolicy;
|
|
22
|
+
}
|
|
23
|
+
export declare const DEFAULT_DSMM_RATE_LIMIT_POLICY: Readonly<DsmmRateLimitPolicy>;
|
|
24
|
+
export declare const DEFAULT_DSMM_RUNTIME_POLICY: Readonly<DsmmRuntimePolicySettings>;
|
|
25
|
+
export declare const DSMM_RATE_LIMIT_BOUNDS: Readonly<Record<keyof DsmmRateLimitPolicy, readonly [number, number]>>;
|
|
26
|
+
export declare function normalizeRoutingStrategy(value: unknown): DsmmRoutingStrategy;
|
|
27
|
+
export declare function normalizeRateLimitOverrides(value: unknown): Partial<DsmmRateLimitPolicy>;
|
|
28
|
+
export declare function normalizeRateLimitPolicy(value?: unknown, defaults?: Readonly<DsmmRateLimitPolicy>): DsmmRateLimitPolicy;
|
|
29
|
+
export declare function normalizeRuntimePolicy(value?: unknown): DsmmRuntimePolicySettings;
|
|
30
|
+
/** Resolve once per immutable settings admission; omission and explicit [] remain distinct. */
|
|
31
|
+
export declare function resolveRoleRuntimePolicy(settings: DsmmSettings, role?: DsmmRoleId): DsmmResolvedRoleRuntimePolicy;
|
|
32
|
+
//# sourceMappingURL=routing-policy.d.ts.map
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
export const DEFAULT_DSMM_RATE_LIMIT_POLICY = Object.freeze({
|
|
2
|
+
maxRetries: 3,
|
|
3
|
+
initialDelayMs: 500,
|
|
4
|
+
maxDelayMs: 10000,
|
|
5
|
+
maxTotalDelayMs: 30000,
|
|
6
|
+
switchAfterRateLimits: 3,
|
|
7
|
+
maxSwitches: 2
|
|
8
|
+
});
|
|
9
|
+
export const DEFAULT_DSMM_RUNTIME_POLICY = Object.freeze({
|
|
10
|
+
strategy: "startup-lock",
|
|
11
|
+
rateLimit: DEFAULT_DSMM_RATE_LIMIT_POLICY
|
|
12
|
+
});
|
|
13
|
+
export const DSMM_RATE_LIMIT_BOUNDS = Object.freeze({
|
|
14
|
+
maxRetries: Object.freeze([0, 10]),
|
|
15
|
+
initialDelayMs: Object.freeze([0, 30000]),
|
|
16
|
+
maxDelayMs: Object.freeze([0, 30000]),
|
|
17
|
+
maxTotalDelayMs: Object.freeze([0, 120000]),
|
|
18
|
+
switchAfterRateLimits: Object.freeze([1, 10]),
|
|
19
|
+
maxSwitches: Object.freeze([0, 10])
|
|
20
|
+
});
|
|
21
|
+
export function normalizeRoutingStrategy(value) {
|
|
22
|
+
if (value !== "startup-lock" && value !== "rate-limit-fallback") {
|
|
23
|
+
throw new TypeError("dsmm strategy must be startup-lock or rate-limit-fallback");
|
|
24
|
+
}
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
export function normalizeRateLimitOverrides(value) {
|
|
28
|
+
if (!isRecord(value))
|
|
29
|
+
throw new TypeError("dsmm rateLimit must be an object");
|
|
30
|
+
const result = {};
|
|
31
|
+
for (const [field, raw] of Object.entries(value)) {
|
|
32
|
+
if (!Object.hasOwn(DSMM_RATE_LIMIT_BOUNDS, field))
|
|
33
|
+
throw new TypeError("dsmm rateLimit contains an unknown field");
|
|
34
|
+
const [minimum, maximum] = DSMM_RATE_LIMIT_BOUNDS[field];
|
|
35
|
+
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < minimum || raw > maximum) {
|
|
36
|
+
throw new TypeError(`dsmm rateLimit ${field} must be an integer from ${minimum} to ${maximum}`);
|
|
37
|
+
}
|
|
38
|
+
result[field] = raw;
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
export function normalizeRateLimitPolicy(value = undefined, defaults = DEFAULT_DSMM_RATE_LIMIT_POLICY) {
|
|
43
|
+
return { ...defaults, ...(value === undefined ? {} : normalizeRateLimitOverrides(value)) };
|
|
44
|
+
}
|
|
45
|
+
export function normalizeRuntimePolicy(value = undefined) {
|
|
46
|
+
if (value === undefined)
|
|
47
|
+
return { strategy: "startup-lock", rateLimit: { ...DEFAULT_DSMM_RATE_LIMIT_POLICY } };
|
|
48
|
+
if (!isRecord(value) || Object.keys(value).some((key) => key !== "strategy" && key !== "rateLimit")) {
|
|
49
|
+
throw new TypeError("dsmm runtimePolicy must contain only strategy and rateLimit");
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
strategy: Object.hasOwn(value, "strategy") ? normalizeRoutingStrategy(value.strategy) : "startup-lock",
|
|
53
|
+
rateLimit: normalizeRateLimitPolicy(Object.hasOwn(value, "rateLimit") ? normalizeRateLimitOverrides(value.rateLimit) : undefined)
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function isRecord(value) {
|
|
57
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
58
|
+
}
|
|
59
|
+
const resolvedRoleRuntimePolicies = new WeakMap();
|
|
60
|
+
/** Resolve once per immutable settings admission; omission and explicit [] remain distinct. */
|
|
61
|
+
export function resolveRoleRuntimePolicy(settings, role) {
|
|
62
|
+
let policies = resolvedRoleRuntimePolicies.get(settings);
|
|
63
|
+
if (policies === undefined) {
|
|
64
|
+
policies = new Map();
|
|
65
|
+
resolvedRoleRuntimePolicies.set(settings, policies);
|
|
66
|
+
}
|
|
67
|
+
const existing = policies.get(role);
|
|
68
|
+
if (existing !== undefined)
|
|
69
|
+
return existing;
|
|
70
|
+
const configured = role === undefined ? undefined : settings.roleRouting[role];
|
|
71
|
+
const defaults = settings.runtimePolicy;
|
|
72
|
+
const primary = configured?.primary === undefined ? undefined : Object.freeze({ ...configured.primary });
|
|
73
|
+
const seen = new Set(primary === undefined ? [] : [JSON.stringify([primary.provider, primary.model])]);
|
|
74
|
+
const fallbacks = [];
|
|
75
|
+
for (const route of configured?.fallbackRoutes ?? settings.runtimeRecovery.fallbackRoutes) {
|
|
76
|
+
const identity = JSON.stringify([route.provider, route.model]);
|
|
77
|
+
if (seen.has(identity))
|
|
78
|
+
continue;
|
|
79
|
+
seen.add(identity);
|
|
80
|
+
fallbacks.push(Object.freeze({ ...route }));
|
|
81
|
+
}
|
|
82
|
+
const policy = Object.freeze({
|
|
83
|
+
strategy: configured?.strategy ?? defaults.strategy,
|
|
84
|
+
rateLimit: Object.freeze(normalizeRateLimitPolicy(configured?.rateLimit, defaults.rateLimit)),
|
|
85
|
+
...(primary === undefined ? {} : { primary }),
|
|
86
|
+
fallbackRoutes: Object.freeze(fallbacks),
|
|
87
|
+
fallbackSource: configured?.fallbackRoutes === undefined ? "global" : "role"
|
|
88
|
+
});
|
|
89
|
+
policies.set(role, policy);
|
|
90
|
+
return policy;
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=routing-policy.js.map
|