index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /** Confined Node programs with host-owned bindings, output limits, and managed process cleanup. */
  2. import { stripTypeScriptTypes } from 'node:module'
  3. import { isAbsolute } from 'node:path'
  4. import { Context } from '@deepseek-ai/cordis'
  5. import z from '@deepseek-ai/schemastery'
  6. import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  7. import type { CodeBindingNamespace, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult, CodeRunSandbox, CodeRunSpec } from '@deepseek-ai/dsh-code-runtime'
  8. import { MAX_TIMER_DELAY_MS, clampTimeout } from '@deepseek-ai/dsh-timeout'
  9. import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from '@deepseek-ai/dsh-sandbox'
  10. import type { ConfinedArgv, SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
  11. import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess'
  12. import type {} from '@deepseek-ai/dsh-sandbox-policy'
  13. import type {} from '@deepseek-ai/dsh-fs'
  14. import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values'
  15. import { validateBindings } from './bindings.ts'
  16. import { JsonChannel } from './channel.ts'
  17. import { bootstrapArgs } from './launch.ts'
  18. import type { LaunchConfig } from './launch.ts'
  19. import { OutputLedger } from './output-ledger.ts'
  20. import { drainOutput } from './output-stream.ts'
  21. import { STARTUP_ENVIRONMENT_NAMES } from './environment.ts'
  22. import { decodeCodeJsonWire, encodeCodeJsonWire } from './json-wire.ts'
  23. import type { ProgramBootData } from './protocol.ts'
  24. /** Deployment-varying runtime bounds and launch choices. */
  25. export interface Config extends LaunchConfig {
  26. /** Default elapsed deadline, including nested tool and approval waits. */
  27. timeoutMs?: number
  28. /** Maximum elapsed deadline accepted by resolve. */
  29. maxTimeoutMs?: number
  30. /** Combined serialized logs, completion and diagnostic byte cap. */
  31. maxOutputBytes?: number
  32. /** V8 old-generation heap limit in MiB; native allocations are excluded. */
  33. maxOldGenerationSizeMb?: number
  34. /** Maximum control frame, outstanding argument and queued control-output bytes. */
  35. maxMessageBytes?: number
  36. /** Maximum simultaneous host binding calls accepted from a program. */
  37. maxPendingCalls?: number
  38. /** Managed process termination and output-drain grace in milliseconds. */
  39. graceMs?: number
  40. }
  41. type ResolvedConfig = Required<Omit<Config, 'bootstrapPath'>> & Pick<Config, 'bootstrapPath'>
  42. interface LiveRun { controller: AbortController; finished: Promise<void> }
  43. const STRIP_PREFIX = 'async function __dsh_program__() {\n'
  44. const STRIP_SUFFIX = '\n}'
  45. function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error) }
  46. function record(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null && !Array.isArray(value) }
  47. /** Node provider; direct file effects use the same sandbox service as Bash. */
  48. export class NodeCodeRuntime extends CodeRuntime {
  49. static inject = ['fs', 'subprocess', 'sandbox', 'sandboxPolicy']
  50. static Config: z<Config> = z.object({
  51. timeoutMs: z.number().default(120_000),
  52. maxTimeoutMs: z.number().default(600_000),
  53. maxOutputBytes: z.number().default(67_108_864),
  54. maxOldGenerationSizeMb: z.number().default(512),
  55. maxMessageBytes: z.number().default(134_217_728),
  56. maxPendingCalls: z.number().default(128),
  57. graceMs: z.number().default(3_000),
  58. nodeExecutable: z.string(),
  59. bootstrapPath: z.string(),
  60. })
  61. readonly language = 'typescript'
  62. readonly isolation = 'process'
  63. private readonly config: ResolvedConfig
  64. private readonly live = new Set<LiveRun>()
  65. private disposed = false
  66. constructor(ctx: Context, config: Config) {
  67. super(ctx)
  68. this.config = { ...config, nodeExecutable: config.nodeExecutable ?? process.execPath } as ResolvedConfig
  69. for (const [key, value] of Object.entries(this.config)) {
  70. if (typeof value === 'number' && (!Number.isFinite(value) || value <= 0)) throw new Error(`code-runtime-node: ${key} must be positive and finite`)
  71. }
  72. for (const key of ['timeoutMs', 'maxTimeoutMs', 'graceMs'] as const) {
  73. if (this.config[key] > MAX_TIMER_DELAY_MS) throw new Error(`code-runtime-node: ${key} exceeds the supported timer range`)
  74. }
  75. if (!Number.isSafeInteger(this.config.maxOutputBytes) || this.config.maxOutputBytes < 4) throw new Error('code-runtime-node: maxOutputBytes must be an integer of at least 4')
  76. if (!Number.isSafeInteger(this.config.maxMessageBytes) || this.config.maxMessageBytes > 0xffff_ffff) throw new Error('code-runtime-node: maxMessageBytes must fit an unsigned 32-bit frame length')
  77. if (!Number.isSafeInteger(this.config.maxPendingCalls)) throw new Error('code-runtime-node: maxPendingCalls must be an integer')
  78. if (!Number.isSafeInteger(this.config.maxOldGenerationSizeMb)) throw new Error('code-runtime-node: maxOldGenerationSizeMb must be an integer')
  79. if (this.config.nodeExecutable.length === 0) throw new Error('code-runtime-node: nodeExecutable must be non-empty')
  80. if (this.config.bootstrapPath !== undefined && !isAbsolute(this.config.bootstrapPath)) throw new Error('code-runtime-node: bootstrapPath must be absolute')
  81. ctx.effect(() => async () => {
  82. this.disposed = true
  83. const active = [...this.live]
  84. for (const run of active) run.controller.abort('runtime disposed')
  85. await Promise.all(active.map(run => run.finished))
  86. }, 'Node code-runtime cleanup')
  87. }
  88. override get sandboxMode(): SandboxMode { return this.ctx.sandboxPolicy.defaultMode }
  89. /**
  90. * Resolve an execution under explicit or deployment policy.
  91. * @param request - Program, bindings, optional cwd/deadline, and resolved authority.
  92. * @returns Complete execution inputs with a capped deadline.
  93. */
  94. resolve(request: CodeRunRequest): CodeRunSpec {
  95. if (this.disposed) throw new Error('code-runtime-node: resolve after disposal')
  96. const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve()
  97. const cwd = request.cwd ?? sandboxPolicy.workspaceRoot
  98. if (!isAbsolute(cwd)) throw new Error('code-runtime-node: cwd must be absolute')
  99. return {
  100. ...request,
  101. cwd,
  102. timeoutMs: clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, 'code-runtime-node: timeoutMs'),
  103. sandboxPolicy,
  104. }
  105. }
  106. /**
  107. * Run a resolved program in a fresh managed and confined Node process.
  108. * @param spec - Inputs returned by resolve; missing authority is caller misuse.
  109. * @returns Output and file-confinement facts after managed cleanup.
  110. */
  111. async run(spec: CodeRunSpec): Promise<CodeRunResult> {
  112. if (this.disposed) throw new Error('code-runtime-node: run after disposal')
  113. if (spec.sandboxPolicy === undefined) throw new Error('code-runtime-node: run requires a resolved sandbox policy')
  114. if (!isAbsolute(spec.cwd) || !Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs) throw new Error('code-runtime-node: run requires resolved cwd and timeout')
  115. const bindings = validateBindings(spec)
  116. const controller = new AbortController()
  117. const completion = Promise.withResolvers<void>()
  118. const live = { controller, finished: completion.promise }
  119. this.live.add(live)
  120. try {
  121. return await this.execute(spec, spec.sandboxPolicy, bindings, controller)
  122. } finally {
  123. this.live.delete(live)
  124. completion.resolve()
  125. }
  126. }
  127. private async execute(
  128. spec: CodeRunSpec,
  129. policy: SandboxExecutionPolicy,
  130. bindings: Map<string, CodeBindingNamespace>,
  131. controller: AbortController,
  132. ): Promise<CodeRunResult> {
  133. const output = new OutputLedger(this.config.maxOutputBytes)
  134. const logs: string[] = []
  135. const sandbox: CodeRunSandbox = { mode: policy.mode, denied: false }
  136. const result = Promise.withResolvers<CodeRunResult>()
  137. const signal = spec.signal === undefined ? controller.signal : AbortSignal.any([spec.signal, controller.signal])
  138. let handle: SubprocessHandle | undefined
  139. let channel: JsonChannel | undefined
  140. let confined: ConfinedArgv | undefined
  141. let settled = false
  142. let timedOut = false
  143. let outputOverflow = false
  144. let overflowResult: CodeRunResult | undefined
  145. let stderr = ''
  146. let parsing = true
  147. const wallTimer = setTimeout(() => { timedOut = true; controller.abort('execution deadline reached') }, spec.timeoutMs)
  148. const finish = (failure?: CodeRunFailure, value?: CodeJsonValue): void => {
  149. if (settled) return
  150. settled = true
  151. clearTimeout(wallTimer)
  152. signal.removeEventListener('abort', onAbort)
  153. channel?.close()
  154. void (async () => {
  155. if (handle !== undefined) {
  156. try {
  157. handle.terminate()
  158. await Promise.all([handle.done.catch(() => {}), handle.waitForExit()])
  159. const drained = await Promise.all([
  160. drainOutput(handle.stdout, this.config.graceMs),
  161. drainOutput(handle.stderr, this.config.graceMs),
  162. ])
  163. if (drained.includes(false) && failure === undefined) {
  164. failure = { kind: 'worker-exit', message: 'Node process output did not close cleanly' }
  165. }
  166. } catch (error: unknown) {
  167. failure = { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(error)}` }
  168. } finally {
  169. handle.stdout?.destroy()
  170. handle.stderr?.destroy()
  171. }
  172. }
  173. const outcome = outputOverflow ? overflowResult ?? output.limit(logs)
  174. : failure === undefined ? output.success(logs, value) : output.failure(logs, failure)
  175. result.resolve({ ...outcome, sandbox: { ...sandbox } })
  176. })()
  177. }
  178. const onAbort = (): void => {
  179. finish(timedOut
  180. ? { kind: 'timeout', message: `execution deadline reached (${spec.timeoutMs}ms)` }
  181. : { kind: 'abort', message: messageOf(signal.reason) })
  182. }
  183. signal.addEventListener('abort', onAbort, { once: true })
  184. if (signal.aborted) onAbort()
  185. try {
  186. // Abort callbacks can settle execution before or during an awaited operation.
  187. // oxlint-disable-next-line typescript/no-unnecessary-condition
  188. if (settled) return await result.promise
  189. const stripped = stripTypeScriptTypes(STRIP_PREFIX + spec.program + STRIP_SUFFIX)
  190. parsing = false
  191. const data: ProgramBootData = {
  192. code: stripped.slice(STRIP_PREFIX.length, stripped.length - STRIP_SUFFIX.length),
  193. namespaces: [...bindings.values()].map(binding => ({
  194. global: binding.global,
  195. names: Object.keys(binding.functions),
  196. ...binding.errorClass ? { errorClass: binding.errorClass } : {},
  197. })),
  198. maxOutputBytes: this.config.maxOutputBytes,
  199. }
  200. const executable = await this.ctx.subprocess.resolveExecutable(this.config.nodeExecutable, undefined, signal)
  201. // Abort callbacks can settle execution before or during an awaited operation.
  202. // oxlint-disable-next-line typescript/no-unnecessary-condition
  203. if (settled) return await result.promise
  204. const argv = [executable, `--max-old-space-size=${this.config.maxOldGenerationSizeMb}`, ...bootstrapArgs(this.ctx.fs, this.config, this.config.maxMessageBytes)]
  205. confined = policy.mode === 'danger-full-access' ? undefined : this.ctx.sandbox.confine(argv, { ...policy, mode: policy.mode })
  206. if (confined !== undefined) sandbox.enforcement = confined.enforcement
  207. // Native launchers need executable search and Windows system paths before the child installs its model environment.
  208. const env: NodeJS.ProcessEnv = Object.fromEntries(Object.keys(process.env)
  209. .filter(key => !STARTUP_ENVIRONMENT_NAMES.has(key.toUpperCase()))
  210. .map(key => [key, undefined]))
  211. if ('pkg' in process && this.config.bootstrapPath === undefined) env.DSH_CODE_RUNTIME_NODE = '1'
  212. handle = this.ctx.subprocess.spawn({ argv: confined?.argv ?? argv, cwd: spec.cwd, env, stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', control: 'pipe' }, graceMs: this.config.graceMs, signal })
  213. const launched = handle
  214. if (launched.control === undefined || launched.stdout === undefined || launched.stderr === undefined) {
  215. throw new Error('subprocess provider did not supply the requested control and output pipes')
  216. }
  217. const admit = (text: string): void => {
  218. if (outputOverflow) return
  219. if (!output.admit(text, logs)) {
  220. outputOverflow = true
  221. overflowResult = output.limit([...logs, text])
  222. finish({ kind: 'output-limit', message: `outer output exceeded ${this.config.maxOutputBytes} bytes` })
  223. }
  224. }
  225. const stdoutDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
  226. const stderrDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
  227. handle.stdout?.on('data', (chunk: Buffer) => {
  228. const text = stdoutDecoder.decode(chunk, { stream: true })
  229. if (text.length > 0) admit(text)
  230. })
  231. handle.stdout?.on('end', () => {
  232. const text = stdoutDecoder.decode()
  233. if (text.length > 0) admit(text)
  234. })
  235. handle.stdout?.on('error', (error: Error) => { finish({ kind: 'worker-exit', message: messageOf(error) }) })
  236. handle.stderr?.on('data', (chunk: Buffer) => {
  237. const text = stderrDecoder.decode(chunk, { stream: true })
  238. stderr = (stderr + text).slice(-this.config.maxOutputBytes)
  239. if (text.length > 0) admit(text)
  240. })
  241. handle.stderr?.on('end', () => {
  242. const text = stderrDecoder.decode()
  243. if (text.length > 0) admit(text)
  244. })
  245. handle.stderr?.on('error', (error: Error) => { finish({ kind: 'worker-exit', message: messageOf(error) }) })
  246. let ready = false
  247. let nextId = 1
  248. let pending = 0
  249. let pendingBytes = 0
  250. const protocolFailure = (message: string): void => { finish({ kind: 'protocol', message }) }
  251. const processFinished = (outcome: SubprocessOutcome): void => {
  252. if (settled) return
  253. finish((confined !== undefined && classifyRunnerFailure(outcome.exitCode, stderr, confined.runnerFailureRules) !== undefined)
  254. ? { kind: 'sandbox-unavailable', message: stderr }
  255. : { kind: 'worker-exit', message: `Node process exited before completing (${String(outcome.exitCode)})${stderr ? `: ${stderr}` : ''}` })
  256. }
  257. const transport: JsonChannel = new JsonChannel(launched.control, this.config.maxMessageBytes, (raw, bytes) => {
  258. if (!record(raw)) { protocolFailure('invalid control frame'); return }
  259. if (!ready) {
  260. if (raw.type !== 'ready') { protocolFailure('program frame arrived before bootstrap readiness'); return }
  261. ready = true
  262. void transport.send({ type: 'boot', data }).catch((error: unknown) => { protocolFailure(messageOf(error)) })
  263. return
  264. }
  265. switch (raw.type) {
  266. case 'log':
  267. if (typeof raw.text !== 'string') { protocolFailure('invalid log frame'); return }
  268. admit(raw.text)
  269. return
  270. case 'output-limit': outputOverflow = true; finish(); return
  271. case 'done': {
  272. if (raw.error !== undefined) {
  273. if (!record(raw.error) || typeof raw.error.message !== 'string' || (raw.error.kind !== 'exception' && raw.error.kind !== 'invalid-output' && raw.error.kind !== 'output-limit')) { protocolFailure('invalid terminal error'); return }
  274. const failure = { kind: raw.error.kind, message: raw.error.message } as CodeRunFailure
  275. if (confined !== undefined) {
  276. sandbox.denied = confined.denialSignatures.some(signature =>
  277. failure.message.toLowerCase().includes(signature.toLowerCase()))
  278. }
  279. if (failure.kind === 'output-limit') outputOverflow = true
  280. finish(failure)
  281. return
  282. }
  283. const value = raw.value === undefined ? undefined : decodeCodeJsonWire(raw.value)
  284. if (raw.value !== undefined && value === undefined) finish({ kind: 'invalid-output', message: 'program completion must be lossless JSON' })
  285. else finish(undefined, value)
  286. return
  287. }
  288. case 'call': {
  289. if (!Number.isSafeInteger(raw.id) || raw.id !== nextId || typeof raw.global !== 'string' || typeof raw.name !== 'string') { protocolFailure('invalid binding call identity'); return }
  290. nextId += 1
  291. const functions = bindings.get(raw.global)?.functions
  292. const fn = functions !== undefined && Object.hasOwn(functions, raw.name) ? functions[raw.name] : undefined
  293. if (typeof fn !== 'function') { protocolFailure('program requested an undeclared binding'); return }
  294. const args = decodeCodeJsonWire(raw.args)
  295. if (args === undefined) { protocolFailure('binding arguments must be lossless JSON'); return }
  296. if (++pending > this.config.maxPendingCalls || (pendingBytes += bytes) > this.config.maxMessageBytes) { protocolFailure('pending binding calls exceed configured limits'); return }
  297. const id = raw.id
  298. void (async () => {
  299. let reply: unknown
  300. try {
  301. const value = snapshotJsonValue(await fn(args))
  302. if (value === undefined) throw new Error('binding resolution must be lossless JSON')
  303. reply = { type: 'reply', id, ok: true, value: encodeCodeJsonWire(value) }
  304. } catch (error: unknown) {
  305. reply = { type: 'reply', id, ok: false, message: messageOf(error) }
  306. } finally {
  307. pending -= 1
  308. pendingBytes -= bytes
  309. }
  310. if (!settled) await transport.send(reply)
  311. })().catch((error: unknown) => { protocolFailure(messageOf(error)) })
  312. return
  313. }
  314. default: protocolFailure('unknown control message')
  315. }
  316. }, (error, kind) => {
  317. if (kind === 'protocol') protocolFailure(messageOf(error))
  318. else if (ready) finish({ kind: 'worker-exit', message: messageOf(error) })
  319. else void launched.done.then(processFinished, (failure: unknown) => { finish({ kind: 'worker-exit', message: messageOf(failure) }) })
  320. })
  321. channel = transport
  322. void launched.done.then((outcome) => { setImmediate(() => { processFinished(outcome) }) }, (error: unknown) => { finish({ kind: confined !== undefined && isRunnerSpawnFailure(error, confined.argv[0], spec.cwd) ? 'sandbox-unavailable' : 'worker-exit', message: messageOf(error) }) })
  323. } catch (error: unknown) {
  324. finish({ kind: error instanceof SandboxUnavailableError ? 'sandbox-unavailable' : parsing ? 'exception' : 'worker-exit', message: messageOf(error) })
  325. }
  326. return await result.promise
  327. }
  328. }
  329. export default NodeCodeRuntime