protocol.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. // The protocol channel is fd 3 from the child's perspective — the host pins it
  9. // positionally via `stdio: ['pipe','pipe','pipe','pipe']` (index.ts), and the
  10. // Python bootstrap reads the same constant from its own protocol.py.
  11. /**
  12. * What the host sends immediately after spawn, as the first line on fd 3. The
  13. * Python bootstrap reads this, applies resource limits, then waits for the
  14. * subsequent run frame. Separated from the run so the run message stays
  15. * pure model input.
  16. */
  17. export interface BootMessage {
  18. type: 'boot'
  19. /** RLIMIT_CPU seconds; the Python bootstrap sets this on itself before executing model code. */
  20. cpuSeconds: number
  21. /** RLIMIT_AS bytes; caps address space so a runaway allocation fails cleanly. */
  22. addressSpaceBytes: number
  23. /** Shared byte budget for captured log text (Python-side ledger). */
  24. maxLogBytes: number
  25. /** Byte cap for the rendered completion value. */
  26. maxValueBytes: number
  27. /**
  28. * The namespaces to materialize inside the program (globals + names;
  29. * functions stay host-side). `errorClass` asks the bootstrap to mint a
  30. * program-visible exception class under that global: rejected calls raise
  31. * its instances carrying the member name on `memberNameProperty`.
  32. */
  33. namespaces: { global: string; names: string[]; errorClass?: { name: string; memberNameProperty: string } }[]
  34. }
  35. // The run request `{ type: 'run', program }` follows BootMessage once the
  36. // child acknowledges with `boot-ack`; the host sends it as an inline literal
  37. // (it carries only the model's program body — caps and bindings crossed on boot).
  38. /** Python → host: acknowledges boot completed and resource limits are in place. */
  39. interface BootAckMessage {
  40. type: 'boot-ack'
  41. }
  42. /** Python → host: one bridged binding call (`await tools.name(args)` inside the program). */
  43. interface CallMessage {
  44. type: 'call'
  45. /** Python-issued correlation id; the host answers each id at most once and ignores duplicates. */
  46. id: number
  47. /** The namespace global the call targets. */
  48. global: string
  49. /** The function name within the namespace. */
  50. name: string
  51. /** The JSON-safe argument the model program passed. */
  52. args: unknown
  53. }
  54. /**
  55. * Python → host: captured text, streamed eagerly so output survives a
  56. * mid-run termination (RLIMIT_CPU, SIGTERM/SIGKILL, host wall-timeout).
  57. */
  58. interface LogMessage {
  59. type: 'log'
  60. text: string
  61. /**
  62. * Set when this frame IS the child ledger's truncation marker rather than
  63. * program output. The two ledgers can exhaust at different points — one
  64. * child entry larger than `maxLogBytes` sends only the marker while the host
  65. * ledger is still nearly empty — so the host cannot infer the child's state
  66. * from its own budget, and comparing the text against the marker string
  67. * would also honour a program that printed that string itself. Carrying it
  68. * as a field lets the host stop capturing at the same point the child did
  69. * and keeps exactly one marker in `logs`.
  70. */
  71. truncated?: boolean
  72. }
  73. /**
  74. * Python → host: the program settled. `error` carries a program exception
  75. * (traceback text), an `invalid-output` (completion value was not lossless
  76. * JSON), or an `output-limit` (serialized completion exceeded the configured
  77. * cap); wall/CPU budgets, aborts, and substrate death are observed host-side.
  78. * `value` is present only on a clean completion that produced one, and crosses
  79. * as exact lossless JSON — never substituted or truncated.
  80. */
  81. interface DoneMessage {
  82. type: 'done'
  83. value?: unknown
  84. error?: { kind: 'exception' | 'invalid-output' | 'output-limit'; message: string }
  85. }
  86. /**
  87. * Every message the Python side sends. The member interfaces stay module-
  88. * private: consumers match on the union's discriminant; the host sends the
  89. * boot and run frames as inline literals.
  90. */
  91. export type ChildToHost = BootAckMessage | CallMessage | LogMessage | DoneMessage
  92. /** Host → Python: the answer to one {@link CallMessage}. */
  93. export type ReplyMessage =
  94. | { type: 'reply'; id: number; ok: true; value: unknown }
  95. | { type: 'reply'; id: number; ok: false; message: string }
  96. /**
  97. * The in-band marker text announcing that log capture stopped at the byte
  98. * budget. Shared wire vocabulary: the Python-side LogBuffer emits it when ITS
  99. * ledger exhausts, and the host emits identical text when its own ledger drops
  100. * a frame first (forged fd-3 traffic, stray stdout bytes) — a truncated run
  101. * reads the same however the cap was hit.
  102. * @param maxBytes - the configured `maxLogBytes` the marker names.
  103. * @returns the marker line.
  104. */
  105. export function logTruncationMarker(maxBytes: number): string {
  106. return `[dsh-code-runtime-python] log capture truncated at ${maxBytes} bytes`
  107. }
  108. /**
  109. * Serialize one JSON-parse-produced value without recursion. `JSON.stringify`
  110. * recurses per nesting level and throws `RangeError` a few thousand levels
  111. * deep, but the seam's `CodeJsonValue` has no depth limit — an honest deep
  112. * completion or binding resolution below the byte budget must cross intact
  113. * (the worker backend's wire is equally stack-safe). Callers must pass a value
  114. * produced by `JSON.parse` (or equally JSON-plain): only `null`, finite
  115. * numbers, booleans, strings, dense arrays, and plain objects — this encoder
  116. * validates nothing. Output matches compact `JSON.stringify` byte for byte
  117. * EXCEPT on an integral double beyond the safe range, where {@link scalarJson}
  118. * emits the exact integer's BigInt digits rather than `JSON.stringify`'s rounded
  119. * spelling (`1152921504606846976`, not `...847000`) so the seam's lossless-JSON
  120. * promise holds across the wire.
  121. * @param value - a JSON-plain value (e.g. straight from `JSON.parse`).
  122. * @returns the compact JSON encoding.
  123. */
  124. export function encodeJsonPlain(value: unknown): string {
  125. type Task = { text: string } | { value: unknown }
  126. const chunks: string[] = []
  127. const tasks: Task[] = [{ value }]
  128. for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
  129. if ('text' in task) {
  130. chunks.push(task.text)
  131. continue
  132. }
  133. const current = task.value
  134. if (typeof current === 'string') {
  135. chunks.push(JSON.stringify(current))
  136. } else if (Array.isArray(current)) {
  137. chunks.push('[')
  138. tasks.push({ text: ']' })
  139. for (let index = current.length - 1; index >= 0; index--) {
  140. if (index < current.length - 1) tasks.push({ text: ',' })
  141. tasks.push({ value: current[index] })
  142. }
  143. } else if (typeof current === 'object' && current !== null) {
  144. const record = current as Record<string, unknown>
  145. chunks.push('{')
  146. tasks.push({ text: '}' })
  147. const keys = Object.keys(record)
  148. for (let index = keys.length - 1; index >= 0; index--) {
  149. const key = keys[index] as string
  150. if (index < keys.length - 1) tasks.push({ text: ',' })
  151. tasks.push({ value: record[key] })
  152. tasks.push({ text: `${JSON.stringify(key)}:` })
  153. }
  154. } else {
  155. chunks.push(scalarJson(current))
  156. }
  157. }
  158. return chunks.join('')
  159. }
  160. /**
  161. * One scalar (null, boolean, finite number) as JSON text. A beyond-safe-range
  162. * integral double needs BigInt digits: `String(2 ** 60)` emits the ROUNDED
  163. * `...847000` form, and echoing that to the child would silently change the
  164. * integer the seam promised to carry losslessly — `BigInt(2 ** 60)` prints the
  165. * exact `...846976` the double actually holds.
  166. * @param current - a JSON-plain scalar (JSON.parse emits nothing else).
  167. * @returns its JSON encoding.
  168. */
  169. function scalarJson(current: unknown): string {
  170. if (typeof current === 'number' && Number.isInteger(current) && !Number.isSafeInteger(current)) {
  171. return BigInt(current).toString()
  172. }
  173. return String(current)
  174. }
  175. /**
  176. * Meter a forged done value's compact-JSON byte length AND its number
  177. * losslessness in one bounded traversal, stopping the instant `maxBytes` is
  178. * crossed. A forged `done.value` arrives straight off fd 3 and can sit anywhere
  179. * below the 256 MiB frame ceiling while `maxValueBytes` defaults to 32 KiB. The
  180. * previous split — an unbounded `hasNonLosslessNumber` scan in
  181. * {@link validateChildFrame} followed by a separate byte meter — pushed every
  182. * member of a wide flat payload onto a scan stack before any cap check ran, so
  183. * a below-ceiling forgery could still force a hundreds-of-megabytes host
  184. * allocation. Folding both jobs here rejects over-budget BEFORE enqueuing an
  185. * array's or object's children, keeping the traversal O(cap). A non-lossless
  186. * number (non-finite, negative zero) is caught only when the value fits the
  187. * budget — an over-budget value is rejected regardless, so the distinction is
  188. * moot. Same JSON-plain precondition and traversal shape as
  189. * {@link encodeJsonPlain}; per-scalar encoding delegates to `JSON.stringify`.
  190. * @param value - a JSON-plain value (e.g. straight from `JSON.parse`).
  191. * @param maxBytes - the completion-value budget in bytes.
  192. * @returns `{ ok: true, bytes }` with the exact serialized size, or
  193. * `{ ok: false, reason }` — `over-budget` once the size exceeds `maxBytes`,
  194. * `non-lossless` on a non-finite or negative-zero number.
  195. */
  196. export function checkDoneValue(value: unknown, maxBytes: number): { ok: true; bytes: number } | { ok: false; reason: 'over-budget' | 'non-lossless' } {
  197. let bytes = 0
  198. const stack: unknown[] = [value]
  199. while (stack.length > 0) {
  200. const current = stack.pop()
  201. if (typeof current === 'number') {
  202. if (!Number.isFinite(current) || Object.is(current, -0)) return { ok: false, reason: 'non-lossless' }
  203. bytes += Buffer.byteLength(scalarJson(current), 'utf8')
  204. } else if (typeof current === 'string') {
  205. // Lower-bound BEFORE materializing the escaped form: every UTF-16 code
  206. // unit is at least one UTF-8 byte plus the two quotes, so a huge or
  207. // control-heavy forged string (whose escaped copy expands severalfold)
  208. // is rejected without allocating that copy.
  209. if (bytes + current.length + 2 > maxBytes) return { ok: false, reason: 'over-budget' }
  210. bytes += Buffer.byteLength(JSON.stringify(current), 'utf8')
  211. } else if (Array.isArray(current)) {
  212. // Brackets plus one comma per gap; elements add themselves. Reject
  213. // BEFORE enqueuing children: every element serializes to at least one
  214. // byte, so a forged flat array below the frame ceiling but far above
  215. // the budget fails here without growing the host stack by millions of
  216. // entries first.
  217. bytes += 2 + (current.length > 1 ? current.length - 1 : 0)
  218. if (bytes + current.length > maxBytes) return { ok: false, reason: 'over-budget' }
  219. for (const item of current) stack.push(item)
  220. } else if (typeof current === 'object' && current !== null) {
  221. const record = current as Record<string, unknown>
  222. // Count own keys WITHOUT Object.entries/Object.keys: either would
  223. // allocate one slot (entries: one pair array) per member before the
  224. // bound below could run, recreating the spike the bound exists to stop.
  225. let count = 0
  226. for (const key in record) if (Object.hasOwn(record, key)) count += 1
  227. bytes += 2 + (count > 1 ? count - 1 : 0)
  228. // Same pre-enqueue bound: each entry contributes its quoted key (>= 2
  229. // bytes), the colon, and a >= 1-byte value.
  230. if (bytes + count * 4 > maxBytes) return { ok: false, reason: 'over-budget' }
  231. for (const key in record) {
  232. if (!Object.hasOwn(record, key)) continue
  233. // The same string lower bound, before escaping the key.
  234. if (bytes + key.length + 3 > maxBytes) return { ok: false, reason: 'over-budget' }
  235. bytes += Buffer.byteLength(JSON.stringify(key), 'utf8') + 1
  236. stack.push(record[key])
  237. }
  238. } else {
  239. bytes += Buffer.byteLength(scalarJson(current), 'utf8')
  240. }
  241. if (bytes > maxBytes) return { ok: false, reason: 'over-budget' }
  242. }
  243. return { ok: true, bytes }
  244. }
  245. /**
  246. * Whether a raw JSON line contains an integer token that would lose precision
  247. * as a JavaScript number. `JSON.parse` silently rounds such a token
  248. * (`9007199254740993` becomes `...992`) BEFORE any validation can see it, so
  249. * the check must read the source text; a beyond-safe-range token whose double
  250. * parse round-trips exactly (`2**53`, `2**60`) is lossless and passes. The scan walks the line skipping string literals (a digit run
  251. * inside a string is data, not a number token) and tests every number token
  252. * in plain integer form — no fraction or exponent, which parse as doubles by
  253. * intent. A reviver cannot do this job: the reviver walk recurses per nesting
  254. * level and would reintroduce the depth limit `encodeJsonPlain` removes.
  255. * @param line - the raw UTF-8 text of one JSON-lines frame.
  256. * @returns true when an unsafe integer token is present outside strings.
  257. */
  258. export function hasUnsafeIntegerToken(line: string): boolean {
  259. for (let index = 0; index < line.length; index++) {
  260. const char = line[index]
  261. if (char === '"') {
  262. // Skip the string literal, honoring backslash escapes.
  263. for (index++; index < line.length; index++) {
  264. if (line[index] === '\\') index++
  265. else if (line[index] === '"') break
  266. }
  267. continue
  268. }
  269. if (char === '-' || (char !== undefined && char >= '0' && char <= '9')) {
  270. let end = index + 1
  271. while (end < line.length) {
  272. const c = line[end] as string
  273. if ((c >= '0' && c <= '9') || c === '.' || c === 'e' || c === 'E' || c === '+' || c === '-') end++
  274. else break
  275. }
  276. const token = line.slice(index, end)
  277. // Beyond the safe range an integer token is still lossless IFF the
  278. // double parse round-trips exactly (2**53 does; 2**53+1 rounds) — the
  279. // canonical boundary accepts every JS-double-exact value, so only a
  280. // genuinely rounding token marks the frame as forged.
  281. if (/^-?\d+$/.test(token)) {
  282. const parsed = Number(token)
  283. // A token that parses to Infinity is trivially lossy; a finite
  284. // beyond-safe-range one is lossy only when the BigInt round-trip
  285. // disagrees.
  286. if (!Number.isFinite(parsed)) return true
  287. if (!Number.isSafeInteger(parsed) && BigInt(token) !== BigInt(parsed)) return true
  288. }
  289. index = end - 1
  290. }
  291. }
  292. return false
  293. }
  294. /**
  295. * Lazily yield one plain object's own enumerable property values. A generator
  296. * (not `Object.values`/`Object.entries`) because {@link hasNonLosslessNumber}
  297. * traverses breadth it cannot bound: those helpers copy the whole member list
  298. * up front, so a wide forged object would cost a second full-breadth
  299. * allocation before a single value is examined.
  300. * @param record - a JSON-parse-produced object.
  301. * @yields each own enumerable property value, in key order.
  302. */
  303. function* ownValues(record: object): Generator {
  304. for (const key in record) {
  305. if (Object.hasOwn(record, key)) yield (record as Record<string, unknown>)[key]
  306. }
  307. }
  308. /**
  309. * Whether a JSON.parse-produced value contains a number outside lossless
  310. * JSON: non-finite (`1e400` parses to `Infinity`) or negative zero (`-0.0`
  311. * parses to JS `-0`, whose sign bit a re-serialization drops). The honest
  312. * child's validator rejects these before sending, so a frame carrying one is
  313. * forged.
  314. *
  315. * Runs on `call.args`, which — unlike a completion value — has NO seam byte
  316. * cap, so there is no budget to reject a wide payload against the way
  317. * {@link checkDoneValue} does. The traversal therefore holds ONE cursor per
  318. * NESTING LEVEL (an array or {@link ownValues} iterator) instead of one entry
  319. * per member: a forged flat `args` just below the 256 MiB frame ceiling would
  320. * otherwise push tens of millions of stack entries — and `Object.values` would
  321. * copy each object's full breadth — allocating hundreds of megabytes beyond
  322. * what `JSON.parse` already holds. Iterative either way, so a deep frame
  323. * cannot overflow the host stack.
  324. * @param value - a JSON-parse-produced value from an fd-3 frame.
  325. * @returns true when any contained number is non-finite or negative zero.
  326. */
  327. export function hasNonLosslessNumber(value: unknown): boolean {
  328. const cursors: Iterator<unknown>[] = [[value].values()]
  329. while (cursors.length > 0) {
  330. // The loop condition guarantees a top cursor.
  331. const cursor = cursors.at(-1) as Iterator<unknown>
  332. const step = cursor.next()
  333. if (step.done === true) {
  334. cursors.pop()
  335. continue
  336. }
  337. const current = step.value
  338. if (typeof current === 'number') {
  339. if (!Number.isFinite(current) || Object.is(current, -0)) return true
  340. } else if (Array.isArray(current)) {
  341. cursors.push((current as unknown[]).values())
  342. } else if (typeof current === 'object' && current !== null) {
  343. cursors.push(ownValues(current))
  344. }
  345. }
  346. return false
  347. }
  348. /**
  349. * Runtime shape gate for inbound fd-3 traffic. Model code has full access to
  350. * fd 3 and can post anything — `null`, primitives, poisoned fields — so the
  351. * compile-time union means nothing here: every field is validated and REBUILT
  352. * before the host reads it (forged extras never ride along; a non-number id
  353. * can never be echoed into a reply). Junk returns `undefined` and is dropped
  354. * so a throw in the host's `message` handler cannot crash the host process.
  355. * @param raw - one JSON-parsed frame from fd 3.
  356. * @returns the rebuilt frame, or `undefined` to drop it silently.
  357. */
  358. export function validateChildFrame(raw: unknown): ChildToHost | undefined {
  359. if (typeof raw !== 'object' || raw === null) return undefined
  360. const m = raw as Record<string, unknown>
  361. switch (m.type) {
  362. case 'boot-ack':
  363. return { type: 'boot-ack' }
  364. case 'log':
  365. if (typeof m.text !== 'string') return undefined
  366. // Rebuilt, not passed through: a forged `truncated` of any other type
  367. // would reach the host as a truthy value and silence capture for the
  368. // rest of the run. Only the literal `true` counts.
  369. return { type: 'log', text: m.text, ...m.truncated === true ? { truncated: true } : {} }
  370. case 'call': {
  371. // The id must be a finite number: it is echoed verbatim into the reply
  372. // frame, and a forged `1e400` id (Infinity after JSON.parse) would make
  373. // the reply unencodable as strict JSON.
  374. if (typeof m.id !== 'number' || !Number.isFinite(m.id) || typeof m.global !== 'string' || typeof m.name !== 'string') return undefined
  375. // A forged frame can omit `args` entirely; rebuilding it as `undefined`
  376. // would invoke the binding with a non-JSON value, bypassing the
  377. // lossless-JSON argument boundary. Any PRESENT value is JSON-plain by
  378. // construction (the frame came from JSON.parse), so presence is the
  379. // whole check.
  380. if (!Object.hasOwn(m, 'args')) return undefined
  381. // JSON.parse yields Infinity for 1e400 and preserves -0; both are
  382. // outside lossless JSON, and the honest child never sends them.
  383. if (hasNonLosslessNumber(m.args)) return undefined
  384. return { type: 'call', id: m.id, global: m.global, name: m.name, args: m.args }
  385. }
  386. case 'done': {
  387. // The value passes through untouched here: scanning it for non-lossless
  388. // numbers would push every member of a wide forged payload before any
  389. // byte cap runs. The done handler's bounded `checkDoneValue` folds the
  390. // losslessness check into the metered traversal, rejecting over-budget
  391. // before it enqueues children.
  392. const err = m.error
  393. if (err === undefined) {
  394. return m.value === undefined ? { type: 'done' } : { type: 'done', value: m.value }
  395. }
  396. if (typeof err !== 'object' || err === null) return undefined
  397. const { kind, message } = err as Record<string, unknown>
  398. if (typeof message !== 'string') return undefined
  399. if (kind !== 'exception' && kind !== 'invalid-output' && kind !== 'output-limit') return undefined
  400. return m.value === undefined
  401. ? { type: 'done', error: { kind, message } }
  402. : { type: 'done', value: m.value, error: { kind, message } }
  403. }
  404. default:
  405. return undefined
  406. }
  407. }