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

baseSchemas.ts

402 lines15.4 KB

1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import * as SchemaGetter from "effect/SchemaGetter";
5import * as SchemaTransformation from "effect/SchemaTransformation";
6​
7// Hermes copies the string on every `trim()`, even when nothing changes.
8// Returning the original keeps repeated IDs shared after decode.
9const trim = (value: string) => {
10 const trimmed = value.trim();
11 return trimmed.length === value.length ? value : trimmed;
12};
13​
14export const TrimmedString = Schema.String.pipe(
15 Schema.decodeTo(
16 Schema.String,
17 SchemaTransformation.transformEffect({
18 decode: (value) => Effect.succeed(trim(value)),
19 encode: (value) => Effect.succeed(trim(value)),
20 }),
21 ),
22);
23// `make` and encode see untrimmed values; `isNonEmpty` would accept whitespace that encodes to an invalid empty string.
24const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, {
25 expected: "a non-blank string",
26 toJsonSchema: () => [{ minLength: 1 }, true],
27 arbitraryConstraint: { minLength: 1 },
28});
29export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank);
30// Keeps edge whitespace. Decoding from plain `String` leaves the check out of JSON Schema, so MCP
31// tool lists stay the size they were with `TrimmedNonEmptyString`.
32export const NonBlankString = Schema.String.pipe(
33 Schema.decodeTo(Schema.toType(TrimmedNonEmptyString)),
34);
35​
36// The CLI tokenizer splits on ASCII whitespace only, so pasted padding such as U+00A0 would
37// become a token. A trailing backslash-escaped space stays part of the last argument.
38export function trimUnescapedCliArgEdges(launchArgs: string): string {
39 const start = launchArgs.trimStart();
40 const trimmed = start.trimEnd();
41 return trimmed.length < start.length && trimmed.endsWith("\\")
42 ? start.slice(0, trimmed.length + 1)
43 : trimmed;
45​
46/** A CLI argument string trimmed at its edges, keeping a trailing escaped space. */
47export const CliArgsString = Schema.String.pipe(
48 Schema.decodeTo(
49 Schema.String,
50 SchemaTransformation.transformEffect({
51 decode: (value) => Effect.succeed(trimUnescapedCliArgEdges(value)),
52 encode: (value) => Effect.succeed(trimUnescapedCliArgEdges(value)),
53 }),
54 ),
55);
56​
57// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such
58// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges.
59export function trimAsciiWhitespace(value: string): string {
60 let start = 0;
61 let end = value.length;
62 while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++;
63 while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--;
64 return end - start === value.length ? value : value.slice(start, end);
66​
67function isAsciiWhitespace(code: number): boolean {
68 return code === 0x20 || (code >= 0x09 && code <= 0x0d);
70​
71const isNonBlankGitRefName = Schema.makeFilter(
72 (value: string) => trimAsciiWhitespace(value).length > 0,
73 {
74 expected: "a non-blank string",
75 toJsonSchema: () => [{ minLength: 1 }, true],
76 arbitraryConstraint: { minLength: 1 },
77 },
78);
79/** A branch, ref or remote name. Unlike `TrimmedNonEmptyString`, it keeps Unicode whitespace. */
80export const GitRefName = Schema.String.pipe(
81 Schema.decodeTo(
82 Schema.String,
83 SchemaTransformation.transformEffect({
84 decode: (value) => Effect.succeed(trimAsciiWhitespace(value)),
85 encode: (value) => Effect.succeed(trimAsciiWhitespace(value)),
86 }),
87 ),
88).check(isNonBlankGitRefName);
89​
90export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
91export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
92export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
93​
94export const DpopFailureReason = Schema.Literals([
95 "time_window",
96 "key_mismatch",
97 "request_mismatch",
98 "token_mismatch",
99 "replay",
100 "invalid_proof",
101]);
102export type DpopFailureReason = typeof DpopFailureReason.Type;
103​
104export const IsoDateTime = Schema.String;
105export type IsoDateTime = typeof IsoDateTime.Type;
106​
107export const ForwardCompatibleOptional = <Value extends Schema.Top>(value: Value) => {
108 const decodeValue = Schema.decodeUnknownOption(value as never);
109 // Unreadable values drop the key: an own undefined property is not JSON and fails RPC encoding.
110 return Schema.optionalKey(Schema.Unknown).pipe(
111 Schema.decodeTo(
112 Schema.optionalKey(Schema.UndefinedOr(value)),
113 SchemaTransformation.transformOptional<Value["Encoded"] | undefined, unknown>({
114 decode: (raw) =>
115 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
116 ? Option.some(raw.value as Value["Encoded"])
117 : Option.none(),
118 encode: (raw) => (Option.isSome(raw) && raw.value !== undefined ? raw : Option.none()),
119 }),
120 ),
121 );
122};
123​
124export const ForwardCompatibleNullable = <Value extends Schema.Top>(value: Value) => {
125 const decodeValue = Schema.decodeUnknownOption(value as never);
126 return Schema.Unknown.pipe(
127 Schema.decodeTo(
128 Schema.NullOr(value),
129 SchemaTransformation.transform<Value["Encoded"] | null, unknown>({
130 decode: (raw) => (Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : null),
131 encode: (raw) => raw,
132 }),
133 ),
134 );
135};
136​
137/** Missing or unknown values decode to null; null encodes as absent for older clients requiring a literal. */
138export const OmittedWhenNull = <Value extends Schema.Top>(value: Value) => {
139 const decodeValue = Schema.decodeUnknownOption(value as never);
140 return Schema.optionalKey(Schema.Unknown).pipe(
141 Schema.decodeTo(
142 Schema.NullOr(value),
143 SchemaTransformation.transformOptional<Value["Encoded"] | null, unknown>({
144 decode: (raw) =>
145 Option.some(
146 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
147 ? (raw.value as Value["Encoded"])
148 : null,
149 ),
150 encode: (raw) =>
151 Option.isSome(raw) && raw.value !== null ? Option.some(raw.value) : Option.none(),
152 }),
153 ),
154 );
155};
156​
157const UnknownArrayElement = Schema.Unknown.pipe(
158 Schema.decodeTo(Schema.Undefined, {
159 decode: SchemaGetter.succeed(undefined),
160 encode: SchemaGetter.passthrough(),
161 }),
162);
163​
164/** Prefer {@link ForwardCompatibleUnion} for tagged unions so malformed known members still fail. */
165export const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) =>
166 // Exit derives its wire codec from the encoded shape, which keeps the union but drops recovery middleware.
167 Schema.Array(
168 Schema.Union([element, UnknownArrayElement]).pipe(
169 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
170 ),
171 ).pipe(
172 Schema.decodeTo(
173 Schema.Array(
174 Schema.UndefinedOr(Schema.toType(element)).pipe(
175 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
176 ),
177 ).check(
178 // Schema.is/make must reject holes; abort before later array checks.
179 Schema.makeFilter(
180 (values) => {
181 // Every index, not `every`, which skips the holes of a sparse array.
182 for (let index = 0; index < values.length; index++) {
183 if (values[index] === undefined) return false;
184 }
185 return true;
186 },
187 { expected: "an array without holes" },
188 true,
189 ),
190 ),
191 SchemaTransformation.transform<
192 ReadonlyArray<Element["Type"]>,
193 ReadonlyArray<Element["Type"] | undefined>
194 >({
195 decode: (values) => values.filter((value) => value !== undefined),
196 encode: (values) => values.filter((value) => value !== undefined),
197 }),
198 ),
199 ) as unknown as ForwardCompatibleArray<Element>;
200export type ForwardCompatibleArray<Element extends Schema.Top> = Schema.Codec<
201 ReadonlyArray<Element["Type"]>,
202 ReadonlyArray<Element["Encoded"]>,
203 Element["DecodingServices"],
204 Element["EncodingServices"]
205>;
206​
207/** Class identity prevents decoded payloads from impersonating unknown members. */
208export class UnknownUnionMember<Tag extends string = string> {
209 readonly tag: Tag;
210 readonly value: string;
211 constructor(tag: Tag, value: string) {
212 this.tag = tag;
213 this.value = value;
214 }
216​
217/** Unknown members are decode-only; encoding one fails. */
218export const ForwardCompatibleUnion = <
219 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
220 const Tag extends string,
221>(
222 members: Members,
223 tag: Tag,
224) => {
225 const known = knownTags(members, tag);
226 const unknownMember = Schema.Struct({
227 [tag]: Schema.String.check(
228 Schema.makeFilter(
229 (value: string) => !known.has(value) || `A known ${tag} must decode in full.`,
230 ),
231 ),
232 } as Record<Tag, Schema.String>).pipe(
233 Schema.decodeTo(Schema.instanceOf(UnknownUnionMember<Tag>), {
234 decode: SchemaGetter.transform(
235 (raw: Record<string, string>) => new UnknownUnionMember(tag, raw[tag]!),
236 ),
237 encode: SchemaGetter.forbidden(() => `Unknown ${tag} values are never sent.`),
238 }),
239 );
240 return Schema.Union([...members, unknownMember]) as unknown as ForwardCompatibleUnion<
241 Members,
242 Tag
243 >;
244};
245export type ForwardCompatibleUnion<
246 Members extends ReadonlyArray<Schema.Top>,
247 Tag extends string,
248> = Schema.Codec<
249 Members[number]["Type"] | UnknownUnionMember<Tag>,
250 Members[number]["Encoded"],
251 Members[number]["DecodingServices"],
252 Members[number]["EncodingServices"]
253>;
254​
255export const hasUnknownUnionTag = (
256 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
257 tag: string,
258): ((value: unknown) => boolean) => {
259 const known = knownTags(members, tag);
260 return (value) =>
261 typeof value === "object" &&
262 value !== null &&
263 tag in value &&
264 !known.has((value as Record<string, unknown>)[tag] as string);
265};
266​
267export const isUnknownUnionMember = <A>(
268 value: A,
269): value is Extract<A, UnknownUnionMember<string>> => value instanceof UnknownUnionMember;
270​
271export const ForwardCompatibleUnionArray = <
272 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
273 const Tag extends string,
274>(
275 members: Members,
276 tag: Tag,
277) =>
278 Schema.Array(ForwardCompatibleUnion(members, tag)).pipe(
279 Schema.decodeTo(
280 Schema.Array(Schema.toType(Schema.Union(members))),
281 SchemaTransformation.transform<
282 ReadonlyArray<Members[number]["Type"]>,
283 ReadonlyArray<Members[number]["Type"] | UnknownUnionMember<Tag>>
284 >({
285 decode: (values) =>
286 values.filter((value) => !isUnknownUnionMember(value)) as ReadonlyArray<
287 Members[number]["Type"]
288 >,
289 encode: (values) => values,
290 }),
291 ),
292 );
293​
294const knownTags = (
295 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
296 tag: string,
297): ReadonlySet<string> => {
298 const tags = new Set<string>();
299 for (const member of members) {
300 const field = (member.fields as Record<string, unknown>)[tag] as
301 | { readonly literal?: unknown; readonly literals?: ReadonlyArray<unknown> }
302 | undefined;
303 for (const literal of field?.literals ?? [field?.literal]) {
304 if (typeof literal !== "string") {
305 throw new Error(`Every ForwardCompatibleUnion member needs a string literal ${tag}.`);
306 }
307 tags.add(literal);
308 }
309 }
310 return tags;
311};
312​
313const makeEntityId = <Brand extends string>(brand: Parameters<typeof Schema.brand<Brand>>[0]) => {
314 return TrimmedNonEmptyString.pipe(Schema.brand<Brand>(brand));
315};
316​
317export const ThreadId = makeEntityId("ThreadId");
318export type ThreadId = typeof ThreadId.Type;
319export const ProjectId = makeEntityId("ProjectId");
320export type ProjectId = typeof ProjectId.Type;
321export const EnvironmentId = makeEntityId("EnvironmentId");
322export type EnvironmentId = typeof EnvironmentId.Type;
323export const CommandId = makeEntityId("CommandId");
324export type CommandId = typeof CommandId.Type;
325export const EventId = makeEntityId("EventId");
326export type EventId = typeof EventId.Type;
327export const MessageId = makeEntityId("MessageId");
328export type MessageId = typeof MessageId.Type;
329export const TurnId = makeEntityId("TurnId");
330export type TurnId = typeof TurnId.Type;
331export const RunId = makeEntityId("RunId");
332export type RunId = typeof RunId.Type;
333export const RunAttemptId = makeEntityId("RunAttemptId");
334export type RunAttemptId = typeof RunAttemptId.Type;
335export const NodeId = makeEntityId("NodeId");
336export type NodeId = typeof NodeId.Type;
337export const GuestShareId = makeEntityId("GuestShareId");
338export type GuestShareId = typeof GuestShareId.Type;
339export const GuestMessageId = makeEntityId("GuestMessageId");
340export type GuestMessageId = typeof GuestMessageId.Type;
341export const AuthSessionId = makeEntityId("AuthSessionId");
342export type AuthSessionId = typeof AuthSessionId.Type;
343export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
344export type RpcClientId = typeof RpcClientId.Type;
345​
346export const ClientSurface = Schema.Literals(["web", "desktop", "mobile", "cli"]);
347export type ClientSurface = typeof ClientSurface.Type;
348​
349export const ClientOs = Schema.Literals([
350 "macOS",
351 "Windows",
352 "Linux",
353 "iOS",
354 "Android",
355 "ChromeOS",
356 "other",
357 "unknown",
358]);
359export type ClientOs = typeof ClientOs.Type;
360​
361export const ClientDeviceType = Schema.Literals(["desktop", "phone", "tablet", "unknown"]);
362export type ClientDeviceType = typeof ClientDeviceType.Type;
363​
364export const ClientWebDeployment = Schema.Literals(["hosted", "server"]);
365export type ClientWebDeployment = typeof ClientWebDeployment.Type;
366​
367export const ClientConnectionMethod = Schema.Literals(["direct", "ssh", "relay", "unknown"]);
368export type ClientConnectionMethod = typeof ClientConnectionMethod.Type;
369​
370export const ProviderItemId = makeEntityId("ProviderItemId");
371export type ProviderItemId = typeof ProviderItemId.Type;
372export const ProviderSessionId = makeEntityId("ProviderSessionId");
373export type ProviderSessionId = typeof ProviderSessionId.Type;
374export const ProviderThreadId = makeEntityId("ProviderThreadId");
375export type ProviderThreadId = typeof ProviderThreadId.Type;
376export const ProviderTurnId = makeEntityId("ProviderTurnId");
377export type ProviderTurnId = typeof ProviderTurnId.Type;
378export const TurnItemId = makeEntityId("TurnItemId");
379export type TurnItemId = typeof TurnItemId.Type;
380export const RuntimeRequestId = makeEntityId("RuntimeRequestId");
381export type RuntimeRequestId = typeof RuntimeRequestId.Type;
382export const ScheduledTaskId = makeEntityId("ScheduledTaskId");
383/** A one-use handle to a secret the user entered for an agent; the agent never sees the value. */
384export const SecretRef = makeEntityId("SecretRef");
385export type SecretRef = typeof SecretRef.Type;
386export type ScheduledTaskId = typeof ScheduledTaskId.Type;
387export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
388export type ApprovalRequestId = typeof ApprovalRequestId.Type;
389export const CheckpointRef = makeEntityId("CheckpointRef");
390export type CheckpointRef = typeof CheckpointRef.Type;
391export const CheckpointId = makeEntityId("CheckpointId");
392export type CheckpointId = typeof CheckpointId.Type;
393export const CheckpointScopeId = makeEntityId("CheckpointScopeId");
394export type CheckpointScopeId = typeof CheckpointScopeId.Type;
395export const ContextHandoffId = makeEntityId("ContextHandoffId");
396export type ContextHandoffId = typeof ContextHandoffId.Type;
397export const ContextTransferId = makeEntityId("ContextTransferId");
398export type ContextTransferId = typeof ContextTransferId.Type;
399export const RawEventId = makeEntityId("RawEventId");
400export type RawEventId = typeof RawEventId.Type;
401export const PlanId = makeEntityId("PlanId");
402export type PlanId = typeof PlanId.Type;