protocol.ts 31 KB

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