@dsmm/dsmm 0.2.2 → 0.3.0

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 (61) hide show
  1. package/README.md +8 -10
  2. package/cordis.patch.yml +14 -0
  3. package/docs/agent-presets.md +4 -4
  4. package/docs/compatibility.md +19 -24
  5. package/docs/deferred-native-approval-risk.md +2 -2
  6. package/docs/model-routing.md +3 -3
  7. package/docs/profiles.md +1 -1
  8. package/docs/releasing.md +46 -6
  9. package/docs/settings-status.md +2 -2
  10. package/lib/agent-registry.d.ts +36 -0
  11. package/lib/agent-registry.js +75 -0
  12. package/lib/child-admission.d.ts +0 -2
  13. package/lib/child-admission.js +13 -24
  14. package/lib/child-capture.d.ts +5 -1
  15. package/lib/child-capture.js +7 -5
  16. package/lib/client/children-locales.d.ts +13 -13
  17. package/lib/client/deployment-controller.js +1 -1
  18. package/lib/client.js +3 -3
  19. package/lib/delivery-authority.d.ts +18 -3
  20. package/lib/delivery-authority.js +149 -12
  21. package/lib/index.d.ts +2 -2
  22. package/lib/index.js +13 -26
  23. package/lib/native-child-evidence.d.ts +1 -3
  24. package/lib/native-child-evidence.js +0 -29
  25. package/lib/permission-rpc.js +3 -3
  26. package/lib/profile-rpc.js +6 -4
  27. package/lib/profile-store.js +2 -2
  28. package/lib/role-control-rpc.js +12 -8
  29. package/lib/role-invocation.d.ts +1 -1
  30. package/lib/role-policy.d.ts +1 -4
  31. package/lib/role-policy.js +24 -41
  32. package/lib/role-providers.d.ts +1 -1
  33. package/lib/role-providers.js +15 -55
  34. package/lib/role-runs.d.ts +17 -14
  35. package/lib/role-runs.js +45 -14
  36. package/lib/role-subagents.js +16 -6
  37. package/lib/runtime-integration.d.ts +4 -35
  38. package/lib/runtime-integration.js +38 -120
  39. package/lib/session-persistence.d.ts +2 -1
  40. package/lib/session-persistence.js +1 -1
  41. package/lib/session-scope.js +4 -1
  42. package/lib/subagent-runtime.d.ts +19 -7
  43. package/lib/subagent-runtime.js +141 -15
  44. package/package.json +110 -100
  45. package/lib/legacy-child-policy.d.ts +0 -51
  46. package/lib/legacy-child-policy.js +0 -123
  47. package/lib/legacy-read-composition.d.ts +0 -20
  48. package/lib/legacy-read-composition.js +0 -144
  49. package/lib/legacy-read-contracts.d.ts +0 -157
  50. package/lib/legacy-read-contracts.js +0 -39
  51. package/lib/legacy-read-host.d.ts +0 -19
  52. package/lib/legacy-read-host.js +0 -67
  53. package/lib/legacy-read-integration.d.ts +0 -121
  54. package/lib/legacy-read-integration.js +0 -522
  55. package/lib/legacy-read-proxy.d.ts +0 -26
  56. package/lib/legacy-read-proxy.js +0 -237
  57. package/scripts/cold-profile-composition.mjs +0 -329
  58. package/scripts/cold-profile-sources.mjs +0 -238
  59. package/scripts/migrate-cold-profile.mjs +0 -315
  60. package/scripts/repair-session-log.mjs +0 -476
  61. package/scripts/session-repair-native-verifier.mjs +0 -367
