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