Open History to see the last commit
1/**
2 * Byte-exact framing for journal reads.
3 *
4 * Both read paths end in {@link toJournalLines}, which counts absolute file
5 * offsets over BYTES, because a position is only useful if `tail -c +N` can
6 * resume from it. The two paths differ only in how they get bytes:
7 *
8 * - The **bounded** read is base64-framed (see `journal.ts` rule 2) and arrives
9 * as one complete `ExecResult.stdout` string, so {@link decodeBase64Stream}
10 * recovers the file's exact bytes regardless of how the provider decoded its
11 * stdout.
12 * - The **follow** read cannot be base64-framed — the encoder's stdio buffer
13 * would swallow the stream — so it arrives as provider-decoded text chunks
14 * and {@link encodeUtf8Stream} turns them back into bytes.
15 *
16 * `atob`, not `Buffer`: this module runs on the host, and the host can itself be
17 * a Cloudflare Worker (`ai-sandbox-cloudflare` drives its sandbox over Workers
18 * RPC from Worker code), where `Buffer` is not a global unless the `nodejs_compat`
19 * flag is on. `atob` is a Web/DOM API available in every host runtime this
20 * package targets, so it is the portable choice here.
21 */
22
23const NEWLINE = 0x0a
24
25/** Decode one complete base64 quantum group to bytes. */
26function decodeQuantumGroup(group: string): Uint8Array {
27 const binary = atob(group)
28 const out = new Uint8Array(binary.length)
29 for (let index = 0; index < binary.length; index += 1) {
30 out[index] = binary.charCodeAt(index)
31 }
32 return out
33}
34
35/**
36 * Decode a streaming base64 frame into raw bytes.
37 *
38 * Whitespace is stripped because `base64(1)` wraps at 76 columns by default and
39 * busybox's build does not accept `-w 0`, so the wrapping cannot be turned off
40 * portably. Only complete 4-character quanta are decoded; a remainder is held
41 * for the next chunk. Padding (`=`) appears only in the final quantum, so an
42 * intermediate group always decodes to exactly 3 bytes.
43 */
44export async function* decodeBase64Stream(
45 chunks: AsyncIterable<string>,
46): AsyncIterable<Uint8Array> {
47 let pending = ''
48 for await (const chunk of chunks) {
49 pending += chunk.replace(/\s+/g, '')
50 const usable = pending.length - (pending.length % 4)
51 if (usable === 0) continue
52 const group = pending.slice(0, usable)
53 pending = pending.slice(usable)
54 yield decodeQuantumGroup(group)
55 }
56 if (pending.length > 0) {
57 // Fail loud. A remainder means the frame was cut off mid-quantum, i.e. the
58 // reader died partway through. Rounding it away would silently drop journal
59 // bytes and desync every position derived from this stream.
60 throw new Error(
61 `journal: base64 frame ended mid-quantum with ${pending.length} character(s) pending`,
62 )
63 }
64}
65
66/**
67 * Re-encode provider-decoded text chunks as UTF-8 bytes.
68 *
69 * This is the follow path's replacement for {@link decodeBase64Stream}: the
70 * follow command emits the journal's raw bytes, the provider hands them over as
71 * `AsyncIterable<string>`, and `TextEncoder` round-trips that text back to the
72 * bytes it was decoded from. Chunk boundaries do not need to fall on character
73 * boundaries here — {@link toJournalLines} buffers bytes until a newline, so a
74 * multi-byte character split across two chunks is reassembled there, exactly as
75 * it is on the base64 path.
76 *
77 * Empty chunks are dropped rather than forwarded: a zero-length `Uint8Array`
78 * carries no bytes and would only make the downstream loop spin.
79 */
80export async function* encodeUtf8Stream(
81 chunks: AsyncIterable<string>,
82): AsyncIterable<Uint8Array> {
83 const encoder = new TextEncoder()
84 for await (const chunk of chunks) {
85 if (chunk.length === 0) continue
86 yield encoder.encode(chunk)
87 }
88}
89
90/** One complete journal line plus the absolute byte position just past its newline. */
91export interface JournalLine {
92 /** The line's text, newline excluded. */
93 line: string
94 /**
95 * Absolute byte offset immediately AFTER this line's newline — i.e. the count
96 * of journal bytes fully consumed once this line has been handled, and
97 * therefore the exact value to resume a `tail -c +N` from.
98 */
99 endPosition: number
100}
101
102function concatBytes(left: Uint8Array, right: Uint8Array): Uint8Array {
103 const out = new Uint8Array(left.length + right.length)
104 out.set(left, 0)
105 out.set(right, left.length)
106 return out
107}
108
109/**
110 * Split a byte stream into newline-terminated lines, tracking absolute
111 * positions from `startPosition`.
112 *
113 * Deliberately unlike `toLines` in `runner.ts`, which yields a trailing
114 * unterminated line: here a trailing partial line is a line the agent is still
115 * writing. Yielding it would hand a truncated JSON string downstream AND
116 * advance the position past bytes the next read must re-see.
117 */
118export async function* toJournalLines(
119 byteChunks: AsyncIterable<Uint8Array>,
120 startPosition: number,
121): AsyncIterable<JournalLine> {
122 const decoder = new TextDecoder()
123 let buffer: Uint8Array = new Uint8Array(0)
124 let position = startPosition
125 for await (const bytes of byteChunks) {
126 buffer = concatBytes(buffer, bytes)
127 let newline = buffer.indexOf(NEWLINE)
128 while (newline !== -1) {
129 const lineBytes = buffer.subarray(0, newline)
130 position += newline + 1
131 yield { line: decoder.decode(lineBytes), endPosition: position }
132 buffer = buffer.slice(newline + 1)
133 newline = buffer.indexOf(NEWLINE)
134 }
135 }
136}