返回 CodeWhale
build.mjs
1 // Build the single-file host bundle that the Rust binary embeds.
2 //
3 // `dist/` is committed so `cargo build` never needs Node or npm; CI rebuilds
4 // and fails on drift (`git diff --exit-code dist`).
5 import { build } from 'esbuild'
6 import { createHash } from 'node:crypto'
7 import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync, mkdirSync } from 'node:fs'
8 import { dirname, join } from 'node:path'
9 import { fileURLToPath } from 'node:url'
10 import { redactMcpOAuthLogs } from './scripts/redact-mcp-oauth-logs.mjs'
11
12 const here = dirname(fileURLToPath(import.meta.url))
13 const outdir = join(here, 'dist')
14 mkdirSync(outdir, { recursive: true })
15 const compatibilityBytes = readFileSync(join(here, 'src/dsh/compatibility.json'))
16 const compatibility = JSON.parse(compatibilityBytes)
17 writeFileSync(join(here, '../../plugins/assets/dsh-compatibility.json'), compatibilityBytes)
18 const reusedPure = compatibility.pure_api.reuse
19 const reusedRoot = join(here, 'node_modules', reusedPure.package)
20 const reusedPackage = JSON.parse(readFileSync(join(reusedRoot, 'package.json'), 'utf8'))
21 const reusedSource = readFileSync(join(reusedRoot, reusedPure.file), 'utf8').split('\n').slice(reusedPure.lines[0] - 1, reusedPure.lines[1]).join('\n')
22 if (reusedPackage.version !== reusedPure.version || createHash('sha256').update(reusedSource).digest('hex') !== reusedPure.sha256) {
23 throw new Error(`${reusedPure.package} ${reusedPure.symbol} differs from the pinned pure helper receipt`)
24 }
25
26 // Built-in host modules (tier 0): each `src/builtin/<id>.ts` is built to
27 // `dist/builtin/<id>.mjs`, the file the core activates under the owner id
28 // `host:<id>`, and `dist/builtin-modules.json` records the SHA-256 of every
29 // one. The Rust table `BUILTIN_MODULES` (src/extension_host/tier.rs) pins the
30 // same digests, and a Rust test fails when the two disagree. The committed
31 // host:mcp module is an explicitly selected SDK adapter over Rust broker sessions.
32 // They are built before the host bundle, which embeds the digests.
33 const builtinSource = join(here, 'src/builtin')
34 const builtinOut = join(outdir, 'builtin')
35 rmSync(builtinOut, { recursive: true, force: true }) // a removed module leaves nothing behind
36 const builtinIds = existsSync(builtinSource)
37 ? readdirSync(builtinSource)
38 .filter((file) => file.endsWith('.ts'))
39 .map((file) => file.slice(0, -'.ts'.length))
40 .sort()
41 : []
42 const builtinDigests = {}
43 const builtinMetafiles = []
44 for (const id of builtinIds) {
45 // Mirrors `valid_module_id` in tier.rs: the id is also a file name.
46 if (!/^[a-z][a-z0-9-]{0,63}$/.test(id)) throw new Error(`src/builtin/${id}.ts is not a valid built-in module name`)
47 const outfile = join(builtinOut, `${id}.mjs`)
48 const builtinAlias = id === 'creator'
49 ? {
50 '@deepseek-ai/dsh-tools': join(here, 'src/dsh/dsh-tools-compat.js'),
51 '@deepseek-ai/dsh-sandbox': join(here, 'src/dsh/upstream/creator/sandbox/escalation.js'),
52 '@deepseek-ai/dsh-app-boot': join(here, 'src/dsh/dsh-app-boot-compat.js'),
53 }
54 : undefined
55 const built = await build({
56 entryPoints: [join(builtinSource, `${id}.ts`)],
57 outfile,
58 absWorkingDir: here,
59 metafile: true,
60 bundle: true,
61 platform: 'node',
62 format: 'esm',
63 target: 'node22.19',
64 sourcemap: false,
65 minify: false,
66 legalComments: 'none',
67 charset: 'utf8',
68 logLevel: 'warning',
69 ...(builtinAlias ? { alias: builtinAlias } : {}),
70 banner: { js: `// codewhale built-in host module ${id} — generated by crates/engine/extension-host/build.mjs; do not edit.` },
71 })
72 builtinMetafiles.push(built.metafile)
73 if (id === 'mcp') {
74 writeFileSync(outfile, redactMcpOAuthLogs(readFileSync(outfile, 'utf8')))
75 }
76 builtinDigests[id] = createHash('sha256').update(readFileSync(outfile)).digest('hex')
77 }
78 writeFileSync(join(outdir, 'builtin-modules.json'), JSON.stringify({ modules: builtinDigests }, null, 2) + '\n')
79
80 const compositionAlias = {
81 '@deepseek-ai/cordis-plugin-loader': join(here, 'src/dsh/upstream/loader/src/index.ts'),
82 }
83
84 const hostBuild = await build({
85 alias: compositionAlias,
86 entryPoints: [join(here, 'src/main.ts')],
87 outfile: join(outdir, 'codewhale-extension-host.mjs'),
88 absWorkingDir: here,
89 metafile: true,
90 bundle: true,
91 platform: 'node',
92 format: 'esm',
93 target: 'node22.19',
94 // Deterministic output: no sourcemap paths, no timestamps, no minification
95 // (a readable bundle keeps the reviewed-bytes story honest).
96 sourcemap: false,
97 minify: false,
98 legalComments: 'none',
99 charset: 'utf8',
100 logLevel: 'warning',
101 // `host/hello` reports these, so the core can check the bundle and its own
102 // pinned table agree (`tier.ts`, `builtinModuleDigests`).
103 define: { __BUILTIN_MODULE_DIGESTS__: JSON.stringify(builtinDigests) },
104 banner: {
105 js: '// codewhale-extension-host — generated by crates/engine/extension-host/build.mjs; do not edit.\n// Third-party notices: LICENSES.txt next to this file.',
106 },
107 })
108
109 // Test-only reviewed hook bridge: Node tests exercise the exact pinned parser.
110 await build({
111 entryPoints: [join(here, 'src/dsh/shell-hooks.ts')],
112 outfile: join(outdir, 'shell-hooks.mjs'),
113 absWorkingDir: here,
114 bundle: true,
115 platform: 'node',
116 format: 'esm',
117 target: 'node22.19',
118 sourcemap: false,
119 minify: false,
120 legalComments: 'none',
121 charset: 'utf8',
122 logLevel: 'warning',
123 })
124
125 // Trusted offline composition reviewer. Embedded beside the host, but has
126 // no HostRoot, RPC handler, plugin import or expression evaluation entrypoint.
127 const reviewBuild = await build({
128 alias: compositionAlias,
129 entryPoints: [join(here, 'src/dsh/review-main.ts')],
130 outfile: join(outdir, 'dsh-composition-review.mjs'),
131 absWorkingDir: here,
132 metafile: true,
133 bundle: true,
134 platform: 'node',
135 format: 'esm',
136 target: 'node22.19',
137 sourcemap: false,
138 minify: false,
139 legalComments: 'none',
140 charset: 'utf8',
141 logLevel: 'warning',
142 banner: { js: '// trusted nonexecuting DSH composition reviewer; third-party notices: LICENSES.txt' },
143 })
144
145 // Test-only pure adapters: the production harness imports exactly this source.
146 await build({entryPoints:[join(here,'src/builtin/shared/stock-adapters.ts')],outfile:join(outdir,'stock-adapters.mjs'),bundle:true,platform:'node',format:'esm',target:'node22.19',sourcemap:false,minify:false,legalComments:'none',charset:'utf8',logLevel:'warning'})
147
148 // Test-only protocol module (codec + validators) so `node --test` can check
149 // the corpus against the exact code the host runs, without booting a host.
150 // Not embedded in the Rust binary.
151 await build({
152 entryPoints: [join(here, 'src/protocol.ts')],
153 outfile: join(outdir, 'protocol.mjs'),
154 bundle: true,
155 platform: 'node',
156 format: 'esm',
157 target: 'node22.19',
158 sourcemap: false,
159 minify: false,
160 legalComments: 'none',
161 charset: 'utf8',
162 logLevel: 'warning',
163 banner: { js: '// generated by crates/engine/extension-host/build.mjs from src/protocol.ts; do not edit.' },
164 })
165
166 // Test-only RPC peer, for the unit tests of its cancellation. Not embedded.
167 await build({
168 entryPoints: [join(here, 'src/rpc.ts')],
169 outfile: join(outdir, 'rpc.mjs'),
170 bundle: true,
171 platform: 'node',
172 format: 'esm',
173 target: 'node22.19',
174 sourcemap: false,
175 minify: false,
176 legalComments: 'none',
177 charset: 'utf8',
178 logLevel: 'warning',
179 banner: { js: '// generated by crates/engine/extension-host/build.mjs from src/rpc.ts; do not edit.' },
180 })
181
182 // Test-only skill-root shim, bundled so tests remain dependency-free before npm ci.
183 await build({
184 entryPoints: [join(here, 'src/shims/skills.ts')],
185 outfile: join(outdir, 'skills.mjs'),
186 absWorkingDir: here,
187 bundle: true,
188 platform: 'node',
189 format: 'esm',
190 target: 'node22.19',
191 sourcemap: false,
192 minify: false,
193 legalComments: 'none',
194 charset: 'utf8',
195 logLevel: 'warning',
196 banner: { js: '// generated by crates/engine/extension-host/build.mjs from src/shims/skills.ts; do not edit.' },
197 })
198
199 // Test-only avatar-pack shim, bundled so tests remain dependency-free before npm ci.
200 await build({
201 entryPoints: [join(here, 'src/shims/avatars.ts')],
202 outfile: join(outdir, 'avatars.mjs'),
203 absWorkingDir: here,
204 bundle: true,
205 platform: 'node',
206 format: 'esm',
207 target: 'node22.19',
208 sourcemap: false,
209 minify: false,
210 legalComments: 'none',
211 charset: 'utf8',
212 logLevel: 'warning',
213 banner: { js: '// generated by crates/engine/extension-host/build.mjs from src/shims/avatars.ts; do not edit.' },
214 })
215
216 // Source-focused raw roster tests use the same discovery/receipt adapter.
217 await build({entryPoints:[join(here,'src/dsh/agent-presets.ts')],outfile:join(outdir,'agent-presets.mjs'),alias:compositionAlias,bundle:true,platform:'node',format:'esm',target:'node22.19',sourcemap:false,minify:false,legalComments:'none',charset:'utf8',logLevel:'warning'})
218
219 // Third-party notices (`dist/LICENSES.txt`), generated from what the bundler
220 // actually put in the host bundle: every package that contributed an input
221 // file, with its own LICENSE file. A package added to or dropped from the
222 // bundle changes this file, and CI's `git diff --exit-code -- dist` then
223 // catches a stale one. The Rust core embeds this file and writes it beside the
224 // materialised bundle, so the banner's promise ("LICENSES.txt next to this
225 // file") holds for every installed copy.
226 const LICENSE_FILES = ['LICENSE', 'LICENSE.md', 'LICENSE.txt', 'LICENCE', 'LICENCE.md', 'license', 'license.md', 'COPYING']
227
228 function bundledPackages(metafile) {
229 const found = new Map()
230 for (const input of Object.keys(metafile.inputs)) {
231 const marker = 'node_modules/'
232 const at = input.lastIndexOf(marker)
233 if (at < 0) continue
234 const [first, second] = input.slice(at + marker.length).split('/')
235 const name = first.startsWith('@') ? `${first}/${second}` : first
236 found.set(name, join(here, input.slice(0, at + marker.length), name))
237 }
238 return [...found.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([name, root]) => ({ name, root }))
239 }
240
241 function readLicense(root, label) {
242 for (const file of LICENSE_FILES) {
243 try {
244 return readFileSync(join(root, file), 'utf8').trim()
245 } catch {}
246 }
247 throw new Error(`${label} is bundled but ships no LICENSE file in ${root}; add its notice by hand before releasing`)
248 }
249
250 // Source vendored into `src/` verbatim rather than imported from node_modules.
251 // The metafile cannot see these, so each names the file that carries the
252 // excerpt and the bundled package whose licence text it shares (checked below).
253 const EXCERPTED = [
254 {
255 name: '@deepseek-ai/dsh-tools',
256 version: compatibility.definition_api.version,
257 license: 'MIT',
258 file: 'src/dsh/dsh-tools-compat.js',
259 licenseOf: '@deepseek-ai/dsh-util-values',
260 },
261 ...compatibility.pure_api.packages.filter(pkg => pkg.excerpted).map(pkg => ({
262 name: pkg.package,
263 version: pkg.version,
264 license: pkg.license,
265 file: compatibility.pure_api.file,
266 sourceSha256: compatibility.pure_api.source_sha256,
267 licenseTextSha256: pkg.license_text_sha256,
268 licenseOf: '@deepseek-ai/dsh-util-values',
269 })),
270 ]
271
272 const packageInputs = [hostBuild.metafile, reviewBuild.metafile, ...builtinMetafiles].flatMap(bundledPackages)
273 const packagesByIdentity = new Map()
274 for (const { name, root } of packageInputs) {
275 const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
276 if (typeof pkg.license !== 'string' || pkg.license.length === 0) throw new Error(`${name} declares no license in package.json`)
277 const entry = { name: pkg.name, version: pkg.version, license: pkg.license, text: readLicense(root, name) }
278 const identity = `${entry.name}@${entry.version}`
279 const prior = packagesByIdentity.get(identity)
280 if (prior && (prior.license !== entry.license || prior.text !== entry.text)) throw new Error(`${identity} contributes conflicting licence texts`)
281 packagesByIdentity.set(identity, entry)
282 }
283 const packages = [...packagesByIdentity.values()]
284 if (packages.length === 0) throw new Error('the host bundle contains no node_modules input: the notice generator is reading the wrong metafile')
285
286 const entries = packages.map((pkg) => ({ ...pkg, note: '' }))
287 for (const excerpt of EXCERPTED) {
288 const source = readFileSync(join(here, excerpt.file), 'utf8')
289 if (excerpt.sourceSha256 ? createHash('sha256').update(source).digest('hex') !== excerpt.sourceSha256 : !source.includes(`${excerpt.name}@${excerpt.version}`)) {
290 throw new Error(`${excerpt.file} no longer names ${excerpt.name}@${excerpt.version}; update EXCERPTED in build.mjs`)
291 }
292 const shared = packages.find((pkg) => pkg.name === excerpt.licenseOf)
293 if (!shared) throw new Error(`${excerpt.licenseOf} (licence text of ${excerpt.name}) is not bundled`)
294 if (excerpt.licenseTextSha256 && (shared.license !== excerpt.license || createHash('sha256').update(shared.text).digest('hex') !== excerpt.licenseTextSha256)) {
295 throw new Error(`${excerpt.name} licence text differs from its pinned pure helper receipt`)
296 }
297 entries.push({
298 name: excerpt.name,
299 version: excerpt.version,
300 license: excerpt.license,
301 text: shared.text,
302 note: `Verbatim excerpts of this package are in ${excerpt.file}, under the same licence text as ${excerpt.licenseOf} above.`,
303 })
304 }
305 const vendoredPin = JSON.parse(readFileSync(join(here, 'src/dsh/upstream/UPSTREAM.json'), 'utf8'))
306 const hooksPin = JSON.parse(readFileSync(join(here, 'src/dsh/upstream/hooks/UPSTREAM.json'), 'utf8'))
307 const personaPin = JSON.parse(readFileSync(join(here, 'src/dsh/persona.UPSTREAM.json'), 'utf8'))
308 const creatorPin = JSON.parse(readFileSync(join(here, 'src/dsh/upstream/creator/UPSTREAM.json'), 'utf8'))
309 const creatorLicense = readLicense(join(here, 'src/dsh/upstream/creator'), 'vendored creator')
310 entries.push({
311 name: '@deepseek-ai/dsh-plugin-manager',
312 version: creatorPin.version,
313 license: creatorPin.license,
314 text: creatorLicense,
315 note: `Pinned @deepseek-ai/dsh-plugin-manager@${creatorPin.version} lib/types/tools.js verbatim in src/dsh/upstream/creator/plugin-manager/tools.js; adapted behind Codewhale broker services in src/dsh/plugin-manager.ts and src/builtin/creator.ts.`,
316 })
317 entries.push({
318 name: '@deepseek-ai/dsh-tool-cordis',
319 version: creatorPin.version,
320 license: creatorPin.license,
321 text: creatorLicense,
322 note: `Pinned @deepseek-ai/dsh-tool-cordis@${creatorPin.version} lib/index.js verbatim in src/dsh/upstream/creator/tool-cordis/index.js; wired behind Codewhale broker services in src/builtin/creator.ts.`,
323 })
324 entries.push({
325 name: '@deepseek-ai/dsh-sandbox',
326 version: creatorPin.version,
327 license: creatorPin.license,
328 text: creatorLicense,
329 note: `Pinned @deepseek-ai/dsh-sandbox@${creatorPin.version} lib/index.js escalation excerpt in src/dsh/upstream/creator/sandbox/escalation.js; Core retains sandbox and approval enforcement.`,
330 })
331 for (const folder of ['loader', 'include', 'group']) {
332 const { version } = JSON.parse(readFileSync(join(here, 'src/dsh/upstream', folder, 'package.json'), 'utf8'))
333 entries.push({
334 name: `@deepseek-ai/cordis-plugin-${folder}`,
335 version,
336 license: 'MIT',
337 text: readLicense(join(here, 'src/dsh/upstream', folder), `vendored ${folder}`),
338 note: `Pinned deepseek-harness ${vendoredPin.commit}. Loader native-internals probe disabled; reviewed imports and non-writing composition retain Codewhale's authority boundary.`,
339 })
340 }
341 entries.push({name:'@deepseek-ai/dsh-agent-presets',version:'0.1.6-alpha.1',license:'MIT',text:readLicense(join(here,'src/dsh/upstream/agent-presets'),'vendored agent-presets'),note:'Pinned deepseek-harness 0d1f50007f9bca3f52b06e1c3074fa14d5fb0720. Discovery/metadata/specifier/inventory algorithms use mandatory receipt-backed IO; Core owns selection, sessions and writable roots.'})
342 for (const name of ['dsh-hook-protocol', 'dsh-hooks-claude-code', 'dsh-hooks-codex']) {
343 entries.push({
344 name: `@deepseek-ai/${name}`,
345 version: hooksPin.version,
346 license: 'MIT',
347 text: readLicense(join(here, 'src/dsh/upstream/hooks'), `vendored ${name}`),
348 note: `Pinned deepseek-harness ${hooksPin.ref}. Pure matcher/codec/merge and configuration parsers reused; local imports and session-writer type declarations adapted. Core retains scheduling and steering.`,
349 })
350 }
351 for (const name of ['dsh-persona', 'dsh-system-prompt']) {
352 entries.push({
353 name: `@deepseek-ai/${name}`,
354 version: personaPin.version,
355 license: 'MIT',
356 text: readLicense(join(here, 'src/dsh/upstream/hooks'), `adapted ${name}`),
357 note: `Pinned deepseek-harness ${personaPin.commit}. Additive persona configuration and strict simple template mapping adapted in src/dsh/persona.ts and the Rust prompt renderer; source and license receipts: src/dsh/persona.UPSTREAM.json. Core retains prompt assembly and accepted model/workspace values.`,
358 })
359 }
360 entries.sort((a, b) => (a.name < b.name ? -1 : 1))
361
362 const sections = [
363 'Third-party software bundled into codewhale-extension-host.mjs, dsh-composition-review.mjs and builtin/*.mjs.',
364 'Generated by crates/engine/extension-host/build.mjs from the bundler metafile; do not edit.',
365 '',
366 'Packages:',
367 ...entries.map((entry) => ` ${entry.name}@${entry.version} (${entry.license})`),
368 ]
369 for (const entry of entries) {
370 sections.push('', '='.repeat(72), `${entry.name}@${entry.version} (${entry.license})`, '='.repeat(72))
371 if (entry.note) sections.push('', entry.note)
372 sections.push('', entry.text)
373 }
374 // Preserve every notice word while keeping generated text free of trailing whitespace.
375 writeFileSync(join(outdir, 'LICENSES.txt'), sections.join('\n').replace(/[ \t]+$/gm, '') + '\n')
376
376 lines Plain Text