@@ -1,237 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { isAbsolute } from "node:path";
3
- import { isDeepStrictEqual } from "node:util";
4
- import { HarnessError, ToolCallId } from "@deepseek-ai/dsh-llm";
5
- import { createScope } from "@deepseek-ai/dsh-scope";
6
- import { assertLegacyReadBindings } from "./legacy-read-composition.js";
7
- import { isLegacyReadCallLease, LegacyReadUnavailable } from "./legacy-read-contracts.js";
8
- export function installLegacyReadProxy(composition, parent, child, evidence, nativeDefinition) {
9
- if (["ready", "disposed"].includes(composition.view().state) || composition.view().activeCalls)
10
- throw new LegacyReadUnavailable("composition-unavailable");
11
- if (nativeDefinition.name !== "read" || parent.ctx.tools.get("read", parent) !== nativeDefinition)
12
- throw new LegacyReadUnavailable("provenance-unavailable");
13
- const standingScope = createScope(child.ctx, child);
14
- const proxyScope = createScope(child.ctx, child);
15
- const calls = new Map();
16
- let removed = false;
17
- const openTurnStart = (agent) => agent.ctx.get("sessionProjections")?.stateOf(agent.session, "turnBoundary")?.openTurnStartSeq;
18
- const assertContext = (call) => {
19
- const context = call.context;
20
- if (context === undefined)
21
- throw new LegacyReadUnavailable("audit-unavailable");
22
- context.assertAvailable();
23
- if (context.approval.kind !== call.lease.approval)
24
- throw new LegacyReadUnavailable("approval-unavailable");
25
- if (context.approval.kind === "coordinated-turn") {
26
- const approval = context.approval;
27
- if (approval.turn.parent !== parent || openTurnStart(parent) == null || approval.turn.openTurnStartSeq !== openTurnStart(parent)
28
- || approval.signal.aborted)
29
- throw new LegacyReadUnavailable("approval-unavailable");
30
- if (approval.childTurn !== undefined && (approval.childTurn.child !== child || openTurnStart(child) == null
31
- || approval.childTurn.openTurnStartSeq !== openTurnStart(child) || approval.childTurn.signal.aborted))
32
- throw new LegacyReadUnavailable("approval-unavailable");
33
- }
34
- };
35
- const callSignal = (exec, call) => AbortSignal.any([exec.signal, call.lease.signal,
36
- ...(call.context === undefined ? [] : [call.context.signal]),
37
- ...(call.context?.approval.kind === "coordinated-turn" ? [call.context.approval.signal,
38
- ...(call.context.approval.childTurn === undefined ? [] : [call.context.approval.childTurn.signal])] : [])]);
39
- const definition = {
40
- name: "read", description: nativeDefinition.description, parameters: nativeDefinition.parameters,
41
- output: { schema: nativeDefinition.output.schema, render: (args, value) => nativeDefinition.output.render(args, value) },
42
- isConcurrencySafe: () => true,
43
- async execute(args, exec) {
44
- const call = calls.get(exec.token);
45
- if (call === undefined || call.invoked || removed)
46
- throw new LegacyReadUnavailable("lifetime-unavailable");
47
- call.invoked = true;
48
- const { lease } = call;
49
- lease.assertActive();
50
- assertContext(call);
51
- const signal = callSignal(exec, call);
52
- signal.throwIfAborted();
53
- const binding = composition.owner.resolveReadBindings(parent, child, lease);
54
- assertLegacyReadBindings(lease, binding);
55
- if (args === null || typeof args !== "object" || Array.isArray(args))
56
- throw new LegacyReadUnavailable("arguments-unavailable");
57
- const row = args;
58
- if (Reflect.ownKeys(row).some(key => !["file_path", "offset", "limit"].includes(String(key)))
59
- || typeof row.file_path !== "string" || !row.file_path.trim() || row.file_path.includes("\0")
60
- || [row.offset, row.limit].some(value => value !== undefined && (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1))
61
- || (typeof row.limit === "number" && row.limit > binding.caps.limit))
62
- throw new LegacyReadUnavailable("arguments-unavailable");
63
- const target = await binding.childFs.resolve(row.file_path, { cwd: child.session.header.cwd, signal });
64
- lease.assertActive();
65
- signal.throwIfAborted();
66
- const hostPath = binding.childFs.processPath(target);
67
- const mapped = binding.parentFs.processPathFromHostPath(hostPath);
68
- if (!isAbsolute(hostPath) || mapped === undefined || !isAbsolute(mapped))
69
- throw new LegacyReadUnavailable("target-unavailable");
70
- const parentTarget = await binding.parentFs.resolve(mapped, { cwd: parent.session.header.cwd, signal });
71
- lease.assertActive();
72
- signal.throwIfAborted();
73
- if (target.targetKey === undefined || target.targetKey !== parentTarget.targetKey)
74
- throw new LegacyReadUnavailable("target-unavailable");
75
- assertLegacyReadBindings(lease, composition.owner.resolveReadBindings(parent, child, lease));
76
- assertContext(call);
77
- signal.throwIfAborted();
78
- const callId = ToolCallId(`legacy-read:${randomUUID()}`);
79
- call.parentExecution = { callId, rootCallId: exec.rootCallId, parent: exec.token };
80
- const result = await parent.ctx.tools.execute({ agent: parent, name: "read", arguments: { ...row, file_path: mapped },
81
- parent: exec.token, rootCallId: exec.rootCallId, callId, signal });
82
- call.parentResult = result;
83
- // Native execution has already settled. Never reclassify it using a newer epoch.
84
- if (result.isError) {
85
- const error = new HarnessError(result.error.message, result.error.info?.code ?? "LEGACY_READ_FAILED");
86
- if (result.error.info !== undefined)
87
- error.name = result.error.info.name;
88
- call.transport = { isError: true, error: { message: error.message, info: { name: error.name, code: error.code } },
89
- content: [{ type: "text", text: `Error: ${error.message}` }] };
90
- throw error;
91
- }
92
- if (result.concludesTurn)
93
- exec.concludeTurn();
94
- call.transport = { isError: false, value: result.value, content: definition.output.render(args, result.value),
95
- ...(result.concludesTurn ? { concludesTurn: true } : {}) };
96
- return result.value;
97
- },
98
- projectContent(exec, result) {
99
- const call = calls.get(exec.token);
100
- // This runs BEFORE child post policy, and never replaces a later transformation.
101
- return call?.projectionOutcome !== undefined && call.parentResult !== undefined && isDeepStrictEqual(result, call.projectionOutcome)
102
- ? call.parentResult.content : undefined;
103
- },
104
- };
105
- const standingGuard = exec => exec.name !== "read" || exec.agent !== child ? undefined
106
- : removed || !calls.has(exec.token) || child.ctx.tools.get("read", child) !== definition
107
- || calls.get(exec.token).lease.signal.aborted ? "Legacy read requires an active child-local operation lease" : undefined;
108
- standingScope.ctx.tools.guard(standingGuard);
109
- // The standing listener outlives the proxy so native completion always retires acquired leases.
110
- const onResult = (exec, childResult) => {
111
- const call = calls.get(exec.token);
112
- if (call === undefined)
113
- return;
114
- calls.delete(exec.token);
115
- const outcomes = { childExecution: exec, childResult,
116
- ...(call.parentExecution === undefined ? {} : { parentExecution: call.parentExecution }),
117
- ...(call.parentResult === undefined ? {} : { parentResult: call.parentResult }) };
118
- const reportFault = (error) => {
119
- void composition.closeForChange("audit-fault");
120
- try {
121
- composition.owner.reportAuditFault(error, outcomes);
122
- }
123
- catch (reportError) {
124
- standingScope.ctx.logger.warn("Legacy read audit fault reporter failed", reportError);
125
- }
126
- };
127
- void (async () => {
128
- try {
129
- if (call.context !== undefined)
130
- await call.context.finish(outcomes);
131
- }
132
- catch (error) {
133
- reportFault(error);
134
- }
135
- finally {
136
- try {
137
- call.context?.release();
138
- }
139
- catch (error) {
140
- reportFault(error);
141
- }
142
- finally {
143
- call.lease.release();
144
- }
145
- }
146
- })();
147
- };
148
- standingScope.ctx.on("tools/result", onResult);
149
- const preExecute = async (exec, next) => {
150
- if (exec.agent !== child || exec.name !== "read")
151
- return next();
152
- let signal = exec.signal;
153
- const unavailable = (error) => signal.aborted ? { kind: "cancel" }
154
- : { kind: "deny", reason: "Legacy read operation unavailable", info: { name: "LegacyReadUnavailable",
155
- code: error instanceof LegacyReadUnavailable ? error.code : "lifetime-unavailable" } };
156
- let call;
157
- try {
158
- const lease = composition.acquireLease(parent, child, evidence, exec.signal);
159
- call = { lease, invoked: false };
160
- calls.set(exec.token, call);
161
- signal = callSignal(exec, call);
162
- const context = await composition.owner.acquireCallContext(parent, child, exec, lease);
163
- if (!isLegacyReadCallLease(context))
164
- throw new LegacyReadUnavailable("audit-unavailable");
165
- call.context = context;
166
- signal = callSignal(exec, call);
167
- lease.assertActive();
168
- assertContext(call);
169
- signal.throwIfAborted();
170
- }
171
- catch (error) {
172
- return unavailable(error);
173
- }
174
- // Downstream exceptions remain native final-errors, and terminal decisions remain authoritative.
175
- const decision = await next();
176
- if (decision.kind === "deny" || decision.kind === "cancel")
177
- return decision;
178
- try {
179
- signal = callSignal(exec, call);
180
- call.lease.assertActive();
181
- assertContext(call);
182
- signal.throwIfAborted();
183
- // This pre-only adapter cannot prove the original child caller includes these lifetimes.
184
- // Parent approval instead receives a merged public execute input from the proxy body.
185
- if (decision.kind === "ask")
186
- throw new LegacyReadUnavailable("approval-unavailable");
187
- }
188
- catch (error) {
189
- return unavailable(error);
190
- }
191
- return decision;
192
- };
193
- proxyScope.ctx.on("tools/pre-execute", preExecute, { prepend: true });
194
- const complete = async (exec, next) => {
195
- const call = calls.get(exec.token);
196
- if (call === undefined)
197
- return next();
198
- const originalSignal = exec.signal;
199
- exec.signal = callSignal(exec, call);
200
- try {
201
- const downstream = await next();
202
- if (call.transport !== undefined && call.parentResult !== undefined && isDeepStrictEqual(downstream, call.transport)) {
203
- call.projectionOutcome = call.parentResult.isError ? call.parentResult : { ...call.transport,
204
- ...(call.parentResult.additionalContexts === undefined ? {} : { additionalContexts: call.parentResult.additionalContexts }) };
205
- return call.parentResult;
206
- }
207
- return downstream;
208
- }
209
- finally {
210
- exec.signal = originalSignal;
211
- }
212
- };
213
- proxyScope.ctx.on("tools/execute", complete, { prepend: true });
214
- proxyScope.ctx.tools.register(definition);
215
- return { parent, child, definition, nativeDefinition, proxyScope, standingScope,
216
- contributions: Object.freeze([
217
- { stage: "pre", scope: proxyScope, reference: preExecute, order: 0 },
218
- { stage: "guard", scope: standingScope, reference: standingGuard, order: 0 },
219
- { stage: "around", scope: proxyScope, reference: complete, order: 0 },
220
- { stage: "project", scope: proxyScope, reference: definition.projectContent, order: 0 },
221
- { stage: "finalization", scope: standingScope, reference: onResult, order: 0 },
222
- ]),
223
- async removeProxy() {
224
- if (composition.view().state === "ready" || composition.view().activeCalls)
225
- throw new LegacyReadUnavailable("composition-unavailable");
226
- removed = true;
227
- await proxyScope.dispose();
228
- },
229
- async releaseAfterChildDispose() {
230
- if (child.ctx.get("agents")?.get(child.id) === child || composition.view().activeCalls)
231
- throw new LegacyReadUnavailable("lifetime-unavailable");
232
- removed = true;
233
- await proxyScope.dispose();
234
- await standingScope.dispose();
235
- }, };
236
- }
237
- //# sourceMappingURL=legacy-read-proxy.js.map
@@ -1,329 +0,0 @@
1
- import { dirname, extname, isAbsolute, join, relative, sep } from "node:path";
2
- import { createRequire } from "node:module";
3
- import { existsSync } from "node:fs";
4
- import { fileURLToPath, pathToFileURL } from "node:url";
5
- import { isDeepStrictEqual } from "node:util";
6
- import { SourceReadset, jsonDocument, refuse } from "./cold-profile-sources.mjs";
7
-
8
- export const BASE_BUNDLE = "@deepseek-ai/dsh-base";
9
- export const MODULE_REPLACEMENTS = Object.freeze({
10
- "@deepseek-ai/dsh-settings": "@dsmm/dsmm/managed-settings",
11
- "@deepseek-ai/dsh-llm": "@dsmm/dsmm/llm-runtime",
12
- "@deepseek-ai/dsh-subagent": "@dsmm/dsmm/subagent-runtime",
13
- "@deepseek-ai/dsh-session-persistence-jsonl": "@dsmm/dsmm/session-persistence",
14
- "@deepseek-ai/dsh-tool-bash": "@dsmm/dsmm/permission-bash",
15
- "@deepseek-ai/dsh-tool-pwsh": "@dsmm/dsmm/permission-pwsh",
16
- "@deepseek-ai/dsh-tool-fs": "@dsmm/dsmm/permission-fs",
17
- "@deepseek-ai/dsh-tool-fs-search": "@dsmm/dsmm/permission-fs-search",
18
- "@deepseek-ai/dsh-tool-web": "@dsmm/dsmm/permission-web",
19
- });
20
- const nativeToolIds = new Map([
21
- ["@deepseek-ai/dsh-tool-fs", "tool-fs"],
22
- ["@deepseek-ai/dsh-tool-fs-search", "tool-fs-search"],
23
- ["@deepseek-ai/dsh-tool-web", "tool-web"],
24
- ]);
25
- const projectedNativeTools = new Set([...nativeToolIds.keys()].map(name => MODULE_REPLACEMENTS[name]));
26
- const nativeGroups = new Set(["cordis:group", "@deepseek-ai/cordis-plugin-group"]);
27
- const nativeIncludes = new Set(["cordis:include", "@deepseek-ai/cordis-plugin-include"]);
28
- const officialLoop = "@deepseek-ai/dsh-agent-loop";
29
- const officialPiAi = "@deepseek-ai/dsh-llm-pi-ai";
30
- const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
31
- const under = (root, filename) => {
32
- const path = relative(root, filename);
33
- return path === "" || (!path.startsWith(`..${sep}`) && path !== ".." && !isAbsolute(path));
34
- };
35
-
36
- function entryWalk(rows, visit) {
37
- if (!Array.isArray(rows)) refuse("UNSUPPORTED_ENTRY_TREE");
38
- for (const row of rows) {
39
- if (!object(row) || typeof row.name !== "string") refuse("UNSUPPORTED_ENTRY_TREE");
40
- visit(row);
41
- if (nativeGroups.has(row.name)) entryWalk(row.config, visit);
42
- else if (row.group) refuse("UNSUPPORTED_GROUP_CARRIER");
43
- }
44
- }
45
-
46
- /** Mutates only approved, original base insertion declarations, never selector names. */
47
- function projectBase(patches, { migrateShell, migrateSubagent, migrateSessionPersistence }) {
48
- patches = structuredClone(patches);
49
- const changed = new Map();
50
- for (const patch of patches) {
51
- if (!patch.insert) continue;
52
- entryWalk(patch.insert, row => {
53
- if (row.name === "@deepseek-ai/dsh-llm") {
54
- if (row.id !== "llm" || changed.has(row.id)) refuse("AMBIGUOUS_BASE_LLM");
55
- } else if (row.name === "@deepseek-ai/dsh-settings") {
56
- if (row.id !== "settings" || changed.has(row.id)) refuse("AMBIGUOUS_BASE_SETTINGS");
57
- } else if (row.name === "@deepseek-ai/dsh-subagent") {
58
- if (!migrateSubagent) return;
59
- if (row.id !== "subagent" || changed.has(row.id)) refuse("AMBIGUOUS_BASE_SUBAGENT");
60
- } else if (row.name === "@deepseek-ai/dsh-session-persistence-jsonl") {
61
- if (!migrateSessionPersistence) return;
62
- if (row.id !== "session-persistence-jsonl" || changed.has(row.id)) refuse("AMBIGUOUS_BASE_SESSION_PERSISTENCE");
63
- } else if (nativeToolIds.has(row.name)) {
64
- if (row.id !== nativeToolIds.get(row.name)) refuse("AMBIGUOUS_BASE_NATIVE_TOOL");
65
- } else if (!migrateShell || !["@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-pwsh"].includes(row.name)) return;
66
- if (typeof row.id !== "string" || changed.has(row.id)) refuse("AMBIGUOUS_BASE_ENTRY");
67
- const name = MODULE_REPLACEMENTS[row.name];
68
- changed.set(row.id, { original: row.name, replacement: name });
69
- row.name = name;
70
- });
71
- }
72
- if (!changed.has("llm")) refuse("ORIGINAL_BASE_LLM_REQUIRED");
73
- if (!changed.has("settings")) refuse("ORIGINAL_BASE_SETTINGS_REQUIRED");
74
- if (migrateSubagent && !changed.has("subagent")) refuse("ORIGINAL_BASE_SUBAGENT_REQUIRED");
75
- if (migrateSessionPersistence && !changed.has("session-persistence-jsonl")) refuse("ORIGINAL_BASE_SESSION_PERSISTENCE_REQUIRED");
76
- return { patches, changed };
77
- }
78
-
79
- function compose(boot, lists) {
80
- const warnings = [];
81
- const rows = boot.composeEntries(lists, warning => warnings.push(warning));
82
- return { rows, warnings };
83
- }
84
-
85
- function expectedRows(rows, changed) {
86
- const expected = structuredClone(rows);
87
- const seen = new Set();
88
- entryWalk(expected, row => {
89
- const change = changed.get(row.id);
90
- if (!change) return;
91
- if (seen.has(row.id) || row.name !== change.original) refuse("ALTERNATE_ENTRY_OWNER");
92
- seen.add(row.id);
93
- row.name = change.replacement;
94
- });
95
- if (seen.size !== changed.size) refuse("MIGRATED_ENTRY_MISSING");
96
- return expected;
97
- }
98
-
99
- function assertSelectorSemantics(composeAll, original, projected) {
100
- const originalPatches = original.flat();
101
- const projectedPatches = projected.flat();
102
- // Prefix composition retains the SDK's single-pass patch index and detects
103
- // changed match/skip decisions even when later patches mask their final values.
104
- for (let count = 1; count <= originalPatches.length; count++) {
105
- if (composeAll([originalPatches.slice(0, count)]).warnings.length !== composeAll([projectedPatches.slice(0, count)]).warnings.length) refuse("SELECTOR_SEMANTICS_CHANGED");
106
- }
107
- }
108
-
109
- function llmRealm(row, inherited, position) {
110
- if (row.intercept?.llm != null) refuse("UNSUPPORTED_LLM_TOPOLOGY");
111
- if (!Object.hasOwn(row.isolate ?? {}, "llm")) return inherited;
112
- const label = row.isolate.llm;
113
- if (label == null || label === "") return "root";
114
- if (label === true) return `local:${position}`;
115
- if (typeof label === "string") return `named:${label}`;
116
- refuse("UNSUPPORTED_LLM_TOPOLOGY");
117
- }
118
-
119
- /** All declarations participate, including disabled/expression-gated rows; this is not activation proof. */
120
- function assertLlmTopology(topology) {
121
- if (topology.owners.length !== 1) refuse("ALTERNATE_LLM_OWNER");
122
- if (topology.loops.length !== 1) refuse("OFFICIAL_AGENT_LOOP_REQUIRED");
123
- const ownerRealm = topology.owners[0];
124
- if ([...topology.loops, ...topology.providers, ...topology.consumers].some(realm => realm !== ownerRealm)) refuse("LLM_REALM_MISMATCH");
125
- }
126
-
127
- function dormantModule(row, options, readset, disabledBaseURL) {
128
- if (!disabledBaseURL || row.group || !object(row.disabled) || typeof row.disabled.__jsExpr !== "string") return false;
129
- const declarations = [
130
- ["dsh-tui-code-runtime", "@deepseek-ai/dsh-code-runtime-worker-thread", "@deepseek-ai/dsh-ptc-runtime-node", "code-runtime"],
131
- ["dsh-tui-agent-presets", "@deepseek-ai/dsh-agent-presets", "@deepseek-ai/dsh-agent-preset-registry", "agent-presets"],
132
- ];
133
- for (const [id, name, capability, official] of declarations) {
134
- if (row.id !== id || row.name !== name) continue;
135
- const expression = `(() => {
136
- const require = process.getBuiltinModule('node:module').createRequire(ctx.baseUrl)
137
- try { require.resolve('${capability}/package.json'); return true } catch {}
138
- return [...ctx.loader.entries()].some(entry => entry.options.id === '${official}' && entry.options.name === '${name}' && !entry.disabled)
139
- })()`;
140
- if (row.disabled.__jsExpr.trim() !== expression) return false;
141
- return readset.dormantCapability(options, disabledBaseURL, `${capability}/package.json`);
142
- }
143
- return false;
144
- }
145
-
146
- /** Native groups inherit context; native includes keep their own patch index and source base. */
147
- function inspectTrees(rows, options, sdk, readset, baseURL, {
148
- ancestors = new Set(), root = true, ids = new Set(), inheritedRealm = "root", prefix = "root",
149
- topology = { owners: [], loops: [], providers: [], consumers: [] },
150
- nativeToolSelection = { projected: [], unprojected: [] },
151
- disabledBaseURL,
152
- } = {}) {
153
- if (!Array.isArray(rows)) refuse("UNSUPPORTED_ENTRY_TREE");
154
- for (const [index, row] of rows.entries()) {
155
- if (!object(row) || typeof row.name !== "string") refuse("UNSUPPORTED_ENTRY_TREE");
156
- const position = `${prefix}/${index}`;
157
- const slot = { path: position, ...(row.id ? { id: row.id } : {}), name: row.name };
158
- if (nativeToolIds.has(row.name)) nativeToolSelection.unprojected.push(slot);
159
- else if (projectedNativeTools.has(row.name)) nativeToolSelection.projected.push(slot);
160
- if (row.id) {
161
- if (ids.has(row.id)) refuse("DUPLICATE_ENTRY_ID");
162
- ids.add(row.id);
163
- }
164
- if ((row.name === "@deepseek-ai/dsh-llm" || row.name === MODULE_REPLACEMENTS["@deepseek-ai/dsh-llm"]) && (!root || row.id !== "llm")) refuse("ALTERNATE_LLM_OWNER");
165
- if ((row.id === "llm" || row.name.endsWith("/llm-runtime")) && row.name !== "@deepseek-ai/dsh-llm" && row.name !== MODULE_REPLACEMENTS["@deepseek-ai/dsh-llm"]) refuse("ALTERNATE_LLM_OWNER");
166
- if (typeof row.inject !== "undefined" && row.inject !== null && !Array.isArray(row.inject) && !object(row.inject)) refuse("UNSUPPORTED_SCOPE_METADATA");
167
- for (const key of ["isolate", "intercept"]) {
168
- if (row[key] !== undefined && row[key] !== null && (!object(row[key]) || row[key].__jsExpr)) refuse("UNSUPPORTED_SCOPE_METADATA");
169
- }
170
- const realm = llmRealm(row, inheritedRealm, position);
171
- if (row.name === "@deepseek-ai/dsh-llm" || row.name === MODULE_REPLACEMENTS["@deepseek-ai/dsh-llm"]) topology.owners.push(realm);
172
- if (row.id === "agent-loop" || row.name === officialLoop || /(?:^|\/)agent-loop(?:$|\/)/.test(row.name)) {
173
- if (row.name !== officialLoop || row.id !== "agent-loop") refuse("ALTERNATE_AGENT_LOOP");
174
- topology.loops.push(realm);
175
- }
176
- if (row.id === "llm-pi-ai" && row.name !== officialPiAi) refuse("ALTERNATE_PROVIDER_OWNER");
177
- if (row.name === officialPiAi || row.name.startsWith("@deepseek-ai/dsh-llm-deepseek-")) topology.providers.push(realm);
178
- if ((Array.isArray(row.inject) && row.inject.includes("llm")) || (object(row.inject) && Object.hasOwn(row.inject, "llm"))) topology.consumers.push(realm);
179
- if (!row.name.startsWith("cordis:") && !dormantModule(row, options, readset, disabledBaseURL)) {
180
- let filename;
181
- const local = row.name.startsWith("file:") || row.name.startsWith(".") || isAbsolute(row.name);
182
- if (local) {
183
- try { filename = isAbsolute(row.name) ? row.name : fileURLToPath(new URL(row.name, baseURL)); } catch { refuse("UNSUPPORTED_MODULE_SOURCE"); }
184
- if (!options.sourceRoots.some(sourceRoot => under(sourceRoot, filename))) refuse("MODULE_OUTSIDE_SOURCE_SCOPE");
185
- readset.module(filename);
186
- } else {
187
- const packageName = row.name.startsWith("@") ? row.name.split("/").slice(0, 2).join("/") : row.name.split("/")[0];
188
- const entry = sdk.resolution.entries.find(entry => entry.name === packageName);
189
- const require = createRequire(baseURL);
190
- const localDir = (require.resolve.paths(packageName) ?? [])
191
- .filter(searchPath => under(options.profileDir, searchPath))
192
- .map(searchPath => join(searchPath, packageName))
193
- .find(candidate => existsSync(join(candidate, "package.json")));
194
- const packageDir = localDir ?? entry?.packageDir;
195
- if (!packageDir) refuse("UNRESOLVED_ENTRY_MODULE");
196
- const manifest = readset.package(join(packageDir, "package.json"));
197
- try {
198
- if (Object.hasOwn(manifest, "exports")) {
199
- const targets = sdk.packageExports.exports(manifest, row.name, { conditions: ["node"] });
200
- if (!targets || targets.length !== 1 || !targets[0].startsWith("./")) refuse("UNSUPPORTED_MODULE_EXPORT");
201
- filename = join(packageDir, targets[0]);
202
- } else {
203
- const subpath = row.name.slice(packageName.length + 1);
204
- filename = createRequire(join(packageDir, "package.json")).resolve(join(packageDir, subpath || manifest.main || "index.js"));
205
- }
206
- } catch {
207
- refuse("UNRESOLVED_ENTRY_MODULE");
208
- }
209
- readset.module(filename, { packageSource: true });
210
- }
211
- }
212
- if (nativeGroups.has(row.name)) {
213
- inspectTrees(row.config, options, sdk, readset, baseURL, { ancestors, root, ids, inheritedRealm: realm, prefix: position, topology, nativeToolSelection });
214
- continue;
215
- }
216
- if (row.group) refuse("UNSUPPORTED_GROUP_CARRIER");
217
- if (row.name === "@deepseek-ai/dsh-agent-preset") {
218
- if (!object(row.config) || !Array.isArray(row.config.plugins)) refuse("UNSUPPORTED_PRESET_PLUGINS");
219
- inspectTrees(row.config.plugins, options, sdk, readset, baseURL, {
220
- ancestors, root: false, inheritedRealm: realm, prefix: `${position}/plugins`, nativeToolSelection,
221
- });
222
- }
223
- if (!nativeIncludes.has(row.name)) continue;
224
- const config = row.config;
225
- if (!object(config) || typeof config.path !== "string" || config.__jsExpr) refuse("UNSUPPORTED_INCLUDE");
226
- let filename;
227
- try { filename = fileURLToPath(new URL(config.path, baseURL)); } catch { refuse("UNSUPPORTED_INCLUDE"); }
228
- if (!options.sourceRoots.some(sourceRoot => under(sourceRoot, filename))) refuse("INCLUDE_OUTSIDE_SOURCE_SCOPE");
229
- if (!new Set([".json", ".yml", ".yaml"]).has(extname(filename)) || /(?:credentials|secrets|\.env)/i.test(filename)) refuse("UNSUPPORTED_INCLUDE");
230
- if (ancestors.has(filename)) refuse("INCLUDE_CYCLE");
231
- const content = readset.read(filename, { optional: true });
232
- const source = content === null ? config.initial : extname(filename) === ".json"
233
- ? jsonDocument(content).value : sdk.yaml.load(content, { schema: sdk.include.entryListSchema });
234
- if (!Array.isArray(source)) refuse("UNSUPPORTED_INCLUDE");
235
- const warnings = [];
236
- const children = sdk.include.applyEntryPatches(source, config.patches, (...args) => warnings.push(args));
237
- if (warnings.length) refuse("INCLUDE_PATCH_DIAGNOSTIC");
238
- const next = new Set(ancestors).add(filename);
239
- inspectTrees(children, options, sdk, readset, new URL(".", pathToFileURL(filename)).href, {
240
- ancestors: next, root: false, inheritedRealm: realm, prefix: `${position}/include`, topology,
241
- nativeToolSelection,
242
- });
243
- }
244
- return topology;
245
- }
246
-
247
- /** Full ordered bundle/profile/Home/explicit-launcher source validation and necessary CAS revision. */
248
- export async function inspectColdComposition(options, sdk, { projectionName, receipt } = {}) {
249
- const readset = new SourceReadset();
250
- const manifestPath = join(options.profileDir, "package.json");
251
- const manifestText = readset.read(manifestPath);
252
- const manifest = jsonDocument(manifestText).value;
253
- const bundles = manifest.dsh?.profile?.bundles;
254
- if (!Array.isArray(bundles) || !bundles.every(name => typeof name === "string")) refuse("INVALID_BUNDLES");
255
- const originalName = receipt?.projectionName ?? BASE_BUNDLE;
256
- const slot = bundles.indexOf(originalName);
257
- if (slot < 0 || bundles.lastIndexOf(originalName) !== slot) refuse("EXACT_BASE_SLOT_REQUIRED");
258
- readset.package(options.installAnchor);
259
- for (const filename of sdk.modulePaths) readset.module(filename, { packageSource: true });
260
- readset.read(join(options.profileDir, "compatibility.json"), { optional: true });
261
- readset.read(join(options.profileDir, "cordis.patch.yml"), { optional: true });
262
- const homePatch = join(options.home, "cordis.patch.yml");
263
- readset.read(homePatch, { optional: true });
264
- for (const filename of options.overlays) readset.read(filename);
265
- if (options.rootConfig) readset.read(options.rootConfig);
266
- if (receipt) readset.read(join(options.profileDir, "node_modules", receipt.projectionName, ".dsmm-cold-profile.json"));
267
- const discover = sdk.boot.loadProfileDirectory("dsmm-cold-profile", options.profileDir, options.installAnchor);
268
- if (discover.skippedBundles.length || discover.layers.length !== bundles.length) refuse("SKIPPED_BUNDLE");
269
- for (const layer of discover.layers) {
270
- readset.package(join(layer.packageDir, "package.json"), { packageSource: layer.packageName !== originalName || !receipt });
271
- for (const filename of layer.patchPaths) readset.read(filename, { packageSource: layer.packageName !== originalName || !receipt });
272
- }
273
- const profile = sdk.boot.loadProfileDirectory("dsmm-cold-profile", options.profileDir, options.installAnchor);
274
- if (profile.skippedBundles.length || profile.layers.length !== bundles.length) refuse("SOURCE_CONFLICT");
275
- const lists = profile.layers.map(layer => layer.patches);
276
- lists.push(profile.patches, sdk.boot.loadOptionalPatches("dsmm-cold-profile", homePatch) ?? []);
277
- lists.push(...options.overlays.map(filename => sdk.boot.loadOverlayPatches("dsmm-cold-profile", filename)));
278
- // Normal profile launchers mount an empty root file. Explicit roots retain their original base.
279
- const rootRows = options.rootConfig
280
- ? sdk.yaml.load(readset.read(options.rootConfig), { schema: sdk.include.entryListSchema }) : [];
281
- if (!Array.isArray(rootRows)) refuse("UNSUPPORTED_ROOT_CONFIG");
282
- const composeAll = layers => {
283
- if (rootRows.length === 0) return compose(sdk.boot, layers);
284
- const warnings = [];
285
- const rows = sdk.include.applyEntryPatches(rootRows, layers.flat(), (...args) => warnings.push(args));
286
- return { rows, warnings };
287
- };
288
- const before = composeAll(lists);
289
- let projected = lists[slot];
290
- let changed;
291
- let after;
292
- if (receipt) {
293
- changed = new Map(receipt.changes.map(change => [change.id, change]));
294
- after = before;
295
- const originalLists = structuredClone(lists);
296
- for (const patch of originalLists[slot]) if (patch.insert) entryWalk(patch.insert, row => {
297
- const change = changed.get(row.id);
298
- if (change && row.name === change.replacement) row.name = change.original;
299
- });
300
- const original = composeAll(originalLists);
301
- assertSelectorSemantics(composeAll, originalLists, lists);
302
- if (!isDeepStrictEqual(expectedRows(original.rows, changed), after.rows) || original.warnings.length !== after.warnings.length) refuse("SELECTOR_SEMANTICS_CHANGED");
303
- } else {
304
- ({ patches: projected, changed } = projectBase(lists[slot], options));
305
- const projectedLists = [...lists];
306
- projectedLists[slot] = projected;
307
- after = composeAll(projectedLists);
308
- assertSelectorSemantics(composeAll, lists, projectedLists);
309
- if (!isDeepStrictEqual(expectedRows(before.rows, changed), after.rows) || before.warnings.length !== after.warnings.length) refuse("SELECTOR_SEMANTICS_CHANGED");
310
- }
311
- const rootURL = pathToFileURL(options.rootConfig ?? join(options.profileDir, "cordis.yml")).href;
312
- const resolution = await sdk.boot.createRuntimeResolution({ installAnchor: options.installAnchor, profile, home: options.home });
313
- const nativeToolSelection = { projected: [], unprojected: [] };
314
- // First disabled evaluation inherits loader.ctx before Entry._patchContext.
315
- // Nested groups/includes/presets receive no proof from their traversal base.
316
- assertLlmTopology(inspectTrees(after.rows, options, { ...sdk, resolution }, readset, rootURL, {
317
- nativeToolSelection, disabledBaseURL: pathToFileURL(dirname(fileURLToPath(rootURL))).href + "/",
318
- }));
319
- readset.assertCurrent();
320
- const context = { ...options, projectionName: receipt?.projectionName ?? projectionName ?? null };
321
- // Generated transaction identity is not part of a caller's expected source revision.
322
- delete context.projectionName;
323
- return {
324
- readset, revision: readset.revision(context), manifestText, manifestPath, slot,
325
- baseLayer: profile.layers[slot], projected, changes: [...changed].map(([id, change]) => ({ id, ...change })),
326
- rows: after.rows,
327
- nativeToolSelection: { status: nativeToolSelection.unprojected.length ? "partial" : "projected", ...nativeToolSelection },
328
- };
329
- }