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