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

composerContext.ts

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