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

composerContext.ts

281 lines10.7 KB

1import * as Schema from "effect/Schema";
2​
3import {
4 ForwardCompatibleArray,
5 NonNegativeInt,
6 PositiveInt,
7 TrimmedNonEmptyString,
8} from "./baseSchemas.ts";
9​
10/**
11 * Inline context records: the typed payload behind every composer chip.
12 * A message's `text` carries position through canonical reference links
13 * (`[label](t3-context://v1/<kind>/<contextId>)`, see
14 * `@t3tools/shared/composerContextReferences`); these records carry the payload,
15 * keyed by `contextId`. Bytes never live here: image and file records bind to a
16 * `ChatAttachment` by id.
17 */
18​
19export const COMPOSER_CONTEXT_KINDS = [
20 "image",
21 "file",
22 "terminal",
23 "element",
24 "preview-annotation",
25 "review-comment",
26 "mention",
27 "skill",
28] as const;
29export type KnownComposerContextKind = (typeof COMPOSER_CONTEXT_KINDS)[number];
30​
31const CONTEXT_ID_MAX_CHARS = 128;
32const CONTEXT_ID_PATTERN = /^[a-z0-9_-]+$/i;
33const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;
34const KNOWN_KIND_PATTERN = new RegExp(`^(?!(?:${COMPOSER_CONTEXT_KINDS.join("|")})$)`);
35​
36export const COMPOSER_CONTEXT_LABEL_MAX_CHARS = 200;
37export const COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS = 64_000;
38const COMPOSER_CONTEXT_ELEMENT_HTML_MAX_CHARS = 8_000;
39const COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS = 8_000;
40/** Exported so producers can clamp to the same boundary the schema enforces, rather than
41 minting a record the send path would fail to encode. */
42export const COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS = 16_000;
43export const COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS = 32_000;
44const COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS = 8_000;
45​
46/** Durable identity of one payload. Shared by every chip that points at it. */
47export const ComposerContextId = TrimmedNonEmptyString.check(
48 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
49 Schema.isPattern(CONTEXT_ID_PATTERN),
50).pipe(Schema.brand("ComposerContextId"));
51export type ComposerContextId = typeof ComposerContextId.Type;
52​
53/** Identity of one occurrence in a document. Changes when a chip is duplicated. */
54export const ComposerContextReferenceId = TrimmedNonEmptyString.check(
55 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
56 Schema.isPattern(CONTEXT_ID_PATTERN),
57).pipe(Schema.brand("ComposerContextReferenceId"));
58export type ComposerContextReferenceId = typeof ComposerContextReferenceId.Type;
59​
60/** Open kind: known kinds get typed records, everything else preserves its payload. */
61export const ComposerContextKind = TrimmedNonEmptyString.check(
62 Schema.isPattern(CONTEXT_KIND_PATTERN),
63);
64export type ComposerContextKind = typeof ComposerContextKind.Type;
65​
66// Same rules as the private `ChatAttachmentId` in orchestration.ts; duplicated here because
67// orchestration.ts imports this module.
68const ContextAttachmentId = TrimmedNonEmptyString.check(
69 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
70 Schema.isPattern(CONTEXT_ID_PATTERN),
71);
72const ContextLabel = Schema.String.check(Schema.isMaxLength(COMPOSER_CONTEXT_LABEL_MAX_CHARS));
73const BoundedString = (max: number) => Schema.String.check(Schema.isMaxLength(max));
74const ShortString = BoundedString(2_048);
75const NullableShortString = Schema.NullOr(ShortString);
76​
77/** Snapshot used to identify and present a pull request carried by a review-context record. */
78export const PullRequestContextMetadata = Schema.Struct({
79 number: PositiveInt,
80 title: ShortString,
81 url: ShortString,
82 headBranch: ShortString,
83 baseBranch: ShortString,
84 state: Schema.Literals(["open", "closed", "merged"]),
85 isDraft: Schema.Boolean,
86});
87export type PullRequestContextMetadata = typeof PullRequestContextMetadata.Type;
88​
89const recordBase = {
90 version: Schema.Literal(1),
91 contextId: ComposerContextId,
92 label: ContextLabel,
93} as const;
94​
95const attachmentBinding = {
96 attachmentId: ContextAttachmentId,
97 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
98 mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
99 sizeBytes: NonNegativeInt,
100} as const;
101​
102export const ImageContextRecord = Schema.Struct({
103 ...recordBase,
104 kind: Schema.Literal("image"),
105 ...attachmentBinding,
106});
107export type ImageContextRecord = typeof ImageContextRecord.Type;
108​
109export const FileContextRecord = Schema.Struct({
110 ...recordBase,
111 kind: Schema.Literal("file"),
112 ...attachmentBinding,
113});
114export type FileContextRecord = typeof FileContextRecord.Type;
115​
116export const TerminalContextRecord = Schema.Struct({
117 ...recordBase,
118 kind: Schema.Literal("terminal"),
119 terminalId: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
120 terminalLabel: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
121 lineStart: NonNegativeInt,
122 lineEnd: NonNegativeInt,
123 text: BoundedString(COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS),
124}).check(Schema.makeFilter((record) => record.lineEnd >= record.lineStart));
125export type TerminalContextRecord = typeof TerminalContextRecord.Type;
126​
127export const ElementContextSource = Schema.Struct({
128 functionName: NullableShortString,
129 fileName: NullableShortString,
130 lineNumber: Schema.NullOr(NonNegativeInt),
131 columnNumber: Schema.NullOr(NonNegativeInt),
132});
133export type ElementContextSource = typeof ElementContextSource.Type;
134​
135/** What a picked page element looks like to the agent; shared by element and annotation records. */
136export const ElementContextDetails = Schema.Struct({
137 pageUrl: ShortString,
138 pageTitle: NullableShortString,
139 tagName: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
140 selector: NullableShortString,
141 htmlPreview: BoundedString(COMPOSER_CONTEXT_ELEMENT_HTML_MAX_CHARS),
142 componentName: NullableShortString,
143 source: Schema.NullOr(ElementContextSource),
144 styles: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
145});
146export type ElementContextDetails = typeof ElementContextDetails.Type;
147​
148export const ElementContextRecord = Schema.Struct({
149 ...recordBase,
150 kind: Schema.Literal("element"),
151 ...ElementContextDetails.fields,
152});
153export type ElementContextRecord = typeof ElementContextRecord.Type;
154​
155export const PreviewAnnotationContextRecord = Schema.Struct({
156 ...recordBase,
157 kind: Schema.Literal("preview-annotation"),
158 annotationId: ShortString,
159 pageUrl: ShortString,
160 pageTitle: NullableShortString,
161 comment: BoundedString(COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS),
162 targetSummary: ShortString,
163 styleChanges: Schema.Array(ShortString).check(Schema.isMaxLength(200)),
164 /** Picked elements inside the annotation, with the detail the agent needs to find them. */
165 elements: Schema.optional(Schema.Array(ElementContextDetails).check(Schema.isMaxLength(50))),
166 /** Original target ids and edits allow pasted annotations to retain exact style changes. */
167 elementIds: Schema.optional(Schema.Array(ShortString).check(Schema.isMaxLength(50))),
168 /** Region and stroke geometry is lossy on purpose, but their counts feed the target summary,
169 so a pasted annotation still says what it marked. */
170 regionCount: Schema.optional(NonNegativeInt),
171 strokeCount: Schema.optional(NonNegativeInt),
172 styleChangeDetails: Schema.optional(
173 Schema.Array(
174 Schema.Struct({
175 targetId: ShortString,
176 selector: NullableShortString,
177 property: ShortString,
178 previousValue: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
179 value: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
180 }),
181 ).check(Schema.isMaxLength(200)),
182 ),
183 /** The screenshot travels as its own image record; this links the two. */
184 screenshotContextId: Schema.optional(ComposerContextId),
185});
186export type PreviewAnnotationContextRecord = typeof PreviewAnnotationContextRecord.Type;
187​
188export const ReviewCommentContextRecord = Schema.Struct({
189 ...recordBase,
190 kind: Schema.Literal("review-comment"),
191 sectionId: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
192 sectionTitle: ShortString,
193 filePath: TrimmedNonEmptyString.check(Schema.isMaxLength(2_048)),
194 startIndex: NonNegativeInt,
195 endIndex: NonNegativeInt,
196 rangeLabel: ShortString,
197 text: BoundedString(COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
198 diff: BoundedString(COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
199 fenceLanguage: Schema.optional(BoundedString(64)),
200 pullRequest: Schema.optional(PullRequestContextMetadata),
201}).check(Schema.makeFilter((record) => record.endIndex >= record.startIndex));
202export type ReviewCommentContextRecord = typeof ReviewCommentContextRecord.Type;
203​
204export const MentionContextRecord = Schema.Struct({
205 ...recordBase,
206 kind: Schema.Literal("mention"),
207 path: TrimmedNonEmptyString.check(Schema.isMaxLength(2_048)),
208});
209export type MentionContextRecord = typeof MentionContextRecord.Type;
210​
211export const SkillContextRecord = Schema.Struct({
212 ...recordBase,
213 kind: Schema.Literal("skill"),
214 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
215});
216export type SkillContextRecord = typeof SkillContextRecord.Type;
217​
218/**
219 * Catch-all for kinds this build does not know. Known discriminators are excluded so a
220 * malformed known record fails its own schema instead of sliding through unchecked.
221 * Mirrors `ChatUnknownAttachment`.
222 */
223export const UnknownContextRecord = Schema.Struct({
224 ...recordBase,
225 kind: ComposerContextKind.check(Schema.isPattern(KNOWN_KIND_PATTERN)),
226 payload: Schema.Unknown.check(
227 Schema.makeFilter((payload) => {
228 try {
229 const encoded = JSON.stringify(payload);
230 return encoded !== undefined && encoded.length <= 64_000;
231 } catch {
232 return false;
233 }
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]);
249export type KnownComposerContextRecord = typeof KnownComposerContextRecord.Type;
250​
251export const ComposerContextRecord = Schema.Union([
252 ...KnownComposerContextRecord.members,
253 UnknownContextRecord,
254]);
255export type ComposerContextRecord = typeof ComposerContextRecord.Type;
256​
257export const COMPOSER_CONTEXT_MAX_RECORDS = 200;
258const COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS = 16_000_000;
259​
260/** Structured context riding on a user message. Undecodable records are dropped, not fatal. */
261export const OrchestrationMessageContext = Schema.Struct({
262 version: Schema.Literal(1),
263 records: Schema.Array(Schema.Unknown)
264 .check(
265 Schema.isMaxLength(COMPOSER_CONTEXT_MAX_RECORDS),
266 Schema.makeFilter((records) => {
267 try {
268 return JSON.stringify(records).length <= COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS;
269 } catch {
270 return false;
271 }
272 }),
273 )
274 .pipe(Schema.decodeTo(ForwardCompatibleArray(ComposerContextRecord)))
275 .check(
276 Schema.makeFilter(
277 (records) => new Set(records.map((record) => record.contextId)).size === records.length,
278 ),
279 ),
280});
281export type OrchestrationMessageContext = typeof OrchestrationMessageContext.Type;