返回 CodeWhale
composition.ts
根目录 / crates / engine / extension-host / src / dsh / composition.ts
1 /**
2 * Immutable, reviewed DSH entry trees in the existing
3 * Cordis owner. Patch/expression/group/isolation semantics are upstream's.
4 * There is no session writer, prompt builder, skill parser or process launcher.
5 */
6 import { Context, Service, type Fiber } from '@deepseek-ai/cordis'
7 import { FiberState } from './fiber-state.ts'
8 import { createHash } from 'node:crypto'
9 import { readFile } from 'node:fs/promises'
10 import { isAbsolute, relative, resolve, sep } from 'node:path'
11 import { fileURLToPath } from 'node:url'
12 import { Loader, EntryTree, Group, type EntryOptions } from './upstream/loader/src/index.ts'
13 import { applyEntryPatches, entryListSchema, type PatchOptions } from './upstream/include/src/index.ts'
14 import { load as loadYaml } from 'js-yaml'
15 import {reviewedMcpModule} from './mcp.ts'
16 import {reviewedSkillModule} from './skill-filesystem.ts'
17 import {reviewedHookModule} from './shell-hooks.ts'
18 import {admitReviewedClosure,explainImportError,importReviewedModule} from './resolve-hooks.ts'
19 import { describeMissingServices } from './missing-services.ts'
20 import { PERSONA, reviewedPersonaModule } from './persona.ts'
21 import { AGENT_PRESETS, defineReviewedAgentPresets, issuePresetReceipt, revokePresetReceipt, type PresetCatalog, type PreparedPreset } from './agent-presets.ts'
22 import { reviewedCotTranslationModule } from './cot-translation.ts'
23 import compatibility from './compatibility.json' with { type: 'json' }
24
25 const MAX_LAYERS = 64
26 const MAX_SOURCE_BYTES = 1024 * 1024
27 const MAX_DATA_BYTES = 4 * 1024 * 1024
28 const MAX_DATA_NODES = 100_000
29 const MAX_ROWS = 1024
30 const MAX_DEPTH = 32
31 const SHA256 = /^[a-f0-9]{64}$/
32
33 export interface ReviewedLayer {
34 /** Original selected layer, for nonexecuting diagnostics. */
35 path: string
36 sha256: string
37 /** Exact UTF-8 source; include's schema retains unevaluated !!js nodes. */
38 source: string
39 }
40
41 export interface ReviewedModule {
42 /** Exact row name; relative names are resolved during Rust staging. */
43 name: string
44 /** Path relative to the immutable Codewhale bundle root. */
45 path: string
46 sha256: string
47 }
48
49 export interface ReviewedComposition {
50 version: 1
51 layers: ReviewedLayer[]
52 modules: ReviewedModule[]
53 /** Original source/asset closure. Rust additionally hashes generated files. */
54 files: Record<string, string>
55 }
56
57 export interface CompositionReview {
58 version: 1
59 /** Upstream's exact effective data. Expression nodes are still data. */
60 entries: EntryOptions[]
61 warnings: string[]
62 skipped: {row?:string;package?:string;reason:string;layer:string;patch:number}[]
63 layers: { path: string; sha256: string }[]
64 }
65
66 function digest(bytes: string | Uint8Array): string {
67 return createHash('sha256').update(bytes).digest('hex')
68 }
69
70 function plainRelative(path: string): boolean {
71 return typeof path === 'string' && path.length > 0 && path.length <= 4096 && !isAbsolute(path)
72 && !path.startsWith('/') && !/[\\:\u0000-\u001f\u007f]/u.test(path)
73 && path.split('/').every(part => part !== '' && part !== '.' && part !== '..')
74 }
75
76 /** Bound traversal before clone/stringification, including repeated YAML aliases. */
77 function boundData(root: unknown): void {
78 let nodes = 0
79 let bytes = 0
80 const ancestors = new Set<object>()
81 function visit(value: unknown, depth: number) {
82 if (++nodes > MAX_DATA_NODES || depth > MAX_DEPTH) throw new Error('composition data exceeds its resource limit')
83 if (typeof value === 'string') bytes += Buffer.byteLength(value)
84 if (bytes > MAX_DATA_BYTES) throw new Error('composition expanded text exceeds 4 MiB')
85 if (value === null || typeof value !== 'object') return
86 if (ancestors.has(value)) throw new Error('cyclic configuration data is unsupported')
87 ancestors.add(value)
88 if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
89 throw new Error('composition configuration must be plain data')
90 }
91 for (const [key, child] of Object.entries(value)) {
92 bytes += Buffer.byteLength(key)
93 visit(child, depth + 1)
94 }
95 ancestors.delete(value)
96 }
97 visit(root, 0)
98 }
99
100 function assignmentSafe(value: object): void {
101 // Patch/entry fields are assigned onto helper objects. Nested configuration
102 // remains literal data; ordinary constructor/prototype config keys are valid.
103 if (Object.hasOwn(value, '__proto__')) throw new Error('prototype-mutating entry field is unsupported')
104 }
105
106 function checkRows(rows: EntryOptions[], depth = 0, count = { value: 0 }): void {
107 if (depth > MAX_DEPTH) throw new Error('composition entry nesting exceeds 32 levels')
108 for (const row of rows) {
109 if (++count.value > MAX_ROWS) throw new Error('composition exceeds 1024 entry rows')
110 if (row === null || typeof row !== 'object' || Array.isArray(row)) throw new Error('entry row must be an object')
111 assignmentSafe(row)
112 if (row.id !== undefined && (typeof row.id !== 'string' || row.id.length > 512)) throw new Error('entry id must be a bounded string')
113 const isolate = (row as { isolate?: unknown }).isolate
114 if (isolate !== undefined && isolate !== null && (typeof isolate !== 'object' || Array.isArray(isolate) || Object.hasOwn(isolate, 'translator'))) {
115 throw new Error('composition row cannot override translator isolation')
116 }
117 if (!(row.group===true && row.name===undefined) && (typeof row.name !== 'string' || row.name.length === 0 || row.name.length > 4096)) throw new Error('entry name must be a bounded string')
118 if ((row.group || row.name==='cordis:group' || row.name==='@deepseek-ai/cordis-plugin-group') && Array.isArray(row.config)) checkRows(row.config, depth + 1, count)
119 }
120 }
121
122 /** Raw preset files are entry lists; apply the same bounded data/row guards
123 * before the borrowed recursive discovery/inventory code sees them. */
124 export function parsePresetComposition(source: string): EntryOptions[] {
125 if (Buffer.byteLength(source) > MAX_SOURCE_BYTES) throw new Error('preset source exceeds its limit')
126 const rows = loadYaml(source, {schema:entryListSchema})
127 boundData(rows)
128 if (!Array.isArray(rows)) throw new Error('preset composition must be an entry list')
129 checkRows(rows as EntryOptions[])
130 return rows as EntryOptions[]
131 }
132
133 /** Trusted pure reviewer: never imports row modules or evaluates expressions. */
134 export function reviewComposition(spec: ReviewedComposition): CompositionReview {
135 if (!spec || spec.version !== 1 || !Array.isArray(spec.layers) || spec.layers.length === 0 || spec.layers.length > MAX_LAYERS) {
136 throw new Error('composition needs 1–64 reviewed layers')
137 }
138 let sourceBytes = 0
139 const patches: PatchOptions[] = []
140 const locations: {layer:string;patch:number}[] = []
141 const layers: CompositionReview['layers'] = []
142 for (const layer of spec.layers) {
143 if (!layer || !plainRelative(layer.path) || typeof layer.source !== 'string' || typeof layer.sha256 !== 'string' || !SHA256.test(layer.sha256)) throw new Error('invalid reviewed layer')
144 sourceBytes += Buffer.byteLength(layer.source)
145 if (sourceBytes > MAX_SOURCE_BYTES || digest(layer.source) !== layer.sha256) throw new Error('layer source changed or exceeds 1 MiB')
146 let parsed: unknown
147 try { parsed = loadYaml(layer.source, { schema: entryListSchema }) } catch { throw new Error('invalid DSH patch data') }
148 if (!Array.isArray(parsed)) throw new Error('DSH patch layer must be a list')
149 boundData(parsed)
150 for (const patch of parsed) {
151 if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new Error('patch must be an object')
152 assignmentSafe(patch)
153 if (patch.insert !== undefined && patch.insert !== null) {
154 if (!Array.isArray(patch.insert)) throw new Error('patch insert must be a list')
155 checkRows(patch.insert)
156 }
157 }
158 patches.push(...parsed)
159 locations.push(...parsed.map((_,i)=>({layer:layer.path,patch:i+1})))
160 layers.push({ path: layer.path, sha256: layer.sha256 })
161 }
162 boundData(patches)
163 const warnings: string[] = []
164 const skipped: CompositionReview['skipped'] = []
165 let entries: EntryOptions[] = []
166 for (const [i,patch] of patches.entries()) {
167 entries = applyEntryPatches(entries,[patch],(message,...args)=>{
168 let index=0
169 const reason=message.replace(/%C/g,()=>JSON.stringify(args[index++]))
170 warnings.push(reason)
171 skipped.push({...(typeof patch.id==='string'?{row:patch.id}:{}),...(typeof patch.name==='string'?{package:patch.name}:{}),reason,...locations[i]})
172 })
173 }
174 boundData(entries)
175 checkRows(entries)
176 return { version: 1, entries, warnings, skipped, layers }
177 }
178
179 /** Known DSH rows that need an unavailable broker/service or replace core authority. */
180 const UNSUPPORTED_ROWS = new Map<string,string>()
181
182 /** These fixed Core adapters resolve without a package-provided module. */
183 export function hasReviewedRowBridge(name:string): boolean { return Object.hasOwn(compatibility.row_bridges, name) }
184
185 /** Readiness uses the same known Core service boundary as final import. */
186 export function compositionRowProblem(name:string): string | undefined { return UNSUPPORTED_ROWS.get(name) }
187
188 /** Upstream Group needs its existing Loader during child creation. Declare
189 * that dependency for the host's strict Cordis service access checks. */
190 class ReviewedGroup extends Group { static inject = ['loader'] }
191
192 /** A Loader that uses upstream lifecycle/config logic without native internals. */
193 export class ReviewedLoader extends Loader {
194 constructor(ctx: Context, config: Loader.Config) {
195 super(ctx, config)
196 this.builtins.group = ReviewedGroup
197 }
198 }
199
200 // Loader installs global Cordis lifecycle observers. One host root must own
201 // exactly one loader; one loader per tree would duplicate interpolation.
202 const loaders = new WeakMap<Context, { ctx: Context; fiber: Fiber }>()
203
204 /** HostRoot calls this before any Native owner can activate. */
205 export function installCompositionLoader(root: Context): void {
206 if (loaders.has(root)) return
207 const ctx = root.isolate('loader')
208 const fiber = ctx.plugin(ReviewedLoader, {})
209 loaders.set(root, { ctx, fiber })
210 }
211
212 class ReviewedTree extends EntryTree {
213 private readonly base: string
214 private readonly modules: ReadonlyMap<string, ReviewedModule>
215 private readonly spec: ReviewedComposition
216
217 constructor(ctx: Context, base: string, spec: ReviewedComposition) {
218 super(ctx)
219 this.base = base
220 this.spec = spec
221 const modules = new Map<string, ReviewedModule>()
222 if (!Array.isArray(spec.modules) || spec.modules.length > MAX_ROWS || !spec.files || Object.keys(spec.files).length > 16384) throw new Error('invalid reviewed module closure')
223 for (const module of spec.modules) {
224 if (!module || typeof module.name !== 'string' || module.name.length === 0 || module.name.length > 4096 || modules.has(module.name) || !plainRelative(module.path) || !SHA256.test(module.sha256)
225 || spec.files[module.path] !== module.sha256) throw new Error('module map differs from reviewed closure')
226 modules.set(module.name, module)
227 }
228 this.modules = modules
229 }
230
231 /** A reviewed composition is input; teardown and self-disposal never rewrite it. */
232 commit(): void {}
233
234 private readonly importFailures = new Map<string, unknown>()
235
236 importFailure(name: string): { error: unknown } | undefined {
237 return this.importFailures.has(name) ? { error: this.importFailures.get(name) } : undefined
238 }
239
240 override import(name: string): unknown {
241 this.importFailures.delete(name)
242 const record = (error: unknown): never => {
243 this.importFailures.set(name, error)
244 throw error
245 }
246 try {
247 const imported = this.importRow(name)
248 return imported instanceof Promise ? imported.catch(record) : imported
249 } catch (error) {
250 return record(error)
251 }
252 }
253
254 private importRow(name: string): unknown {
255 if (name === PERSONA) return reviewedPersonaModule
256 if (name === AGENT_PRESETS) return defineReviewedAgentPresets(mountReviewedComposition)
257 if (name === 'cordis:group' || name === '@deepseek-ai/cordis-plugin-group') return ReviewedGroup
258 if(name==='@deepseek-ai/dsh-mcp-client')return reviewedMcpModule()
259 if(name==='@deepseek-ai/dsh-skill-filesystem')return reviewedSkillModule()
260 if(name==='@deepseek-ai/dsh-hooks-claude-code')return reviewedHookModule('claude-code',fileURLToPath(this.base),this.spec.files)
261 if(name==='@deepseek-ai/dsh-hooks-codex')return reviewedHookModule('codex',fileURLToPath(this.base),this.spec.files)
262 const rowBridge = Object.hasOwn(compatibility.row_bridges, name)
263 ? (compatibility.row_bridges as Record<string, string>)[name]
264 : undefined
265 if (rowBridge === 'host-spine') return Object.freeze({ name, apply() {} })
266 if (rowBridge === 'cot-translation') return reviewedCotTranslationModule()
267 if (UNSUPPORTED_ROWS.has(name)) throw new Error(`${name}: ${UNSUPPORTED_ROWS.get(name)}`)
268 const module = this.modules.get(name)
269 if (!module) throw new Error(`row requires ${JSON.stringify(name)}, absent from the reviewed module closure`)
270 return this.importReviewed(module)
271 }
272
273 private async importReviewed(module: ReviewedModule): Promise<unknown> {
274 const root = fileURLToPath(this.base)
275 const path = resolve(root, module.path)
276 const inside = relative(root, path)
277 if (inside.startsWith(`..${sep}`) || inside === '..' || isAbsolute(inside)) throw new Error('module escapes reviewed bundle')
278 if (this.spec.files[module.path] !== module.sha256 || digest(await readFile(path)) !== module.sha256) throw new Error('module changed after review')
279 // Transitive module bytes remain covered by the existing Rust Native
280 // receipt, immutable staging and per-call liveness checks. Native code is
281 // not contained from co-resident arbitrary Native code by this helper.
282 return importReviewedModule(this.base,module.path)
283 }
284 }
285
286 export interface CompositionMount {
287 readonly tree: EntryTree
288 dispose(): Promise<void>
289 }
290
291 interface ReviewedMountConfig {
292 baseUrl: string
293 spec: ReviewedComposition
294 review: CompositionReview
295 releaseClosure: () => void
296 }
297
298 const mountedTrees = new WeakMap<ReviewedMountConfig, CompositionMount>()
299
300 /** Validate configured rows too: upstream logs a failed create before it can
301 * enter tree.store, so iterating only the store would acknowledge no work. */
302 function validateInventory(group: import('./upstream/loader/src/config/group.ts').EntryGroup): void {
303 for (const row of group.data) {
304 const entry = group.tree.store[row.id]
305 if (!entry || entry.parent !== group || entry.options !== row) {
306 throw new Error(`composition row ${JSON.stringify(row.id ?? row.name)} was not created`)
307 }
308 if (entry.disabled) continue
309 if (entry.subgroup) validateInventory(entry.subgroup)
310 if (entry.subtree) validateInventory(entry.subtree.root)
311 }
312 }
313
314 function describeCause(error: unknown): string {
315 return error instanceof Error ? `${error.name}: ${error.message}` : String(error)
316 }
317
318 function fiberStateName(state: number): string {
319 return Object.entries(FiberState).find(([, value]) => value === state)?.[0] ?? String(state)
320 }
321
322 /** Trusted carrier, following upstream PresetTree's explicit loader inject.
323 * The Native wrapper never gains a second loader or a global service grant. */
324 class ReviewedCarrier {
325 static inject = ['loader']
326 private readonly tree: ReviewedTree
327 private disposed = false
328
329 constructor(private readonly ctx: Context, private readonly config: ReviewedMountConfig) {
330 this.tree = new ReviewedTree(ctx, config.baseUrl, config.spec)
331 mountedTrees.set(config, { tree: this.tree, dispose: () => this.dispose() })
332 }
333
334 private async dispose(): Promise<void> {
335 if (this.disposed) return
336 this.disposed = true
337 const fibers = [...new Set([...this.tree.entries()].map(entry => entry.fiber)
338 .filter((fiber): fiber is Fiber => fiber !== undefined))].reverse()
339 const pending = this.tree.getTasks()
340 let stopError: unknown
341 try { this.tree.root.stop() } catch (error) { stopError = error }
342 const outcomes = await Promise.allSettled([
343 ...pending,
344 ...fibers.map(fiber => Promise.resolve().then(() => fiber.dispose())),
345 ])
346 try {
347 await this.tree.await()
348 if (stopError !== undefined) throw stopError
349 const failed = outcomes.find((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')
350 if (failed) throw failed.reason
351 } finally { this.config.releaseClosure() }
352 }
353
354 async *[Service.init]() {
355 yield () => this.dispose()
356 await this.tree.root.update(this.config.review.entries)
357 await this.tree.await()
358 validateInventory(this.tree.root)
359 for (const entry of this.tree.entries()) {
360 if (entry.disabled) continue
361 const row = `composition row ${JSON.stringify(entry.options.id ?? entry.options.name)}`
362 if (!entry.fiber || entry.fiber.uid === null) {
363 const failure = this.tree.importFailure(entry.options.name)
364 throw new Error(failure !== undefined
365 ? `${row} failed activation: ${describeCause(explainImportError(failure.error))}`
366 : `${row} failed activation (${entry.fiber ? `fiber ${fiberStateName(entry.fiber.state)}` : 'no fiber'}); see the logged error above`, failure !== undefined ? { cause: failure.error } : undefined)
367 }
368 await entry.fiber.await()
369 const missing = Object.keys(entry.fiber.inject).filter(name => entry.fiber!.ctx.get(name) === undefined)
370 if (missing.length) throw new Error(`${row} requires ${describeMissingServices(missing)}`)
371 if (entry.fiber.state !== FiberState.ACTIVE) throw new Error(`${row} is not active (fiber ${fiberStateName(entry.fiber.state)})`)
372 }
373 const leaked = leakedServices(this.ctx, this.ctx.fiber)
374 if (leaked.length) throw new Error(`composition published shared-root services: ${leaked.join(', ')}`)
375 }
376 }
377
378 /** Called only from the reviewed generated native entry, under its owner. */
379 export async function mountReviewedComposition(ctx: Context, baseUrl: string, spec: ReviewedComposition): Promise<CompositionMount> {
380 const review = reviewComposition(spec)
381 // Anonymous legacy structural groups are explicit Group fibers; preserve the
382 // source patch identity comparison and normalize only the mounted projection.
383 function groups(rows: EntryOptions[]) { for (const row of rows) { if (row.group===true && row.name===undefined) row.name='cordis:group'; if (row.name===AGENT_PRESETS) row.isolate = { ...row.isolate, agentPresets: true }; if ((row.group===true || row.name==='cordis:group' || row.name==='@deepseek-ai/cordis-plugin-group') && Array.isArray(row.config)) groups(row.config) } }
384 groups(review.entries)
385 const installed = loaders.get(ctx.root)
386 if (!installed) throw new Error('composition loader was not installed by this host')
387 await installed.fiber.await()
388 const loaderCtx = ctx.extend({
389 baseUrl,
390 [Context.isolate]: Object.assign(Object.create(ctx[Context.isolate]), {
391 loader: installed.ctx[Context.isolate].loader,
392 translator: Symbol('translator'),
393 }),
394 })
395 const config: ReviewedMountConfig = { baseUrl, spec, review, releaseClosure: admitReviewedClosure(baseUrl, spec.files) }
396 const carrier = loaderCtx.plugin(ReviewedCarrier, config)
397 let disposed = false
398 const dispose = async () => {
399 if (disposed) return
400 disposed = true
401 try {
402 await mountedTrees.get(config)?.dispose()
403 await carrier.dispose()
404 } finally { config.releaseClosure() }
405 }
406 ctx.effect(() => dispose, 'reviewed DSH composition teardown')
407 try {
408 await carrier.await()
409 const mount = mountedTrees.get(config)
410 if (!mount || carrier.state !== FiberState.ACTIVE) throw new Error('reviewed composition carrier did not activate')
411 return { tree: mount.tree, dispose }
412 } catch (error) {
413 await dispose().catch(() => undefined)
414 throw error
415 }
416 }
417
418 /** Reused fiber-identity/root-realm audit from DSH agent-presets/src/mount.ts. */
419 function leakedServices(ctx: Context, mount: Fiber): string[] {
420 const rootIsolate = ctx.root[Context.isolate]
421 const leaked: string[] = []
422 for (const key of Object.getOwnPropertySymbols(ctx.reflect.store)) {
423 const impl = ctx.reflect.store[key]
424 if (impl === undefined) continue
425 let current = impl.ctx.fiber
426 while (current !== mount && current.parent.fiber !== current) current = current.parent.fiber
427 if (current === mount && rootIsolate[impl.name] === key) leaked.push(impl.name)
428 }
429 return leaked.sort((left, right) => left.localeCompare(right))
430 }
431
432 /** Installer-created Native entry mounts the raw roster row and its selected
433 * subtree in one existing owner scope. No process-wide selected preset exists. */
434 export async function mountReviewedPreset(ctx: Context, baseUrl: string, spec: ReviewedComposition, catalog: PresetCatalog, selected: PreparedPreset): Promise<CompositionMount> {
435 if (!selected) throw new Error('agent-presets: explicit selection is required when no default is configured')
436 const entries = structuredClone(reviewComposition(spec).entries)
437 const snapshot = { catalog, selected, base_url: baseUrl }
438 const receipt = issuePresetReceipt(snapshot)
439 let found = 0
440 function prepare(rows: EntryOptions[]) {
441 for (const row of rows) {
442 if (row.group === true || row.name === 'cordis:group' || row.name === '@deepseek-ai/cordis-plugin-group') {
443 prepare(row.config as EntryOptions[])
444 } else if (row.name === AGENT_PRESETS) {
445 found++
446 row.isolate = { ...row.isolate, agentPresets: true }
447 row.config = { codewhale_reviewed: snapshot, codewhale_receipt: receipt }
448 }
449 }
450 }
451 prepare(entries)
452 if (found !== 1) {
453 revokePresetReceipt(receipt)
454 throw new Error('exactly one raw roster row is required for a selected preset')
455 }
456 const source = JSON.stringify([{ insert: entries }])
457 let top: CompositionMount
458 try {
459 top = await mountReviewedComposition(ctx, baseUrl, { ...spec, layers: [{ path: 'selected-preset.json', sha256: digest(source), source }] })
460 } finally {
461 revokePresetReceipt(receipt)
462 }
463 try {
464 // Service injection requires ACTIVE. Build the raw roster's scope first,
465 // then mount its selected subtree, matching upstream's later standing mount.
466 const entry = [...top.tree.entries()].find(entry => entry.options.name === AGENT_PRESETS && !entry.disabled)
467 const roster = entry?.ctx.get('agentPresets' as any) as { mountSelected(): Promise<unknown> } | undefined
468 if (!roster) throw new Error('selected raw roster did not become active')
469 await roster.mountSelected()
470 return top
471 } catch (error) { await top.dispose(); throw error }
472 }
473
473 lines TYPESCRIPT