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

errors.ts

453 lines13.0 KB

1import * as Schema from "effect/Schema";
2import * as SchemaAST from "effect/SchemaAST";
3import type * as SchemaIssue from "effect/SchemaIssue";
4​
5import * as AcpSchema from "./_generated/schema.gen.ts";
6​
7const AcpRequestOperation = Schema.Literals([
8 "decode-extension-request-payload",
9 "encode-extension-response",
10 "handle-request",
11 "handle-extension-request",
12 "receive-response",
13 "receive-streaming-response",
14]);
15type AcpRequestOperation = typeof AcpRequestOperation.Type;
16​
17export const AcpRequestId = Schema.Union([Schema.String, Schema.Number]);
18export type AcpRequestId = typeof AcpRequestId.Type;
19​
20const AcpSchemaIssueKind = Schema.Literals([
21 "Filter",
22 "Encoding",
23 "Pointer",
24 "Composite",
25 "AnyOf",
26 "InvalidType",
27 "InvalidValue",
28 "MissingKey",
29 "UnexpectedKey",
30 "Forbidden",
31 "OneOf",
32]);
33type AcpSchemaIssueKind = typeof AcpSchemaIssueKind.Type;
34​
35interface AcpSchemaIssueDiagnostics {
36 readonly issueCount: number;
37 readonly issueKinds: ReadonlyArray<AcpSchemaIssueKind>;
38 readonly maximumPathDepth: number;
40​
41const MAX_SUMMARY_ISSUES = 3;
42const MAX_SUMMARY_PATH_SEGMENTS = 8;
43​
44// Record keys come from the payload, so a key that is not a plain identifier
45// is shown as `*` rather than copied.
46const summaryPathSegment = (segment: PropertyKey): string =>
47 typeof segment === "number" || /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(String(segment))
48 ? String(segment)
49 : "*";
50​
51const summaryPath = (path: ReadonlyArray<PropertyKey>): string => {
52 if (path.length === 0) return "payload";
53 const shown = path.slice(0, MAX_SUMMARY_PATH_SEGMENTS).map(summaryPathSegment).join(".");
54 return path.length > MAX_SUMMARY_PATH_SEGMENTS ? `${shown}…` : shown;
55};
56​
57const summaryReason = (issue: SchemaIssue.Issue): string => {
58 switch (issue._tag) {
59 case "MissingKey":
60 return "missing";
61 case "UnexpectedKey":
62 return "unexpected";
63 case "InvalidType":
64 return "wrong type";
65 default:
66 return "invalid";
67 }
68};
69​
70const isCatchAllMember = (issue: SchemaIssue.Issue) =>
71 "ast" in issue && SchemaAST.resolveTitle(issue.ast) === "other";
72​
73/**
74 * Names where a payload broke its schema, such as `update.used missing`,
75 * without copying any value from it. ACP unions end in a member titled
76 * "other" that admits custom and future variants; it fails only because the
77 * discriminator names a known variant, so the known variant's issues are the
78 * ones reported.
79 */
80const schemaIssueSummary = (root: SchemaIssue.Issue): string => {
81 const entries = new Set<string>();
82 const visit = (issue: SchemaIssue.Issue, path: ReadonlyArray<PropertyKey>): void => {
83 switch (issue._tag) {
84 case "Filter":
85 case "Encoding":
86 visit(issue.issue, path);
87 return;
88 case "Pointer":
89 visit(issue.issue, [...path, ...issue.path]);
90 return;
91 case "Composite":
92 case "AnyOf": {
93 const known = issue.issues.filter((child) => !isCatchAllMember(child));
94 const children = known.length > 0 ? known : issue.issues;
95 if (children.length === 0) entries.add(`${summaryPath(path)} ${summaryReason(issue)}`);
96 for (const child of children) visit(child, path);
97 return;
98 }
99 default:
100 entries.add(`${summaryPath(path)} ${summaryReason(issue)}`);
101 }
102 };
103 visit(root, []);
104 const shown = [...entries].slice(0, MAX_SUMMARY_ISSUES);
105 const hidden = entries.size - shown.length;
106 return hidden > 0 ? `${shown.join(", ")} (+${hidden} more)` : shown.join(", ");
107};
108​
109const schemaIssueDiagnostics = (root: SchemaIssue.Issue): AcpSchemaIssueDiagnostics => {
110 let issueCount = 0;
111 let maximumPathDepth = 0;
112 const issueKinds = new Set<AcpSchemaIssueKind>();
113​
114 const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {
115 issueCount += 1;
116 issueKinds.add(issue._tag);
117 maximumPathDepth = Math.max(maximumPathDepth, pathDepth);
118 switch (issue._tag) {
119 case "Filter":
120 case "Encoding":
121 visit(issue.issue, pathDepth);
122 break;
123 case "Pointer":
124 visit(issue.issue, pathDepth + issue.path.length);
125 break;
126 case "Composite":
127 case "AnyOf":
128 for (const child of issue.issues) visit(child, pathDepth);
129 break;
130 }
131 };
132​
133 visit(root, 0);
134 return {
135 issueCount,
136 issueKinds: [...issueKinds],
137 maximumPathDepth,
138 };
139};
140​
141export interface AcpRequestDiagnostics {
142 readonly method?: string;
143 readonly requestId?: AcpRequestId;
144 readonly operation?: AcpRequestOperation;
145 readonly cause?: unknown;
146 readonly issueCount?: number;
147 readonly issueKinds?: ReadonlyArray<AcpSchemaIssueKind>;
148 readonly maximumPathDepth?: number;
150​
151export class AcpSpawnError extends Schema.TaggedError<AcpSpawnError>()("AcpSpawnError", {
152 command: Schema.optional(Schema.String),
153 cause: Schema.Defect(),
154}) {
155 override get message() {
156 return this.command
157 ? `Failed to spawn ACP process for command: ${this.command}`
158 : "Failed to spawn ACP process";
159 }
161​
162export class AcpProcessExitedError extends Schema.TaggedError<AcpProcessExitedError>()(
163 "AcpProcessExitedError",
164 {
165 code: Schema.optional(Schema.Number),
166 pid: Schema.optionalKey(Schema.Int),
167 stderr: Schema.optionalKey(Schema.String),
168 cause: Schema.optional(Schema.Defect()),
169 },
170) {
171 override get message() {
172 const base =
173 this.code === undefined ? "ACP process exited" : `ACP process exited with code ${this.code}`;
174 const excerpt = this.stderr?.trim();
175 return excerpt && excerpt.length > 0 ? `${base}\n${excerpt}` : base;
176 }
178​
179export const AcpProtocolParseOperation = Schema.Literals([
180 "encode-message",
181 "decode-wire-message",
182 "decode-notification-payload",
183]);
184export type AcpProtocolParseOperation = typeof AcpProtocolParseOperation.Type;
185​
186export class AcpProtocolParseError extends Schema.TaggedError<AcpProtocolParseError>()(
187 "AcpProtocolParseError",
188 {
189 operation: AcpProtocolParseOperation,
190 method: Schema.optionalKey(Schema.String),
191 requestId: Schema.optionalKey(AcpRequestId),
192 issueCount: Schema.optionalKey(Schema.Number),
193 issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
194 maximumPathDepth: Schema.optionalKey(Schema.Number),
195 /** Where the payload broke its schema, e.g. `update.used missing`; never payload values. */
196 issueSummary: Schema.optionalKey(Schema.String),
197 cause: Schema.Defect(),
198 },
199) {
200 override get message() {
201 const method = this.method === undefined ? "" : ` for method '${this.method}'`;
202 const summary = this.issueSummary === undefined ? "" : `: ${this.issueSummary}`;
203 return `ACP protocol operation '${this.operation}' failed${method}${summary}.`;
204 }
205​
206 static fromSchemaError(
207 operation: AcpProtocolParseOperation,
208 method: string,
209 cause: Schema.SchemaError,
210 ) {
211 return new AcpProtocolParseError({
212 operation,
213 method,
214 ...schemaIssueDiagnostics(cause.issue),
215 issueSummary: schemaIssueSummary(cause.issue),
216 cause,
217 });
218 }
219​
220 static fromEncodingError(
221 method: string | undefined,
222 requestId: AcpRequestId | undefined,
223 cause: unknown,
224 ) {
225 return new AcpProtocolParseError({
226 operation: "encode-message",
227 ...(method === undefined ? {} : { method }),
228 ...(requestId === undefined ? {} : { requestId }),
229 cause,
230 });
231 }
233​
234export class AcpTransportError extends Schema.TaggedError<AcpTransportError>()(
235 "AcpTransportError",
236 {
237 operation: Schema.optional(
238 Schema.Literals(["call-rpc", "read-input-stream", "read-process-exit-status"]),
239 ),
240 method: Schema.optional(Schema.String),
241 detail: Schema.optional(Schema.String),
242 pid: Schema.optionalKey(Schema.Int),
243 cause: Schema.Defect(),
244 },
245) {
246 override get message() {
247 const method = this.method ? ` for method ${this.method}` : "";
248 return this.operation
249 ? `ACP transport operation ${this.operation} failed${method}.`
250 : "ACP transport operation failed.";
251 }
253​
254export class AcpInputStreamEndedError extends Schema.TaggedError<AcpInputStreamEndedError>()(
255 "AcpInputStreamEndedError",
256 {},
257) {
258 override get message() {
259 return "ACP input stream ended.";
260 }
262​
263export class AcpRequestError extends Schema.TaggedError<AcpRequestError>()("AcpRequestError", {
264 code: AcpSchema.ErrorCode,
265 errorMessage: Schema.String,
266 data: Schema.optional(Schema.Unknown),
267 method: Schema.optionalKey(Schema.String),
268 requestId: Schema.optionalKey(AcpRequestId),
269 operation: Schema.optionalKey(AcpRequestOperation),
270 issueCount: Schema.optionalKey(Schema.Number),
271 issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
272 maximumPathDepth: Schema.optionalKey(Schema.Number),
273 cause: Schema.optionalKey(Schema.Defect()),
274}) {
275 override get message() {
276 return this.errorMessage;
277 }
278​
279 static fromProtocolError(
280 error: AcpSchema.Error,
281 context: {
282 readonly method: string;
283 readonly requestId?: AcpRequestId;
284 readonly cause?: unknown;
285 },
286 ) {
287 return new AcpRequestError({
288 code: error.code,
289 errorMessage: error.message,
290 ...(error.data !== undefined ? { data: error.data } : {}),
291 method: context.method,
292 ...(context.requestId === undefined ? {} : { requestId: context.requestId }),
293 operation: "receive-response",
294 cause: context.cause ?? error,
295 });
296 }
297​
298 static fromExtensionResponseFailure(method: string, requestId: AcpRequestId, cause: unknown) {
299 return AcpRequestError.internalError("Extension request failed", undefined, {
300 method,
301 requestId,
302 operation: "receive-response",
303 cause,
304 });
305 }
306​
307 static fromExtensionResponseEncodingError(
308 method: string,
309 requestId: AcpRequestId,
310 cause: AcpProtocolParseError,
311 ) {
312 return AcpRequestError.internalError("Internal error", undefined, {
313 method,
314 requestId,
315 operation: "encode-extension-response",
316 cause,
317 });
318 }
319​
320 static unsupportedStreamingResponse(method: string, requestId: AcpRequestId) {
321 return AcpRequestError.internalError(
322 "Streaming extension responses are not supported",
323 undefined,
324 {
325 method,
326 requestId,
327 operation: "receive-streaming-response",
328 },
329 );
330 }
331​
332 static fromCoreHandlerError(error: AcpError, method: string) {
333 if (error._tag === "AcpRequestError") {
334 return error;
335 }
336 return AcpRequestError.internalError(
337 `ACP request handler failed for method '${method}'`,
338 undefined,
339 {
340 method,
341 operation: "handle-request",
342 cause: error,
343 },
344 );
345 }
346​
347 static fromExtensionHandlerError(error: AcpError, method: string) {
348 if (error._tag === "AcpRequestError") {
349 return error;
350 }
351 return AcpRequestError.internalError(
352 `ACP extension request handler failed for method '${method}'`,
353 undefined,
354 {
355 method,
356 operation: "handle-extension-request",
357 cause: error,
358 },
359 );
360 }
361​
362 static parseError(message = "Parse error", data?: unknown) {
363 return new AcpRequestError({
364 code: -32700,
365 errorMessage: message,
366 ...(data !== undefined ? { data } : {}),
367 });
368 }
369​
370 static invalidRequest(message = "Invalid request", data?: unknown) {
371 return new AcpRequestError({
372 code: -32600,
373 errorMessage: message,
374 ...(data !== undefined ? { data } : {}),
375 });
376 }
377​
378 static methodNotFound(method: string) {
379 return new AcpRequestError({
380 code: -32601,
381 errorMessage: `Method not found: ${method}`,
382 });
383 }
384​
385 static invalidParams(message = "Invalid params", data?: unknown) {
386 return new AcpRequestError({
387 code: -32602,
388 errorMessage: message,
389 ...(data !== undefined ? { data } : {}),
390 });
391 }
392​
393 static invalidExtensionPayload(method: string, cause: Schema.SchemaError) {
394 const diagnostics = schemaIssueDiagnostics(cause.issue);
395 return new AcpRequestError({
396 code: -32602,
397 errorMessage: `Invalid payload for ACP extension method '${method}'.`,
398 data: diagnostics,
399 method,
400 operation: "decode-extension-request-payload",
401 ...diagnostics,
402 cause,
403 });
404 }
405​
406 static internalError(
407 message = "Internal error",
408 data?: unknown,
409 diagnostics: AcpRequestDiagnostics = {},
410 ) {
411 return new AcpRequestError({
412 code: -32603,
413 errorMessage: message,
414 ...(data !== undefined ? { data } : {}),
415 ...diagnostics,
416 });
417 }
418​
419 static authRequired(message = "Authentication required", data?: unknown) {
420 return new AcpRequestError({
421 code: -32000,
422 errorMessage: message,
423 ...(data !== undefined ? { data } : {}),
424 });
425 }
426​
427 static resourceNotFound(message = "Resource not found", data?: unknown) {
428 return new AcpRequestError({
429 code: -32002,
430 errorMessage: message,
431 ...(data !== undefined ? { data } : {}),
432 });
433 }
434​
435 toProtocolError() {
436 return AcpSchema.Error.make({
437 code: this.code,
438 message: this.errorMessage,
439 ...(this.data !== undefined ? { data: this.data } : {}),
440 });
441 }
443​
444export const AcpError = Schema.Union([
445 AcpRequestError,
446 AcpSpawnError,
447 AcpProcessExitedError,
448 AcpProtocolParseError,
449 AcpTransportError,
450 AcpInputStreamEndedError,
451]);
452​
453export type AcpError = typeof AcpError.Type;