protocol.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /**
  2. * Versionless, JSON-lines wire protocol between the Node host and the CPython subprocess. Frames
  3. * travel on the child's fd 3 (one JSON object per line), leaving stdout/stderr free for the
  4. * program's own output. Host treats every inbound frame as hostile because model code can post
  5. * anything through the same fd; the Python bootstrap trusts host replies.
  6. * @module @deepseek-ai/dsh-code-runtime-python/src/protocol
  7. */
  8. /**
  9. * The framed-JSON channel's file descriptor from the child's perspective. The
  10. * host pins it positionally when it spawns the child (`stdio` index 3, i.e.
  11. * `['pipe','pipe','pipe','pipe']`), and the Python bootstrap reads the same
  12. * number from its own `protocol.py`. Exported as the single TS-side source of
  13. * truth: the host wiring uses it, and the cross-language mirror test asserts the
  14. * Python constant equals it, so a drift on either side breaks the boot channel
  15. * loudly rather than silently.
  16. */
  17. export const PROTOCOL_FD = 3
  18. /**
  19. * One binding namespace declaration inside a {@link BootMessage}. `global` is
  20. * the program-visible name the namespace is materialized under; `errorClass`,
  21. * when present, asks the bootstrap to mint a program-visible exception class.
  22. */
  23. interface Namespace {
  24. global: string
  25. names: string[]
  26. errorClass?: ErrorClass
  27. }
  28. /**
  29. * A namespace's program-visible exception class: rejected calls raise its
  30. * instances carrying the failed member name on `memberNameProperty`.
  31. */
  32. interface ErrorClass {
  33. name: string
  34. memberNameProperty: string
  35. }
  36. /**
  37. * What the host sends immediately after spawn, as the first line on fd 3. The
  38. * Python bootstrap reads this, applies resource limits, then waits for the
  39. * subsequent run frame. Separated from the run so the run message stays
  40. * pure model input.
  41. */
  42. export interface BootMessage {
  43. type: 'boot'
  44. /** RLIMIT_CPU seconds; the Python bootstrap sets this on itself before executing model code. */
  45. cpuSeconds: number
  46. /** RLIMIT_AS bytes; caps address space so a runaway allocation fails cleanly. */
  47. addressSpaceBytes: number
  48. /** Shared byte budget for captured log text (Python-side ledger). */
  49. maxLogBytes: number
  50. /** Byte cap for the rendered completion value. */
  51. maxValueBytes: number
  52. /**
  53. * The namespaces to materialize inside the program (globals + names;
  54. * functions stay host-side). See {@link Namespace}.
  55. */
  56. namespaces: Namespace[]
  57. }
  58. /** Host → Python: sent after `boot-ack`; carries only the model's program body. */
  59. interface RunMessage {
  60. type: 'run'
  61. program: string
  62. }
  63. /** Python → host: acknowledges boot completed and resource limits are in place. */
  64. interface BootAckMessage {
  65. type: 'boot-ack'
  66. }
  67. /** Python → host: one bridged binding call (`await tools.name(args)` inside the program). */
  68. interface CallMessage {
  69. type: 'call'
  70. /** Python-issued correlation id; the host answers each id at most once and ignores duplicates. */
  71. id: number
  72. /** The namespace global the call targets. */
  73. global: string
  74. /** The function name within the namespace. */
  75. name: string
  76. /** The JSON-safe argument the model program passed. */
  77. args: unknown
  78. }
  79. /**
  80. * Python → host: captured text, streamed eagerly so output survives a
  81. * mid-run termination (RLIMIT_CPU, SIGTERM/SIGKILL, host wall-timeout).
  82. */
  83. interface LogMessage {
  84. type: 'log'
  85. text: string
  86. /**
  87. * Set when this frame IS the child ledger's truncation marker rather than
  88. * program output. The two ledgers can exhaust at different points — one
  89. * child entry larger than `maxLogBytes` sends only the marker while the host
  90. * ledger is still nearly empty — so the host cannot infer the child's state
  91. * from its own budget, and comparing the text against the marker string
  92. * would also honour a program that printed that string itself. Carrying it
  93. * as a field lets the host stop capturing at the same point the child did
  94. * and keeps exactly one marker in `logs`.
  95. */
  96. truncated?: boolean
  97. /**
  98. * Set on the frame an explicit `flush()` (or the settlement flush) pushes for
  99. * an UNTERMINATED line: the host holds it and appends the next log frame to
  100. * the same entry, so `print('a', end='', flush=True); print('b')` reads back
  101. * as one `'ab'` entry rather than a fake newline between two entries.
  102. */
  103. open?: boolean
  104. }
  105. /** The failure carried on a {@link DoneMessage}: one of three kinds plus text. */
  106. interface DoneErrorField {
  107. kind: 'exception' | 'invalid-output' | 'output-limit'
  108. message: string
  109. }
  110. /**
  111. * Python → host: the program settled. `error` carries a program exception
  112. * (traceback text), an `invalid-output` (completion value was not lossless
  113. * JSON), or an `output-limit` (serialized completion exceeded the configured
  114. * cap); wall/CPU budgets, aborts, and substrate death are observed host-side.
  115. * From the honest child `value` is present only on a clean completion that
  116. * produced one, and crosses as exact lossless JSON — never substituted or
  117. * truncated. A forged frame CAN carry both `value` and `error`;
  118. * {@link validateChildFrame} preserves both rather than guessing which to drop,
  119. * so a consumer MUST check `error` first and ignore `value` when it is set.
  120. */
  121. interface DoneMessage {
  122. type: 'done'
  123. value?: unknown
  124. error?: DoneErrorField
  125. }
  126. /**
  127. * Every message the Python side sends. The member interfaces stay module-
  128. * private: consumers match on the union's discriminant; the host sends the
  129. * boot and run frames as inline literals.
  130. */
  131. export type ChildToHost = BootAckMessage | CallMessage | LogMessage | DoneMessage
  132. /** Host → Python: successful answer to one {@link CallMessage}. */
  133. interface ReplyOk {
  134. type: 'reply'
  135. id: number
  136. ok: true
  137. value: unknown
  138. }
  139. /** Host → Python: failed answer to one {@link CallMessage}. */
  140. interface ReplyErr {
  141. type: 'reply'
  142. id: number
  143. ok: false
  144. message: string
  145. }
  146. /** Host → Python: the answer to one {@link CallMessage}. */
  147. export type ReplyMessage = ReplyOk | ReplyErr
  148. /** The required (non-optional) keys of `T`, as string literals. */
  149. type RequiredKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T] & string
  150. /** The optional keys of `T`, as string literals. */
  151. type OptionalKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? K : never }[keyof T] & string
  152. /**
  153. * Whether each key of frame `T` is a `'required'` or `'optional'` wire field.
  154. * Because it is `Record<keyof T, …>`, an entry MUST list every key — a field
  155. * added to the interface without a corresponding entry fails typecheck — and
  156. * `keyof T`-typed keys reject a name no frame declares. The `'required'` /
  157. * `'optional'` tag must match the field's actual optionality (checked by the
  158. * `satisfies FrameFieldRoles<…>` clause on {@link WIRE_FRAME_FIELD_ROLES}), so
  159. * an optionality flip is caught too. This is the exhaustive counterpart the
  160. * array form could not express (a subset array satisfied it silently).
  161. */
  162. type FrameFieldRoles<T> = Record<RequiredKeys<T>, 'required'> & Record<OptionalKeys<T>, 'optional'>
  163. interface WireFrameShapes {
  164. BootMessage: BootMessage
  165. Namespace: Namespace
  166. RunMessage: RunMessage
  167. BootAckMessage: BootAckMessage
  168. CallMessage: CallMessage
  169. LogMessage: LogMessage
  170. DoneErrorField: DoneErrorField
  171. DoneMessage: DoneMessage
  172. ErrorClass: ErrorClass
  173. ReplyOk: ReplyOk
  174. ReplyErr: ReplyErr
  175. }
  176. /**
  177. * The frames carried on a message union: everything the host and child send as
  178. * a top-level frame (`ChildToHost`, the two reply variants, and the host→child
  179. * boot/run frames). The nested shapes `Namespace`, `ErrorClass`, and
  180. * `DoneErrorField` are fields of other frames, not frames themselves, so they
  181. * are excluded here and covered only by the roles `satisfies` and the mirror e2e.
  182. */
  183. type MessageFrames = ChildToHost | ReplyMessage | BootMessage | RunMessage
  184. /** The roster's value types minus the three nested (non-frame) shapes. */
  185. type RosterMessageFrames = Exclude<WireFrameShapes[keyof WireFrameShapes], Namespace | ErrorClass | DoneErrorField>
  186. /**
  187. * Compile-time proof that {@link WireFrameShapes}'s message-frame entries are
  188. * EXACTLY the frames on the message unions — checked BOTH directions. Forward
  189. * (`MessageFrames extends RosterMessageFrames`) catches a frame added to a union
  190. * without a roster entry; reverse (`RosterMessageFrames extends MessageFrames`)
  191. * catches a frame removed from a union while the roster still lists it (e.g.
  192. * dropping `ReplyErr` from `ReplyMessage`). Either divergence makes an alias
  193. * `false`, failing the assignment below. Type-only; the `const`s emit nothing
  194. * meaningful at runtime.
  195. */
  196. type UnionSubsetOfRoster = [MessageFrames] extends [RosterMessageFrames] ? true : false
  197. type RosterSubsetOfUnion = [RosterMessageFrames] extends [MessageFrames] ? true : false
  198. const _unionSubsetOfRoster: UnionSubsetOfRoster = true
  199. const _rosterSubsetOfUnion: RosterSubsetOfUnion = true
  200. void _unionSubsetOfRoster
  201. void _rosterSubsetOfUnion
  202. /**
  203. * Each frame's wire fields tagged by required/optional, keyed by field name so
  204. * the mapping is exhaustive over the frame interface (see {@link FrameFieldRoles})
  205. * across the whole {@link WireFrameShapes} roster. Bound to the interfaces by
  206. * `satisfies` below; {@link WIRE_FRAME_FIELDS} projects it to sorted
  207. * required/optional arrays for the cross-language mirror comparison. `global` is
  208. * the JSON key {@link CallMessage} and {@link Namespace} send (a reserved word
  209. * the Python side carries via a functional `TypedDict`).
  210. */
  211. const WIRE_FRAME_FIELD_ROLES = {
  212. BootMessage: { type: 'required', cpuSeconds: 'required', addressSpaceBytes: 'required', maxLogBytes: 'required', maxValueBytes: 'required', namespaces: 'required' },
  213. Namespace: { global: 'required', names: 'required', errorClass: 'optional' },
  214. RunMessage: { type: 'required', program: 'required' },
  215. BootAckMessage: { type: 'required' },
  216. CallMessage: { type: 'required', id: 'required', global: 'required', name: 'required', args: 'required' },
  217. LogMessage: { type: 'required', text: 'required', truncated: 'optional', open: 'optional' },
  218. DoneErrorField: { kind: 'required', message: 'required' },
  219. DoneMessage: { type: 'required', value: 'optional', error: 'optional' },
  220. ErrorClass: { name: 'required', memberNameProperty: 'required' },
  221. ReplyOk: { type: 'required', id: 'required', ok: 'required', value: 'required' },
  222. ReplyErr: { type: 'required', id: 'required', ok: 'required', message: 'required' },
  223. } as const satisfies { [K in keyof WireFrameShapes]: FrameFieldRoles<WireFrameShapes[K]> }
  224. /**
  225. * The wire field names of each frame, split into sorted required and optional
  226. * key arrays — the shape the cross-language mirror test compares against
  227. * `py/protocol.py`'s `TypedDict` `__required_keys__`/`__optional_keys__`.
  228. * Projected from {@link WIRE_FRAME_FIELD_ROLES}, so it inherits that mapping's
  229. * exhaustive, optionality-checked binding to the frame interfaces: a TS-side
  230. * field add, remove, rename, or optionality flip fails typecheck at the roles
  231. * map, and a Python-side divergence fails the mirror test at runtime.
  232. */
  233. export const WIRE_FRAME_FIELDS =
  234. Object.fromEntries(
  235. Object.entries(WIRE_FRAME_FIELD_ROLES).map(([frame, roles]) => {
  236. const required = Object.keys(roles).filter(key => (roles as Record<string, string>)[key] === 'required').sort()
  237. const optional = Object.keys(roles).filter(key => (roles as Record<string, string>)[key] === 'optional').sort()
  238. return [frame, { required, optional }]
  239. }),
  240. ) as Record<keyof typeof WIRE_FRAME_FIELD_ROLES, { required: string[]; optional: string[] }>
  241. /**
  242. * The in-band marker text announcing that log capture stopped at the byte
  243. * budget. Shared wire vocabulary: the Python-side LogBuffer emits it when ITS
  244. * ledger exhausts, and the host emits identical text when its own ledger drops
  245. * a frame first (forged fd-3 traffic, stray stdout bytes) — a truncated run
  246. * reads the same however the cap was hit.
  247. * @param maxBytes - the configured `maxLogBytes` the marker names.
  248. * @returns the marker line.
  249. */
  250. export function logTruncationMarker(maxBytes: number): string {
  251. return `[dsh-code-runtime-python] log capture truncated at ${maxBytes} bytes`
  252. }
  253. /**
  254. * Serialize one JSON-parse-produced value without recursion. `JSON.stringify`
  255. * recurses per nesting level and throws `RangeError` a few thousand levels
  256. * deep, but the seam's `CodeJsonValue` has no depth limit — an honest deep
  257. * completion or binding resolution below the byte budget must cross intact
  258. * (the worker backend's wire is equally stack-safe). Callers must pass a value
  259. * produced by `JSON.parse` (or equally JSON-plain): only `null`, finite
  260. * numbers, booleans, strings, dense arrays, and plain objects — this encoder
  261. * validates nothing. Output matches compact `JSON.stringify` byte for byte
  262. * EXCEPT on an integral double beyond the safe range, where {@link scalarJson}
  263. * emits the exact integer's BigInt digits rather than `JSON.stringify`'s rounded
  264. * spelling (`1152921504606846976`, not `...847000`) so the seam's lossless-JSON
  265. * promise holds across the wire.
  266. * @param value - a JSON-plain value (e.g. straight from `JSON.parse`).
  267. * @returns the compact JSON encoding.
  268. */
  269. export function encodeJsonPlain(value: unknown): string {
  270. type Task = { text: string } | { value: unknown }
  271. const chunks: string[] = []
  272. const tasks: Task[] = [{ value }]
  273. for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
  274. if ('text' in task) {
  275. chunks.push(task.text)
  276. continue
  277. }
  278. const current = task.value
  279. if (typeof current === 'string') {
  280. chunks.push(JSON.stringify(current))
  281. } else if (Array.isArray(current)) {
  282. chunks.push('[')
  283. tasks.push({ text: ']' })
  284. for (let index = current.length - 1; index >= 0; index--) {
  285. if (index < current.length - 1) tasks.push({ text: ',' })
  286. tasks.push({ value: current[index] })
  287. }
  288. } else if (typeof current === 'object' && current !== null) {
  289. const record = current as Record<string, unknown>
  290. chunks.push('{')
  291. tasks.push({ text: '}' })
  292. const keys = Object.keys(record)
  293. for (let index = keys.length - 1; index >= 0; index--) {
  294. const key = keys[index] as string
  295. if (index < keys.length - 1) tasks.push({ text: ',' })
  296. tasks.push({ value: record[key] })
  297. tasks.push({ text: `${JSON.stringify(key)}:` })
  298. }
  299. } else {
  300. chunks.push(scalarJson(current))
  301. }
  302. }
  303. return chunks.join('')
  304. }
  305. /**
  306. * One scalar (null, boolean, finite number) as JSON text. A beyond-safe-range
  307. * integral double needs BigInt digits: `String(2 ** 60)` emits the ROUNDED
  308. * `...847000` form, and echoing that to the child would silently change the
  309. * integer the seam promised to carry losslessly — `BigInt(2 ** 60)` prints the
  310. * exact `...846976` the double actually holds.
  311. * @param current - a JSON-plain scalar (JSON.parse emits nothing else).
  312. * @returns its JSON encoding.
  313. */
  314. function scalarJson(current: unknown): string {
  315. if (typeof current === 'number' && Number.isInteger(current) && !Number.isSafeInteger(current)) {
  316. return BigInt(current).toString()
  317. }
  318. return String(current)
  319. }
  320. /**
  321. * Exact UTF-8 byte length of one string's compact JSON form (quotes + escapes),
  322. * computed by a single non-allocating scan that stops the instant the running
  323. * total exceeds `maxBytes`. Used instead of `Buffer.byteLength(JSON.stringify(s))`
  324. * so a control-heavy forged string — whose escaped copy expands up to ~6x — is
  325. * rejected BEFORE that copy is materialized: `JSON.stringify` would allocate the
  326. * full escaped form first, the very hundreds-of-MB spike the metered traversal
  327. * exists to avoid. Mirrors `JSON.stringify`'s escaping byte-for-byte: `"` and
  328. * `\` and the five short C0 escapes cost 2, other C0 controls `\uXXXX` cost 6, a
  329. * valid surrogate pair is one astral code point emitted as raw 4-byte UTF-8, a
  330. * LONE surrogate becomes `\uXXXX` at 6, and any other code point costs its raw
  331. * UTF-8 width.
  332. * @param text - the string to meter.
  333. * @param maxBytes - largest serialized size the caller can still admit.
  334. * @returns the exact serialized byte length, or `undefined` once it exceeds `maxBytes`.
  335. */
  336. function jsonStringBytesUpTo(text: string, maxBytes: number): number | undefined {
  337. let bytes = 2 // the two quotes
  338. if (bytes > maxBytes) return undefined
  339. for (let index = 0; index < text.length; index++) {
  340. const code = text.charCodeAt(index)
  341. if (code === 0x22 || code === 0x5c || code === 0x08 || code === 0x09 || code === 0x0a || code === 0x0c || code === 0x0d) {
  342. bytes += 2 // `\"` `\\` `\b` `\t` `\n` `\f` `\r`
  343. } else if (code < 0x20) {
  344. bytes += 6 // other C0 controls: `\uXXXX`
  345. } else if (code < 0x80) {
  346. bytes += 1
  347. } else if (code < 0x800) {
  348. bytes += 2
  349. } else if (code >= 0xd800 && code <= 0xdbff && index + 1 < text.length) {
  350. const next = text.charCodeAt(index + 1)
  351. if (next >= 0xdc00 && next <= 0xdfff) {
  352. bytes += 4 // valid high+low pair: one astral code point, raw 4-byte UTF-8
  353. index++
  354. } else {
  355. bytes += 6 // lone high surrogate: `\uXXXX`
  356. }
  357. } else if (code >= 0xd800 && code <= 0xdfff) {
  358. bytes += 6 // lone surrogate (unpaired high at end, or any low): `\uXXXX`
  359. } else {
  360. bytes += 3 // other BMP code point
  361. }
  362. if (bytes > maxBytes) return undefined
  363. }
  364. return bytes
  365. }
  366. /**
  367. * Meter a `JSON.parse`-produced done value's compact-JSON byte length AND its
  368. * number losslessness in one traversal, stopping the instant `maxBytes` is
  369. * crossed. This bounds the INCREMENTAL allocation the check itself would add on
  370. * top of the already-parsed value — the enqueued children; strings and keys are
  371. * metered by {@link jsonStringBytesUpTo} without allocating an escaped copy —
  372. * not the parse that produced `value`.
  373. * That upstream width is bounded separately, by the host-side cap on inbound
  374. * fd-3 frame size before `JSON.parse` runs (owned by the runtime that reads the
  375. * channel), so `value` cannot be arbitrarily large when it reaches here. The
  376. * budget is the `maxValueBytes` the boot frame carries — a required wire field
  377. * with no default at this layer. The traversal rejects over-budget BEFORE
  378. * materializing a string's escaped form or enqueuing an array's/object's
  379. * children, so a forgery within that frame cap cannot force those secondary
  380. * allocations. Object key COUNTING is
  381. * unavoidably O(keys) — JS has no lazy own-key iterator, and the parse already
  382. * built the key set — but the check still refuses the per-entry work before the
  383. * enqueue loop. A non-lossless number (non-finite, negative zero) is caught only
  384. * when the value fits the budget — an over-budget value is rejected regardless,
  385. * so the distinction is moot. Same JSON-plain precondition and traversal shape
  386. * as {@link encodeJsonPlain}; a number's byte length is measured through
  387. * {@link scalarJson} (matching the encoder, so a beyond-safe-range integer
  388. * meters its exact BigInt digits, not `JSON.stringify`'s rounded spelling) and
  389. * a string's/key's through {@link jsonStringBytesUpTo} (the exact escaped size,
  390. * scanned without allocating the escaped copy).
  391. * @param value - a JSON-plain value (e.g. straight from `JSON.parse`).
  392. * @param maxBytes - the completion-value budget in bytes.
  393. * @returns `{ ok: true, bytes }` with the exact serialized size, or
  394. * `{ ok: false, reason }` — `over-budget` once the size exceeds `maxBytes`,
  395. * `non-lossless` on a non-finite or negative-zero number.
  396. */
  397. export function checkDoneValue(value: unknown, maxBytes: number): { ok: true; bytes: number } | { ok: false; reason: 'over-budget' | 'non-lossless' } {
  398. let bytes = 0
  399. // A non-lossless number is recorded, not returned on sight: over-budget must
  400. // win regardless of where in the value each violation sits, so the whole
  401. // metering finishes first. Otherwise `["<huge>", 1e400]` and `[1e400,
  402. // "<huge>"]` — the same over-budget value in two member orders — would
  403. // classify differently (non-lossless vs over-budget), and the JSDoc promises
  404. // an over-budget value is rejected as over-budget regardless.
  405. let nonLossless = false
  406. const stack: unknown[] = [value]
  407. while (stack.length > 0) {
  408. const current = stack.pop()
  409. if (typeof current === 'number') {
  410. // Flag a non-lossless number but keep counting its encoded bytes: a value
  411. // that is BOTH non-lossless and over-budget must classify as over-budget
  412. // (the loop's byte check below wins), so the byte count cannot skip the
  413. // offending number. `scalarJson` gives the same spelling a legit scalar
  414. // would meter.
  415. if (!Number.isFinite(current) || Object.is(current, -0)) nonLossless = true
  416. bytes += Buffer.byteLength(scalarJson(current), 'utf8')
  417. } else if (typeof current === 'string') {
  418. // Meter the escaped form WITHOUT allocating it: jsonStringBytesUpTo scans
  419. // and bails the instant the running cost crosses the remaining budget, so
  420. // a control-heavy forgery (escaped copy up to ~6x) never materializes that
  421. // copy the way `JSON.stringify` would.
  422. const stringBytes = jsonStringBytesUpTo(current, maxBytes - bytes)
  423. if (stringBytes === undefined) return { ok: false, reason: 'over-budget' }
  424. bytes += stringBytes
  425. } else if (Array.isArray(current)) {
  426. // Brackets plus one comma per gap; elements add themselves. Reject
  427. // BEFORE enqueuing children: every element serializes to at least one
  428. // byte, so a forged flat array far above the budget fails here without
  429. // pushing its elements onto the host stack. (The array itself is already
  430. // materialized by the upstream parse; this only bounds the extra stack.)
  431. bytes += 2 + (current.length > 1 ? current.length - 1 : 0)
  432. if (bytes + current.length > maxBytes) return { ok: false, reason: 'over-budget' }
  433. for (const item of current) stack.push(item)
  434. } else if (typeof current === 'object' && current !== null) {
  435. const record = current as Record<string, unknown>
  436. // Count own keys with for...in + hasOwn. This IS O(keys) — JS has no lazy
  437. // own-key iterator and the parse already built the key set — so the count
  438. // cannot be sublinear; what the bound below buys is refusing the per-entry
  439. // work (key escaping, value enqueue) before it runs. Each entry costs at
  440. // least a quoted key (>= 2 bytes) + colon + >= 1-byte value.
  441. let count = 0
  442. for (const key in record) if (Object.hasOwn(record, key)) count += 1
  443. bytes += 2 + (count > 1 ? count - 1 : 0)
  444. if (bytes + count * 4 > maxBytes) return { ok: false, reason: 'over-budget' }
  445. for (const key in record) {
  446. if (!Object.hasOwn(record, key)) continue
  447. // Meter the key's escaped form without allocating it (same reason as the
  448. // string branch), then add the colon separator. `+ 1` for the `:`.
  449. const keyBytes = jsonStringBytesUpTo(key, maxBytes - bytes)
  450. if (keyBytes === undefined) return { ok: false, reason: 'over-budget' }
  451. bytes += keyBytes + 1
  452. stack.push(record[key])
  453. }
  454. } else {
  455. bytes += Buffer.byteLength(scalarJson(current), 'utf8')
  456. }
  457. if (bytes > maxBytes) return { ok: false, reason: 'over-budget' }
  458. }
  459. // The whole value fit the budget; a recorded number violation is the verdict.
  460. if (nonLossless) return { ok: false, reason: 'non-lossless' }
  461. return { ok: true, bytes }
  462. }
  463. /**
  464. * Whether a raw JSON line contains an integer token that would lose precision
  465. * as a JavaScript number. `JSON.parse` silently rounds such a token
  466. * (`9007199254740993` becomes `...992`) BEFORE any validation can see it, so
  467. * the check must read the source text; a beyond-safe-range token whose double
  468. * parse round-trips exactly (`2**53`, `2**60`) is lossless and passes. The scan walks the line skipping string literals (a digit run
  469. * inside a string is data, not a number token) and tests every number token
  470. * in plain integer form — no fraction or exponent, which parse as doubles by
  471. * intent. A reviver cannot do this job: the reviver walk recurses per nesting
  472. * level and would reintroduce the depth limit `encodeJsonPlain` removes.
  473. * @param line - the raw UTF-8 text of one JSON-lines frame.
  474. * @returns true when an unsafe integer token is present outside strings.
  475. */
  476. export function hasUnsafeIntegerToken(line: string): boolean {
  477. for (let index = 0; index < line.length; index++) {
  478. const char = line[index]
  479. if (char === '"') {
  480. // Skip the string literal, honoring backslash escapes.
  481. for (index++; index < line.length; index++) {
  482. if (line[index] === '\\') index++
  483. else if (line[index] === '"') break
  484. }
  485. continue
  486. }
  487. if (char === '-' || (char !== undefined && char >= '0' && char <= '9')) {
  488. let end = index + 1
  489. while (end < line.length) {
  490. const c = line[end] as string
  491. if ((c >= '0' && c <= '9') || c === '.' || c === 'e' || c === 'E' || c === '+' || c === '-') end++
  492. else break
  493. }
  494. const token = line.slice(index, end)
  495. // Beyond the safe range an integer token is still lossless IFF the
  496. // double parse round-trips exactly (2**53 does; 2**53+1 rounds) — the
  497. // canonical boundary accepts every JS-double-exact value, so only a
  498. // genuinely rounding token marks the frame as forged.
  499. if (/^-?\d+$/.test(token)) {
  500. const parsed = Number(token)
  501. // A token that parses to Infinity is trivially lossy; a finite
  502. // beyond-safe-range one is lossy only when the BigInt round-trip
  503. // disagrees.
  504. if (!Number.isFinite(parsed)) return true
  505. if (!Number.isSafeInteger(parsed) && BigInt(token) !== BigInt(parsed)) return true
  506. }
  507. index = end - 1
  508. }
  509. }
  510. return false
  511. }
  512. /**
  513. * Lazily yield one plain object's own enumerable property values. A generator
  514. * (not `Object.values`/`Object.entries`) because {@link hasNonLosslessNumber}
  515. * walks breadth it cannot bound: those helpers copy the whole VALUE (or
  516. * key/value pair) list into a fresh array up front, so a wide object would cost
  517. * that second full-breadth allocation before a single value is examined. The
  518. * `for...in` here does not make the walk sublinear — V8 still materializes the
  519. * key-name enumeration when the loop starts — but it avoids the extra value
  520. * array, yielding each value straight off the already-parsed object.
  521. * @param record - a JSON-parse-produced object.
  522. * @yields each own enumerable property value, in key order.
  523. */
  524. function* ownValues(record: object): Generator {
  525. for (const key in record) {
  526. if (Object.hasOwn(record, key)) yield (record as Record<string, unknown>)[key]
  527. }
  528. }
  529. /**
  530. * Whether a JSON.parse-produced value contains a number outside lossless
  531. * JSON: non-finite (`1e400` parses to `Infinity`) or negative zero (`-0.0`
  532. * parses to JS `-0`, whose sign bit a re-serialization drops). The honest
  533. * child's validator rejects these before sending, so a frame carrying one is
  534. * forged.
  535. *
  536. * Runs on `call.args`, which — unlike a completion value — has NO seam byte
  537. * cap, so there is no budget to reject a wide payload against the way
  538. * {@link checkDoneValue} does. The traversal therefore holds ONE cursor per
  539. * NESTING LEVEL (an array or {@link ownValues} iterator) instead of one entry
  540. * per member: a forged flat `args` at the top of the host's inbound frame-size
  541. * cap would
  542. * otherwise push tens of millions of stack entries — and `Object.values` would
  543. * copy each object's full breadth — allocating hundreds of megabytes beyond
  544. * what `JSON.parse` already holds. Iterative either way, so a deep frame
  545. * cannot overflow the host stack.
  546. * @param value - a JSON-parse-produced value from an fd-3 frame.
  547. * @returns true when any contained number is non-finite or negative zero.
  548. */
  549. export function hasNonLosslessNumber(value: unknown): boolean {
  550. const cursors: Iterator<unknown>[] = [[value].values()]
  551. while (cursors.length > 0) {
  552. // The loop condition guarantees a top cursor.
  553. const cursor = cursors.at(-1) as Iterator<unknown>
  554. const step = cursor.next()
  555. if (step.done === true) {
  556. cursors.pop()
  557. continue
  558. }
  559. const current = step.value
  560. if (typeof current === 'number') {
  561. if (!Number.isFinite(current) || Object.is(current, -0)) return true
  562. } else if (Array.isArray(current)) {
  563. cursors.push((current as unknown[]).values())
  564. } else if (typeof current === 'object' && current !== null) {
  565. cursors.push(ownValues(current))
  566. }
  567. }
  568. return false
  569. }
  570. /**
  571. * Runtime shape gate for inbound fd-3 traffic. Model code has full access to
  572. * fd 3 and can post anything — `null`, primitives, poisoned fields — so the
  573. * compile-time union means nothing here: every field is validated and REBUILT
  574. * before the host reads it (forged extras never ride along; a non-number id
  575. * can never be echoed into a reply). Junk returns `undefined` and is dropped
  576. * so a throw in the host's `message` handler cannot crash the host process.
  577. * @param raw - one JSON-parsed frame from fd 3.
  578. * @returns the rebuilt frame, or `undefined` to drop it silently.
  579. */
  580. export function validateChildFrame(raw: unknown): ChildToHost | undefined {
  581. if (typeof raw !== 'object' || raw === null) return undefined
  582. const m = raw as Record<string, unknown>
  583. switch (m.type) {
  584. case 'boot-ack':
  585. return { type: 'boot-ack' }
  586. case 'log':
  587. if (typeof m.text !== 'string') return undefined
  588. // Rebuilt, not passed through: a forged `truncated` of any other type
  589. // would reach the host as a truthy value and silence capture for the
  590. // rest of the run. Only the literal `true` counts; `open` likewise.
  591. return {
  592. type: 'log',
  593. text: m.text,
  594. ...m.truncated === true ? { truncated: true } : {},
  595. ...m.open === true ? { open: true } : {},
  596. }
  597. case 'call': {
  598. // The id must be a finite number: it is echoed verbatim into the reply
  599. // frame, and a forged `1e400` id (Infinity after JSON.parse) would make
  600. // the reply unencodable as strict JSON. Negative zero is rejected too:
  601. // it passes `Number.isFinite`, but the reply re-serializes it as `0`
  602. // (`JSON.stringify({id:-0})` is `{"id":0}`), colliding with a real call
  603. // whose id is `0` — the honest child never issues `-0`.
  604. if (typeof m.id !== 'number' || !Number.isFinite(m.id) || Object.is(m.id, -0) || typeof m.global !== 'string' || typeof m.name !== 'string') return undefined
  605. // A forged frame can omit `args` entirely; rebuilding it as `undefined`
  606. // would invoke the binding with a non-JSON value, bypassing the
  607. // lossless-JSON argument boundary. Any PRESENT value is JSON-plain by
  608. // construction (the frame came from JSON.parse), so presence is the
  609. // whole check.
  610. if (!Object.hasOwn(m, 'args')) return undefined
  611. // JSON.parse yields Infinity for 1e400 and preserves -0; both are
  612. // outside lossless JSON, and the honest child never sends them.
  613. if (hasNonLosslessNumber(m.args)) return undefined
  614. return { type: 'call', id: m.id, global: m.global, name: m.name, args: m.args }
  615. }
  616. case 'done': {
  617. // The value passes through untouched here: scanning it for non-lossless
  618. // numbers would push every member of a wide forged payload before any
  619. // byte cap runs. The done handler's bounded `checkDoneValue` folds the
  620. // losslessness check into the metered traversal, rejecting over-budget
  621. // before it enqueues children.
  622. const err = m.error
  623. if (err === undefined) {
  624. return m.value === undefined ? { type: 'done' } : { type: 'done', value: m.value }
  625. }
  626. if (typeof err !== 'object' || err === null) return undefined
  627. const { kind, message } = err as Record<string, unknown>
  628. if (typeof message !== 'string') return undefined
  629. if (kind !== 'exception' && kind !== 'invalid-output' && kind !== 'output-limit') return undefined
  630. return m.value === undefined
  631. ? { type: 'done', error: { kind, message } }
  632. : { type: 'done', value: m.value, error: { kind, message } }
  633. }
  634. default:
  635. return undefined
  636. }
  637. }