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
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// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such
37// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges.
38export function trimAsciiWhitespace(value: string): string {
39 let start = 0;
40 let end = value.length;
41 while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++;
42 while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--;
43 return end - start === value.length ? value : value.slice(start, end);
44}
45
46function isAsciiWhitespace(code: number): boolean {
47 return code === 0x20 || (code >= 0x09 && code <= 0x0d);
48}
49
50const isNonBlankGitRefName = Schema.makeFilter(
51 (value: string) => trimAsciiWhitespace(value).length > 0,
52 {
53 expected: "a non-blank string",
54 toJsonSchema: () => [{ minLength: 1 }, true],
55 arbitraryConstraint: { minLength: 1 },
56 },
57);
58/** A branch, ref or remote name. Unlike `TrimmedNonEmptyString`, it keeps Unicode whitespace. */
59export const GitRefName = Schema.String.pipe(
60 Schema.decodeTo(
61 Schema.String,
62 SchemaTransformation.transformEffect({
63 decode: (value) => Effect.succeed(trimAsciiWhitespace(value)),
64 encode: (value) => Effect.succeed(trimAsciiWhitespace(value)),
65 }),
66 ),
67).check(isNonBlankGitRefName);
68
69export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
70export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
71export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
72
73export const DpopFailureReason = Schema.Literals([
74 "time_window",
75 "key_mismatch",
76 "request_mismatch",
77 "token_mismatch",
78 "replay",
79 "invalid_proof",
80]);
81export type DpopFailureReason = typeof DpopFailureReason.Type;
82
83export const IsoDateTime = Schema.String;
84export type IsoDateTime = typeof IsoDateTime.Type;
85
86export const ForwardCompatibleOptional = <Value extends Schema.Top>(value: Value) => {
87 const decodeValue = Schema.decodeUnknownOption(value as never);
88 // Unreadable values drop the key: an own undefined property is not JSON and fails RPC encoding.
89 return Schema.optionalKey(Schema.Unknown).pipe(
90 Schema.decodeTo(
91 Schema.optionalKey(Schema.UndefinedOr(value)),
92 SchemaTransformation.transformOptional<Value["Encoded"] | undefined, unknown>({
93 decode: (raw) =>
94 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
95 ? Option.some(raw.value as Value["Encoded"])
96 : Option.none(),
97 encode: (raw) => (Option.isSome(raw) && raw.value !== undefined ? raw : Option.none()),
98 }),
99 ),
100 );
101};
102
103export const ForwardCompatibleNullable = <Value extends Schema.Top>(value: Value) => {
104 const decodeValue = Schema.decodeUnknownOption(value as never);
105 return Schema.Unknown.pipe(
106 Schema.decodeTo(
107 Schema.NullOr(value),
108 SchemaTransformation.transform<Value["Encoded"] | null, unknown>({
109 decode: (raw) => (Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : null),
110 encode: (raw) => raw,
111 }),
112 ),
113 );
114};
115
116/** Missing or unknown values decode to null; null encodes as absent for older clients requiring a literal. */
117export const OmittedWhenNull = <Value extends Schema.Top>(value: Value) => {
118 const decodeValue = Schema.decodeUnknownOption(value as never);
119 return Schema.optionalKey(Schema.Unknown).pipe(
120 Schema.decodeTo(
121 Schema.NullOr(value),
122 SchemaTransformation.transformOptional<Value["Encoded"] | null, unknown>({
123 decode: (raw) =>
124 Option.some(
125 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
126 ? (raw.value as Value["Encoded"])
127 : null,
128 ),
129 encode: (raw) =>
130 Option.isSome(raw) && raw.value !== null ? Option.some(raw.value) : Option.none(),
131 }),
132 ),
133 );
134};
135
136const UnknownArrayElement = Schema.Unknown.pipe(
137 Schema.decodeTo(Schema.Undefined, {
138 decode: SchemaGetter.succeed(undefined),
139 encode: SchemaGetter.passthrough(),
140 }),
141);
142
143/** Prefer {@link ForwardCompatibleUnion} for tagged unions so malformed known members still fail. */
144export const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) =>
145 // Exit derives its wire codec from the encoded shape, which keeps the union but drops recovery middleware.
146 Schema.Array(
147 Schema.Union([element, UnknownArrayElement]).pipe(
148 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
149 ),
150 ).pipe(
151 Schema.decodeTo(
152 Schema.Array(
153 Schema.UndefinedOr(Schema.toType(element)).pipe(
154 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
155 ),
156 ).check(
157 // Schema.is/make must reject holes; abort before later array checks.
158 Schema.makeFilter(
159 (values) => {
160 // Every index, not `every`, which skips the holes of a sparse array.
161 for (let index = 0; index < values.length; index++) {
162 if (values[index] === undefined) return false;
163 }
164 return true;
165 },
166 { expected: "an array without holes" },
167 true,
168 ),
169 ),
170 SchemaTransformation.transform<
171 ReadonlyArray<Element["Type"]>,
172 ReadonlyArray<Element["Type"] | undefined>
173 >({
174 decode: (values) => values.filter((value) => value !== undefined),
175 encode: (values) => values.filter((value) => value !== undefined),
176 }),
177 ),
178 ) as unknown as ForwardCompatibleArray<Element>;
179export type ForwardCompatibleArray<Element extends Schema.Top> = Schema.Codec<
180 ReadonlyArray<Element["Type"]>,
181 ReadonlyArray<Element["Encoded"]>,
182 Element["DecodingServices"],
183 Element["EncodingServices"]
184>;
185
186/** Class identity prevents decoded payloads from impersonating unknown members. */
187export class UnknownUnionMember<Tag extends string = string> {
188 readonly tag: Tag;
189 readonly value: string;
190 constructor(tag: Tag, value: string) {
191 this.tag = tag;
192 this.value = value;
193 }
194}
195
196/** Unknown members are decode-only; encoding one fails. */
197export const ForwardCompatibleUnion = <
198 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
199 const Tag extends string,
200>(
201 members: Members,
202 tag: Tag,
203) => {
204 const known = knownTags(members, tag);
205 const unknownMember = Schema.Struct({
206 [tag]: Schema.String.check(
207 Schema.makeFilter(
208 (value: string) => !known.has(value) || `A known ${tag} must decode in full.`,
209 ),
210 ),
211 } as Record<Tag, Schema.String>).pipe(
212 Schema.decodeTo(Schema.instanceOf(UnknownUnionMember<Tag>), {
213 decode: SchemaGetter.transform(
214 (raw: Record<string, string>) => new UnknownUnionMember(tag, raw[tag]!),
215 ),
216 encode: SchemaGetter.forbidden(() => `Unknown ${tag} values are never sent.`),
217 }),
218 );
219 return Schema.Union([...members, unknownMember]) as unknown as ForwardCompatibleUnion<
220 Members,
221 Tag
222 >;
223};
224export type ForwardCompatibleUnion<
225 Members extends ReadonlyArray<Schema.Top>,
226 Tag extends string,
227> = Schema.Codec<
228 Members[number]["Type"] | UnknownUnionMember<Tag>,
229 Members[number]["Encoded"],
230 Members[number]["DecodingServices"],
231 Members[number]["EncodingServices"]
232>;
233
234export const hasUnknownUnionTag = (
235 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
236 tag: string,
237): ((value: unknown) => boolean) => {
238 const known = knownTags(members, tag);
239 return (value) =>
240 typeof value === "object" &&
241 value !== null &&
242 tag in value &&
243 !known.has((value as Record<string, unknown>)[tag] as string);
244};
245
246export const isUnknownUnionMember = <A>(
247 value: A,
248): value is Extract<A, UnknownUnionMember<string>> => value instanceof UnknownUnionMember;
249
250export const ForwardCompatibleUnionArray = <
251 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
252 const Tag extends string,
253>(
254 members: Members,
255 tag: Tag,
256) =>
257 Schema.Array(ForwardCompatibleUnion(members, tag)).pipe(
258 Schema.decodeTo(
259 Schema.Array(Schema.toType(Schema.Union(members))),
260 SchemaTransformation.transform<
261 ReadonlyArray<Members[number]["Type"]>,
262 ReadonlyArray<Members[number]["Type"] | UnknownUnionMember<Tag>>
263 >({
264 decode: (values) =>
265 values.filter((value) => !isUnknownUnionMember(value)) as ReadonlyArray<
266 Members[number]["Type"]
267 >,
268 encode: (values) => values,
269 }),
270 ),
271 );
272
273const knownTags = (
274 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
275 tag: string,
276): ReadonlySet<string> => {
277 const tags = new Set<string>();
278 for (const member of members) {
279 const field = (member.fields as Record<string, unknown>)[tag] as
280 | { readonly literal?: unknown; readonly literals?: ReadonlyArray<unknown> }
281 | undefined;
282 for (const literal of field?.literals ?? [field?.literal]) {
283 if (typeof literal !== "string") {
284 throw new Error(`Every ForwardCompatibleUnion member needs a string literal ${tag}.`);
285 }
286 tags.add(literal);
287 }
288 }
289 return tags;
290};
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 GuestShareId = makeEntityId("GuestShareId");
317export type GuestShareId = typeof GuestShareId.Type;
318export const GuestMessageId = makeEntityId("GuestMessageId");
319export type GuestMessageId = typeof GuestMessageId.Type;
320export const AuthSessionId = makeEntityId("AuthSessionId");
321export type AuthSessionId = typeof AuthSessionId.Type;
322export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
323export type RpcClientId = typeof RpcClientId.Type;
324
325export const ClientSurface = Schema.Literals(["web", "desktop", "mobile", "cli"]);
326export type ClientSurface = typeof ClientSurface.Type;
327
328export const ClientOs = Schema.Literals([
329 "macOS",
330 "Windows",
331 "Linux",
332 "iOS",
333 "Android",
334 "ChromeOS",
335 "other",
336 "unknown",
337]);
338export type ClientOs = typeof ClientOs.Type;
339
340export const ClientDeviceType = Schema.Literals(["desktop", "phone", "tablet", "unknown"]);
341export type ClientDeviceType = typeof ClientDeviceType.Type;
342
343export const ClientWebDeployment = Schema.Literals(["hosted", "server"]);
344export type ClientWebDeployment = typeof ClientWebDeployment.Type;
345
346export const ClientConnectionMethod = Schema.Literals(["direct", "ssh", "relay", "unknown"]);
347export type ClientConnectionMethod = typeof ClientConnectionMethod.Type;
348
349export const ProviderItemId = makeEntityId("ProviderItemId");
350export type ProviderItemId = typeof ProviderItemId.Type;
351export const ProviderSessionId = makeEntityId("ProviderSessionId");
352export type ProviderSessionId = typeof ProviderSessionId.Type;
353export const ProviderThreadId = makeEntityId("ProviderThreadId");
354export type ProviderThreadId = typeof ProviderThreadId.Type;
355export const ProviderTurnId = makeEntityId("ProviderTurnId");
356export type ProviderTurnId = typeof ProviderTurnId.Type;
357export const TurnItemId = makeEntityId("TurnItemId");
358export type TurnItemId = typeof TurnItemId.Type;
359export const RuntimeRequestId = makeEntityId("RuntimeRequestId");
360export type RuntimeRequestId = typeof RuntimeRequestId.Type;
361export const ScheduledTaskId = makeEntityId("ScheduledTaskId");
362/** A one-use handle to a secret the user entered for an agent; the agent never sees the value. */
363export const SecretRef = makeEntityId("SecretRef");
364export type SecretRef = typeof SecretRef.Type;
365export type ScheduledTaskId = typeof ScheduledTaskId.Type;
366export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
367export type ApprovalRequestId = typeof ApprovalRequestId.Type;
368export const CheckpointRef = makeEntityId("CheckpointRef");
369export type CheckpointRef = typeof CheckpointRef.Type;
370export const CheckpointId = makeEntityId("CheckpointId");
371export type CheckpointId = typeof CheckpointId.Type;
372export const CheckpointScopeId = makeEntityId("CheckpointScopeId");
373export type CheckpointScopeId = typeof CheckpointScopeId.Type;
374export const ContextHandoffId = makeEntityId("ContextHandoffId");
375export type ContextHandoffId = typeof ContextHandoffId.Type;
376export const ContextTransferId = makeEntityId("ContextTransferId");
377export type ContextTransferId = typeof ContextTransferId.Type;
378export const RawEventId = makeEntityId("RawEventId");
379export type RawEventId = typeof RawEventId.Type;
380export const PlanId = makeEntityId("PlanId");
381export type PlanId = typeof PlanId.Type;