Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3import { SnapShotSource } from "./chatAttachment.ts";
4
5import { AssistantCitation } from "./assistantCitations.ts";
6import {
7 EnvironmentId,
8 ForwardCompatibleArray,
9 GuestMessageId,
10 GuestShareId,
11 NonNegativeInt,
12 PositiveInt,
13 ThreadId,
14 TrimmedNonEmptyString,
15 TurnItemId,
16} from "./baseSchemas.ts";
17import { GUEST_MESSAGE_MAX_LENGTH, GUEST_NAME_MAX_LENGTH } from "./guestShare.ts";
18
19/** Image and file records reference `ChatAttachment` ids, never bytes. */
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 "environment",
32 "response",
33] as const;
34export type KnownComposerContextKind = (typeof COMPOSER_CONTEXT_KINDS)[number];
35
36const CONTEXT_ID_MAX_CHARS = 128;
37const CONTEXT_ID_PATTERN = /^[a-z0-9_-]+$/i;
38const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;
39const KNOWN_KIND_PATTERN = new RegExp(`^(?!(?:${COMPOSER_CONTEXT_KINDS.join("|")})$)`);
40
41export const COMPOSER_CONTEXT_LABEL_MAX_CHARS = 200;
42export const COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS = 64_000;
43const COMPOSER_CONTEXT_ELEMENT_HTML_MAX_CHARS = 8_000;
44const COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS = 8_000;
45export const COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS = 16_000;
46export const COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS = 32_000;
47export const COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS = 8_000;
48export const COMPOSER_CONTEXT_PAGE_URL_MAX_CHARS = 2_048;
49export const COMPOSER_CONTEXT_PAGE_TITLE_MAX_CHARS = 2_048;
50
51export const ComposerContextId = TrimmedNonEmptyString.check(
52 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
53 Schema.isPattern(CONTEXT_ID_PATTERN),
54).pipe(Schema.brand("ComposerContextId"));
55export type ComposerContextId = typeof ComposerContextId.Type;
56
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
63export const ComposerContextKind = TrimmedNonEmptyString.check(
64 Schema.isPattern(CONTEXT_KIND_PATTERN),
65);
66export type ComposerContextKind = typeof ComposerContextKind.Type;
67
68// Duplicates the private ChatAttachmentId rules to avoid an orchestration.ts import cycle.
69const ContextAttachmentId = TrimmedNonEmptyString.check(
70 Schema.isMaxLength(CONTEXT_ID_MAX_CHARS),
71 Schema.isPattern(CONTEXT_ID_PATTERN),
72);
73const ContextLabel = Schema.String.check(Schema.isMaxLength(COMPOSER_CONTEXT_LABEL_MAX_CHARS));
74const BoundedString = (max: number) => Schema.String.check(Schema.isMaxLength(max));
75const ShortString = BoundedString(2_048);
76const NullableShortString = Schema.NullOr(ShortString);
77const PageUrl = BoundedString(COMPOSER_CONTEXT_PAGE_URL_MAX_CHARS);
78const PageTitle = Schema.NullOr(BoundedString(COMPOSER_CONTEXT_PAGE_TITLE_MAX_CHARS));
79
80export const PullRequestContextMetadata = Schema.Struct({
81 number: PositiveInt,
82 title: ShortString,
83 url: ShortString,
84 headBranch: ShortString,
85 baseBranch: ShortString,
86 state: Schema.Literals(["open", "closed", "merged"]),
87 isDraft: Schema.Boolean,
88});
89export type PullRequestContextMetadata = typeof PullRequestContextMetadata.Type;
90
91const recordBase = {
92 version: Schema.Literal(1),
93 contextId: ComposerContextId,
94 label: ContextLabel,
95} as const;
96
97const attachmentBinding = {
98 attachmentId: ContextAttachmentId,
99 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
100 mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
101 sizeBytes: NonNegativeInt,
102} as const;
103
104export const ImageContextRecord = Schema.Struct({
105 ...recordBase,
106 kind: Schema.Literal("image"),
107 ...attachmentBinding,
108 source: Schema.optional(SnapShotSource),
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
138export const ElementContextDetails = Schema.Struct({
139 pageUrl: PageUrl,
140 pageTitle: PageTitle,
141 tagName: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
142 selector: NullableShortString,
143 htmlPreview: BoundedString(COMPOSER_CONTEXT_ELEMENT_HTML_MAX_CHARS),
144 componentName: NullableShortString,
145 source: Schema.NullOr(ElementContextSource),
146 styles: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
147});
148export type ElementContextDetails = typeof ElementContextDetails.Type;
149
150export const ElementContextRecord = Schema.Struct({
151 ...recordBase,
152 kind: Schema.Literal("element"),
153 ...ElementContextDetails.fields,
154});
155export type ElementContextRecord = typeof ElementContextRecord.Type;
156
157// `optionalKey` rejects explicit undefined within one record, so only that record is dropped.
158export const PreviewAnnotationContextRecord = Schema.Struct({
159 ...recordBase,
160 kind: Schema.Literal("preview-annotation"),
161 annotationId: ShortString,
162 pageUrl: PageUrl,
163 pageTitle: PageTitle,
164 comment: BoundedString(COMPOSER_CONTEXT_PREVIEW_COMMENT_MAX_CHARS),
165 targetSummary: ShortString,
166 styleChanges: Schema.Array(ShortString).check(Schema.isMaxLength(200)),
167 elements: Schema.optionalKey(Schema.Array(ElementContextDetails).check(Schema.isMaxLength(50))),
168 elementIds: Schema.optionalKey(Schema.Array(ShortString).check(Schema.isMaxLength(50))),
169 regionCount: Schema.optionalKey(NonNegativeInt),
170 strokeCount: Schema.optionalKey(NonNegativeInt),
171 styleChangeDetails: Schema.optionalKey(
172 Schema.Array(
173 Schema.Struct({
174 targetId: ShortString,
175 selector: NullableShortString,
176 property: ShortString,
177 previousValue: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
178 value: BoundedString(COMPOSER_CONTEXT_ELEMENT_STYLES_MAX_CHARS),
179 }),
180 ).check(Schema.isMaxLength(200)),
181 ),
182 screenshotContextId: Schema.optionalKey(ComposerContextId),
183});
184export type PreviewAnnotationContextRecord = typeof PreviewAnnotationContextRecord.Type;
185
186export const ReviewCommentContextRecord = Schema.Struct({
187 ...recordBase,
188 kind: Schema.Literal("review-comment"),
189 sectionId: Schema.NonEmptyString.check(Schema.isMaxLength(255)),
190 sectionTitle: ShortString,
191 filePath: Schema.NonEmptyString.check(Schema.isMaxLength(2_048)),
192 startIndex: NonNegativeInt,
193 endIndex: NonNegativeInt,
194 rangeLabel: ShortString,
195 text: BoundedString(COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS),
196 diff: BoundedString(COMPOSER_CONTEXT_REVIEW_DIFF_MAX_CHARS),
197 fenceLanguage: Schema.optionalKey(BoundedString(64)),
198 pullRequest: Schema.optionalKey(PullRequestContextMetadata),
199}).check(Schema.makeFilter((record) => record.endIndex >= record.startIndex));
200export type ReviewCommentContextRecord = typeof ReviewCommentContextRecord.Type;
201
202export const MentionContextRecord = Schema.Struct({
203 ...recordBase,
204 kind: Schema.Literal("mention"),
205 path: Schema.NonEmptyString.check(Schema.isMaxLength(2_048)),
206});
207export type MentionContextRecord = typeof MentionContextRecord.Type;
208
209export const SkillContextRecord = Schema.Struct({
210 ...recordBase,
211 kind: Schema.Literal("skill"),
212 name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
213});
214export type SkillContextRecord = typeof SkillContextRecord.Type;
215
216export const ThreadContextRecord = Schema.Struct({
217 ...recordBase,
218 kind: Schema.Literal("thread"),
219 environmentId: EnvironmentId,
220 threadId: ThreadId,
221 title: ContextLabel,
222});
223export type ThreadContextRecord = typeof ThreadContextRecord.Type;
224
225/**
226 * One of the user's machines (a T3 Code environment), mentioned so the agent
227 * links it or works there. Only identity travels: the agent links it by id,
228 * and the user's client supplies its addresses.
229 */
230export const EnvironmentContextRecord = Schema.Struct({
231 ...recordBase,
232 kind: Schema.Literal("environment"),
233 environmentId: EnvironmentId,
234});
235export type EnvironmentContextRecord = typeof EnvironmentContextRecord.Type;
236
237/**
238 * An earlier assistant response the user is replying to. Only its identity and opening travel:
239 * the agent rereads the rest by item id, so a reply costs the same however long the response is.
240 */
241export const ResponseContextRecord = Schema.Struct({
242 ...recordBase,
243 kind: Schema.Literal("response"),
244 /** Where the response is and how it starts, as the reader saw it. */
245 citation: AssistantCitation,
246 itemId: TurnItemId,
247 /** The subagents whose results that response reported on. */
248 subagents: Schema.optional(
249 Schema.Array(
250 Schema.Struct({
251 threadId: ThreadId,
252 title: ContextLabel,
253 /** Set when the subagent's thread lives on a linked environment. */
254 environmentId: Schema.optional(EnvironmentId),
255 }),
256 ).check(Schema.isMaxLength(20)),
257 ),
258});
259export type ResponseContextRecord = typeof ResponseContextRecord.Type;
260
261const isJson = Schema.is(Schema.Json);
262
263/** Excludes known discriminators so malformed known records fail their own schema. */
264export const UnknownContextRecord = Schema.Struct({
265 ...recordBase,
266 kind: ComposerContextKind.check(Schema.isPattern(KNOWN_KIND_PATTERN)),
267 payload: Schema.Unknown.check(
268 Schema.makeFilter((payload) => {
269 let encoded: string | undefined;
270 try {
271 encoded = JSON.stringify(payload);
272 } catch {
273 return false;
274 }
275 return encoded !== undefined && encoded.length <= 64_000 && isJson(payload);
276 }),
277 ),
278});
279export type UnknownContextRecord = typeof UnknownContextRecord.Type;
280
281export const KnownComposerContextRecord = Schema.Union([
282 ImageContextRecord,
283 FileContextRecord,
284 TerminalContextRecord,
285 ElementContextRecord,
286 PreviewAnnotationContextRecord,
287 ReviewCommentContextRecord,
288 MentionContextRecord,
289 SkillContextRecord,
290 ThreadContextRecord,
291 EnvironmentContextRecord,
292 ResponseContextRecord,
293]);
294export type KnownComposerContextRecord = typeof KnownComposerContextRecord.Type;
295
296export const ComposerContextRecord = Schema.Union([
297 ...KnownComposerContextRecord.members,
298 UnknownContextRecord,
299]);
300export type ComposerContextRecord = typeof ComposerContextRecord.Type;
301
302export const COMPOSER_CONTEXT_MAX_RECORDS = 200;
303const COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS = 16_000_000;
304
305/**
306 * Marks a user message as a guest's, sent by the owner. The message `text` keeps the attributed
307 * form the agent reads; clients show `text` here with `name` beside it. Only the server sets it.
308 */
309export const GuestMessageAttribution = Schema.Struct({
310 guestMessageId: GuestMessageId,
311 name: TrimmedNonEmptyString.check(Schema.isMaxLength(GUEST_NAME_MAX_LENGTH)),
312 text: Schema.String.check(Schema.isMaxLength(GUEST_MESSAGE_MAX_LENGTH)),
313 /** The link the guest used. Only that link's guest may load the message's files. */
314 shareId: Schema.optional(GuestShareId),
315});
316export type GuestMessageAttribution = typeof GuestMessageAttribution.Type;
317
318/** Structured context riding on a user message. Undecodable records are dropped, not fatal. */
319export const OrchestrationMessageContext = Schema.Struct({
320 version: Schema.Literal(1),
321 guest: Schema.optional(GuestMessageAttribution),
322 records: Schema.Array(Schema.Unknown)
323 .check(
324 Schema.isMaxLength(COMPOSER_CONTEXT_MAX_RECORDS),
325 Schema.makeFilter((records) => {
326 try {
327 return JSON.stringify(records).length <= COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS;
328 } catch {
329 return false;
330 }
331 }),
332 )
333 .pipe(Schema.decodeTo(ForwardCompatibleArray(ComposerContextRecord)))
334 .check(
335 Schema.makeFilter(
336 (records) => new Set(records.map((record) => record.contextId)).size === records.length,
337 ),
338 ),
339});
340export type OrchestrationMessageContext = typeof OrchestrationMessageContext.Type;