返回 CodeWhale
main.ts
1 /**
2 * codewhale-extension-host entry point.
3 *
4 * Boot order matters: stdout is the protocol channel, so it is captured and
5 * every other writer is rebound to stderr *before* any plugin code can load.
6 */
7 import { createHash } from 'node:crypto'
8 import { readFileSync } from 'node:fs'
9 import { createRequire } from 'node:module'
10 import { fileURLToPath } from 'node:url'
11 import * as cordis from '@deepseek-ai/cordis'
12 import * as schemastery from '@deepseek-ai/schemastery'
13 import * as cosmokit from '@deepseek-ai/cosmokit'
14 import * as dshUtilValues from '@deepseek-ai/dsh-util-values'
15 import * as dshToolsCompat from './dsh/dsh-tools-compat.js'
16 import { createUserMessage, SessionId, PERSONA_PREFIX_SECTION, HarnessError, UserQuestionError } from './dsh/dsh-message-compat.js'
17 import * as dshComposition from './dsh/composition.ts'
18 import * as dshLoader from './dsh/upstream/loader/src/index.ts'
19 import * as dshInclude from './dsh/upstream/include/src/index.ts'
20 import { installResolveHooks } from './dsh/resolve-hooks.ts'
21 import { dispatchPluginRoute } from './dsh/webserver.ts'
22 import { ErrorCode, FrameDecoder, encodeFrame, PROTOCOL_VERSION, type Message, type HarnessRunParams, type McpOpenParams, type McpRequestParams, type McpCloseParams, type PluginRouteDispatchParams } from './protocol.ts'
23 import { RpcError, RpcPeer } from './rpc.ts'
24 import { HostRoot, ownerStorage } from './root.ts'
25 import { RUNTIME, applyMemoryLimit, denyNativeCode } from './runtime.ts'
26 import { builtinModuleDigests, parseTier } from './tier.ts'
27 import { windowsSandboxProbe } from './windows-sandbox-probe.mjs'
28
29 export const HOST_VERSION = '0.1.0'
30
31 // 0a. Which trust tier this process serves (`--tier=plugin|builtin`). Anything
32 // else is refused before the host does any work. `process.exit` is still
33 // the real one here; step 2 replaces it.
34 const TIER = (() => {
35 try {
36 return parseTier(process.argv.slice(2))
37 } catch (error) {
38 process.stderr.write(`codewhale-extension-host: ${(error as Error).message}\n`)
39 return process.exit(64)
40 }
41 })()
42
43 // Fixed diagnostic mode is selected only by Core before Native admission. It
44 // works in the compiled image too, without inventing a second host executable.
45 if (process.argv.includes('--windows-sandbox-probe')) {
46 if (process.platform !== 'win32' || TIER !== 'plugin') process.exit(64)
47 try {
48 process.stdout.write(JSON.stringify(await windowsSandboxProbe()) + '\n')
49 process.exit(0)
50 } catch (error) {
51 process.stderr.write(`Windows sandbox probe: ${(error as Error).message}\n`)
52 process.exit(70)
53 }
54 }
55
56 // 0b. The kernel memory limit the core asked for (macOS + Bun). This may
57 // re-execute the process in place (argv, and so the tier, are kept), so it
58 // runs before anything else that has an effect.
59 const MEMORY_LIMIT_MIB = applyMemoryLimit()
60
61 // 1. Own the protocol channel; rebind every other stdout writer to stderr.
62 const channelWrite = process.stdout.write.bind(process.stdout)
63 const stderrWrite = process.stderr.write.bind(process.stderr)
64 process.stdout.write = ((chunk: any, encoding?: any, callback?: any) =>
65 stderrWrite(chunk, encoding, callback)) as typeof process.stdout.write
66 for (const method of ['log', 'info', 'debug', 'trace', 'dir'] as const) {
67 ;(console as any)[method] = (...args: unknown[]) => console.error(...args)
68 }
69
70 // 2. A plugin bug must not be able to end the host. (Not a security control:
71 // `process.kill(process.pid)` still works.)
72 const realExit = process.exit.bind(process)
73 process.exit = ((code?: number) => {
74 throw new Error(`process.exit(${code ?? ''}) is not available to plugins`)
75 }) as typeof process.exit
76 process.abort = (() => {
77 throw new Error('process.abort() is not available to plugins')
78 }) as typeof process.abort
79
80 // 3. One Cordis, one schemastery, one cosmokit for every plugin.
81 installResolveHooks({
82 cordis: cordis as unknown as Record<string, unknown>,
83 schemastery: schemastery as unknown as Record<string, unknown>,
84 cosmokit: cosmokit as unknown as Record<string, unknown>,
85 'dsh-util-values': dshUtilValues as unknown as Record<string, unknown>,
86 'dsh-tools': dshToolsCompat as unknown as Record<string, unknown>,
87 'dsh-llm-values': { createUserMessage, HarnessError },
88 'dsh-user-questions-values': { UserQuestionError },
89 'dsh-session-values': { SessionId },
90 'dsh-system-prompt-values': { PERSONA_PREFIX_SECTION },
91 'dsh-composition': dshComposition as unknown as Record<string, unknown>,
92 'dsh-loader': dshLoader as unknown as Record<string, unknown>,
93 'dsh-include': dshInclude as unknown as Record<string, unknown>,
94 'dsh-group': { default: dshLoader.Group },
95 // `@deepseek-ai/dsh-commands/brand`: the brands are plain strings at runtime.
96 'dsh-commands-brand': { CommandDefinitionId: (id: string) => id, CommandId: (id: string) => id },
97 })
98
99 // Only the release compiler defines this constant. Runtime environments never
100 // supply it: the compiled image still identifies the canonical embedded source.
101 declare const CODEWHALE_COMPILED_BUNDLE_SHA256: string | undefined
102
103 function bundleDigest(): string {
104 if (typeof CODEWHALE_COMPILED_BUNDLE_SHA256 === 'string') return CODEWHALE_COMPILED_BUNDLE_SHA256
105 try {
106 return createHash('sha256').update(readFileSync(fileURLToPath(import.meta.url))).digest('hex')
107 } catch {
108 return 'unknown'
109 }
110 }
111
112 // 3b. When the core goes away, take every process this host started with it.
113 // On Unix the core spawns the host as the leader of its own process group
114 // and says so; killing the group reaches plugin children (not ones that
115 // called `setsid`). On Windows the core's Job Object does this when the
116 // core's handle closes.
117 const OWN_GROUP = process.platform !== 'win32' && process.env.CODEWHALE_HOST_PROCESS_GROUP === '1'
118
119 function killHostTree(): never {
120 if (OWN_GROUP) {
121 try {
122 process.kill(-process.pid, 'SIGKILL')
123 } catch {
124 // Not a group leader after all; exit alone.
125 }
126 }
127 return realExit(0)
128 }
129
130 // A plugin that blocks the event loop would never see stdin EOF, so a
131 // watchdog on its own thread notices the parent going away (the host is
132 // re-parented, which PID reuse cannot fake) and kills the tree from there.
133 // `require`, not `import`: under Bun an ESM import would fix the module's
134 // namespace before `denyNativeCode` replaces `Worker` for plugins.
135 const { Worker } = createRequire(import.meta.url)('node:worker_threads') as typeof import('node:worker_threads')
136 const watchdog = new Worker(
137 `const { workerData } = require('node:worker_threads')
138 const parent = process.ppid
139 setInterval(() => {
140 if (process.ppid === parent) return
141 try { process.kill(workerData.group ? -workerData.pid : workerData.pid, 'SIGKILL') } catch {}
142 }, 500)`,
143 // A Worker isolate reserves its own executable code range. On Linux x64
144 // with Node 24 that reservation is charged in full to the host's 1 GiB
145 // RLIMIT_DATA cap, so a default-sized range aborted the host at startup
146 // ("Failed to reserve virtual memory for CodeRange"). This loop needs
147 // almost no generated code.
148 { eval: true, workerData: { pid: process.pid, group: OWN_GROUP }, resourceLimits: { maxOldGenerationSizeMb: 8, codeRangeSizeMb: 16 } },
149 )
150 watchdog.unref()
151
152 // 3c. No in-process native code for plugins (`runtime.ts`). After the
153 // watchdog, which is the host's only Worker.
154 await denyNativeCode()
155
156 function shutdownNow(code: number) {
157 // Let queued frames flush before exiting.
158 channelWrite('', () => realExit(code))
159 setTimeout(() => realExit(code), 200).unref()
160 }
161
162 const rpc = new RpcPeer((message: Message) => {
163 channelWrite(encodeFrame(message))
164 }, TIER)
165 const host = new HostRoot(rpc, TIER)
166 let initialized = false
167
168 rpc.onRequest('host/initialize', (params: any) => {
169 if (params.protocol !== PROTOCOL_VERSION) {
170 stderrWrite(`codewhale-extension-host: core speaks protocol ${params.protocol}, host speaks ${PROTOCOL_VERSION}\n`)
171 setImmediate(() => realExit(78))
172 throw new RpcError(ErrorCode.InvalidParams, `unsupported protocol ${params.protocol}`)
173 }
174 initialized = true
175 setImmediate(() => rpc.notify('host/ready', {}))
176 return {}
177 })
178
179 function requireInitialized() {
180 if (!initialized) throw new RpcError(ErrorCode.InvalidRequest, 'host is not initialized')
181 }
182
183 rpc.onRequest('host/ping', () => {
184 requireInitialized()
185 return {}
186 })
187
188 rpc.onRequest('ext/activate', async (params: any) => {
189 requireInitialized()
190 return host.activate(params)
191 })
192
193 rpc.onRequest('ext/deactivate', async (params: any) => {
194 requireInitialized()
195 return host.deactivate(params.owner, params.entry)
196 })
197
198 rpc.onRequest('tool/call', async (params: any, cx) => {
199 requireInitialized()
200 return host.callTool(params.handle, params.input, params.call_id, cx.signal, params.workspace, params.ticket, params)
201 })
202
203 rpc.onRequest('command/run', async (params: any, cx) => {
204 requireInitialized()
205 return host.callCommand(params.handle, params.raw_input, params.command_id, cx.signal, params.workspace, params)
206 })
207
208 rpc.onRequest('hook/evaluate', async (params: any, cx) => {
209 requireInitialized()
210 return host.evaluateHook(params, cx.signal)
211 })
212
213 rpc.onRequest('plugin_route/dispatch', async (params, cx) => {
214 requireInitialized()
215 return dispatchPluginRoute(host, params as PluginRouteDispatchParams, cx.signal, (owner, fn) => ownerStorage.run(owner, fn))
216 })
217
218 rpc.onRequest('harness/run', async (params, cx) => { requireInitialized(); return host.harnessRun(params as HarnessRunParams, cx.signal) })
219 rpc.onRequest('mcp/open', async (params, cx) => { requireInitialized(); return host.mcpOpen(params as McpOpenParams, cx.signal) })
220 rpc.onRequest('mcp/request', async (params, cx) => { requireInitialized(); return host.mcpRequest(params as McpRequestParams, cx.signal) })
221 rpc.onRequest('mcp/close', async (params) => { requireInitialized(); return host.mcpClose(params as McpCloseParams) })
222
223 rpc.onRequest('host/shutdown', async () => {
224 await host.deactivateAll(2_000)
225 setImmediate(() => shutdownNow(0))
226 return {}
227 })
228
229 // 4. Faults are attributed to the owning fiber, which is disposed; the host survives.
230 function onFault(error: unknown) {
231 const owner = ownerStorage.getStore()
232 const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
233 if (owner && owner.state !== 'disposed') {
234 rpc.notify('ext/faulted', { owner: owner.ref, error: text.slice(0, 4096) })
235 void host.disposeOwner(owner).catch(() => undefined)
236 } else {
237 host.log('error', `unattributed plugin fault: ${text}`)
238 }
239 }
240 process.on('uncaughtException', onFault)
241 process.on('unhandledRejection', onFault)
242
243 // 5. The channel: stdin EOF means the core is gone, whatever the reason.
244 const decoder = new FrameDecoder()
245 process.stdin.on('data', (chunk: Buffer) => {
246 let messages: unknown[]
247 try {
248 messages = decoder.push(chunk)
249 } catch (error) {
250 stderrWrite(`codewhale-extension-host: ${(error as Error).message}\n`)
251 realExit(65)
252 return
253 }
254 for (const message of messages) {
255 try {
256 rpc.handle(message)
257 } catch (error) {
258 stderrWrite(`codewhale-extension-host: protocol error: ${(error as Error).message}\n`)
259 realExit(65)
260 return
261 }
262 }
263 })
264 process.stdin.on('end', () => {
265 rpc.close('core closed the channel')
266 killHostTree()
267 })
268
269 rpc.notify('host/hello', {
270 protocol: { min: PROTOCOL_VERSION, max: PROTOCOL_VERSION },
271 host_version: HOST_VERSION,
272 bundle_sha256: bundleDigest(),
273 runtime: RUNTIME,
274 tier: TIER,
275 builtin_modules: builtinModuleDigests(),
276 ...(MEMORY_LIMIT_MIB === undefined ? {} : { memory_limit_mib: MEMORY_LIMIT_MIB }),
277 })
278
278 lines TYPESCRIPT