@dsmm/dsmm 0.1.1 → 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.
Files changed (108) hide show
  1. package/README.md +26 -15
  2. package/agent-presets/dsmm-builder/agent.cordis.yml +14 -12
  3. package/agent-presets/dsmm-builder/preset.yml +1 -1
  4. package/agent-presets/dsmm-clarifier/agent.cordis.yml +4 -2
  5. package/agent-presets/dsmm-clarifier/preset.yml +1 -1
  6. package/agent-presets/dsmm-code-search/agent.cordis.yml +4 -2
  7. package/agent-presets/dsmm-code-search/preset.yml +1 -1
  8. package/agent-presets/dsmm-creative/agent.cordis.yml +3 -1
  9. package/agent-presets/dsmm-creative/preset.yml +1 -1
  10. package/agent-presets/dsmm-doc-search/agent.cordis.yml +4 -2
  11. package/agent-presets/dsmm-doc-search/preset.yml +1 -1
  12. package/agent-presets/dsmm-media-reader/agent.cordis.yml +4 -2
  13. package/agent-presets/dsmm-media-reader/preset.yml +1 -1
  14. package/agent-presets/dsmm-oracle/agent.cordis.yml +3 -1
  15. package/agent-presets/dsmm-oracle/preset.yml +1 -1
  16. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +3 -1
  17. package/agent-presets/dsmm-oracle-2nd/preset.yml +1 -1
  18. package/agent-presets/dsmm-orchestrator/agent.cordis.yml +15 -13
  19. package/agent-presets/dsmm-orchestrator/preset.yml +2 -2
  20. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +4 -2
  21. package/agent-presets/dsmm-plan-critic/preset.yml +1 -1
  22. package/agent-presets/dsmm-planner/agent.cordis.yml +4 -2
  23. package/agent-presets/dsmm-planner/preset.yml +1 -1
  24. package/agent-presets/dsmm-reviewer/agent.cordis.yml +4 -2
  25. package/agent-presets/dsmm-reviewer/preset.yml +1 -1
  26. package/docs/agent-presets.md +15 -5
  27. package/docs/compatibility.md +66 -11
  28. package/docs/migration-from-ocmm.md +8 -0
  29. package/docs/model-routing.md +25 -7
  30. package/docs/profiles.md +95 -0
  31. package/docs/releasing.md +66 -19
  32. package/docs/runtime-recovery.md +39 -14
  33. package/docs/settings-status.md +13 -5
  34. package/lib/client/ProfilesSection.d.ts +11 -0
  35. package/lib/client/ProfilesSection.js +66 -0
  36. package/lib/client/SessionProfiles.d.ts +19 -0
  37. package/lib/client/SessionProfiles.js +24 -0
  38. package/lib/client/StructuredEditor.d.ts +11 -0
  39. package/lib/client/StructuredEditor.js +74 -0
  40. package/lib/client/controller.d.ts +115 -0
  41. package/lib/client/controller.js +340 -0
  42. package/lib/client/index.d.ts +13 -0
  43. package/lib/client/index.js +54 -0
  44. package/lib/client/locales.d.ts +145 -0
  45. package/lib/client/locales.js +91 -0
  46. package/lib/client/session-labels.d.ts +8 -0
  47. package/lib/client/session-labels.js +13 -0
  48. package/lib/client/structured.d.ts +18 -0
  49. package/lib/client/structured.js +98 -0
  50. package/lib/client/styles.d.ts +3 -0
  51. package/lib/client/styles.js +36 -0
  52. package/lib/client.js +2825 -0
  53. package/lib/commands.d.ts +3 -3
  54. package/lib/commands.js +5 -4
  55. package/lib/dsh-types.d.ts +20 -0
  56. package/lib/guards.d.ts +2 -2
  57. package/lib/guards.js +3 -2
  58. package/lib/index.d.ts +12 -4
  59. package/lib/index.js +98 -20
  60. package/lib/mode.d.ts +2 -2
  61. package/lib/mode.js +1 -1
  62. package/lib/model-routing.d.ts +2 -2
  63. package/lib/model-routing.js +100 -15
  64. package/lib/preset-registry.js +5 -3
  65. package/lib/profile-remote.d.ts +37 -0
  66. package/lib/profile-remote.js +219 -0
  67. package/lib/profile-rpc.d.ts +35 -0
  68. package/lib/profile-rpc.js +187 -0
  69. package/lib/profile-runtime.d.ts +63 -0
  70. package/lib/profile-runtime.js +310 -0
  71. package/lib/profile-store.d.ts +60 -0
  72. package/lib/profile-store.js +588 -0
  73. package/lib/profile-types.d.ts +80 -0
  74. package/lib/profile-types.js +2 -0
  75. package/lib/profiles.d.ts +26 -0
  76. package/lib/profiles.js +269 -0
  77. package/lib/prompts.d.ts +2 -2
  78. package/lib/prompts.js +4 -4
  79. package/lib/role-providers.d.ts +2 -2
  80. package/lib/role-providers.js +49 -6
  81. package/lib/role-routing.d.ts +37 -3
  82. package/lib/role-routing.js +110 -35
  83. package/lib/role-subagents.d.ts +2 -2
  84. package/lib/role-subagents.js +6 -4
  85. package/lib/roles.d.ts +4 -0
  86. package/lib/roles.js +43 -27
  87. package/lib/routing-policy.d.ts +32 -0
  88. package/lib/routing-policy.js +92 -0
  89. package/lib/runtime-recovery.d.ts +2 -2
  90. package/lib/runtime-recovery.js +215 -54
  91. package/lib/session-metadata.d.ts +13 -0
  92. package/lib/session-metadata.js +34 -0
  93. package/lib/session-persistence.d.ts +35 -0
  94. package/lib/session-persistence.js +304 -0
  95. package/lib/settings.d.ts +34 -1
  96. package/lib/settings.js +33 -7
  97. package/lib/state.d.ts +1 -0
  98. package/lib/state.js +4 -0
  99. package/lib/status.d.ts +9 -1
  100. package/lib/status.js +34 -12
  101. package/locale/en.json +6 -0
  102. package/locale/zh.json +6 -0
  103. package/package.json +66 -15
  104. package/patches/agent-presets-root.example.cordis.patch.yml +6 -10
  105. package/prompts/deepseek-v4-pro.md +1 -1
  106. package/prompts/deepwork.md +3 -3
  107. package/scripts/repair-session-log.mjs +476 -0
  108. package/scripts/session-repair-native-verifier.mjs +367 -0
