返回 CodeWhale
resolve-hooks.ts
根目录 / crates / engine / extension-host / src / dsh / resolve-hooks.ts
1 /**
2 * Module resolution for plugin code: one Cordis, one schemastery, one cosmokit.
3 *
4 * DSH packages import these by bare specifier, as peers or (for schemastery,
5 * sometimes) as plain dependencies. Two copies of Cordis break `instanceof`,
6 * symbols and services, so every import of these specifiers — however the
7 * package declared it, and ignoring any copy under the package's own
8 * `node_modules` — resolves to the single instance bundled into this host.
9 *
10 * `@deepseek-ai/dsh-tools` resolves to the definition-side compat module, and
11 * `@deepseek-ai/dsh-commands/brand` (the `CommandDefinitionId` constructor DSH
12 * command plugins import) to its two identity functions. Any other `@deepseek-ai/dsh-*` package fails the import loudly: the host
13 * does not provide it, and a silent partial load would be worse.
14 *
15 * Node: `module.registerHooks`. Bun has no `registerHooks` (a named import of
16 * it fails at link time, so it is read off the namespace). Bun gets the same
17 * rules through `Bun.plugin`, with three pieces (see `installBunResolver`).
18 */
19 import * as nodeModule from 'node:module'
20 import {createHash} from 'node:crypto'
21 import {fileURLToPath,pathToFileURL} from 'node:url'
22 import {resolve,isAbsolute,dirname} from 'node:path'
23 import {readFileSync} from 'node:fs'
24 import { canonicalPath, insideKey, pathKey, unlinkedKeyMatches } from './canonical-path.ts'
25 import { RUNTIME } from '../runtime.ts'
26 import { prepareBunSource, REVIEWED_IMPORT } from './bun-closure.ts'
27 import * as dshMessageCompat from './dsh-message-compat.js'
28 import {
29 dshAgentModule,
30 dshAppBootModule,
31 dshAtomicWriteModule,
32 dshCredentialsModule,
33 dshHomePathsModule,
34 dshSessionSurfaceModule,
35 dshSettingsModule,
36 dshSkillModule,
37 dshSubagentModule,
38 dshTypertProtocolModule,
39 dshWorkspaceModule,
40 } from './dsh-shims.ts'
41 import compatibility from './compatibility.json' with { type: 'json' }
42
43 const SCHEME = 'codewhale-host:'
44 const REGISTRY_KEY = Symbol.for('codewhale.extension-host.modules')
45
46 /** Specifier → singleton key. */
47 const SINGLETONS: Readonly<Record<string, string>> = compatibility.module_singletons
48
49 export class UnsupportedPeerError extends Error {
50 constructor(readonly specifier: string) {
51 super(`requires \`${specifier}\`, which the Codewhale plugin host does not provide`)
52 this.name = 'UnsupportedPeerError'
53 }
54 }
55
56 function packageName(specifier: string): string {
57 const parts = specifier.split('/')
58 return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]
59 }
60
61 /** Map a bare specifier to a singleton key, `null` for "not ours", or throw for an unsupported DSH peer. */
62 export function classifySpecifier(specifier: string): string | null {
63 if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.includes(':')) return null
64 if (Object.hasOwn(SINGLETONS, specifier)) return SINGLETONS[specifier]
65 const name = packageName(specifier)
66 if (Object.hasOwn(SINGLETONS, name)) {
67 if (specifier !== name) throw new UnsupportedPeerError(specifier)
68 return SINGLETONS[name]
69 }
70 if (name.startsWith('@deepseek-ai/dsh-') || name.startsWith('@deepseek-ai/cordis-')) {
71 throw new UnsupportedPeerError(name)
72 }
73 return null
74 }
75
76 function virtualSource(key: string, namespace: Record<string, unknown>): string {
77 const lines = [`const ns = globalThis[Symbol.for(${JSON.stringify(REGISTRY_KEY.description)})][${JSON.stringify(key)}];`]
78 for (const name of Object.keys(namespace)) {
79 if (name === 'default') continue
80 if (!/^[A-Za-z_$][\w$]*$/.test(name)) continue
81 lines.push(`export const ${name} = ns[${JSON.stringify(name)}];`)
82 }
83 if ('default' in namespace) lines.push('export default ns.default;')
84 return lines.join('\n')
85 }
86
87 /**
88 * A path inside a `node_modules` copy of a package the host owns or refuses:
89 * the singletons and every `@deepseek-ai/dsh-*` / `@deepseek-ai/cordis-*` peer.
90 */
91 const PEER_PATH =
92 /[\\/]node_modules[\\/]((?:@deepseek-ai[\\/](?:dsh-[^\\/]+|cordis(?:-[^\\/]+)?|schemastery|cosmokit))|cosmokit)[\\/]/
93
94 /**
95 * Bun reports a bare import it cannot find as `Cannot find package 'X'`,
96 * where Node would have run the resolve hook and thrown `UnsupportedPeerError`.
97 * This gives the same error for unsupported peers. Other errors pass through.
98 */
99 export function explainImportError(error: unknown): unknown {
100 const match = error instanceof Error ? /Cannot find package '([^']+)'/.exec(error.message) : null
101 if (!match) return error
102 try {
103 classifySpecifier(match[1])
104 } catch (unsupported) {
105 return unsupported
106 }
107 return error
108 }
109
110 /**
111 * Bun 1.4: runtime `onResolve` is not called for bare package names, only for
112 * some subpaths. So:
113 * 1. `build.module` serves each singleton by its exact name.
114 * 2. `onResolve` applies `classifySpecifier` to every bare specifier Bun does
115 * pass it, which catches subpaths such as `@deepseek-ai/cordis/lib/x`.
116 * 3. `onLoad` refuses any file under a `node_modules` copy of a peer. A second
117 * Cordis, or a dsh peer that a plugin ships itself, never loads.
118 * `explainImportError` covers peers that are not installed at all.
119 */
120 function installBunResolver(modules: Record<string, Record<string, unknown>>) {
121 const bun = (globalThis as any).Bun
122 Object.defineProperty(globalThis,REVIEWED_IMPORT,{value:async(specifier:unknown,caller:string,options?:unknown)=>{
123 if(typeof specifier==='symbol')throw new TypeError('composition import specifier cannot be a symbol')
124 const name=String(specifier)
125 const closure=closureAt(caller)
126 if(!closure)throw new Error('composition module closure is no longer admitted')
127 const target=checkedBunSpecifier(name,closure.receipt,caller,false)
128 const singleton=classifySpecifier(target)
129 if(singleton!==null)return modules[singleton]
130 return import(target,options as any)
131 },writable:false,configurable:false})
132 bun.plugin({
133 name: 'codewhale-host-modules',
134 setup(build: any) {
135 for (const [specifier, key] of Object.entries(SINGLETONS)) {
136 if (key in modules) build.module(specifier, () => ({ exports: modules[key], loader: 'object' }))
137 }
138 build.onResolve({ filter: /^[^./]/ }, (args: { path: string }) => {
139 const key = classifySpecifier(args.path)
140 if (key !== null && !(key in modules)) throw new UnsupportedPeerError(args.path)
141 return undefined
142 })
143 build.onLoad({ filter: new RegExp(`${PEER_PATH.source}|\\.(?:mjs|js|cjs|mts|cts|ts|tsx|jsx|json)$`) }, (args: { path: string }) => {
144 const match = PEER_PATH.exec(args.path)
145 if(match)throw new UnsupportedPeerError(match[1].replaceAll('\\', '/'))
146 const closure=closureAt(pathToFileURL(args.path).href)
147 if(!closure) {
148 const extension=args.path.split('.').at(-1)
149 if(extension==='json')return {contents:`export default JSON.parse(${JSON.stringify(readFileSync(args.path,'utf8'))});`,loader:'js'}
150 const loader=extension==='tsx'?'tsx'
151 :extension==='ts' || extension==='mts' || extension==='cts'?'ts'
152 :extension==='jsx' || extension==='js'?'jsx':'js'
153 return {contents:readFileSync(args.path,'utf8'),loader}
154 }
155 if(!(closure.path in closure.receipt.files) || !unlinkedInside(closure.receipt,closure.path,args.path))throw new Error('module was absent from reviewed composition closure or contains a symbolic link')
156 const bytes=readFileSync(args.path)
157 if(bytes.length>256*1024*1024 || createHash('sha256').update(bytes).digest('hex')!==closure.receipt.files[closure.path])throw new Error('composition module bytes changed after review')
158 // Bun 1.4 runtime onLoad treats its JSON loader as JS. Preserve exact
159 // JSON semantics (including __proto__ data keys) via a JS data module.
160 if(closure.path.endsWith('.json'))return {contents:`export default JSON.parse(${JSON.stringify(bytes.toString('utf8'))});`,loader:'js'}
161 let source:string
162 try {source=prepareBunSource(bytes.toString('utf8'),args.path,(specifier,require)=>checkedBunSpecifier(specifier,closure.receipt,pathToFileURL(args.path).href,require))}
163 catch(error){if(error instanceof SyntaxError)throw new Error('reviewed composition module has unsupported JavaScript syntax');throw error}
164 return {contents:source,loader:'js'}
165 })
166 },
167 })
168 }
169
170 function checkedBunSpecifier(specifier:string,closure:ReviewedClosure,caller:string,require:boolean):string {
171 const key=classifySpecifier(specifier)
172 if(key!==null) {
173 if(!(key in (globalThis as any)[REGISTRY_KEY]))throw new UnsupportedPeerError(specifier)
174 return specifier
175 }
176 if(nodeModule.isBuiltin(specifier))return specifier.startsWith('node:')?specifier:`node:${specifier}`
177 const callerPath=fileURLToPath(caller)
178 const file=(specifier.startsWith('file:') || specifier.startsWith('.') || isAbsolute(specifier))
179 ?new URL(specifier,caller):undefined
180 if(file?.search || file?.hash)throw new Error('Bun does not preserve reviewed module query or fragment identity; select [extension_host] runtime = "node" for this composition')
181 let path:string
182 if(file) path=require && !specifier.startsWith('file:')?resolve(dirname(callerPath),specifier):resolve(fileURLToPath(file))
183 else if(require) path=nodeModule.createRequire(caller).resolve(specifier)
184 else path=bunResolve(specifier,dirname(callerPath),caller)
185 const inside=keyIn(closure,path)
186 if(inside===undefined || !(inside in closure.files) || !unlinkedInside(closure,inside,path))throw new Error('composition import escapes the reviewed file closure')
187 return require?path:file?file.href:pathToFileURL(path).href
188 }
189
190 function bunResolve(specifier:string,from:string,caller:string):string {
191 const bun=(globalThis as any).Bun
192 if(typeof bun?.resolveSync==='function') {
193 try {return bun.resolveSync(specifier,from)} catch {}
194 }
195 return nodeModule.createRequire(caller).resolve(specifier)
196 }
197
198 // Module graph admission for an already-reviewed composition. This is an
199 // ephemeral resolver index over the existing tree's file receipt, not an owner,
200 // session or plugin state store. Native JS remains arbitrary co-resident code.
201 //
202 // Keyed by the canonical root's `pathKey`. A module path is matched lexically
203 // against the canonical root or a raw root it was admitted under — never a raw
204 // spelling against a canonical one (see canonical-path.ts): on Windows the two
205 // differ in prefix, 8.3 names and case for the very same directory.
206 interface ReviewedClosure {files:Readonly<Record<string,string>>,refs:number,canonicalRoot:string,rawRoots:Set<string>}
207 const reviewedClosures=new Map<string,ReviewedClosure>()
208 function keyIn(closure:ReviewedClosure,path:string):string|undefined {
209 const canonical=insideKey(closure.canonicalRoot,path)
210 if(canonical!==undefined)return canonical
211 for(const root of closure.rawRoots) {
212 const raw=insideKey(root,path)
213 if(raw!==undefined)return raw
214 }
215 }
216 /** `path` is `root/key` with no link inside the root (both sides canonicalized). */
217 function unlinkedInside(closure:ReviewedClosure,key:string,path:string):boolean {
218 let canonical:string
219 try {canonical=canonicalPath(path)} catch {return false}
220 return unlinkedKeyMatches(closure.canonicalRoot,key,canonical)
221 }
222 export function admitReviewedClosure(baseUrl:string,files:Readonly<Record<string,string>>):()=>void {
223 const rawRoot=resolve(fileURLToPath(baseUrl))
224 const canonicalRoot=canonicalPath(rawRoot)
225 const id=pathKey(canonicalRoot)
226 const accepted:Record<string,string>=Object.create(null)
227 const keys=Object.keys(files)
228 if (keys.length>16384) throw new Error('reviewed composition closure exceeds its file limit')
229 for (const key of keys) {
230 if (!key || key.split('/').some(part=>!part || part==='.' || part==='..') || key.includes('\\') || key.includes(':') || isAbsolute(key) || !/^[a-f0-9]{64}$/.test(files[key])) throw new Error('invalid reviewed composition closure file')
231 accepted[key]=files[key]
232 }
233 const existing=reviewedClosures.get(id)
234 if(existing) {
235 if(Object.keys(existing.files).length!==keys.length || keys.some(key=>existing.files[key]!==accepted[key])) throw new Error('the same composition root carries different file receipts')
236 existing.refs++
237 existing.rawRoots.add(rawRoot)
238 } else reviewedClosures.set(id,{files:Object.freeze(accepted),refs:1,canonicalRoot,rawRoots:new Set([rawRoot])})
239 let disposed=false
240 return ()=>{if(disposed)return;disposed=true;const current=reviewedClosures.get(id);if(current && --current.refs===0)reviewedClosures.delete(id)}
241 }
242 /** Both runtimes consume the same exact admitted source-file receipt. */
243 export async function importReviewedModule(baseUrl:string,path:string):Promise<unknown> {
244 const rawRoot=resolve(fileURLToPath(baseUrl))
245 const id=pathKey(canonicalPath(rawRoot))
246 const receipt=reviewedClosures.get(id)
247 if(!receipt)throw new Error('composition module closure is no longer admitted')
248 // The entry keeps the caller's spelling of the root: the one the composition
249 // already read and hashed the module through.
250 const entry=resolve(rawRoot,path)
251 const admitted=closureAt(pathToFileURL(entry).href)
252 if(!admitted || admitted.root!==id || !(admitted.path in receipt.files))throw new Error('composition module is absent from reviewed closure')
253 return import(pathToFileURL(entry).href)
254 }
255 function closureAt(url:string|undefined) {
256 if(!url?.startsWith('file:'))return
257 const path=resolve(fileURLToPath(url))
258 for(const [root,receipt] of reviewedClosures) {
259 const inside=keyIn(receipt,path)
260 if(inside!==undefined)return {root,receipt,path:inside}
261 }
262 }
263
264 let installed = false
265
266 /**
267 * Install the hooks once, publishing `modules` (key → module namespace) as the
268 * singletons plugin code will see.
269 */
270 function withDefaultDshModules(modules: Record<string, Record<string, unknown>>): Record<string, Record<string, unknown>> {
271 const llmDefaults: Record<string, unknown> = {
272 createUserMessage: dshMessageCompat.createUserMessage,
273 createAssistantMessage: dshMessageCompat.createAssistantMessage,
274 createSystemMessage: dshMessageCompat.createSystemMessage,
275 createToolResultMessage: dshMessageCompat.createToolResultMessage,
276 freezeMessage: dshMessageCompat.freezeMessage,
277 contentHasImage: dshMessageCompat.contentHasImage,
278 ReasoningEffortId: dshMessageCompat.ReasoningEffortId,
279 MessageId: dshMessageCompat.MessageId,
280 ToolCallId: dshMessageCompat.ToolCallId,
281 isAgentLoopRequest: dshMessageCompat.isAgentLoopRequest,
282 resolveRetryPolicy: dshMessageCompat.resolveRetryPolicy,
283 boundContextSummary: dshMessageCompat.boundContextSummary,
284 BlockAssembler: dshMessageCompat.BlockAssembler,
285 LlmAdapter: dshMessageCompat.LlmAdapter,
286 LlmError: dshMessageCompat.LlmError,
287 HarnessError: dshMessageCompat.HarnessError,
288 }
289 const sessionDefaults: Record<string, unknown> = {
290 SessionId: dshMessageCompat.SessionId,
291 SESSION_FORMAT_VERSION: dshMessageCompat.SESSION_FORMAT_VERSION,
292 KNOWN_SESSION_EVENT_TYPES: dshMessageCompat.KNOWN_SESSION_EVENT_TYPES,
293 deriveEventMessage: dshMessageCompat.deriveEventMessage,
294 }
295 return {
296 'dsh-error': { HarnessError: dshMessageCompat.HarnessError },
297 'dsh-credentials': dshCredentialsModule as unknown as Record<string, unknown>,
298 'dsh-settings': dshSettingsModule as unknown as Record<string, unknown>,
299 'dsh-home-paths': dshHomePathsModule as unknown as Record<string, unknown>,
300 'dsh-atomic-write': dshAtomicWriteModule as unknown as Record<string, unknown>,
301 'dsh-skill': dshSkillModule as unknown as Record<string, unknown>,
302 'dsh-typert-protocol': dshTypertProtocolModule as unknown as Record<string, unknown>,
303 'dsh-workspace': dshWorkspaceModule as unknown as Record<string, unknown>,
304 'dsh-session-surface': dshSessionSurfaceModule as unknown as Record<string, unknown>,
305 'dsh-subagent': dshSubagentModule as unknown as Record<string, unknown>,
306 'dsh-agent': dshAgentModule as unknown as Record<string, unknown>,
307 'dsh-app-boot': dshAppBootModule as unknown as Record<string, unknown>,
308 ...modules,
309 'dsh-llm-values': { ...llmDefaults, ...(modules['dsh-llm-values'] ?? {}) },
310 'dsh-session-values': { ...sessionDefaults, ...(modules['dsh-session-values'] ?? {}) },
311 }
312 }
313
314 export function installResolveHooks(modules: Record<string, Record<string, unknown>>) {
315 if (installed) return
316 installed = true
317 const merged = withDefaultDshModules(modules)
318 ;(globalThis as any)[REGISTRY_KEY] = merged
319 if (RUNTIME.name === 'bun') {
320 installBunResolver(merged)
321 return
322 }
323 nodeModule.registerHooks({
324 resolve(specifier, context, nextResolve) {
325 const key = classifySpecifier(specifier)
326 if (key !== null) {
327 if (!(key in merged)) throw new UnsupportedPeerError(specifier)
328 return { url: `${SCHEME}${key}`, format: 'module', shortCircuit: true }
329 }
330 const caller=closureAt(context.parentURL)
331 const bare=!nodeModule.isBuiltin(specifier) && !specifier.startsWith('.') && !specifier.startsWith('/') && !specifier.startsWith('file:')
332 const result=nextResolve(specifier, context)
333 if(caller) {
334 if(result.url.startsWith('file:')) {
335 const target=closureAt(result.url)
336 if(!target || target.root!==caller.root || !(target.path in caller.receipt.files) || !unlinkedInside(caller.receipt,target.path,fileURLToPath(result.url))) throw new Error('composition import escapes the reviewed file closure')
337 } else if(bare) {
338 throw new Error('composition import escapes the reviewed file closure')
339 }
340 }
341 return result
342 },
343 load(url, context, nextLoad) {
344 if (url.startsWith(SCHEME)) {
345 const key = url.slice(SCHEME.length)
346 return { format: 'module', source: virtualSource(key, merged[key]), shortCircuit: true }
347 }
348 const result=nextLoad(url, context)
349 const closure=closureAt(url)
350 if(closure) {
351 if(!(closure.path in closure.receipt.files) || result.source===undefined || result.source===null) throw new Error('module was absent from reviewed composition closure')
352 // Windows runs Node with --preserve-symlinks, so a linked module keeps
353 // its in-closure URL; refuse it here as the Bun loader does.
354 if(!unlinkedInside(closure.receipt,closure.path,fileURLToPath(url))) throw new Error('module was absent from reviewed composition closure or contains a symbolic link')
355 const source=typeof result.source==='string'?Buffer.from(result.source):Buffer.from(result.source as Uint8Array)
356 if(source.length>256*1024*1024 || createHash('sha256').update(source).digest('hex')!==closure.receipt.files[closure.path]) throw new Error('composition module bytes changed after review')
357 }
358 return result
359 },
360 })
361 }
362
362 lines TYPESCRIPT