Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentSessionJson.ts

202 lines6.7 KB

1import * as Schema from "effect/Schema";
2import * as SchemaAST from "effect/SchemaAST";
3import { none, type Many } from "stream-chain/defs.js";
4import { Assembler } from "stream-json/core/assembler.js";
5import * as StreamJson from "stream-json/core/parser.js";
6import type { ParserOptions, Token } from "stream-json/core/parser.js";
7​
8type JsonPath = ReadonlyArray<string | number | null>;
9​
10export function createTranscriptJsonSelector(schema: { readonly ast: SchemaAST.AST }) {
11 const ast = SchemaAST.toEncoded(schema.ast);
12 const includes = (node: SchemaAST.AST, path: JsonPath, index: number): boolean => {
13 if (index === path.length) return true;
14 switch (node._tag) {
15 case "Objects":
16 if (node.indexSignatures.length > 0) return true;
17 return node.propertySignatures.some(
18 (property) =>
19 String(property.name) === path[index] && includes(property.type, path, index + 1),
20 );
21 case "Arrays": {
22 const key = path[index];
23 if (typeof key !== "number") return true;
24 const element = node.elements[key];
25 if (element) return includes(element, path, index + 1);
26 return node.rest.length === 0 || node.rest.some((item) => includes(item, path, index + 1));
27 }
28 case "Union":
29 return node.types.some((type) => includes(type, path, index));
30 case "Suspend":
31 return includes(node.thunk(), path, index);
32 case "Unknown":
33 case "Any":
34 case "ObjectKeyword":
35 case "Declaration":
36 return true;
37 default:
38 return false;
39 }
40 };
41 return (path: JsonPath) => includes(ast, path, 0);
43​
44export class TranscriptJsonLimitError extends Schema.TaggedError<TranscriptJsonLimitError>()(
45 "TranscriptJsonLimitError",
46 { message: Schema.String },
47) {}
48​
49export function createTranscriptJsonReader(
50 reserve: (bytes: number) => void,
51 selectPath: (path: JsonPath) => boolean,
52 options?: {
53 readonly maxDepth?: number;
54 // Reports each selected top-level string field as soon as it ends, before the record does.
55 readonly onTopLevelString?: (key: string, value: string) => void;
56 },
57) {
58 // 3.6.0 omits the synchronous tokenizer from types; parser() adds an unnecessary async generator.
59 const { jsonParser } = StreamJson as typeof StreamJson & {
60 jsonParser: (
61 options: ParserOptions,
62 ) => (input: string | typeof none) => Many<Token> | typeof none;
63 };
64 const tokenize = jsonParser({ packValues: false });
65 const assembler = new Assembler();
66 let key: string | null = null;
67 let value = "";
68 let depth = 0;
69 let complete = false;
70 let malformed = false;
71​
72 const assemble = (token: Token) => {
73 reserve(
74 64 + ("value" in token && typeof token.value === "string" ? token.value.length * 2 : 0),
75 );
76 switch (token.name) {
77 case "startString":
78 case "startNumber":
79 value = "";
80 break;
81 case "stringChunk":
82 case "numberChunk":
83 value += token.value;
84 break;
85 case "endString":
86 assembler.consume({ name: "stringValue", value });
87 value = "";
88 break;
89 case "endNumber":
90 assembler.consume({ name: "numberValue", value });
91 value = "";
92 break;
93 default:
94 assembler.consume(token);
95 }
96 };
97 // Preserve actual keys; adjacent duplicates share a path, but JSON.parse keeps the last value.
98 const stack: Array<{ path: JsonPath; key: string | number | null; selected: boolean }> = [];
99 let selectedValue = false;
100 const startValue = () => {
101 const parent = stack.at(-1);
102 const path = parent?.selected ? [...parent.path, parent.key] : [];
103 const selected = (parent?.selected ?? true) && selectPath(path);
104 if (selected && typeof parent?.key === "string") {
105 assemble({ name: "keyValue", value: parent.key });
106 }
107 return { path, selected };
108 };
109 const endValue = () => {
110 const parent = stack.at(-1);
111 if (parent && typeof parent.key === "number") parent.key++;
112 };
113 const selectToken = (token: Token | typeof none) => {
114 if (token === none) return;
115 switch (token.name) {
116 case "keyValue": {
117 const parent = stack.at(-1);
118 if (parent) parent.key = token.value;
119 return;
120 }
121 case "startObject":
122 case "startArray": {
123 const frame = startValue();
124 stack.push({ ...frame, key: token.name === "startArray" ? 0 : null });
125 if (frame.selected) assemble(token);
126 return;
127 }
128 case "endObject":
129 case "endArray":
130 if (stack.pop()?.selected) assemble(token);
131 endValue();
132 return;
133 case "startString":
134 case "startNumber":
135 selectedValue = startValue().selected;
136 if (selectedValue) assemble(token);
137 return;
138 case "endString":
139 case "endNumber":
140 if (selectedValue) {
141 const parent = stack[0];
142 if (token.name === "endString" && stack.length === 1 && typeof parent?.key === "string") {
143 options?.onTopLevelString?.(parent.key, value);
144 }
145 assemble(token);
146 }
147 endValue();
148 return;
149 case "nullValue":
150 case "trueValue":
151 case "falseValue":
152 if (startValue().selected) assemble(token);
153 endValue();
154 return;
155 default:
156 if (selectedValue) assemble(token);
157 }
158 };
159 const consume = (input: string | typeof none) => {
160 if (malformed) return;
161 try {
162 const tokens = tokenize(input);
163 if (tokens === none) return;
164 for (const token of tokens.values) {
165 if (token.name === "startObject" || token.name === "startArray") {
166 if (++depth > (options?.maxDepth ?? 128))
167 throw new TranscriptJsonLimitError({
168 message: "Transcript JSON nesting exceeds the depth limit",
169 });
170 } else if (token.name === "endObject" || token.name === "endArray") {
171 if (--depth === 0) complete = true;
172 }
173 if (token.name === "startKey") {
174 key = "";
175 } else if (token.name === "stringChunk" && key !== null) {
176 reserve(token.value.length * 2);
177 key += token.value;
178 } else if (token.name === "endKey") {
179 selectToken({ name: "keyValue", value: key ?? "" });
180 key = null;
181 } else {
182 selectToken(token);
183 }
184 }
185 } catch (cause) {
186 if (cause instanceof Error && cause.message.startsWith("Parser ")) {
187 malformed = true;
188 } else {
189 throw cause;
190 }
191 }
192 };
193 return {
194 write: (chunk: string) => consume(chunk),
195 finish: (): unknown => {
196 consume(none);
197 if (malformed || !complete) return undefined;
198 selectToken(none);
199 return assembler.done ? assembler.current : undefined;
200 },
201 };