The best way to control Claude Code, Codex and more from any computer or phone

main
ts 72 lines 2.45 KB
Raw
1 import type { LogEntry } from "./Model.ts";
2
3 const CAPTURE_BYTES = 256 * 1024;
4 const TOTAL_BYTES = 16 * 1024 * 1024;
5 const TRUNCATED = "[Earlier output omitted from preview; full output is in the run log.]";
6
7 /** Bounded live previews; every original entry is persisted before trimming. */
8 export const makeCapture = (limits = { capture: CAPTURE_BYTES, total: TOTAL_BYTES }) => {
9 const buffers = new Map<Array<LogEntry>, number>();
10 let total = 0;
11 const size = (entry: LogEntry) => Buffer.byteLength(entry.message, "utf8") + 64;
12 const release = (buffer: Array<LogEntry>) => {
13 total -= buffers.get(buffer) ?? 0;
14 buffers.delete(buffer);
15 buffer.length = 0;
16 };
17 const trim = (buffer: Array<LogEntry>, limit: number) => {
18 let bytes = buffers.get(buffer) ?? 0;
19 let removed = false;
20 while (bytes > limit && buffer.length > 0) {
21 const entry = buffer.shift()!;
22 const cost = size(entry);
23 bytes -= cost;
24 total -= cost;
25 removed = true;
26 }
27 if (removed && buffer.length > 0 && buffer[0]!.message !== TRUNCATED) {
28 const entry = {
29 level: "info",
30 message: TRUNCATED,
31 time: buffer[0]!.time,
32 };
33 buffer.unshift(entry);
34 bytes += size(entry);
35 total += size(entry);
36 }
37 if (bytes === 0) buffers.delete(buffer);
38 else buffers.set(buffer, bytes);
39 };
40 const create = (persist: (entry: LogEntry) => void): Array<LogEntry> => {
41 const buffer: Array<LogEntry> = [];
42 buffer.push = (...entries) => {
43 for (const entry of entries) {
44 persist(entry);
45 // A single oversized message must not defeat either preview limit.
46 const maxChars = Math.max(
47 0,
48 Math.floor((Math.min(limits.capture, limits.total) - 256) / 4),
49 );
50 const preview =
51 entry.message.length > maxChars
52 ? {
53 ...entry,
54 message: `${TRUNCATED}\n${maxChars === 0 ? "" : entry.message.slice(-maxChars)}`,
55 }
56 : entry;
57 Array.prototype.push.call(buffer, preview);
58 const cost = size(preview);
59 buffers.set(buffer, (buffers.get(buffer) ?? 0) + cost);
60 total += cost;
61 trim(buffer, Math.max(0, limits.capture - 256));
62 while (total > limits.total && buffers.size > 0) {
63 const oldest = buffers.keys().next().value!;
64 release(oldest);
65 }
66 }
67 return buffer.length;
68 };
69 return buffer;
70 };
71 return { create, release };
72 };