Open History to see the last commit
1import * as Schema from "effect/Schema";
2import type * as SchemaIssue from "effect/SchemaIssue";
3
4import * as AcpSchema from "./_generated/schema.gen.ts";
5
6const AcpRequestOperation = Schema.Literals([
7 "decode-extension-request-payload",
8 "encode-extension-response",
9 "handle-request",
10 "handle-extension-request",
11 "receive-response",
12 "receive-streaming-response",
13]);
14type AcpRequestOperation = typeof AcpRequestOperation.Type;
15
16export const AcpRequestId = Schema.Union([Schema.String, Schema.Number]);
17export type AcpRequestId = typeof AcpRequestId.Type;
18
19const AcpSchemaIssueKind = Schema.Literals([
20 "Filter",
21 "Encoding",
22 "Pointer",
23 "Composite",
24 "AnyOf",
25 "InvalidType",
26 "InvalidValue",
27 "MissingKey",
28 "UnexpectedKey",
29 "Forbidden",
30 "OneOf",
31]);
32type AcpSchemaIssueKind = typeof AcpSchemaIssueKind.Type;
33
34interface AcpSchemaIssueDiagnostics {
35 readonly issueCount: number;
36 readonly issueKinds: ReadonlyArray<AcpSchemaIssueKind>;
37 readonly maximumPathDepth: number;
38}
39
40const schemaIssueDiagnostics = (root: SchemaIssue.Issue): AcpSchemaIssueDiagnostics => {
41 let issueCount = 0;
42 let maximumPathDepth = 0;
43 const issueKinds = new Set<AcpSchemaIssueKind>();
44
45 const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {
46 issueCount += 1;
47 issueKinds.add(issue._tag);
48 maximumPathDepth = Math.max(maximumPathDepth, pathDepth);
49 switch (issue._tag) {
50 case "Filter":
51 case "Encoding":
52 visit(issue.issue, pathDepth);
53 break;
54 case "Pointer":
55 visit(issue.issue, pathDepth + issue.path.length);
56 break;
57 case "Composite":
58 case "AnyOf":
59 for (const child of issue.issues) visit(child, pathDepth);
60 break;
61 }
62 };
63
64 visit(root, 0);
65 return {
66 issueCount,
67 issueKinds: [...issueKinds],
68 maximumPathDepth,
69 };
70};
71
72export interface AcpRequestDiagnostics {
73 readonly method?: string;
74 readonly requestId?: AcpRequestId;
75 readonly operation?: AcpRequestOperation;
76 readonly cause?: unknown;
77 readonly issueCount?: number;
78 readonly issueKinds?: ReadonlyArray<AcpSchemaIssueKind>;
79 readonly maximumPathDepth?: number;
80}
81
82export class AcpSpawnError extends Schema.TaggedError<AcpSpawnError>()("AcpSpawnError", {
83 command: Schema.optional(Schema.String),
84 cause: Schema.Defect(),
85}) {
86 override get message() {
87 return this.command
88 ? `Failed to spawn ACP process for command: ${this.command}`
89 : "Failed to spawn ACP process";
90 }
91}
92
93export class AcpProcessExitedError extends Schema.TaggedError<AcpProcessExitedError>()(
94 "AcpProcessExitedError",
95 {
96 code: Schema.optional(Schema.Number),
97 pid: Schema.optionalKey(Schema.Int),
98 cause: Schema.optional(Schema.Defect()),
99 },
100) {
101 override get message() {
102 return this.code === undefined
103 ? "ACP process exited"
104 : `ACP process exited with code ${this.code}`;
105 }
106}
107
108export const AcpProtocolParseOperation = Schema.Literals([
109 "encode-message",
110 "decode-wire-message",
111 "decode-notification-payload",
112]);
113export type AcpProtocolParseOperation = typeof AcpProtocolParseOperation.Type;
114
115export class AcpProtocolParseError extends Schema.TaggedError<AcpProtocolParseError>()(
116 "AcpProtocolParseError",
117 {
118 operation: AcpProtocolParseOperation,
119 method: Schema.optionalKey(Schema.String),
120 requestId: Schema.optionalKey(AcpRequestId),
121 issueCount: Schema.optionalKey(Schema.Number),
122 issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
123 maximumPathDepth: Schema.optionalKey(Schema.Number),
124 cause: Schema.Defect(),
125 },
126) {
127 override get message() {
128 const method = this.method === undefined ? "" : ` for method '${this.method}'`;
129 return `ACP protocol operation '${this.operation}' failed${method}.`;
130 }
131
132 static fromSchemaError(
133 operation: AcpProtocolParseOperation,
134 method: string,
135 cause: Schema.SchemaError,
136 ) {
137 return new AcpProtocolParseError({
138 operation,
139 method,
140 ...schemaIssueDiagnostics(cause.issue),
141 cause,
142 });
143 }
144
145 static fromEncodingError(
146 method: string | undefined,
147 requestId: AcpRequestId | undefined,
148 cause: unknown,
149 ) {
150 return new AcpProtocolParseError({
151 operation: "encode-message",
152 ...(method === undefined ? {} : { method }),
153 ...(requestId === undefined ? {} : { requestId }),
154 cause,
155 });
156 }
157}
158
159export class AcpTransportError extends Schema.TaggedError<AcpTransportError>()(
160 "AcpTransportError",
161 {
162 operation: Schema.optional(
163 Schema.Literals(["call-rpc", "read-input-stream", "read-process-exit-status"]),
164 ),
165 method: Schema.optional(Schema.String),
166 detail: Schema.optional(Schema.String),
167 pid: Schema.optionalKey(Schema.Int),
168 cause: Schema.Defect(),
169 },
170) {
171 override get message() {
172 const method = this.method ? ` for method ${this.method}` : "";
173 return this.operation
174 ? `ACP transport operation ${this.operation} failed${method}.`
175 : "ACP transport operation failed.";
176 }
177}
178
179export class AcpInputStreamEndedError extends Schema.TaggedError<AcpInputStreamEndedError>()(
180 "AcpInputStreamEndedError",
181 {},
182) {
183 override get message() {
184 return "ACP input stream ended.";
185 }
186}
187
188export class AcpRequestError extends Schema.TaggedError<AcpRequestError>()("AcpRequestError", {
189 code: AcpSchema.ErrorCode,
190 errorMessage: Schema.String,
191 data: Schema.optional(Schema.Unknown),
192 method: Schema.optionalKey(Schema.String),
193 requestId: Schema.optionalKey(AcpRequestId),
194 operation: Schema.optionalKey(AcpRequestOperation),
195 issueCount: Schema.optionalKey(Schema.Number),
196 issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
197 maximumPathDepth: Schema.optionalKey(Schema.Number),
198 cause: Schema.optionalKey(Schema.Defect()),
199}) {
200 override get message() {
201 return this.errorMessage;
202 }
203
204 static fromProtocolError(
205 error: AcpSchema.Error,
206 context: {
207 readonly method: string;
208 readonly requestId?: AcpRequestId;
209 readonly cause?: unknown;
210 },
211 ) {
212 return new AcpRequestError({
213 code: error.code,
214 errorMessage: error.message,
215 ...(error.data !== undefined ? { data: error.data } : {}),
216 method: context.method,
217 ...(context.requestId === undefined ? {} : { requestId: context.requestId }),
218 operation: "receive-response",
219 cause: context.cause ?? error,
220 });
221 }
222
223 static fromExtensionResponseFailure(method: string, requestId: AcpRequestId, cause: unknown) {
224 return AcpRequestError.internalError("Extension request failed", undefined, {
225 method,
226 requestId,
227 operation: "receive-response",
228 cause,
229 });
230 }
231
232 static fromExtensionResponseEncodingError(
233 method: string,
234 requestId: AcpRequestId,
235 cause: AcpProtocolParseError,
236 ) {
237 return AcpRequestError.internalError("Internal error", undefined, {
238 method,
239 requestId,
240 operation: "encode-extension-response",
241 cause,
242 });
243 }
244
245 static unsupportedStreamingResponse(method: string, requestId: AcpRequestId) {
246 return AcpRequestError.internalError(
247 "Streaming extension responses are not supported",
248 undefined,
249 {
250 method,
251 requestId,
252 operation: "receive-streaming-response",
253 },
254 );
255 }
256
257 static fromCoreHandlerError(error: AcpError, method: string) {
258 if (error._tag === "AcpRequestError") {
259 return error;
260 }
261 return AcpRequestError.internalError(
262 `ACP request handler failed for method '${method}'`,
263 undefined,
264 {
265 method,
266 operation: "handle-request",
267 cause: error,
268 },
269 );
270 }
271
272 static fromExtensionHandlerError(error: AcpError, method: string) {
273 if (error._tag === "AcpRequestError") {
274 return error;
275 }
276 return AcpRequestError.internalError(
277 `ACP extension request handler failed for method '${method}'`,
278 undefined,
279 {
280 method,
281 operation: "handle-extension-request",
282 cause: error,
283 },
284 );
285 }
286
287 static parseError(message = "Parse error", data?: unknown) {
288 return new AcpRequestError({
289 code: -32700,
290 errorMessage: message,
291 ...(data !== undefined ? { data } : {}),
292 });
293 }
294
295 static invalidRequest(message = "Invalid request", data?: unknown) {
296 return new AcpRequestError({
297 code: -32600,
298 errorMessage: message,
299 ...(data !== undefined ? { data } : {}),
300 });
301 }
302
303 static methodNotFound(method: string) {
304 return new AcpRequestError({
305 code: -32601,
306 errorMessage: `Method not found: ${method}`,
307 });
308 }
309
310 static invalidParams(message = "Invalid params", data?: unknown) {
311 return new AcpRequestError({
312 code: -32602,
313 errorMessage: message,
314 ...(data !== undefined ? { data } : {}),
315 });
316 }
317
318 static invalidExtensionPayload(method: string, cause: Schema.SchemaError) {
319 const diagnostics = schemaIssueDiagnostics(cause.issue);
320 return new AcpRequestError({
321 code: -32602,
322 errorMessage: `Invalid payload for ACP extension method '${method}'.`,
323 data: diagnostics,
324 method,
325 operation: "decode-extension-request-payload",
326 ...diagnostics,
327 cause,
328 });
329 }
330
331 static internalError(
332 message = "Internal error",
333 data?: unknown,
334 diagnostics: AcpRequestDiagnostics = {},
335 ) {
336 return new AcpRequestError({
337 code: -32603,
338 errorMessage: message,
339 ...(data !== undefined ? { data } : {}),
340 ...diagnostics,
341 });
342 }
343
344 static authRequired(message = "Authentication required", data?: unknown) {
345 return new AcpRequestError({
346 code: -32000,
347 errorMessage: message,
348 ...(data !== undefined ? { data } : {}),
349 });
350 }
351
352 static resourceNotFound(message = "Resource not found", data?: unknown) {
353 return new AcpRequestError({
354 code: -32002,
355 errorMessage: message,
356 ...(data !== undefined ? { data } : {}),
357 });
358 }
359
360 toProtocolError() {
361 return AcpSchema.Error.make({
362 code: this.code,
363 message: this.errorMessage,
364 ...(this.data !== undefined ? { data: this.data } : {}),
365 });
366 }
367}
368
369export const AcpError = Schema.Union([
370 AcpRequestError,
371 AcpSpawnError,
372 AcpProcessExitedError,
373 AcpProtocolParseError,
374 AcpTransportError,
375 AcpInputStreamEndedError,
376]);
377
378export type AcpError = typeof AcpError.Type;