@@ -0,0 +1,219 @@
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"]);
3
+ const idPattern = /^[a-z0-9][a-z0-9_-]{0,63}$/u;
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;
6
+ /** Shared wire grammar for native codec validation and local form feedback. */
7
+ export function isProfileId(value) {
8
+ return typeof value === "string" && idPattern.test(value)
9
+ && !/^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])$/iu.test(value);
10
+ }
11
+ function fail(field) { throw new TypeError(`Invalid Deepwork profile wire field: ${field}`); }
12
+ function text(value, field, maximum = 1024) {
13
+ if (typeof value !== "string" || value.length > maximum)
14
+ fail(field);
15
+ return value;
16
+ }
17
+ function id(value) {
18
+ const result = text(value, "id", 64);
19
+ if (!isProfileId(result))
20
+ fail("id");
21
+ return result;
22
+ }
23
+ function revision(value) {
24
+ const result = text(value, "revision", 64);
25
+ if (!revisionPattern.test(result))
26
+ fail("revision");
27
+ return result;
28
+ }
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
+ }
63
+ function object(value, required, optional = []) {
64
+ if (value === null || typeof value !== "object" || Array.isArray(value))
65
+ fail("object");
66
+ const result = value;
67
+ if (Object.keys(result).some((key) => !required.includes(key) && !optional.includes(key))
68
+ || required.some((key) => !Object.hasOwn(result, key)))
69
+ fail("object keys");
70
+ return result;
71
+ }
72
+ function optional(value, key, parse) {
73
+ return Object.hasOwn(value, key) ? { [key]: parse(value[key]) } : {};
74
+ }
75
+ function errorInfo(value) {
76
+ const item = object(value, ["code", "message"], ["field"]);
77
+ const code = text(item.code, "code");
78
+ if (!errorCodes.has(code))
79
+ fail("code");
80
+ return { code: code, message: text(item.message, "message", 4096), ...optional(item, "field", (input) => text(input, "field", 256)) };
81
+ }
82
+ function readResult(value) {
83
+ const item = object(value, ["id", "revision", "content"], ["label"]);
84
+ return { id: id(item.id), revision: revision(item.revision), content: content(item.content), ...optional(item, "label", (input) => text(input, "label", 120)) };
85
+ }
86
+ function content(value) {
87
+ const result = text(value, "content", 128 * 1024);
88
+ if (new TextEncoder().encode(result).byteLength > 128 * 1024)
89
+ fail("content");
90
+ return result;
91
+ }
92
+ function snapshot(value) {
93
+ const item = object(value, ["profiles", "selectedId", "appliedRevision", "selectionRevision"], ["selectionError", "roles", "editorDefaults"]);
94
+ if (!Array.isArray(item.profiles) || item.profiles.length > 128)
95
+ fail("profiles");
96
+ return {
97
+ profiles: item.profiles.map((input) => {
98
+ const row = object(input, ["id", "revision"], ["label", "error"]);
99
+ return { id: text(row.id, "id", 64), revision: row.revision === null ? null : revision(row.revision), ...optional(row, "label", (input) => text(input, "label", 120)), ...optional(row, "error", errorInfo) };
100
+ }),
101
+ selectedId: item.selectedId === null ? null : id(item.selectedId),
102
+ appliedRevision: item.appliedRevision === null ? null : revision(item.appliedRevision),
103
+ selectionRevision: item.selectionRevision === "unavailable" && Object.hasOwn(item, "selectionError") ? "unavailable" : selectionRevision(item.selectionRevision),
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),
167
+ };
168
+ }
169
+ function saveRequest(value) {
170
+ const item = object(value, ["id", "content", "expectedRevision"]);
171
+ return { id: id(item.id), content: content(item.content), expectedRevision: item.expectedRevision === null ? null : revision(item.expectedRevision) };
172
+ }
173
+ function selectRequest(value) {
174
+ const item = object(value, ["id", "expectedSelectionRevision"], ["expectedRevision"]);
175
+ const result = { id: item.id === null ? null : id(item.id), expectedSelectionRevision: selectionRevision(item.expectedSelectionRevision), ...optional(item, "expectedRevision", revision) };
176
+ if (result.id !== null && result.expectedRevision === undefined)
177
+ fail("expectedRevision");
178
+ if (result.id === null && result.expectedRevision !== undefined)
179
+ fail("expectedRevision");
180
+ return result;
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
+ }
187
+ function codec(symbol, parse) {
188
+ return { mode: "strict", typeSymbol: `@dsmm/dsmm#${symbol}`, create: () => ({ parse }) };
189
+ }
190
+ function descriptor(method, result, parameter) {
191
+ return { id: `@dsmm/dsmm#dsmmProfiles/${method}`, service: "dsmmProfiles", namespace: "dsmmProfiles", method, invocation: { kind: "direct" }, parameters: parameter === undefined ? [] : [{ name: parameter.name, wire: parameter.name, source: "json", codec: parameter.codec }], result };
192
+ }
193
+ /** Explicit strict Host contract; no SRC fallback or browser-supplied authority. */
194
+ export const TYPERT_REMOTE = {
195
+ package: "@dsmm/dsmm",
196
+ descriptors: [
197
+ descriptor("describe", codec("ProfileSnapshot", snapshot)),
198
+ descriptor("read", codec("ProfileReadResult", readResult), { name: "id", codec: codec("ProfileId", id) }),
199
+ descriptor("save", codec("ProfileReadResult", readResult), { name: "request", codec: codec("ProfileSaveRequest", saveRequest) }),
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
+ },
212
+ ],
213
+ };
214
+ export const TYPERT_HOST = {
215
+ package: "@dsmm/dsmm", face: "host", schemas: [],
216
+ model: { services: [], events: [], objects: [] }, invocations: TYPERT_REMOTE.descriptors,
217
+ };
218
+ export default TYPERT_REMOTE;
219
+ //# sourceMappingURL=profile-remote.js.map
@@ -0,0 +1,35 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
3
+ import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSnapshot, SessionProfileSelectRequest, SessionProfileSnapshot } from "./profile-types.js";
4
+ import type { DshAgent } from "./dsh-types.js";
5
+ export interface ProfilesBackend {
6
+ describe(): Promise<ProfileSnapshot>;
7
+ read(id: string): Promise<ProfileReadResult>;
8
+ save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
9
+ select(request: ProfileSelectRequest): Promise<ProfileSnapshot>;
10
+ getSession(agent: DshAgent): Promise<SessionProfileSnapshot>;
11
+ selectSession(request: SessionProfileSelectRequest, capturedAgent: DshAgent, signal?: AbortSignal, assertAuthority?: () => void): Promise<SessionProfileSnapshot>;
12
+ }
13
+ /** Business service addressed only by native Typert Gateway invocations. */
14
+ export declare class DsmmProfilesHost extends TypertRemoteService {
15
+ readonly backend: ProfilesBackend;
16
+ private readonly lifetime;
17
+ constructor(ctx: Context, backend: ProfilesBackend);
18
+ private invoke;
19
+ describe(): Promise<ProfileSnapshot>;
20
+ read(id: string): Promise<ProfileReadResult>;
21
+ save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
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>;
27
+ }
28
+ declare module "@deepseek-ai/cordis" {
29
+ interface Context {
30
+ dsmmProfiles: DsmmProfilesHost;
31
+ }
32
+ }
33
+ /** The caller supplies the owned injection fiber; withdrawal stays native. */
34
+ export declare function registerProfilesRpc(ctx: Context, backend: ProfilesBackend): DsmmProfilesHost;
35
+ //# sourceMappingURL=profile-rpc.d.ts.map
@@ -0,0 +1,187 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
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";
38
+ import { TYPERT_HOST } from "./profile-remote.js";
39
+ import { DsmmProfileError, profileErrorInfo } from "./profiles.js";
40
+ /** Business service addressed only by native Typert Gateway invocations. */
41
+ let DsmmProfilesHost = (() => {
42
+ let _classSuper = TypertRemoteService;
43
+ let _instanceExtraInitializers = [];
44
+ let _describe_decorators;
45
+ let _read_decorators;
46
+ let _save_decorators;
47
+ let _select_decorators;
48
+ let _describeSession_decorators;
49
+ let _selectSession_decorators;
50
+ return class DsmmProfilesHost extends _classSuper {
51
+ static {
52
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
53
+ _describe_decorators = [Remote];
54
+ _read_decorators = [Remote];
55
+ _save_decorators = [Remote];
56
+ _select_decorators = [Remote];
57
+ _describeSession_decorators = [Remote];
58
+ _selectSession_decorators = [Remote];
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);
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);
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);
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);
65
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
66
+ }
67
+ backend = __runInitializers(this, _instanceExtraInitializers);
68
+ lifetime = new AbortController();
69
+ constructor(ctx, backend) {
70
+ super(ctx, "dsmmProfiles");
71
+ this.backend = backend;
72
+ ctx.effect(() => () => this.lifetime.abort(), "dsmmProfiles: cancel scoped operations");
73
+ }
74
+ async invoke(operation) {
75
+ const invocation = this.ctx.invocation;
76
+ if (invocation === undefined || invocation.peer === undefined) {
77
+ throw new RemoteError("dsmm-profiles/peer-required", "Use Deepwork Profiles through the native Host connection.", {});
78
+ }
79
+ invocation.signal.throwIfAborted();
80
+ try {
81
+ return await operation();
82
+ }
83
+ catch (error) {
84
+ throw new RemoteError("dsmm-profiles/refused", "The Host refused the profile operation.", profileErrorInfo(error));
85
+ }
86
+ }
87
+ describe() { return this.invoke(() => this.backend.describe()); }
88
+ read(id) { return this.invoke(() => this.backend.read(id)); }
89
+ save(request) { return this.invoke(() => this.backend.save(request)); }
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
+ }
178
+ };
179
+ })();
180
+ export { DsmmProfilesHost };
181
+ /** The caller supplies the owned injection fiber; withdrawal stays native. */
182
+ export function registerProfilesRpc(ctx, backend) {
183
+ const service = new DsmmProfilesHost(ctx, backend);
184
+ ctx.typert.register(TYPERT_HOST);
185
+ return service;
186
+ }
187
+ //# sourceMappingURL=profile-rpc.js.map
@@ -0,0 +1,63 @@
1
+ import type { DshAgent, DshContext } from "./dsh-types.js";
2
+ import type { LoadedProfileSelection, LoadedSessionProfileSelection, SessionProfileCommit } from "./profile-store.js";
3
+ import type { ProfileReadResult, ProfileSaveRequest, ProfileSelectRequest, ProfileSelectionState, ProfileSnapshot, SessionProfileSelectRequest, SessionProfileSnapshot } from "./profile-types.js";
4
+ import type { DsmmProfileDocument } from "./profiles.js";
5
+ import type { DsmmProfileAdmission, DsmmSettings, DsmmSettingsGetter } from "./settings.js";
6
+ export interface DsmmProfileRuntimeStore {
7
+ loadSelection(): Promise<LoadedProfileSelection>;
8
+ describe(): Promise<ProfileSnapshot>;
9
+ read(id: string): Promise<ProfileReadResult>;
10
+ save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
11
+ select<T>(request: ProfileSelectRequest, validateCandidate: (document: DsmmProfileDocument | null) => T | Promise<T>): Promise<{
12
+ selection: ProfileSelectionState;
13
+ prepared: T;
14
+ }>;
15
+ loadSessionSelection(sessionId: string): Promise<LoadedSessionProfileSelection>;
16
+ selectSession<T>(request: SessionProfileSelectRequest, epoch: string, validateCandidate: (document: DsmmProfileDocument | null) => T | Promise<T>, commit: SessionProfileCommit<T>): Promise<{
17
+ selection: LoadedSessionProfileSelection;
18
+ prepared: T;
19
+ }>;
20
+ }
21
+ export interface DsmmProfileRuntimeOptions {
22
+ /** Trusted test/integration seam, never a wire-supplied path or callback. */
23
+ validateCandidate?: (settings: DsmmSettings) => void | Promise<void>;
24
+ }
25
+ interface AdmittedProfile extends ProfileSelectionState, DsmmProfileAdmission {
26
+ }
27
+ /** Global defaults admit new roots; scoped idle switches replace one root's epoch. */
28
+ export declare class DsmmProfileRuntime {
29
+ private readonly ctx;
30
+ private readonly store;
31
+ private readonly options;
32
+ readonly getSettings: DsmmSettingsGetter;
33
+ private current;
34
+ private readonly baseline;
35
+ private readonly bound;
36
+ private readonly admitting;
37
+ private readonly disposedAgents;
38
+ private readonly switching;
39
+ private disposed;
40
+ private selectionQueue;
41
+ constructor(ctx: DshContext, baseline: DsmmSettings, store: DsmmProfileRuntimeStore, options?: DsmmProfileRuntimeOptions);
42
+ initialize(): Promise<void>;
43
+ admission(agent?: DshAgent): AdmittedProfile;
44
+ getSession(agent: DshAgent): Promise<SessionProfileSnapshot>;
45
+ /** The fourth argument is trusted native caller authority, never wire data. */
46
+ selectSession(request: SessionProfileSelectRequest, agent: DshAgent, signal?: AbortSignal, assertAuthority?: () => void): Promise<SessionProfileSnapshot>;
47
+ describe(): Promise<ProfileSnapshot>;
48
+ read(id: string): Promise<ProfileReadResult>;
49
+ save(request: ProfileSaveRequest): Promise<ProfileReadResult>;
50
+ select(request: ProfileSelectRequest): Promise<ProfileSnapshot>;
51
+ private prepare;
52
+ private profileAdmission;
53
+ private agents;
54
+ private bind;
55
+ private owner;
56
+ private assertRoot;
57
+ private admit;
58
+ private validate;
59
+ }
60
+ /** No guessed home fallback: native deployment context owns this directory. */
61
+ export declare function createProfileRuntime(ctx: DshContext, baseline: DsmmSettings): Promise<DsmmProfileRuntime>;
62
+ export {};
63
+ //# sourceMappingURL=profile-runtime.d.ts.map