返回 CodeWhale
harness.mjs
根目录 / crates / engine / extension-host / test / harness.mjs
1 // A minimal fake core: spawns the committed host bundle and speaks CWX1 to it.
2 // Tests import only dist/ — no type stripping, no install.
3 import { spawn } from 'node:child_process'
4 import { createHash } from 'node:crypto'
5 import { readFileSync } from 'node:fs'
6 import { dirname, join } from 'node:path'
7 import { fileURLToPath } from 'node:url'
8 import { FrameDecoder, encodeFrame, validateMessage } from '../dist/protocol.mjs'
9
10 const here = dirname(fileURLToPath(import.meta.url))
11 export const BUNDLE = join(here, '..', 'dist', 'codewhale-extension-host.mjs')
12 export const FIXTURES = join(here, '..', '..', 'tests', 'fixtures', 'extension_host')
13
14 export function sha256File(path) {
15 return createHash('sha256').update(readFileSync(path)).digest('hex')
16 }
17
18 /** The runtime running these tests also runs the host: `node --test` or `bun test`. */
19 export const IS_BUN = typeof process.versions.bun === 'string'
20
21 /**
22 * The runtime flags and environment the Rust core passes
23 * (`supervisor::runtime_args` / `runtime_env`); keep them in sync. Bun ignores
24 * Node's heap and `__proto__` flags, so it gets its own: never auto-install
25 * packages, ignore `bunfig.toml` and `.env` files in the working directory,
26 * and no ShadowRealm. Node switches off `node:sqlite`, and `node:ffi` where
27 * this Node has it. Both get a blank `NODE_OPTIONS`, so an inherited preload
28 * cannot run before the native-code lockdown.
29 */
30 export const HOST_ARGS = IS_BUN
31 ? ['--no-install', '--no-env-file', `--config=${process.platform === 'win32' ? 'NUL' : '/dev/null'}`, '--no-addons']
32 : [
33 '--max-old-space-size=256',
34 '--disable-proto=throw',
35 '--no-addons',
36 ...(process.platform === 'win32' ? ['--preserve-symlinks', '--preserve-symlinks-main'] : []),
37 '--no-experimental-sqlite',
38 ...(process.allowedNodeEnvironmentFlags.has('--no-experimental-ffi') ? ['--no-experimental-ffi'] : []),
39 ]
40 export const HOST_ENV = { NODE_OPTIONS: '', ...(IS_BUN ? { BUN_JSC_useShadowRealm: '0', BUN_OPTIONS: '', BUN_BE_BUN: '0' } : {}) }
41
42 export const LIMITS = { max_frame: 32 * 1024 * 1024, max_inflight: 256, dispose_deadline_ms: 2000, activate_deadline_ms: 5000 }
43
44 /**
45 * Start a host. `admit(spec, owner)` decides `registry/register`: return a
46 * handle number or `{ refused }`. Registry traffic is recorded in `registry`.
47 * `tier` is the trust tier it serves (`--tier=`, after the bundle, as the Rust
48 * core passes it); `null` passes none, as a host started by hand would.
49 * `coreCall(params, id)` answers a `core/call` request: return a tool result, or
50 * `{ error: { code, message } }`; it may be async, and a request the host
51 * cancelled is not answered. Requests are recorded in `coreCalls`, the host's
52 * `$/cancel` ids in `cancels`.
53 */
54 export async function startHost({ admit, env, ownGroup = false, tier = 'plugin', coreCall, checkpoint, userQuestions, subagent, dshBroker, compiledHost, cwd } = {}) {
55 const started = performance.now()
56 // `ownGroup` spawns the host as a process-group leader and tells it so, as
57 // the Rust core does on Unix.
58 const child = spawn(compiledHost ?? process.execPath, [...(compiledHost ? [] : [...HOST_ARGS, BUNDLE]), ...(tier === null ? [] : [`--tier=${tier}`])], {
59 stdio: ['pipe', 'pipe', 'pipe'],
60 cwd,
61 env: { ...process.env, ...HOST_ENV, ...env, ...(compiledHost ? { NODE_OPTIONS: '', BUN_OPTIONS: '', BUN_BE_BUN: '0', BUN_JSC_useShadowRealm: '0' } : {}), ...(ownGroup ? { CODEWHALE_HOST_PROCESS_GROUP: '1' } : {}) },
62 detached: ownGroup,
63 })
64 const decoder = new FrameDecoder()
65 const pending = new Map()
66 const waiters = []
67 let stopping = false
68 const host = {
69 child,
70 stderr: '',
71 logs: [],
72 faulted: [],
73 coreCalls: [],
74 brokerCalls: [],
75 checkpoints: [],
76 questions: [],
77 subagents: [],
78 cancels: [],
79 registry: [],
80 hello: null,
81 nextId: 1,
82 nextHandle: 1,
83 exit: new Promise((resolve) => child.on('exit', (code, signal) => resolve({ code, signal }))),
84 send(message) {
85 // Shutdown abandons queued fake-core replies; never write them to stdin
86 // after `stop()` has ended the stream (Windows reports this as an error).
87 if (stopping || child.exitCode !== null || child.signalCode !== null || child.stdin.destroyed || child.stdin.writableEnded) return false
88 validateMessage(message, 'core_to_host', tier ?? 'plugin')
89 return child.stdin.write(encodeFrame(message))
90 },
91 request(method, params) {
92 const id = host.nextId++
93 const promise = new Promise((resolve, reject) => pending.set(id, { resolve, reject }))
94 host.send({ jsonrpc: '2.0', id, method, params })
95 return { id, promise }
96 },
97 call(method, params) {
98 return host.request(method, params).promise
99 },
100 cancel(id) {
101 host.send({ jsonrpc: '2.0', method: '$/cancel', params: { id } })
102 },
103 waitFor(predicate, timeoutMs = 5000) {
104 return new Promise((resolve, reject) => {
105 const timer = setTimeout(() => reject(new Error('timed out waiting for host message')), timeoutMs)
106 waiters.push({ predicate, resolve: (value) => { clearTimeout(timer); resolve(value) } })
107 })
108 },
109 async stop() {
110 if (child.exitCode === null && child.signalCode === null) {
111 // The child can still have a core/call response queued on the fake
112 // core while it handles stdin EOF. Those replies are intentionally
113 // abandoned once shutdown starts.
114 stopping = true
115 child.stdin.end()
116 await host.exit
117 }
118 },
119 }
120 child.stderr.on('data', (chunk) => { host.stderr += chunk.toString() })
121 child.stdout.on('data', (chunk) => {
122 for (const raw of decoder.push(chunk)) {
123 const message = validateMessage(raw, 'host_to_core', tier ?? 'plugin')
124 for (let i = waiters.length - 1; i >= 0; i--) {
125 if (waiters[i].predicate(message)) waiters.splice(i, 1)[0].resolve(message)
126 }
127 if ('method' in message) {
128 switch (message.method) {
129 case 'host/hello':
130 host.hello = message.params
131 break
132 case 'log':
133 host.logs.push(message.params)
134 break
135 case 'ext/faulted':
136 host.faulted.push(message.params)
137 break
138 case 'registry/register': {
139 host.registry.push({ op: 'register', ...message.params })
140 const verdict = admit ? admit(message.params.spec, message.params.owner) : undefined
141 const result = verdict && typeof verdict === 'object' ? verdict : { handle: verdict ?? host.nextHandle++ }
142 if ('handle' in result) host.registry.at(-1).handle = result.handle
143 host.send({ jsonrpc: '2.0', id: message.id, result })
144 break
145 }
146 case '$/cancel':
147 host.cancels.push(message.params.id)
148 break
149 case 'session/checkpoint':
150 case 'user-questions/ask':
151 case 'subagent/start':
152 case 'subagent/result':
153 case 'subagent/dispose':
154 case 'subagent/prompt':
155 case 'dsh/broker':
156 case 'core/call': {
157 const childRequest = message.method.startsWith('subagent/')
158 const handler = message.method === 'session/checkpoint'
159 ? checkpoint
160 : message.method === 'user-questions/ask'
161 ? userQuestions
162 : childRequest
163 ? subagent
164 : message.method === 'dsh/broker'
165 ? dshBroker
166 : coreCall
167 const records = message.method === 'session/checkpoint'
168 ? host.checkpoints
169 : message.method === 'user-questions/ask'
170 ? host.questions
171 : childRequest
172 ? host.subagents
173 : message.method === 'dsh/broker'
174 ? host.brokerCalls
175 : host.coreCalls
176 records.push({ id: message.id, ...(childRequest ? { method: message.method } : {}), ...message.params })
177 const answer = handler ? handler(message.params, message.id, message.method) : { error: { code: -32002, message: 'no handler for ' + message.method } }
178 const id = message.id
179 Promise.resolve(answer).then((value) => {
180 if (host.cancels.includes(id) || child.exitCode !== null || stopping) return
181 if (value && typeof value === 'object' && 'error' in value) host.send({ jsonrpc: '2.0', id, error: value.error })
182 else host.send({ jsonrpc: '2.0', id, result: value })
183 })
184 break
185 }
186 case 'registry/unregister':
187 host.registry.push({ op: 'unregister', ...message.params })
188 host.send({ jsonrpc: '2.0', id: message.id, result: {} })
189 break
190 }
191 } else {
192 const waiter = pending.get(message.id)
193 if (waiter) {
194 pending.delete(message.id)
195 if ('error' in message) waiter.reject(Object.assign(new Error(message.error.message), { code: message.error.code }))
196 else waiter.resolve(message.result)
197 }
198 }
199 }
200 })
201 await host.waitFor((m) => m.method === 'host/hello')
202 const ready = host.waitFor((m) => m.method === 'host/ready')
203 await host.call('host/initialize', { protocol: 1, limits: LIMITS })
204 await ready
205 host.readyMs = performance.now() - started
206 return host
207 }
208
209 let token = 0
210 export function owner(pluginId) {
211 token += 1
212 return { plugin_id: pluginId, generation: 1, owner_token: `token-${pluginId}-${token}-${'0'.repeat(24)}` }
213 }
214
215 /** `extra` adds or replaces `ext/activate` params, such as `config` and `data_dir`. */
216 export async function activate(host, fixture, entryPath = join(FIXTURES, fixture, 'index.mjs'), extra = {}) {
217 const ref = owner(fixture)
218 const result = await host.call('ext/activate', {
219 owner: ref,
220 plugin_name: fixture,
221 entry: { path: entryPath, sha256: sha256File(entryPath) },
222 config: {},
223 ...extra,
224 })
225 return { ref, result }
226 }
227
227 lines Plain Text