Open History to see the last commit
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
7export const TrimmedString = Schema.String.pipe(
8 Schema.decodeTo(
9 Schema.String,
10 SchemaTransformation.transformEffect({
11 decode: (value) => Effect.succeed(value.trim()),
12 encode: (value) => Effect.succeed(value.trim()),
13 }),
14 ),
15);
16/**
17 * A `TrimmedString` only trims when decoding or encoding, so `make` and encode see the untrimmed
18 * value: a plain `isNonEmpty` would accept `" "` there and encode it to `""`, which no longer
19 * decodes.
20 */
21const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, {
22 expected: "a non-blank string",
23 toJsonSchema: () => [{ minLength: 1 }, true],
24 arbitraryConstraint: { minLength: 1 },
25});
26export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank);
27
28export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
29export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
30export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
31
32export const DpopFailureReason = Schema.Literals([
33 "time_window",
34 "key_mismatch",
35 "request_mismatch",
36 "token_mismatch",
37 "replay",
38 "invalid_proof",
39]);
40export type DpopFailureReason = typeof DpopFailureReason.Type;
41
42export const IsoDateTime = Schema.String;
43export type IsoDateTime = typeof IsoDateTime.Type;
44
45export const ForwardCompatibleOptional = <Value extends Schema.Top>(value: Value) => {
46 const decodeValue = Schema.decodeUnknownOption(value as never);
47 return Schema.optionalKey(
48 Schema.Unknown.pipe(
49 Schema.decodeTo(
50 Schema.UndefinedOr(value),
51 SchemaTransformation.transform<Value["Encoded"] | undefined, unknown>({
52 decode: (raw) =>
53 Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : undefined,
54 encode: (raw) => raw,
55 }),
56 ),
57 ),
58 );
59};
60
61export const ForwardCompatibleNullable = <Value extends Schema.Top>(value: Value) => {
62 const decodeValue = Schema.decodeUnknownOption(value as never);
63 return Schema.Unknown.pipe(
64 Schema.decodeTo(
65 Schema.NullOr(value),
66 SchemaTransformation.transform<Value["Encoded"] | null, unknown>({
67 decode: (raw) => (Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : null),
68 encode: (raw) => raw,
69 }),
70 ),
71 );
72};
73
74/**
75 * A nullable setting whose null is "unset" and never crosses the wire: it
76 * decodes from a missing or unknown key and encodes back to a missing key.
77 * For a field that older clients decode as a required literal, so a null
78 * on the wire would fail their whole settings snapshot.
79 */
80export const OmittedWhenNull = <Value extends Schema.Top>(value: Value) => {
81 const decodeValue = Schema.decodeUnknownOption(value as never);
82 return Schema.optionalKey(Schema.Unknown).pipe(
83 Schema.decodeTo(
84 Schema.NullOr(value),
85 SchemaTransformation.transformOptional<Value["Encoded"] | null, unknown>({
86 decode: (raw) =>
87 Option.some(
88 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
89 ? (raw.value as Value["Encoded"])
90 : null,
91 ),
92 encode: (raw) =>
93 Option.isSome(raw) && raw.value !== null ? Option.some(raw.value) : Option.none(),
94 }),
95 ),
96 );
97};
98
99/**
100 * For a tagged union, prefer {@link ForwardCompatibleUnion}: it drops only values whose tag this
101 * build does not know, so a known member with a broken payload still fails loudly.
102 */
103export const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) =>
104 Schema.Array(
105 Schema.UndefinedOr(element).pipe(
106 Schema.catchDecoding(() => Effect.succeedSome(undefined)),
107 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
108 ),
109 ).pipe(
110 Schema.decodeTo(
111 Schema.Array(
112 Schema.UndefinedOr(Schema.toType(element)).pipe(
113 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
114 ),
115 ).check(
116 // The holes above are an encoding detail: a decoded value has none, so
117 // `Schema.is` and `make` still reject an array that does. Aborts, so a
118 // later check on the array never sees a hole.
119 Schema.makeFilter(
120 (values) => {
121 // Every index, not `every`, which skips the holes of a sparse array.
122 for (let index = 0; index < values.length; index++) {
123 if (values[index] === undefined) return false;
124 }
125 return true;
126 },
127 { expected: "an array without holes" },
128 true,
129 ),
130 ),
131 SchemaTransformation.transform<
132 ReadonlyArray<Element["Type"]>,
133 ReadonlyArray<Element["Type"] | undefined>
134 >({
135 decode: (values) => values.filter((value) => value !== undefined),
136 encode: (values) => values.filter((value) => value !== undefined),
137 }),
138 ),
139 ) as unknown as ForwardCompatibleArray<Element>;
140export type ForwardCompatibleArray<Element extends Schema.Top> = Schema.Codec<
141 ReadonlyArray<Element["Type"]>,
142 ReadonlyArray<Element["Encoded"]>,
143 Element["DecodingServices"],
144 Element["EncodingServices"]
145>;
146
147/**
148 * A class, so only the codec can make one: no decoded payload, however it is shaped, is ever
149 * mistaken for it.
150 */
151export class UnknownUnionMember<Tag extends string = string> {
152 readonly tag: Tag;
153 readonly value: string;
154 constructor(tag: Tag, value: string) {
155 this.tag = tag;
156 this.value = value;
157 }
158}
159
160/**
161 * Unknown members are decode-only; encoding one fails.
162 */
163export const ForwardCompatibleUnion = <
164 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
165 const Tag extends string,
166>(
167 members: Members,
168 tag: Tag,
169) => {
170 const known = knownTags(members, tag);
171 const unknownMember = Schema.Struct({
172 [tag]: Schema.String.check(
173 Schema.makeFilter(
174 (value: string) => !known.has(value) || `A known ${tag} must decode in full.`,
175 ),
176 ),
177 } as Record<Tag, Schema.String>).pipe(
178 Schema.decodeTo(Schema.instanceOf(UnknownUnionMember<Tag>), {
179 decode: SchemaGetter.transform(
180 (raw: Record<string, string>) => new UnknownUnionMember(tag, raw[tag]!),
181 ),
182 encode: SchemaGetter.forbidden(() => `Unknown ${tag} values are never sent.`),
183 }),
184 );
185 return Schema.Union([...members, unknownMember]) as unknown as ForwardCompatibleUnion<
186 Members,
187 Tag
188 >;
189};
190export type ForwardCompatibleUnion<
191 Members extends ReadonlyArray<Schema.Top>,
192 Tag extends string,
193> = Schema.Codec<
194 Members[number]["Type"] | UnknownUnionMember<Tag>,
195 Members[number]["Encoded"],
196 Members[number]["DecodingServices"],
197 Members[number]["EncodingServices"]
198>;
199
200export const hasUnknownUnionTag = (
201 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
202 tag: string,
203): ((value: unknown) => boolean) => {
204 const known = knownTags(members, tag);
205 return (value) =>
206 typeof value === "object" &&
207 value !== null &&
208 tag in value &&
209 !known.has((value as Record<string, unknown>)[tag] as string);
210};
211
212export const isUnknownUnionMember = <A>(
213 value: A,
214): value is Extract<A, UnknownUnionMember<string>> => value instanceof UnknownUnionMember;
215
216export const ForwardCompatibleUnionArray = <
217 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
218 const Tag extends string,
219>(
220 members: Members,
221 tag: Tag,
222) =>
223 Schema.Array(ForwardCompatibleUnion(members, tag)).pipe(
224 Schema.decodeTo(
225 Schema.Array(Schema.toType(Schema.Union(members))),
226 SchemaTransformation.transform<
227 ReadonlyArray<Members[number]["Type"]>,
228 ReadonlyArray<Members[number]["Type"] | UnknownUnionMember<Tag>>
229 >({
230 decode: (values) =>
231 values.filter((value) => !isUnknownUnionMember(value)) as ReadonlyArray<
232 Members[number]["Type"]
233 >,
234 encode: (values) => values,
235 }),
236 ),
237 );
238
239const knownTags = (
240 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
241 tag: string,
242): ReadonlySet<string> => {
243 const tags = new Set<string>();
244 for (const member of members) {
245 const field = (member.fields as Record<string, unknown>)[tag] as
246 | { readonly literal?: unknown; readonly literals?: ReadonlyArray<unknown> }
247 | undefined;
248 for (const literal of field?.literals ?? [field?.literal]) {
249 if (typeof literal !== "string") {
250 throw new Error(`Every ForwardCompatibleUnion member needs a string literal ${tag}.`);
251 }
252 tags.add(literal);
253 }
254 }
255 return tags;
256};
257
258const makeEntityId = <Brand extends string>(brand: Parameters<typeof Schema.brand<Brand>>[0]) => {
259 return TrimmedNonEmptyString.pipe(Schema.brand<Brand>(brand));
260};
261
262export const ThreadId = makeEntityId("ThreadId");
263export type ThreadId = typeof ThreadId.Type;
264export const ProjectId = makeEntityId("ProjectId");
265export type ProjectId = typeof ProjectId.Type;
266export const EnvironmentId = makeEntityId("EnvironmentId");
267export type EnvironmentId = typeof EnvironmentId.Type;
268export const CommandId = makeEntityId("CommandId");
269export type CommandId = typeof CommandId.Type;
270export const EventId = makeEntityId("EventId");
271export type EventId = typeof EventId.Type;
272export const MessageId = makeEntityId("MessageId");
273export type MessageId = typeof MessageId.Type;
274export const TurnId = makeEntityId("TurnId");
275export type TurnId = typeof TurnId.Type;
276export const RunId = makeEntityId("RunId");
277export type RunId = typeof RunId.Type;
278export const RunAttemptId = makeEntityId("RunAttemptId");
279export type RunAttemptId = typeof RunAttemptId.Type;
280export const NodeId = makeEntityId("NodeId");
281export type NodeId = typeof NodeId.Type;
282export const AuthSessionId = makeEntityId("AuthSessionId");
283export type AuthSessionId = typeof AuthSessionId.Type;
284export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
285export type RpcClientId = typeof RpcClientId.Type;
286
287export const ClientSurface = Schema.Literals(["web", "desktop", "mobile", "cli"]);
288export type ClientSurface = typeof ClientSurface.Type;
289
290export const ClientOs = Schema.Literals([
291 "macOS",
292 "Windows",
293 "Linux",
294 "iOS",
295 "Android",
296 "ChromeOS",
297 "other",
298 "unknown",
299]);
300export type ClientOs = typeof ClientOs.Type;
301
302export const ClientDeviceType = Schema.Literals(["desktop", "phone", "tablet", "unknown"]);
303export type ClientDeviceType = typeof ClientDeviceType.Type;
304
305export const ClientWebDeployment = Schema.Literals(["hosted", "server"]);
306export type ClientWebDeployment = typeof ClientWebDeployment.Type;
307
308export const ClientConnectionMethod = Schema.Literals(["direct", "ssh", "relay", "unknown"]);
309export type ClientConnectionMethod = typeof ClientConnectionMethod.Type;
310
311export const ProviderItemId = makeEntityId("ProviderItemId");
312export type ProviderItemId = typeof ProviderItemId.Type;
313export const ProviderSessionId = makeEntityId("ProviderSessionId");
314export type ProviderSessionId = typeof ProviderSessionId.Type;
315export const ProviderThreadId = makeEntityId("ProviderThreadId");
316export type ProviderThreadId = typeof ProviderThreadId.Type;
317export const ProviderTurnId = makeEntityId("ProviderTurnId");
318export type ProviderTurnId = typeof ProviderTurnId.Type;
319export const RuntimeSessionId = makeEntityId("RuntimeSessionId");
320export type RuntimeSessionId = typeof RuntimeSessionId.Type;
321export const RuntimeItemId = makeEntityId("RuntimeItemId");
322export type RuntimeItemId = typeof RuntimeItemId.Type;
323export const TurnItemId = makeEntityId("TurnItemId");
324export type TurnItemId = typeof TurnItemId.Type;
325export const RuntimeRequestId = makeEntityId("RuntimeRequestId");
326export type RuntimeRequestId = typeof RuntimeRequestId.Type;
327export const RuntimeTaskId = makeEntityId("RuntimeTaskId");
328export type RuntimeTaskId = typeof RuntimeTaskId.Type;
329export const ScheduledTaskId = makeEntityId("ScheduledTaskId");
330/** A one-use handle to a secret the user entered for an agent; the agent never sees the value. */
331export const SecretRef = makeEntityId("SecretRef");
332export type SecretRef = typeof SecretRef.Type;
333export type ScheduledTaskId = typeof ScheduledTaskId.Type;
334export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
335export type ApprovalRequestId = typeof ApprovalRequestId.Type;
336export const CheckpointRef = makeEntityId("CheckpointRef");
337export type CheckpointRef = typeof CheckpointRef.Type;
338export const CheckpointId = makeEntityId("CheckpointId");
339export type CheckpointId = typeof CheckpointId.Type;
340export const CheckpointScopeId = makeEntityId("CheckpointScopeId");
341export type CheckpointScopeId = typeof CheckpointScopeId.Type;
342export const ContextHandoffId = makeEntityId("ContextHandoffId");
343export type ContextHandoffId = typeof ContextHandoffId.Type;
344export const ContextTransferId = makeEntityId("ContextTransferId");
345export type ContextTransferId = typeof ContextTransferId.Type;
346export const RawEventId = makeEntityId("RawEventId");
347export type RawEventId = typeof RawEventId.Type;
348export const PlanId = makeEntityId("PlanId");
349export type PlanId = typeof PlanId.Type;