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

composerContext.ts

282 lines9.9 KB

1import * as Schema from "effect/Schema";
2​
3import {
4 EnvironmentId,
5 ForwardCompatibleArray,
6 NonNegativeInt,
7 PositiveInt,
8 ThreadId,
9 TrimmedNonEmptyString,
10} from "./baseSchemas.ts";
11​
12/**
13 * Bytes never live here: image and file records bind to a `ChatAttachment` by id.
14 */
15​
16export const COMPOSER_CONTEXT_KINDS = [
17 "image",
18 "file",
19 "terminal",
20 "element",
21 "preview-annotation",
22 "review-comment",
23 "mention",
24 "skill",
25 "thread",
26] as const;
27export type KnownComposerContextKind = (typeof COMPOSER_CONTEXT_KINDS)[number];
28​
29const CONTEXT_ID_MAX_CHARS = 128;
30const CONTEXT_ID_PATTERN = /^[a-z0-9_-]+$/i;
31const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;
32const KNOWN_KIND_PATTERN = new RegExp(`^(?!(?:${COMPOSER_CONTEXT_KINDS.join("|")})$)`);
33​
34export const COMPOSER_CONTEXT_LABEL_MAX_CHARS = 200;
35export const COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS = 64_000;
36const COMPOSER_CONTEXT_ELEMENT_HTML_MAX_CHARS = 8_000;
37const COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS = 8_000;
38export const COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS = 16_000;
39export const COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS = 32_000;
40const COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS = 8_000;
41​
42export const ComposerContextId = TrimmedNonEmptyString.check(
43 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
44 Schema.isPattern(CONTEXT_ID_PATTERN),
45).pipe(Schema.brand("ComposerContextId"));
46export type ComposerContextId = typeof ComposerContextId.Type;
47​
48export const ComposerContextReferenceId = TrimmedNonEmptyString.check(
49 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
50 Schema.isPattern(CONTEXT_ID_PATTERN),
51).pipe(Schema.brand("ComposerContextReferenceId"));
52export type ComposerContextReferenceId = typeof ComposerContextReferenceId.Type;
53​
54export const ComposerContextKind = TrimmedNonEmptyString.check(
55 Schema.isPattern(CONTEXT_KIND_PATTERN),
56);
57export type ComposerContextKind = typeof ComposerContextKind.Type;
58​
59// Same rules as the private `ChatAttachmentId` in orchestration.ts; duplicated here because
60// orchestration.ts imports this module.
61const ContextAttachmentId = TrimmedNonEmptyString.check(
62 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
63 Schema.isPattern(CONTEXT_ID_PATTERN),
64);
65const ContextLabel = Schema.String.check(Schema.isMaxLength(COMPOSER_CONTEXT_LABEL_MAX_CHARS));
66const BoundedString = (max: number) => Schema.String.check(Schema.isMaxLength(max));
67const ShortString = BoundedString(2_048);
68const NullableShortString = Schema.NullOr(ShortString);
69​
70export const PullRequestContextMetadata = Schema.Struct({
71 number: PositiveInt,
72 title: ShortString,
73 url: ShortString,
74 headBranch: ShortString,
75 baseBranch: ShortString,
76 state: Schema.Literals(["open", "closed", "merged"]),
77 isDraft: Schema.Boolean,
78});
79export type PullRequestContextMetadata = typeof PullRequestContextMetadata.Type;
80​
81const recordBase = {
82 version: Schema.Literal(1),
83 contextId: ComposerContextId,
84 label: ContextLabel,
85} as const;
86​
87const attachmentBinding = {
88 attachmentId: ContextAttachmentId,
89 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
90 mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
91 sizeBytes: NonNegativeInt,
92} as const;
93​
94export const ImageContextRecord = Schema.Struct({
95 ...recordBase,
96 kind: Schema.Literal("image"),
97 ...attachmentBinding,
98});
99export type ImageContextRecord = typeof ImageContextRecord.Type;
100​
101export const FileContextRecord = Schema.Struct({
102 ...recordBase,
103 kind: Schema.Literal("file"),
104 ...attachmentBinding,
105});
106export type FileContextRecord = typeof FileContextRecord.Type;
107​
108export const TerminalContextRecord = Schema.Struct({
109 ...recordBase,
110 kind: Schema.Literal("terminal"),
111 terminalId: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
112 terminalLabel: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
113 lineStart: NonNegativeInt,
114 lineEnd: NonNegativeInt,
115 text: BoundedString(COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS),
116}).check(Schema.makeFilter((record) => record.lineEnd >= record.lineStart));
117export type TerminalContextRecord = typeof TerminalContextRecord.Type;
118​
119export const ElementContextSource = Schema.Struct({
120 functionName: NullableShortString,
121 fileName: NullableShortString,
122 lineNumber: Schema.NullOr(NonNegativeInt),
123 columnNumber: Schema.NullOr(NonNegativeInt),
124});
125export type ElementContextSource = typeof ElementContextSource.Type;
126​
127export const ElementContextDetails = Schema.Struct({
128 pageUrl: ShortString,
129 pageTitle: NullableShortString,
130 tagName: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
131 selector: NullableShortString,
132 htmlPreview: BoundedString(COMPOSER_CONTEXT_ELEMENT_HTML_MAX_CHARS),
133 componentName: NullableShortString,
134 source: Schema.NullOr(ElementContextSource),
135 styles: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
136});
137export type ElementContextDetails = typeof ElementContextDetails.Type;
138​
139export const ElementContextRecord = Schema.Struct({
140 ...recordBase,
141 kind: Schema.Literal("element"),
142 ...ElementContextDetails.fields,
143});
144export type ElementContextRecord = typeof ElementContextRecord.Type;
145​
146// Optional record fields are `optionalKey`: a record holding an explicit
147// `undefined` cannot be sent as JSON, so it fails its own check and is dropped
148// alone instead of failing the whole message.
149export const PreviewAnnotationContextRecord = Schema.Struct({
150 ...recordBase,
151 kind: Schema.Literal("preview-annotation"),
152 annotationId: ShortString,
153 pageUrl: ShortString,
154 pageTitle: NullableShortString,
155 comment: BoundedString(COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS),
156 targetSummary: ShortString,
157 styleChanges: Schema.Array(ShortString).check(Schema.isMaxLength(200)),
158 elements: Schema.optionalKey(Schema.Array(ElementContextDetails).check(Schema.isMaxLength(50))),
159 elementIds: Schema.optionalKey(Schema.Array(ShortString).check(Schema.isMaxLength(50))),
160 regionCount: Schema.optionalKey(NonNegativeInt),
161 strokeCount: Schema.optionalKey(NonNegativeInt),
162 styleChangeDetails: Schema.optionalKey(
163 Schema.Array(
164 Schema.Struct({
165 targetId: ShortString,
166 selector: NullableShortString,
167 property: ShortString,
168 previousValue: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
169 value: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
170 }),
171 ).check(Schema.isMaxLength(200)),
172 ),
173 screenshotContextId: Schema.optionalKey(ComposerContextId),
174});
175export type PreviewAnnotationContextRecord = typeof PreviewAnnotationContextRecord.Type;
176​
177export const ReviewCommentContextRecord = Schema.Struct({
178 ...recordBase,
179 kind: Schema.Literal("review-comment"),
180 sectionId: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
181 sectionTitle: ShortString,
182 filePath: TrimmedNonEmptyString.check(Schema.isMaxLength(2_048)),
183 startIndex: NonNegativeInt,
184 endIndex: NonNegativeInt,
185 rangeLabel: ShortString,
186 text: BoundedString(COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
187 diff: BoundedString(COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
188 fenceLanguage: Schema.optionalKey(BoundedString(64)),
189 pullRequest: Schema.optionalKey(PullRequestContextMetadata),
190}).check(Schema.makeFilter((record) => record.endIndex >= record.startIndex));
191export type ReviewCommentContextRecord = typeof ReviewCommentContextRecord.Type;
192​
193export const MentionContextRecord = Schema.Struct({
194 ...recordBase,
195 kind: Schema.Literal("mention"),
196 path: TrimmedNonEmptyString.check(Schema.isMaxLength(2_048)),
197});
198export type MentionContextRecord = typeof MentionContextRecord.Type;
199​
200export const SkillContextRecord = Schema.Struct({
201 ...recordBase,
202 kind: Schema.Literal("skill"),
203 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
204});
205export type SkillContextRecord = typeof SkillContextRecord.Type;
206​
207export const ThreadContextRecord = Schema.Struct({
208 ...recordBase,
209 kind: Schema.Literal("thread"),
210 environmentId: EnvironmentId,
211 threadId: ThreadId,
212 title: ContextLabel,
213});
214export type ThreadContextRecord = typeof ThreadContextRecord.Type;
215​
216const isJson = Schema.is(Schema.Json);
217​
218/**
219 * Known discriminators are excluded so a malformed known record fails its own schema instead of
220 * sliding through unchecked.
221 */
222export const UnknownContextRecord = Schema.Struct({
223 ...recordBase,
224 kind: ComposerContextKind.check(Schema.isPattern(KNOWN_KIND_PATTERN)),
225 payload: Schema.Unknown.check(
226 Schema.makeFilter((payload) => {
227 let encoded: string | undefined;
228 try {
229 encoded = JSON.stringify(payload);
230 } catch {
231 return false;
232 }
233 return encoded !== undefined && encoded.length <= 64_000 && isJson(payload);
234 }),
235 ),
236});
237export type UnknownContextRecord = typeof UnknownContextRecord.Type;
238​
239export const KnownComposerContextRecord = Schema.Union([
240 ImageContextRecord,
241 FileContextRecord,
242 TerminalContextRecord,
243 ElementContextRecord,
244 PreviewAnnotationContextRecord,
245 ReviewCommentContextRecord,
246 MentionContextRecord,
247 SkillContextRecord,
248 ThreadContextRecord,
249]);
250export type KnownComposerContextRecord = typeof KnownComposerContextRecord.Type;
251​
252export const ComposerContextRecord = Schema.Union([
253 ...KnownComposerContextRecord.members,
254 UnknownContextRecord,
255]);
256export type ComposerContextRecord = typeof ComposerContextRecord.Type;
257​
258export const COMPOSER_CONTEXT_MAX_RECORDS = 200;
259const COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS = 16_000_000;
260​
261/** Structured context riding on a user message. Undecodable records are dropped, not fatal. */
262export const OrchestrationMessageContext = Schema.Struct({
263 version: Schema.Literal(1),
264 records: Schema.Array(Schema.Unknown)
265 .check(
266 Schema.isMaxLength(COMPOSER_CONTEXT_MAX_RECORDS),
267 Schema.makeFilter((records) => {
268 try {
269 return JSON.stringify(records).length <= COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS;
270 } catch {
271 return false;
272 }
273 }),
274 )
275 .pipe(Schema.decodeTo(ForwardCompatibleArray(ComposerContextRecord)))
276 .check(
277 Schema.makeFilter(
278 (records) => new Set(records.map((record) => record.contextId)).size === records.length,
279 ),
280 ),
281});
282export type OrchestrationMessageContext = typeof OrchestrationMessageContext.Type;