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 * Non-empty once trimmed. A `TrimmedString` only trims when decoding or
18 * encoding, so `make` and encode see the untrimmed value: a plain
19 * `isNonEmpty` would accept `" "` there and encode it to `""`, which no
20 * longer decodes.
21 */
22const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, {
23 expected: "a non-blank string",
24 toJsonSchema: () => [{ minLength: 1 }, true],
25 arbitraryConstraint: { minLength: 1 },
26});
27export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank);
28
29export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
30export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
31export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
32
33/**
34 * Safe categories for a failed DPoP proof. These describe the class of failure
35 * without exposing proof contents or server-side authentication details.
36 */
37export const DpopFailureReason = Schema.Literals([
38 "time_window",
39 "key_mismatch",
40 "request_mismatch",
41 "token_mismatch",
42 "replay",
43 "invalid_proof",
44]);
45export type DpopFailureReason = typeof DpopFailureReason.Type;
46
47export const IsoDateTime = Schema.String;
48export type IsoDateTime = typeof IsoDateTime.Type;
49
50/**
51 * Same idea for one optional value whose literal set grows over time: a
52 * member this build does not know decodes as absent rather than failing the
53 * enclosing struct. Encoding is the plain encoding.
54 */
55export const ForwardCompatibleOptional = <Value extends Schema.Top>(value: Value) => {
56 const decodeValue = Schema.decodeUnknownOption(value as never);
57 return Schema.optionalKey(
58 Schema.Unknown.pipe(
59 Schema.decodeTo(
60 Schema.UndefinedOr(value),
61 SchemaTransformation.transform<Value["Encoded"] | undefined, unknown>({
62 decode: (raw) =>
63 Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : undefined,
64 encode: (raw) => raw,
65 }),
66 ),
67 ),
68 );
69};
70
71/**
72 * The nullable form, for a persisted setting whose literal set grows over
73 * time: a member this build does not know (or a missing key) decodes as null
74 * rather than failing the enclosing struct. Encoding is the plain encoding.
75 */
76export const ForwardCompatibleNullable = <Value extends Schema.Top>(value: Value) => {
77 const decodeValue = Schema.decodeUnknownOption(value as never);
78 return Schema.Unknown.pipe(
79 Schema.decodeTo(
80 Schema.NullOr(value),
81 SchemaTransformation.transform<Value["Encoded"] | null, unknown>({
82 decode: (raw) => (Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : null),
83 encode: (raw) => raw,
84 }),
85 ),
86 );
87};
88
89/**
90 * A nullable setting whose null is "unset" and never crosses the wire: it
91 * decodes from a missing or unknown key and encodes back to a missing key.
92 * For a field that older clients decode as a required literal, so a null
93 * on the wire would fail their whole settings snapshot.
94 */
95export const OmittedWhenNull = <Value extends Schema.Top>(value: Value) => {
96 const decodeValue = Schema.decodeUnknownOption(value as never);
97 return Schema.optionalKey(Schema.Unknown).pipe(
98 Schema.decodeTo(
99 Schema.NullOr(value),
100 SchemaTransformation.transformOptional<Value["Encoded"] | null, unknown>({
101 decode: (raw) =>
102 Option.some(
103 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
104 ? (raw.value as Value["Encoded"])
105 : null,
106 ),
107 encode: (raw) =>
108 Option.isSome(raw) && raw.value !== null ? Option.some(raw.value) : Option.none(),
109 }),
110 ),
111 );
112};
113
114/**
115 * Wire codec for a server→client value whose shape grows over time: a union
116 * a newer server may add members to, or an array of such values. Clients keep
117 * decoding payloads from servers newer than themselves instead of failing the
118 * connection over data they could not act on anyway.
119 *
120 * Decoding runs each value through its own schema, so transformations (dates,
121 * trimming, decoding defaults) apply as usual. Only values that schema
122 * rejects are dropped, on either side.
123 *
124 * For a tagged union, prefer {@link ForwardCompatibleUnion}: it drops only
125 * values whose tag this build does not know, so a known member with a broken
126 * payload still fails loudly.
127 */
128export const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) =>
129 Schema.Array(
130 Schema.UndefinedOr(element).pipe(
131 // An element this build cannot read becomes a hole, filtered out below.
132 Schema.catchDecoding(() => Effect.succeedSome(undefined)),
133 // Likewise an element that cannot be encoded is sent as a hole, so one
134 // bad element costs only itself rather than the whole payload.
135 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
136 ),
137 ).pipe(
138 Schema.decodeTo(
139 Schema.Array(
140 Schema.UndefinedOr(Schema.toType(element)).pipe(
141 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
142 ),
143 ),
144 SchemaTransformation.transform<
145 ReadonlyArray<Element["Type"]>,
146 ReadonlyArray<Element["Type"] | undefined>
147 >({
148 decode: (values) => values.filter((value) => value !== undefined),
149 encode: (values) => values,
150 }),
151 ),
152 ) as unknown as ForwardCompatibleArray<Element>;
153export type ForwardCompatibleArray<Element extends Schema.Top> = Schema.Codec<
154 ReadonlyArray<Element["Type"]>,
155 ReadonlyArray<Element["Encoded"]>,
156 Element["DecodingServices"],
157 Element["EncodingServices"]
158>;
159
160/**
161 * A member of a {@link ForwardCompatibleUnion} whose tag this build does not
162 * know. A class, so only the codec can make one: no decoded payload, however
163 * it is shaped, is ever mistaken for it.
164 */
165export class UnknownUnionMember<Tag extends string = string> {
166 readonly tag: Tag;
167 readonly value: string;
168 constructor(tag: Tag, value: string) {
169 this.tag = tag;
170 this.value = value;
171 }
172}
173
174/**
175 * Wire codec for a server→client tagged union a newer server may add members
176 * to. A value whose `tag` field holds a value this build does not know decodes
177 * to {@link UnknownUnionMember} instead of failing; a known member decodes
178 * through its own schema, so a broken known payload still fails. Callers
179 * decide what an unknown member means: skip it, or show a fallback.
180 *
181 * Unknown members are decode-only; encoding one fails.
182 */
183export const ForwardCompatibleUnion = <
184 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
185 const Tag extends string,
186>(
187 members: Members,
188 tag: Tag,
189) => {
190 const known = knownTags(members, tag);
191 const unknownMember = Schema.Struct({
192 [tag]: Schema.String.check(
193 Schema.makeFilter(
194 (value: string) => !known.has(value) || `A known ${tag} must decode in full.`,
195 ),
196 ),
197 } as Record<Tag, Schema.String>).pipe(
198 Schema.decodeTo(Schema.instanceOf(UnknownUnionMember<Tag>), {
199 decode: SchemaGetter.transform(
200 (raw: Record<string, string>) => new UnknownUnionMember(tag, raw[tag]!),
201 ),
202 encode: SchemaGetter.forbidden(() => `Unknown ${tag} values are never sent.`),
203 }),
204 );
205 return Schema.Union([...members, unknownMember]) as unknown as ForwardCompatibleUnion<
206 Members,
207 Tag
208 >;
209};
210export type ForwardCompatibleUnion<
211 Members extends ReadonlyArray<Schema.Top>,
212 Tag extends string,
213> = Schema.Codec<
214 Members[number]["Type"] | UnknownUnionMember<Tag>,
215 Members[number]["Encoded"],
216 Members[number]["DecodingServices"],
217 Members[number]["EncodingServices"]
218>;
219
220/**
221 * Whether a raw, undecoded value carries a `tag` this build does not know
222 * among `members`. For checks outside a {@link ForwardCompatibleUnion}, such
223 * as an envelope that must skip a payload of an unknown kind.
224 */
225export const hasUnknownUnionTag = (
226 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
227 tag: string,
228): ((value: unknown) => boolean) => {
229 const known = knownTags(members, tag);
230 return (value) =>
231 typeof value === "object" &&
232 value !== null &&
233 tag in value &&
234 !known.has((value as Record<string, unknown>)[tag] as string);
235};
236
237/** Whether a decoded {@link ForwardCompatibleUnion} value is a member this build does not know. */
238export const isUnknownUnionMember = <A>(
239 value: A,
240): value is Extract<A, UnknownUnionMember<string>> => value instanceof UnknownUnionMember;
241
242/**
243 * An array of a growing tagged union that drops members this build does not
244 * know. Known members decode through their own schema and still fail when
245 * broken. Encoding is the plain array encoding.
246 */
247export const ForwardCompatibleUnionArray = <
248 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
249 const Tag extends string,
250>(
251 members: Members,
252 tag: Tag,
253) =>
254 Schema.Array(ForwardCompatibleUnion(members, tag)).pipe(
255 Schema.decodeTo(
256 Schema.Array(Schema.toType(Schema.Union(members))),
257 SchemaTransformation.transform<
258 ReadonlyArray<Members[number]["Type"]>,
259 ReadonlyArray<Members[number]["Type"] | UnknownUnionMember<Tag>>
260 >({
261 decode: (values) =>
262 values.filter((value) => !isUnknownUnionMember(value)) as ReadonlyArray<
263 Members[number]["Type"]
264 >,
265 encode: (values) => values,
266 }),
267 ),
268 );
269
270const knownTags = (
271 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
272 tag: string,
273): ReadonlySet<string> => {
274 const tags = new Set<string>();
275 for (const member of members) {
276 const field = (member.fields as Record<string, unknown>)[tag] as
277 | { readonly literal?: unknown; readonly literals?: ReadonlyArray<unknown> }
278 | undefined;
279 for (const literal of field?.literals ?? [field?.literal]) {
280 if (typeof literal !== "string") {
281 throw new Error(`Every ForwardCompatibleUnion member needs a string literal ${tag}.`);
282 }
283 tags.add(literal);
284 }
285 }
286 return tags;
287};
288
289/**
290 * Construct a branded identifier. Enforces non-empty trimmed strings
291 */
292const makeEntityId = <Brand extends string>(brand: Parameters<typeof Schema.brand<Brand>>[0]) => {
293 return TrimmedNonEmptyString.pipe(Schema.brand<Brand>(brand));
294};
295
296export const ThreadId = makeEntityId("ThreadId");
297export type ThreadId = typeof ThreadId.Type;
298export const ProjectId = makeEntityId("ProjectId");
299export type ProjectId = typeof ProjectId.Type;
300export const EnvironmentId = makeEntityId("EnvironmentId");
301export type EnvironmentId = typeof EnvironmentId.Type;
302export const CommandId = makeEntityId("CommandId");
303export type CommandId = typeof CommandId.Type;
304export const EventId = makeEntityId("EventId");
305export type EventId = typeof EventId.Type;
306export const MessageId = makeEntityId("MessageId");
307export type MessageId = typeof MessageId.Type;
308export const TurnId = makeEntityId("TurnId");
309export type TurnId = typeof TurnId.Type;
310export const RunId = makeEntityId("RunId");
311export type RunId = typeof RunId.Type;
312export const RunAttemptId = makeEntityId("RunAttemptId");
313export type RunAttemptId = typeof RunAttemptId.Type;
314export const NodeId = makeEntityId("NodeId");
315export type NodeId = typeof NodeId.Type;
316export const AuthSessionId = makeEntityId("AuthSessionId");
317export type AuthSessionId = typeof AuthSessionId.Type;
318export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
319export type RpcClientId = typeof RpcClientId.Type;
320
321/**
322 * Which client surface a connection or command comes from. Unlike
323 * `AuthClientMetadataDeviceType` (a UA-style device class where web and
324 * desktop are both "desktop"), this names the actual product surface.
325 * Optional everywhere it appears: old clients never send it.
326 */
327export const ClientSurface = Schema.Literals(["web", "desktop", "mobile", "cli"]);
328export type ClientSurface = typeof ClientSurface.Type;
329
330export const ClientOs = Schema.Literals([
331 "macOS",
332 "Windows",
333 "Linux",
334 "iOS",
335 "Android",
336 "ChromeOS",
337 "other",
338 "unknown",
339]);
340export type ClientOs = typeof ClientOs.Type;
341
342export const ClientDeviceType = Schema.Literals(["desktop", "phone", "tablet", "unknown"]);
343export type ClientDeviceType = typeof ClientDeviceType.Type;
344
345export const ClientWebDeployment = Schema.Literals(["hosted", "server"]);
346export type ClientWebDeployment = typeof ClientWebDeployment.Type;
347
348export const ClientConnectionMethod = Schema.Literals(["direct", "ssh", "relay", "unknown"]);
349export type ClientConnectionMethod = typeof ClientConnectionMethod.Type;
350
351export const ProviderItemId = makeEntityId("ProviderItemId");
352export type ProviderItemId = typeof ProviderItemId.Type;
353export const ProviderSessionId = makeEntityId("ProviderSessionId");
354export type ProviderSessionId = typeof ProviderSessionId.Type;
355export const ProviderThreadId = makeEntityId("ProviderThreadId");
356export type ProviderThreadId = typeof ProviderThreadId.Type;
357export const ProviderTurnId = makeEntityId("ProviderTurnId");
358export type ProviderTurnId = typeof ProviderTurnId.Type;
359export const RuntimeSessionId = makeEntityId("RuntimeSessionId");
360export type RuntimeSessionId = typeof RuntimeSessionId.Type;
361export const RuntimeItemId = makeEntityId("RuntimeItemId");
362export type RuntimeItemId = typeof RuntimeItemId.Type;
363export const TurnItemId = makeEntityId("TurnItemId");
364export type TurnItemId = typeof TurnItemId.Type;
365export const RuntimeRequestId = makeEntityId("RuntimeRequestId");
366export type RuntimeRequestId = typeof RuntimeRequestId.Type;
367export const RuntimeTaskId = makeEntityId("RuntimeTaskId");
368export type RuntimeTaskId = typeof RuntimeTaskId.Type;
369export const ScheduledTaskId = makeEntityId("ScheduledTaskId");
370/** A one-use handle to a secret the user entered for an agent; the agent never sees the value. */
371export const SecretRef = makeEntityId("SecretRef");
372export type SecretRef = typeof SecretRef.Type;
373export type ScheduledTaskId = typeof ScheduledTaskId.Type;
374export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
375export type ApprovalRequestId = typeof ApprovalRequestId.Type;
376export const CheckpointRef = makeEntityId("CheckpointRef");
377export type CheckpointRef = typeof CheckpointRef.Type;
378export const CheckpointId = makeEntityId("CheckpointId");
379export type CheckpointId = typeof CheckpointId.Type;
380export const CheckpointScopeId = makeEntityId("CheckpointScopeId");
381export type CheckpointScopeId = typeof CheckpointScopeId.Type;
382export const ContextHandoffId = makeEntityId("ContextHandoffId");
383export type ContextHandoffId = typeof ContextHandoffId.Type;
384export const ContextTransferId = makeEntityId("ContextTransferId");
385export type ContextTransferId = typeof ContextTransferId.Type;
386export const RawEventId = makeEntityId("RawEventId");
387export type RawEventId = typeof RawEventId.Type;
388export const PlanId = makeEntityId("PlanId");
389export type PlanId = typeof PlanId.Type;