lody 0.72.0 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4133 @@
1
+ import { c as array, e as unknown, N as NEVER, u as union, n as number, s as string, o as object, r as record, G as int, l as literal, b as boolean, y as intersection, H as url } from "./schemas-BDpQ67Nq.js";
2
+ const AGENT_METHODS = {
3
+ initialize: "initialize",
4
+ authenticate: "authenticate",
5
+ providers_list: "providers/list",
6
+ providers_set: "providers/set",
7
+ providers_disable: "providers/disable",
8
+ session_new: "session/new",
9
+ session_load: "session/load",
10
+ session_set_mode: "session/set_mode",
11
+ session_set_config_option: "session/set_config_option",
12
+ session_prompt: "session/prompt",
13
+ session_cancel: "session/cancel",
14
+ session_list: "session/list",
15
+ session_delete: "session/delete",
16
+ session_fork: "session/fork",
17
+ session_resume: "session/resume",
18
+ session_close: "session/close",
19
+ logout: "logout",
20
+ nes_start: "nes/start",
21
+ nes_suggest: "nes/suggest",
22
+ nes_accept: "nes/accept",
23
+ nes_reject: "nes/reject",
24
+ nes_close: "nes/close",
25
+ document_did_open: "document/didOpen",
26
+ document_did_change: "document/didChange",
27
+ document_did_close: "document/didClose",
28
+ document_did_save: "document/didSave",
29
+ document_did_focus: "document/didFocus"
30
+ };
31
+ const CLIENT_METHODS = {
32
+ session_request_permission: "session/request_permission",
33
+ session_update: "session/update",
34
+ fs_write_text_file: "fs/write_text_file",
35
+ fs_read_text_file: "fs/read_text_file",
36
+ terminal_create: "terminal/create",
37
+ terminal_output: "terminal/output",
38
+ terminal_release: "terminal/release",
39
+ terminal_wait_for_exit: "terminal/wait_for_exit",
40
+ terminal_kill: "terminal/kill",
41
+ elicitation_create: "elicitation/create",
42
+ elicitation_complete: "elicitation/complete"
43
+ };
44
+ const PROTOCOL_VERSION = 1;
45
+ const skippedItem = Symbol("skippedItem");
46
+ function defaultOnError(schema, fallback) {
47
+ return schema.catch(fallback);
48
+ }
49
+ function requiredDefaultOnError(schema, fallback) {
50
+ const schemaWithCatch = schema.catch(fallback);
51
+ return unknown().transform((value, context) => {
52
+ if (value !== void 0)
53
+ return schemaWithCatch.parse(value);
54
+ context.addIssue({
55
+ code: "custom",
56
+ message: "Required value is missing"
57
+ });
58
+ return NEVER;
59
+ });
60
+ }
61
+ function stringTag(value, key) {
62
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
63
+ return void 0;
64
+ }
65
+ const tag = value[key];
66
+ return typeof tag === "string" ? tag : void 0;
67
+ }
68
+ function excludeKnownTags(schema, key, knownTags) {
69
+ return schema.superRefine((value, context) => {
70
+ const tag = stringTag(value, key);
71
+ if (tag !== void 0 && knownTags.includes(tag)) {
72
+ context.addIssue({
73
+ code: "custom",
74
+ path: [key],
75
+ message: `${key} ${JSON.stringify(tag)} is reserved by a known variant, but the value does not match that variant's schema`
76
+ });
77
+ }
78
+ });
79
+ }
80
+ function preserveCustomPayload(schema, key, knownTags) {
81
+ return unknown().transform((value, context) => {
82
+ const result = schema.safeParse(value);
83
+ if (!result.success) {
84
+ for (const issue of result.error.issues) {
85
+ context.addIssue({ ...issue, input: value });
86
+ }
87
+ return NEVER;
88
+ }
89
+ const output = result.data;
90
+ const tag = stringTag(value, key);
91
+ if (tag !== void 0 && !knownTags.includes(tag)) {
92
+ const raw = value;
93
+ for (const [property, rawValue] of Object.entries(raw)) {
94
+ if (property === "__proto__")
95
+ continue;
96
+ if (!Object.hasOwn(output, property))
97
+ output[property] = rawValue;
98
+ }
99
+ }
100
+ return output;
101
+ });
102
+ }
103
+ function vecSkipError(itemSchema) {
104
+ return array(itemSchema.catch(skippedItem)).transform((items) => items.filter((item) => item !== skippedItem));
105
+ }
106
+ const zRequestId = union([number(), string()]).nullable();
107
+ const zSessionId = string();
108
+ const zWriteTextFileRequest = object({
109
+ sessionId: zSessionId,
110
+ path: string(),
111
+ content: string(),
112
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
113
+ });
114
+ const zReadTextFileRequest = object({
115
+ sessionId: zSessionId,
116
+ path: string(),
117
+ line: defaultOnError(int().gte(0).max(4294967295, {
118
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
119
+ }).nullish(), () => void 0),
120
+ limit: defaultOnError(int().gte(0).max(4294967295, {
121
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
122
+ }).nullish(), () => void 0),
123
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
124
+ });
125
+ const zToolCallId = string();
126
+ const zToolKind = union([
127
+ literal("read"),
128
+ literal("edit"),
129
+ literal("delete"),
130
+ literal("move"),
131
+ literal("search"),
132
+ literal("execute"),
133
+ literal("think"),
134
+ literal("fetch"),
135
+ literal("switch_mode"),
136
+ literal("other")
137
+ ]);
138
+ const zToolCallStatus = union([
139
+ literal("pending"),
140
+ literal("in_progress"),
141
+ literal("completed"),
142
+ literal("failed")
143
+ ]);
144
+ const zRole = union([literal("assistant"), literal("user")]);
145
+ const zAnnotations = object({
146
+ audience: defaultOnError(vecSkipError(zRole).nullish(), () => void 0),
147
+ lastModified: defaultOnError(string().nullish(), () => void 0),
148
+ priority: defaultOnError(number().nullish(), () => void 0),
149
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
150
+ });
151
+ const zTextContent = object({
152
+ annotations: defaultOnError(zAnnotations.nullish(), () => void 0),
153
+ text: string(),
154
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
155
+ });
156
+ const zImageContent = object({
157
+ annotations: defaultOnError(zAnnotations.nullish(), () => void 0),
158
+ data: string(),
159
+ mimeType: string(),
160
+ uri: defaultOnError(string().nullish(), () => void 0),
161
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
162
+ });
163
+ const zAudioContent = object({
164
+ annotations: defaultOnError(zAnnotations.nullish(), () => void 0),
165
+ data: string(),
166
+ mimeType: string(),
167
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
168
+ });
169
+ const zResourceLink = object({
170
+ annotations: defaultOnError(zAnnotations.nullish(), () => void 0),
171
+ description: defaultOnError(string().nullish(), () => void 0),
172
+ mimeType: defaultOnError(string().nullish(), () => void 0),
173
+ name: string(),
174
+ size: defaultOnError(number().nullish(), () => void 0),
175
+ title: defaultOnError(string().nullish(), () => void 0),
176
+ uri: string(),
177
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
178
+ });
179
+ const zTextResourceContents = object({
180
+ mimeType: defaultOnError(string().nullish(), () => void 0),
181
+ text: string(),
182
+ uri: string(),
183
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
184
+ });
185
+ const zBlobResourceContents = object({
186
+ blob: string(),
187
+ mimeType: defaultOnError(string().nullish(), () => void 0),
188
+ uri: string(),
189
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
190
+ });
191
+ const zEmbeddedResourceResource = union([
192
+ zTextResourceContents,
193
+ zBlobResourceContents
194
+ ]);
195
+ const zEmbeddedResource = object({
196
+ annotations: defaultOnError(zAnnotations.nullish(), () => void 0),
197
+ resource: zEmbeddedResourceResource,
198
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
199
+ });
200
+ const zContentBlock = union([
201
+ zTextContent.and(object({
202
+ type: literal("text")
203
+ })),
204
+ zImageContent.and(object({
205
+ type: literal("image")
206
+ })),
207
+ zAudioContent.and(object({
208
+ type: literal("audio")
209
+ })),
210
+ zResourceLink.and(object({
211
+ type: literal("resource_link")
212
+ })),
213
+ zEmbeddedResource.and(object({
214
+ type: literal("resource")
215
+ }))
216
+ ]);
217
+ const zContent = object({
218
+ content: zContentBlock,
219
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
220
+ });
221
+ const zDiff = object({
222
+ path: string(),
223
+ oldText: defaultOnError(string().nullish(), () => void 0),
224
+ newText: string(),
225
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
226
+ });
227
+ const zTerminalId = string();
228
+ const zTerminal = object({
229
+ terminalId: zTerminalId,
230
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
231
+ });
232
+ const zToolCallContent = union([
233
+ zContent.and(object({
234
+ type: literal("content")
235
+ })),
236
+ zDiff.and(object({
237
+ type: literal("diff")
238
+ })),
239
+ zTerminal.and(object({
240
+ type: literal("terminal")
241
+ }))
242
+ ]);
243
+ const zToolCallLocation = object({
244
+ path: string(),
245
+ line: defaultOnError(int().gte(0).max(4294967295, {
246
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
247
+ }).nullish(), () => void 0),
248
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
249
+ });
250
+ const zToolCallUpdate = object({
251
+ toolCallId: zToolCallId,
252
+ kind: defaultOnError(zToolKind.nullish(), () => void 0),
253
+ status: defaultOnError(zToolCallStatus.nullish(), () => void 0),
254
+ title: defaultOnError(string().nullish(), () => void 0),
255
+ name: defaultOnError(string().nullish(), () => void 0),
256
+ content: defaultOnError(vecSkipError(zToolCallContent).nullish(), () => void 0),
257
+ locations: defaultOnError(vecSkipError(zToolCallLocation).nullish(), () => void 0),
258
+ rawInput: defaultOnError(unknown().optional(), () => void 0),
259
+ rawOutput: defaultOnError(unknown().optional(), () => void 0),
260
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
261
+ });
262
+ const zPermissionOptionId = string();
263
+ const zPermissionOptionKind = union([
264
+ literal("allow_once"),
265
+ literal("allow_always"),
266
+ literal("reject_once"),
267
+ literal("reject_always")
268
+ ]);
269
+ const zPermissionOption = object({
270
+ optionId: zPermissionOptionId,
271
+ name: string(),
272
+ kind: zPermissionOptionKind,
273
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
274
+ });
275
+ const zRequestPermissionRequest = object({
276
+ sessionId: zSessionId,
277
+ toolCall: zToolCallUpdate,
278
+ options: array(zPermissionOption),
279
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
280
+ });
281
+ const zEnvVariable = object({
282
+ name: string(),
283
+ value: string(),
284
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
285
+ });
286
+ const zCreateTerminalRequest = object({
287
+ sessionId: zSessionId,
288
+ command: string(),
289
+ args: defaultOnError(vecSkipError(string()).optional(), () => []),
290
+ env: defaultOnError(vecSkipError(zEnvVariable).optional(), () => []),
291
+ cwd: defaultOnError(string().nullish(), () => void 0),
292
+ outputByteLimit: defaultOnError(number().nullish(), () => void 0),
293
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
294
+ });
295
+ const zTerminalOutputRequest = object({
296
+ sessionId: zSessionId,
297
+ terminalId: zTerminalId,
298
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
299
+ });
300
+ const zReleaseTerminalRequest = object({
301
+ sessionId: zSessionId,
302
+ terminalId: zTerminalId,
303
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
304
+ });
305
+ const zWaitForTerminalExitRequest = object({
306
+ sessionId: zSessionId,
307
+ terminalId: zTerminalId,
308
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
309
+ });
310
+ const zKillTerminalRequest = object({
311
+ sessionId: zSessionId,
312
+ terminalId: zTerminalId,
313
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
314
+ });
315
+ const zElicitationSessionScope = object({
316
+ sessionId: zSessionId,
317
+ toolCallId: defaultOnError(zToolCallId.nullish(), () => void 0)
318
+ });
319
+ const zElicitationRequestScope = object({
320
+ requestId: zRequestId
321
+ });
322
+ const zElicitationSchemaType = literal("object");
323
+ const zStringFormat = union([
324
+ literal("email"),
325
+ literal("uri"),
326
+ literal("date"),
327
+ literal("date-time")
328
+ ]);
329
+ const zEnumOption = object({
330
+ const: string(),
331
+ title: string(),
332
+ description: defaultOnError(string().nullish(), () => void 0),
333
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
334
+ });
335
+ const zStringPropertySchema = object({
336
+ title: defaultOnError(string().nullish(), () => void 0),
337
+ description: defaultOnError(string().nullish(), () => void 0),
338
+ minLength: int().gte(0).max(4294967295, {
339
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
340
+ }).nullish(),
341
+ maxLength: int().gte(0).max(4294967295, {
342
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
343
+ }).nullish(),
344
+ pattern: string().nullish(),
345
+ format: zStringFormat.nullish(),
346
+ default: defaultOnError(string().nullish(), () => void 0),
347
+ enum: array(string()).nullish(),
348
+ oneOf: array(zEnumOption).nullish(),
349
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
350
+ });
351
+ const zNumberPropertySchema = object({
352
+ title: defaultOnError(string().nullish(), () => void 0),
353
+ description: defaultOnError(string().nullish(), () => void 0),
354
+ minimum: number().nullish(),
355
+ maximum: number().nullish(),
356
+ default: defaultOnError(number().nullish(), () => void 0),
357
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
358
+ });
359
+ const zIntegerPropertySchema = object({
360
+ title: defaultOnError(string().nullish(), () => void 0),
361
+ description: defaultOnError(string().nullish(), () => void 0),
362
+ minimum: number().nullish(),
363
+ maximum: number().nullish(),
364
+ default: defaultOnError(number().nullish(), () => void 0),
365
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
366
+ });
367
+ const zBooleanPropertySchema = object({
368
+ title: defaultOnError(string().nullish(), () => void 0),
369
+ description: defaultOnError(string().nullish(), () => void 0),
370
+ default: defaultOnError(boolean().nullish(), () => void 0),
371
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
372
+ });
373
+ const zStringMultiSelectItems = object({
374
+ enum: array(string()),
375
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
376
+ });
377
+ const zTitledMultiSelectItems = object({
378
+ anyOf: array(zEnumOption),
379
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
380
+ });
381
+ const zMultiSelectItems = preserveCustomPayload(union([
382
+ zStringMultiSelectItems.and(object({
383
+ type: literal("string")
384
+ })),
385
+ excludeKnownTags(object({
386
+ type: string()
387
+ }), "type", ["string"]),
388
+ zTitledMultiSelectItems
389
+ ]), "type", ["string"]);
390
+ const zMultiSelectPropertySchema = object({
391
+ title: defaultOnError(string().nullish(), () => void 0),
392
+ description: defaultOnError(string().nullish(), () => void 0),
393
+ minItems: number().nullish(),
394
+ maxItems: number().nullish(),
395
+ items: zMultiSelectItems,
396
+ default: defaultOnError(vecSkipError(string()).nullish(), () => void 0),
397
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
398
+ });
399
+ const zElicitationPropertySchema = preserveCustomPayload(union([
400
+ zStringPropertySchema.and(object({
401
+ type: literal("string")
402
+ })),
403
+ zNumberPropertySchema.and(object({
404
+ type: literal("number")
405
+ })),
406
+ zIntegerPropertySchema.and(object({
407
+ type: literal("integer")
408
+ })),
409
+ zBooleanPropertySchema.and(object({
410
+ type: literal("boolean")
411
+ })),
412
+ zMultiSelectPropertySchema.and(object({
413
+ type: literal("array")
414
+ })),
415
+ excludeKnownTags(object({
416
+ type: string()
417
+ }), "type", ["array", "boolean", "integer", "number", "string"])
418
+ ]), "type", ["array", "boolean", "integer", "number", "string"]);
419
+ const zElicitationSchema = object({
420
+ type: defaultOnError(zElicitationSchemaType.optional().default("object"), () => "object"),
421
+ title: defaultOnError(string().nullish(), () => void 0),
422
+ properties: record(string(), zElicitationPropertySchema).optional().default({}),
423
+ required: array(string()).nullish(),
424
+ description: defaultOnError(string().nullish(), () => void 0),
425
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
426
+ });
427
+ const zElicitationFormMode = intersection(union([zElicitationSessionScope, zElicitationRequestScope]), object({
428
+ requestedSchema: zElicitationSchema
429
+ }));
430
+ const zElicitationId = string();
431
+ const zElicitationUrlMode = intersection(union([zElicitationSessionScope, zElicitationRequestScope]), object({
432
+ elicitationId: zElicitationId,
433
+ url: url()
434
+ }));
435
+ const zCreateElicitationRequest = preserveCustomPayload(intersection(union([
436
+ zElicitationFormMode.and(object({
437
+ mode: literal("form")
438
+ })),
439
+ zElicitationUrlMode.and(object({
440
+ mode: literal("url")
441
+ })),
442
+ excludeKnownTags(intersection(union([zElicitationSessionScope, zElicitationRequestScope]), object({
443
+ mode: string()
444
+ })), "mode", ["form", "url"])
445
+ ]), object({
446
+ message: string(),
447
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
448
+ })), "mode", ["form", "url"]);
449
+ const zMcpServerAcpId = string();
450
+ const zConnectMcpRequest = object({
451
+ serverId: zMcpServerAcpId,
452
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
453
+ });
454
+ const zMcpConnectionId = string();
455
+ const zMessageMcpRequest = object({
456
+ connectionId: zMcpConnectionId,
457
+ method: string(),
458
+ params: record(string(), unknown()).nullish(),
459
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
460
+ });
461
+ const zDisconnectMcpRequest = object({
462
+ connectionId: zMcpConnectionId,
463
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
464
+ });
465
+ const zExtRequest = unknown();
466
+ object({
467
+ id: zRequestId,
468
+ method: string(),
469
+ params: union([
470
+ zWriteTextFileRequest,
471
+ zReadTextFileRequest,
472
+ zRequestPermissionRequest,
473
+ zCreateTerminalRequest,
474
+ zTerminalOutputRequest,
475
+ zReleaseTerminalRequest,
476
+ zWaitForTerminalExitRequest,
477
+ zKillTerminalRequest,
478
+ zCreateElicitationRequest,
479
+ zConnectMcpRequest,
480
+ zMessageMcpRequest,
481
+ zDisconnectMcpRequest,
482
+ zExtRequest
483
+ ]).nullish()
484
+ });
485
+ const zProtocolVersion = int().gte(0).lte(65535);
486
+ const zPromptCapabilities = object({
487
+ image: defaultOnError(boolean().optional().default(false), () => false),
488
+ audio: defaultOnError(boolean().optional().default(false), () => false),
489
+ embeddedContext: defaultOnError(boolean().optional().default(false), () => false),
490
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
491
+ });
492
+ const zMcpCapabilities = object({
493
+ http: defaultOnError(boolean().optional().default(false), () => false),
494
+ sse: defaultOnError(boolean().optional().default(false), () => false),
495
+ acp: defaultOnError(boolean().optional().default(false), () => false),
496
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
497
+ });
498
+ const zSessionListCapabilities = object({
499
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
500
+ });
501
+ const zSessionDeleteCapabilities = object({
502
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
503
+ });
504
+ const zSessionAdditionalDirectoriesCapabilities = object({
505
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
506
+ });
507
+ const zSessionForkCapabilities = object({
508
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
509
+ });
510
+ const zSessionResumeCapabilities = object({
511
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
512
+ });
513
+ const zSessionCloseCapabilities = object({
514
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
515
+ });
516
+ const zSessionCapabilities = object({
517
+ list: defaultOnError(zSessionListCapabilities.nullish(), () => void 0),
518
+ delete: defaultOnError(zSessionDeleteCapabilities.nullish(), () => void 0),
519
+ additionalDirectories: defaultOnError(zSessionAdditionalDirectoriesCapabilities.nullish(), () => void 0),
520
+ fork: defaultOnError(zSessionForkCapabilities.nullish(), () => void 0),
521
+ resume: defaultOnError(zSessionResumeCapabilities.nullish(), () => void 0),
522
+ close: defaultOnError(zSessionCloseCapabilities.nullish(), () => void 0),
523
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
524
+ });
525
+ const zLogoutCapabilities = object({
526
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
527
+ });
528
+ const zAgentAuthCapabilities = object({
529
+ logout: defaultOnError(zLogoutCapabilities.nullish(), () => void 0),
530
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
531
+ });
532
+ const zProvidersCapabilities = object({
533
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
534
+ });
535
+ const zNesDocumentDidOpenCapabilities = object({
536
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
537
+ });
538
+ const zTextDocumentSyncKind = union([
539
+ literal("full"),
540
+ literal("incremental")
541
+ ]);
542
+ const zNesDocumentDidChangeCapabilities = object({
543
+ syncKind: zTextDocumentSyncKind,
544
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
545
+ });
546
+ const zNesDocumentDidCloseCapabilities = object({
547
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
548
+ });
549
+ const zNesDocumentDidSaveCapabilities = object({
550
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
551
+ });
552
+ const zNesDocumentDidFocusCapabilities = object({
553
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
554
+ });
555
+ const zNesDocumentEventCapabilities = object({
556
+ didOpen: defaultOnError(zNesDocumentDidOpenCapabilities.nullish(), () => void 0),
557
+ didChange: defaultOnError(zNesDocumentDidChangeCapabilities.nullish(), () => void 0),
558
+ didClose: defaultOnError(zNesDocumentDidCloseCapabilities.nullish(), () => void 0),
559
+ didSave: defaultOnError(zNesDocumentDidSaveCapabilities.nullish(), () => void 0),
560
+ didFocus: defaultOnError(zNesDocumentDidFocusCapabilities.nullish(), () => void 0),
561
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
562
+ });
563
+ const zNesEventCapabilities = object({
564
+ document: defaultOnError(zNesDocumentEventCapabilities.nullish(), () => void 0),
565
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
566
+ });
567
+ const zNesRecentFilesCapabilities = object({
568
+ maxCount: defaultOnError(int().gte(0).max(4294967295, {
569
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
570
+ }).nullish(), () => void 0),
571
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
572
+ });
573
+ const zNesRelatedSnippetsCapabilities = object({
574
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
575
+ });
576
+ const zNesEditHistoryCapabilities = object({
577
+ maxCount: defaultOnError(int().gte(0).max(4294967295, {
578
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
579
+ }).nullish(), () => void 0),
580
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
581
+ });
582
+ const zNesUserActionsCapabilities = object({
583
+ maxCount: defaultOnError(int().gte(0).max(4294967295, {
584
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
585
+ }).nullish(), () => void 0),
586
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
587
+ });
588
+ const zNesOpenFilesCapabilities = object({
589
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
590
+ });
591
+ const zNesDiagnosticsCapabilities = object({
592
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
593
+ });
594
+ const zNesContextCapabilities = object({
595
+ recentFiles: defaultOnError(zNesRecentFilesCapabilities.nullish(), () => void 0),
596
+ relatedSnippets: defaultOnError(zNesRelatedSnippetsCapabilities.nullish(), () => void 0),
597
+ editHistory: defaultOnError(zNesEditHistoryCapabilities.nullish(), () => void 0),
598
+ userActions: defaultOnError(zNesUserActionsCapabilities.nullish(), () => void 0),
599
+ openFiles: defaultOnError(zNesOpenFilesCapabilities.nullish(), () => void 0),
600
+ diagnostics: defaultOnError(zNesDiagnosticsCapabilities.nullish(), () => void 0),
601
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
602
+ });
603
+ const zNesCapabilities = object({
604
+ events: defaultOnError(zNesEventCapabilities.nullish(), () => void 0),
605
+ context: defaultOnError(zNesContextCapabilities.nullish(), () => void 0),
606
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
607
+ });
608
+ const zPositionEncodingKind = union([
609
+ literal("utf-16"),
610
+ literal("utf-32"),
611
+ literal("utf-8")
612
+ ]);
613
+ const zAgentCapabilities = object({
614
+ loadSession: defaultOnError(boolean().optional().default(false), () => false),
615
+ promptCapabilities: defaultOnError(zPromptCapabilities.optional().default({
616
+ image: false,
617
+ audio: false,
618
+ embeddedContext: false
619
+ }), () => ({
620
+ image: false,
621
+ audio: false,
622
+ embeddedContext: false
623
+ })),
624
+ mcpCapabilities: defaultOnError(zMcpCapabilities.optional().default({
625
+ http: false,
626
+ sse: false,
627
+ acp: false
628
+ }), () => ({
629
+ http: false,
630
+ sse: false,
631
+ acp: false
632
+ })),
633
+ sessionCapabilities: defaultOnError(zSessionCapabilities.optional().default({}), () => ({})),
634
+ auth: defaultOnError(zAgentAuthCapabilities.optional().default({}), () => ({})),
635
+ providers: defaultOnError(zProvidersCapabilities.nullish(), () => void 0),
636
+ nes: defaultOnError(zNesCapabilities.nullish(), () => void 0),
637
+ positionEncoding: defaultOnError(zPositionEncodingKind.nullish(), () => void 0),
638
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
639
+ });
640
+ const zAuthMethodId = string();
641
+ const zAuthEnvVar = object({
642
+ name: string(),
643
+ label: defaultOnError(string().nullish(), () => void 0),
644
+ secret: defaultOnError(boolean().optional().default(true), () => true),
645
+ optional: defaultOnError(boolean().optional().default(false), () => false),
646
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
647
+ });
648
+ const zAuthMethodEnvVar = object({
649
+ id: zAuthMethodId,
650
+ name: string(),
651
+ description: defaultOnError(string().nullish(), () => void 0),
652
+ vars: requiredDefaultOnError(vecSkipError(zAuthEnvVar), () => []),
653
+ link: defaultOnError(string().nullish(), () => void 0),
654
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
655
+ });
656
+ const zAuthMethodTerminal = object({
657
+ id: zAuthMethodId,
658
+ name: string(),
659
+ description: defaultOnError(string().nullish(), () => void 0),
660
+ args: defaultOnError(vecSkipError(string()).optional(), () => []),
661
+ env: defaultOnError(record(string(), string()).optional(), () => void 0),
662
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
663
+ });
664
+ const zAuthMethodAgent = object({
665
+ id: zAuthMethodId,
666
+ name: string(),
667
+ description: defaultOnError(string().nullish(), () => void 0),
668
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
669
+ });
670
+ const zAuthMethod = union([
671
+ zAuthMethodEnvVar.and(object({
672
+ type: literal("env_var")
673
+ })),
674
+ zAuthMethodTerminal.and(object({
675
+ type: literal("terminal")
676
+ })),
677
+ zAuthMethodAgent
678
+ ]);
679
+ const zImplementation = object({
680
+ name: string(),
681
+ title: defaultOnError(string().nullish(), () => void 0),
682
+ version: string(),
683
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
684
+ });
685
+ const zInitializeResponse = object({
686
+ protocolVersion: zProtocolVersion,
687
+ agentCapabilities: defaultOnError(zAgentCapabilities.optional().default({
688
+ loadSession: false,
689
+ promptCapabilities: {
690
+ image: false,
691
+ audio: false,
692
+ embeddedContext: false
693
+ },
694
+ mcpCapabilities: {
695
+ http: false,
696
+ sse: false,
697
+ acp: false
698
+ },
699
+ sessionCapabilities: {},
700
+ auth: {}
701
+ }), () => ({
702
+ loadSession: false,
703
+ promptCapabilities: {
704
+ image: false,
705
+ audio: false,
706
+ embeddedContext: false
707
+ },
708
+ mcpCapabilities: {
709
+ http: false,
710
+ sse: false,
711
+ acp: false
712
+ },
713
+ sessionCapabilities: {},
714
+ auth: {}
715
+ })),
716
+ authMethods: defaultOnError(vecSkipError(zAuthMethod).optional().default([]), () => []),
717
+ agentInfo: defaultOnError(zImplementation.nullish(), () => void 0),
718
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
719
+ });
720
+ const zAuthenticateResponse = object({
721
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
722
+ });
723
+ const zProviderId = string();
724
+ const zLlmProtocol = union([
725
+ literal("anthropic"),
726
+ literal("openai"),
727
+ literal("azure"),
728
+ literal("vertex"),
729
+ literal("bedrock"),
730
+ string()
731
+ ]);
732
+ const zProviderCurrentConfig = object({
733
+ apiType: zLlmProtocol,
734
+ baseUrl: string(),
735
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
736
+ });
737
+ const zProviderInfo = object({
738
+ providerId: zProviderId,
739
+ supported: requiredDefaultOnError(vecSkipError(zLlmProtocol), () => []),
740
+ required: boolean(),
741
+ current: zProviderCurrentConfig.nullish(),
742
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
743
+ });
744
+ const zListProvidersResponse = object({
745
+ providers: array(zProviderInfo),
746
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
747
+ });
748
+ const zSetProviderResponse = object({
749
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
750
+ });
751
+ const zDisableProviderResponse = object({
752
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
753
+ });
754
+ const zLogoutResponse = object({
755
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
756
+ });
757
+ const zSessionModeId = string();
758
+ const zSessionMode = object({
759
+ id: zSessionModeId,
760
+ name: string(),
761
+ description: defaultOnError(string().nullish(), () => void 0),
762
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
763
+ });
764
+ const zSessionModeState = object({
765
+ currentModeId: zSessionModeId,
766
+ availableModes: requiredDefaultOnError(vecSkipError(zSessionMode), () => []),
767
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
768
+ });
769
+ const zSessionConfigId = string();
770
+ const zSessionConfigOptionCategory = union([
771
+ literal("mode"),
772
+ literal("model"),
773
+ literal("model_config"),
774
+ literal("thought_level"),
775
+ string()
776
+ ]);
777
+ const zSessionConfigValueId = string();
778
+ const zSessionConfigSelectOption = object({
779
+ value: zSessionConfigValueId,
780
+ name: string(),
781
+ description: defaultOnError(string().nullish(), () => void 0),
782
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
783
+ });
784
+ const zSessionConfigGroupId = string();
785
+ const zSessionConfigSelectGroup = object({
786
+ group: zSessionConfigGroupId,
787
+ name: string(),
788
+ options: requiredDefaultOnError(vecSkipError(zSessionConfigSelectOption), () => []),
789
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
790
+ });
791
+ const zSessionConfigSelectOptions = union([
792
+ array(zSessionConfigSelectOption),
793
+ array(zSessionConfigSelectGroup)
794
+ ]);
795
+ const zSessionConfigSelect = object({
796
+ currentValue: zSessionConfigValueId,
797
+ options: zSessionConfigSelectOptions
798
+ });
799
+ const zSessionConfigBoolean = object({
800
+ currentValue: boolean()
801
+ });
802
+ const zSessionConfigOption = intersection(union([
803
+ zSessionConfigSelect.and(object({
804
+ type: literal("select")
805
+ })),
806
+ zSessionConfigBoolean.and(object({
807
+ type: literal("boolean")
808
+ }))
809
+ ]), object({
810
+ id: zSessionConfigId,
811
+ name: string(),
812
+ description: defaultOnError(string().nullish(), () => void 0),
813
+ category: defaultOnError(zSessionConfigOptionCategory.nullish(), () => void 0),
814
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
815
+ }));
816
+ const zNewSessionResponse = object({
817
+ sessionId: zSessionId,
818
+ modes: defaultOnError(zSessionModeState.nullish(), () => void 0),
819
+ configOptions: defaultOnError(vecSkipError(zSessionConfigOption).nullish(), () => void 0),
820
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
821
+ });
822
+ const zLoadSessionResponse = object({
823
+ modes: defaultOnError(zSessionModeState.nullish(), () => void 0),
824
+ configOptions: defaultOnError(vecSkipError(zSessionConfigOption).nullish(), () => void 0),
825
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
826
+ });
827
+ const zSessionInfo = object({
828
+ sessionId: zSessionId,
829
+ cwd: string(),
830
+ additionalDirectories: defaultOnError(vecSkipError(string()).optional(), () => []),
831
+ title: defaultOnError(string().nullish(), () => void 0),
832
+ updatedAt: defaultOnError(string().nullish(), () => void 0),
833
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
834
+ });
835
+ const zListSessionsResponse = object({
836
+ sessions: requiredDefaultOnError(vecSkipError(zSessionInfo), () => []),
837
+ nextCursor: defaultOnError(string().nullish(), () => void 0),
838
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
839
+ });
840
+ const zDeleteSessionResponse = object({
841
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
842
+ });
843
+ const zForkSessionResponse = object({
844
+ sessionId: zSessionId,
845
+ modes: defaultOnError(zSessionModeState.nullish(), () => void 0),
846
+ configOptions: defaultOnError(vecSkipError(zSessionConfigOption).nullish(), () => void 0),
847
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
848
+ });
849
+ const zResumeSessionResponse = object({
850
+ modes: defaultOnError(zSessionModeState.nullish(), () => void 0),
851
+ configOptions: defaultOnError(vecSkipError(zSessionConfigOption).nullish(), () => void 0),
852
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
853
+ });
854
+ const zCloseSessionResponse = object({
855
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
856
+ });
857
+ const zSetSessionModeResponse = object({
858
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
859
+ });
860
+ const zSetSessionConfigOptionResponse = object({
861
+ configOptions: requiredDefaultOnError(vecSkipError(zSessionConfigOption), () => []),
862
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
863
+ });
864
+ const zStopReason = union([
865
+ literal("end_turn"),
866
+ literal("max_tokens"),
867
+ literal("max_turn_requests"),
868
+ literal("refusal"),
869
+ literal("cancelled")
870
+ ]);
871
+ const zUsage = object({
872
+ totalTokens: number(),
873
+ inputTokens: number(),
874
+ outputTokens: number(),
875
+ thoughtTokens: defaultOnError(number().nullish(), () => void 0),
876
+ cachedReadTokens: defaultOnError(number().nullish(), () => void 0),
877
+ cachedWriteTokens: defaultOnError(number().nullish(), () => void 0),
878
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
879
+ });
880
+ const zPromptResponse = object({
881
+ stopReason: zStopReason,
882
+ usage: defaultOnError(zUsage.nullish(), () => void 0),
883
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
884
+ });
885
+ const zStartNesResponse = object({
886
+ sessionId: zSessionId,
887
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
888
+ });
889
+ const zNesSuggestionId = string();
890
+ const zPosition = object({
891
+ line: int().gte(0).max(4294967295, {
892
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
893
+ }),
894
+ character: int().gte(0).max(4294967295, {
895
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
896
+ }),
897
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
898
+ });
899
+ const zRange = object({
900
+ start: zPosition,
901
+ end: zPosition,
902
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
903
+ });
904
+ const zNesTextEdit = object({
905
+ range: zRange,
906
+ newText: string(),
907
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
908
+ });
909
+ const zNesEditSuggestion = object({
910
+ id: zNesSuggestionId,
911
+ uri: string(),
912
+ edits: array(zNesTextEdit),
913
+ cursorPosition: defaultOnError(zPosition.nullish(), () => void 0),
914
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
915
+ });
916
+ const zNesJumpSuggestion = object({
917
+ id: zNesSuggestionId,
918
+ uri: string(),
919
+ position: zPosition,
920
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
921
+ });
922
+ const zNesRenameSuggestion = object({
923
+ id: zNesSuggestionId,
924
+ uri: string(),
925
+ position: zPosition,
926
+ newName: string(),
927
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
928
+ });
929
+ const zNesSearchAndReplaceSuggestion = object({
930
+ id: zNesSuggestionId,
931
+ uri: string(),
932
+ search: string(),
933
+ replace: string(),
934
+ isRegex: boolean().nullish(),
935
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
936
+ });
937
+ const zNesSuggestion = union([
938
+ zNesEditSuggestion.and(object({
939
+ kind: literal("edit")
940
+ })),
941
+ zNesJumpSuggestion.and(object({
942
+ kind: literal("jump")
943
+ })),
944
+ zNesRenameSuggestion.and(object({
945
+ kind: literal("rename")
946
+ })),
947
+ zNesSearchAndReplaceSuggestion.and(object({
948
+ kind: literal("searchAndReplace")
949
+ }))
950
+ ]);
951
+ const zSuggestNesResponse = object({
952
+ suggestions: array(zNesSuggestion),
953
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
954
+ });
955
+ const zCloseNesResponse = object({
956
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
957
+ });
958
+ const zExtResponse = unknown();
959
+ const zMessageMcpResponse = unknown();
960
+ const zErrorCode = union([
961
+ literal(-32700),
962
+ literal(-32600),
963
+ literal(-32601),
964
+ literal(-32602),
965
+ literal(-32603),
966
+ literal(-32800),
967
+ literal(-32e3),
968
+ literal(-32002),
969
+ int().min(-2147483648, {
970
+ error: "Invalid value: Expected int32 to be >= -2147483648"
971
+ }).max(2147483647, {
972
+ error: "Invalid value: Expected int32 to be <= 2147483647"
973
+ })
974
+ ]);
975
+ const zError = object({
976
+ code: zErrorCode,
977
+ message: string(),
978
+ data: defaultOnError(unknown().optional(), () => void 0)
979
+ });
980
+ union([
981
+ object({
982
+ id: zRequestId,
983
+ result: union([
984
+ zInitializeResponse,
985
+ zAuthenticateResponse,
986
+ zListProvidersResponse,
987
+ zSetProviderResponse,
988
+ zDisableProviderResponse,
989
+ zLogoutResponse,
990
+ zNewSessionResponse,
991
+ zLoadSessionResponse,
992
+ zListSessionsResponse,
993
+ zDeleteSessionResponse,
994
+ zForkSessionResponse,
995
+ zResumeSessionResponse,
996
+ zCloseSessionResponse,
997
+ zSetSessionModeResponse,
998
+ zSetSessionConfigOptionResponse,
999
+ zPromptResponse,
1000
+ zStartNesResponse,
1001
+ zSuggestNesResponse,
1002
+ zCloseNesResponse,
1003
+ zExtResponse,
1004
+ zMessageMcpResponse
1005
+ ])
1006
+ }),
1007
+ object({
1008
+ id: zRequestId,
1009
+ error: zError
1010
+ })
1011
+ ]);
1012
+ const zMessageId = string();
1013
+ const zContentChunk = object({
1014
+ content: zContentBlock,
1015
+ messageId: defaultOnError(zMessageId.nullish(), () => void 0),
1016
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1017
+ });
1018
+ const zToolCall = object({
1019
+ toolCallId: zToolCallId,
1020
+ title: string(),
1021
+ name: defaultOnError(string().nullish(), () => void 0),
1022
+ kind: defaultOnError(zToolKind.optional(), () => void 0),
1023
+ status: defaultOnError(zToolCallStatus.optional(), () => void 0),
1024
+ content: defaultOnError(vecSkipError(zToolCallContent).optional(), () => []),
1025
+ locations: defaultOnError(vecSkipError(zToolCallLocation).optional(), () => []),
1026
+ rawInput: defaultOnError(unknown().optional(), () => void 0),
1027
+ rawOutput: defaultOnError(unknown().optional(), () => void 0),
1028
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1029
+ });
1030
+ const zPlanEntryPriority = union([
1031
+ literal("high"),
1032
+ literal("medium"),
1033
+ literal("low")
1034
+ ]);
1035
+ const zPlanEntryStatus = union([
1036
+ literal("pending"),
1037
+ literal("in_progress"),
1038
+ literal("completed")
1039
+ ]);
1040
+ const zPlanEntry = object({
1041
+ content: string(),
1042
+ priority: zPlanEntryPriority,
1043
+ status: zPlanEntryStatus,
1044
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1045
+ });
1046
+ const zPlan = object({
1047
+ entries: requiredDefaultOnError(vecSkipError(zPlanEntry), () => []),
1048
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1049
+ });
1050
+ const zPlanId = string();
1051
+ const zPlanItems = object({
1052
+ planId: zPlanId,
1053
+ entries: requiredDefaultOnError(vecSkipError(zPlanEntry), () => []),
1054
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1055
+ });
1056
+ const zPlanFile = object({
1057
+ planId: zPlanId,
1058
+ uri: string(),
1059
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1060
+ });
1061
+ const zPlanMarkdown = object({
1062
+ planId: zPlanId,
1063
+ content: string(),
1064
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1065
+ });
1066
+ const zPlanUpdateContent = union([
1067
+ zPlanItems.and(object({
1068
+ type: literal("items")
1069
+ })),
1070
+ zPlanFile.and(object({
1071
+ type: literal("file")
1072
+ })),
1073
+ zPlanMarkdown.and(object({
1074
+ type: literal("markdown")
1075
+ }))
1076
+ ]);
1077
+ const zPlanUpdate = object({
1078
+ plan: zPlanUpdateContent,
1079
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1080
+ });
1081
+ const zPlanRemoved = object({
1082
+ planId: zPlanId,
1083
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1084
+ });
1085
+ const zUnstructuredCommandInput = object({
1086
+ hint: string(),
1087
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1088
+ });
1089
+ const zAvailableCommandInput = zUnstructuredCommandInput;
1090
+ const zAvailableCommand = object({
1091
+ name: string(),
1092
+ description: string(),
1093
+ input: defaultOnError(zAvailableCommandInput.nullish(), () => void 0),
1094
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1095
+ });
1096
+ const zAvailableCommandsUpdate = object({
1097
+ availableCommands: requiredDefaultOnError(vecSkipError(zAvailableCommand), () => []),
1098
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1099
+ });
1100
+ const zCurrentModeUpdate = object({
1101
+ currentModeId: zSessionModeId,
1102
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1103
+ });
1104
+ const zConfigOptionUpdate = object({
1105
+ configOptions: requiredDefaultOnError(vecSkipError(zSessionConfigOption), () => []),
1106
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1107
+ });
1108
+ const zSessionInfoUpdate = object({
1109
+ title: defaultOnError(string().nullish(), () => void 0),
1110
+ updatedAt: defaultOnError(string().nullish(), () => void 0),
1111
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1112
+ });
1113
+ const zCost = object({
1114
+ amount: number(),
1115
+ currency: string(),
1116
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1117
+ });
1118
+ const zUsageUpdate = object({
1119
+ used: number(),
1120
+ size: number(),
1121
+ cost: defaultOnError(zCost.nullish(), () => void 0),
1122
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1123
+ });
1124
+ const zSessionUpdate = union([
1125
+ zContentChunk.and(object({
1126
+ sessionUpdate: literal("user_message_chunk")
1127
+ })),
1128
+ zContentChunk.and(object({
1129
+ sessionUpdate: literal("agent_message_chunk")
1130
+ })),
1131
+ zContentChunk.and(object({
1132
+ sessionUpdate: literal("agent_thought_chunk")
1133
+ })),
1134
+ zToolCall.and(object({
1135
+ sessionUpdate: literal("tool_call")
1136
+ })),
1137
+ zToolCallUpdate.and(object({
1138
+ sessionUpdate: literal("tool_call_update")
1139
+ })),
1140
+ zPlan.and(object({
1141
+ sessionUpdate: literal("plan")
1142
+ })),
1143
+ zPlanUpdate.and(object({
1144
+ sessionUpdate: literal("plan_update")
1145
+ })),
1146
+ zPlanRemoved.and(object({
1147
+ sessionUpdate: literal("plan_removed")
1148
+ })),
1149
+ zAvailableCommandsUpdate.and(object({
1150
+ sessionUpdate: literal("available_commands_update")
1151
+ })),
1152
+ zCurrentModeUpdate.and(object({
1153
+ sessionUpdate: literal("current_mode_update")
1154
+ })),
1155
+ zConfigOptionUpdate.and(object({
1156
+ sessionUpdate: literal("config_option_update")
1157
+ })),
1158
+ zSessionInfoUpdate.and(object({
1159
+ sessionUpdate: literal("session_info_update")
1160
+ })),
1161
+ zUsageUpdate.and(object({
1162
+ sessionUpdate: literal("usage_update")
1163
+ }))
1164
+ ]);
1165
+ const zSessionNotification = object({
1166
+ sessionId: zSessionId,
1167
+ update: zSessionUpdate,
1168
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1169
+ });
1170
+ const zCompleteElicitationNotification = object({
1171
+ elicitationId: zElicitationId,
1172
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1173
+ });
1174
+ const zMessageMcpNotification = object({
1175
+ connectionId: zMcpConnectionId,
1176
+ method: string(),
1177
+ params: defaultOnError(record(string(), unknown()).nullish(), () => void 0),
1178
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1179
+ });
1180
+ const zExtNotification = unknown();
1181
+ object({
1182
+ method: string(),
1183
+ params: union([
1184
+ zSessionNotification,
1185
+ zCompleteElicitationNotification,
1186
+ zMessageMcpNotification,
1187
+ zExtNotification
1188
+ ]).nullish()
1189
+ });
1190
+ const zFileSystemCapabilities = object({
1191
+ readTextFile: defaultOnError(boolean().optional().default(false), () => false),
1192
+ writeTextFile: defaultOnError(boolean().optional().default(false), () => false),
1193
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1194
+ });
1195
+ const zBooleanConfigOptionCapabilities = object({
1196
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1197
+ });
1198
+ const zSessionConfigOptionsCapabilities = object({
1199
+ boolean: defaultOnError(zBooleanConfigOptionCapabilities.nullish(), () => void 0),
1200
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1201
+ });
1202
+ const zClientSessionCapabilities = object({
1203
+ configOptions: defaultOnError(zSessionConfigOptionsCapabilities.nullish(), () => void 0),
1204
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1205
+ });
1206
+ const zPlanCapabilities = object({
1207
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1208
+ });
1209
+ const zAuthCapabilities = object({
1210
+ terminal: defaultOnError(boolean().optional().default(false), () => false),
1211
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1212
+ });
1213
+ const zElicitationFormCapabilities = object({
1214
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1215
+ });
1216
+ const zElicitationUrlCapabilities = object({
1217
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1218
+ });
1219
+ const zElicitationCapabilities = object({
1220
+ form: defaultOnError(zElicitationFormCapabilities.nullish(), () => void 0),
1221
+ url: defaultOnError(zElicitationUrlCapabilities.nullish(), () => void 0),
1222
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1223
+ });
1224
+ const zNesJumpCapabilities = object({
1225
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1226
+ });
1227
+ const zNesRenameCapabilities = object({
1228
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1229
+ });
1230
+ const zNesSearchAndReplaceCapabilities = object({
1231
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1232
+ });
1233
+ const zClientNesCapabilities = object({
1234
+ jump: defaultOnError(zNesJumpCapabilities.nullish(), () => void 0),
1235
+ rename: defaultOnError(zNesRenameCapabilities.nullish(), () => void 0),
1236
+ searchAndReplace: defaultOnError(zNesSearchAndReplaceCapabilities.nullish(), () => void 0),
1237
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1238
+ });
1239
+ const zClientCapabilities = object({
1240
+ fs: defaultOnError(zFileSystemCapabilities.optional().default({ readTextFile: false, writeTextFile: false }), () => ({ readTextFile: false, writeTextFile: false })),
1241
+ terminal: defaultOnError(boolean().optional().default(false), () => false),
1242
+ session: defaultOnError(zClientSessionCapabilities.nullish(), () => void 0),
1243
+ plan: defaultOnError(zPlanCapabilities.nullish(), () => void 0),
1244
+ auth: defaultOnError(zAuthCapabilities.optional().default({ terminal: false }), () => ({ terminal: false })),
1245
+ elicitation: defaultOnError(zElicitationCapabilities.nullish(), () => void 0),
1246
+ nes: defaultOnError(zClientNesCapabilities.nullish(), () => void 0),
1247
+ positionEncodings: defaultOnError(vecSkipError(zPositionEncodingKind).optional(), () => []),
1248
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1249
+ });
1250
+ const zInitializeRequest = object({
1251
+ protocolVersion: zProtocolVersion,
1252
+ clientCapabilities: defaultOnError(zClientCapabilities.optional().default({
1253
+ fs: { readTextFile: false, writeTextFile: false },
1254
+ terminal: false,
1255
+ auth: { terminal: false }
1256
+ }), () => ({
1257
+ fs: { readTextFile: false, writeTextFile: false },
1258
+ terminal: false,
1259
+ auth: { terminal: false }
1260
+ })),
1261
+ clientInfo: defaultOnError(zImplementation.nullish(), () => void 0),
1262
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1263
+ });
1264
+ const zAuthenticateRequest = object({
1265
+ methodId: zAuthMethodId,
1266
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1267
+ });
1268
+ const zListProvidersRequest = object({
1269
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1270
+ });
1271
+ const zSetProviderRequest = object({
1272
+ providerId: zProviderId,
1273
+ apiType: zLlmProtocol,
1274
+ baseUrl: string(),
1275
+ headers: record(string(), string()).optional(),
1276
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1277
+ });
1278
+ const zDisableProviderRequest = object({
1279
+ providerId: zProviderId,
1280
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1281
+ });
1282
+ const zLogoutRequest = object({
1283
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1284
+ });
1285
+ const zHttpHeader = object({
1286
+ name: string(),
1287
+ value: string(),
1288
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1289
+ });
1290
+ const zMcpServerHttp = object({
1291
+ name: string(),
1292
+ url: string(),
1293
+ headers: array(zHttpHeader),
1294
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1295
+ });
1296
+ const zMcpServerSse = object({
1297
+ name: string(),
1298
+ url: string(),
1299
+ headers: array(zHttpHeader),
1300
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1301
+ });
1302
+ const zMcpServerAcp = object({
1303
+ name: string(),
1304
+ serverId: zMcpServerAcpId,
1305
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1306
+ });
1307
+ const zMcpServerStdio = object({
1308
+ name: string(),
1309
+ command: string(),
1310
+ args: array(string()),
1311
+ env: array(zEnvVariable),
1312
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1313
+ });
1314
+ const zMcpServer = union([
1315
+ zMcpServerHttp.and(object({
1316
+ type: literal("http")
1317
+ })),
1318
+ zMcpServerSse.and(object({
1319
+ type: literal("sse")
1320
+ })),
1321
+ zMcpServerAcp.and(object({
1322
+ type: literal("acp")
1323
+ })),
1324
+ zMcpServerStdio
1325
+ ]);
1326
+ const zNewSessionRequest = object({
1327
+ cwd: string(),
1328
+ additionalDirectories: defaultOnError(vecSkipError(string()).optional(), () => []),
1329
+ mcpServers: requiredDefaultOnError(vecSkipError(zMcpServer), () => []),
1330
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1331
+ });
1332
+ const zLoadSessionRequest = object({
1333
+ mcpServers: requiredDefaultOnError(vecSkipError(zMcpServer), () => []),
1334
+ cwd: string(),
1335
+ additionalDirectories: defaultOnError(vecSkipError(string()).optional(), () => []),
1336
+ sessionId: zSessionId,
1337
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1338
+ });
1339
+ const zListSessionsRequest = object({
1340
+ cwd: string().nullish(),
1341
+ cursor: string().nullish(),
1342
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1343
+ });
1344
+ const zDeleteSessionRequest = object({
1345
+ sessionId: zSessionId,
1346
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1347
+ });
1348
+ const zForkSessionRequest = object({
1349
+ sessionId: zSessionId,
1350
+ cwd: string(),
1351
+ additionalDirectories: defaultOnError(vecSkipError(string()).optional(), () => []),
1352
+ mcpServers: defaultOnError(vecSkipError(zMcpServer).optional(), () => []),
1353
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1354
+ });
1355
+ const zResumeSessionRequest = object({
1356
+ sessionId: zSessionId,
1357
+ cwd: string(),
1358
+ additionalDirectories: defaultOnError(vecSkipError(string()).optional(), () => []),
1359
+ mcpServers: defaultOnError(vecSkipError(zMcpServer).optional(), () => []),
1360
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1361
+ });
1362
+ const zCloseSessionRequest = object({
1363
+ sessionId: zSessionId,
1364
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1365
+ });
1366
+ const zSetSessionModeRequest = object({
1367
+ sessionId: zSessionId,
1368
+ modeId: zSessionModeId,
1369
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1370
+ });
1371
+ const zSetSessionConfigOptionRequest = intersection(union([
1372
+ object({
1373
+ value: boolean(),
1374
+ type: literal("boolean")
1375
+ }),
1376
+ object({
1377
+ value: zSessionConfigValueId
1378
+ })
1379
+ ]), object({
1380
+ sessionId: zSessionId,
1381
+ configId: zSessionConfigId,
1382
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1383
+ }));
1384
+ const zPromptRequest = object({
1385
+ sessionId: zSessionId,
1386
+ prompt: array(zContentBlock),
1387
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1388
+ });
1389
+ const zWorkspaceFolder = object({
1390
+ uri: string(),
1391
+ name: string(),
1392
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1393
+ });
1394
+ const zNesRepository = object({
1395
+ name: string(),
1396
+ owner: string(),
1397
+ remoteUrl: string(),
1398
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1399
+ });
1400
+ const zStartNesRequest = object({
1401
+ workspaceUri: defaultOnError(string().nullish(), () => void 0),
1402
+ workspaceFolders: array(zWorkspaceFolder).nullish(),
1403
+ repository: defaultOnError(zNesRepository.nullish(), () => void 0),
1404
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1405
+ });
1406
+ const zNesTriggerKind = union([
1407
+ literal("automatic"),
1408
+ literal("diagnostic"),
1409
+ literal("manual")
1410
+ ]);
1411
+ const zNesRecentFile = object({
1412
+ uri: string(),
1413
+ languageId: string(),
1414
+ text: string(),
1415
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1416
+ });
1417
+ const zNesExcerpt = object({
1418
+ startLine: int().gte(0).max(4294967295, {
1419
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
1420
+ }),
1421
+ endLine: int().gte(0).max(4294967295, {
1422
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
1423
+ }),
1424
+ text: string(),
1425
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1426
+ });
1427
+ const zNesRelatedSnippet = object({
1428
+ uri: string(),
1429
+ excerpts: array(zNesExcerpt),
1430
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1431
+ });
1432
+ const zNesEditHistoryEntry = object({
1433
+ uri: string(),
1434
+ diff: string(),
1435
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1436
+ });
1437
+ const zNesUserAction = object({
1438
+ action: string(),
1439
+ uri: string(),
1440
+ position: zPosition,
1441
+ timestampMs: number(),
1442
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1443
+ });
1444
+ const zNesOpenFile = object({
1445
+ uri: string(),
1446
+ languageId: string(),
1447
+ visibleRange: defaultOnError(zRange.nullish(), () => void 0),
1448
+ lastFocusedMs: defaultOnError(number().nullish(), () => void 0),
1449
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1450
+ });
1451
+ const zNesDiagnosticSeverity = union([
1452
+ literal("error"),
1453
+ literal("warning"),
1454
+ literal("information"),
1455
+ literal("hint")
1456
+ ]);
1457
+ const zNesDiagnostic = object({
1458
+ uri: string(),
1459
+ range: zRange,
1460
+ severity: zNesDiagnosticSeverity,
1461
+ message: string(),
1462
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1463
+ });
1464
+ const zNesSuggestContext = object({
1465
+ recentFiles: array(zNesRecentFile).nullish(),
1466
+ relatedSnippets: array(zNesRelatedSnippet).nullish(),
1467
+ editHistory: array(zNesEditHistoryEntry).nullish(),
1468
+ userActions: array(zNesUserAction).nullish(),
1469
+ openFiles: array(zNesOpenFile).nullish(),
1470
+ diagnostics: array(zNesDiagnostic).nullish(),
1471
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1472
+ });
1473
+ const zSuggestNesRequest = object({
1474
+ sessionId: zSessionId,
1475
+ uri: string(),
1476
+ version: number(),
1477
+ position: zPosition,
1478
+ selection: zRange.nullish(),
1479
+ triggerKind: zNesTriggerKind,
1480
+ context: zNesSuggestContext.nullish(),
1481
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1482
+ });
1483
+ const zCloseNesRequest = object({
1484
+ sessionId: zSessionId,
1485
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1486
+ });
1487
+ object({
1488
+ id: zRequestId,
1489
+ method: string(),
1490
+ params: union([
1491
+ zInitializeRequest,
1492
+ zAuthenticateRequest,
1493
+ zListProvidersRequest,
1494
+ zSetProviderRequest,
1495
+ zDisableProviderRequest,
1496
+ zLogoutRequest,
1497
+ zNewSessionRequest,
1498
+ zLoadSessionRequest,
1499
+ zListSessionsRequest,
1500
+ zDeleteSessionRequest,
1501
+ zForkSessionRequest,
1502
+ zResumeSessionRequest,
1503
+ zCloseSessionRequest,
1504
+ zSetSessionModeRequest,
1505
+ zSetSessionConfigOptionRequest,
1506
+ zPromptRequest,
1507
+ zStartNesRequest,
1508
+ zSuggestNesRequest,
1509
+ zCloseNesRequest,
1510
+ zMessageMcpRequest,
1511
+ zExtRequest
1512
+ ]).nullish()
1513
+ });
1514
+ const zWriteTextFileResponse = object({
1515
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1516
+ });
1517
+ const zReadTextFileResponse = object({
1518
+ content: string(),
1519
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1520
+ });
1521
+ const zSelectedPermissionOutcome = object({
1522
+ optionId: zPermissionOptionId,
1523
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1524
+ });
1525
+ const zRequestPermissionOutcome = union([
1526
+ object({
1527
+ outcome: literal("cancelled")
1528
+ }),
1529
+ zSelectedPermissionOutcome.and(object({
1530
+ outcome: literal("selected")
1531
+ }))
1532
+ ]);
1533
+ const zRequestPermissionResponse = object({
1534
+ outcome: zRequestPermissionOutcome,
1535
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1536
+ });
1537
+ const zCreateTerminalResponse = object({
1538
+ terminalId: zTerminalId,
1539
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1540
+ });
1541
+ const zTerminalExitStatus = object({
1542
+ exitCode: defaultOnError(int().gte(0).max(4294967295, {
1543
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
1544
+ }).nullish(), () => void 0),
1545
+ signal: defaultOnError(string().nullish(), () => void 0),
1546
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1547
+ });
1548
+ const zTerminalOutputResponse = object({
1549
+ output: string(),
1550
+ truncated: boolean(),
1551
+ exitStatus: defaultOnError(zTerminalExitStatus.nullish(), () => void 0),
1552
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1553
+ });
1554
+ const zReleaseTerminalResponse = object({
1555
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1556
+ });
1557
+ const zWaitForTerminalExitResponse = object({
1558
+ exitCode: defaultOnError(int().gte(0).max(4294967295, {
1559
+ error: "Invalid value: Expected uint32 to be <= 4294967295"
1560
+ }).nullish(), () => void 0),
1561
+ signal: defaultOnError(string().nullish(), () => void 0),
1562
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1563
+ });
1564
+ const zKillTerminalResponse = object({
1565
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1566
+ });
1567
+ const zElicitationContentValue = union([
1568
+ string(),
1569
+ number(),
1570
+ number(),
1571
+ boolean(),
1572
+ array(string())
1573
+ ]);
1574
+ const zElicitationAcceptAction = object({
1575
+ content: record(string(), zElicitationContentValue).nullish()
1576
+ });
1577
+ const zCreateElicitationResponse = preserveCustomPayload(intersection(union([
1578
+ zElicitationAcceptAction.and(object({
1579
+ action: literal("accept")
1580
+ })),
1581
+ object({
1582
+ action: literal("decline")
1583
+ }),
1584
+ object({
1585
+ action: literal("cancel")
1586
+ }),
1587
+ excludeKnownTags(object({
1588
+ action: string()
1589
+ }), "action", ["accept", "cancel", "decline"])
1590
+ ]), object({
1591
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1592
+ })), "action", ["accept", "cancel", "decline"]);
1593
+ const zConnectMcpResponse = object({
1594
+ connectionId: zMcpConnectionId,
1595
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1596
+ });
1597
+ const zDisconnectMcpResponse = object({
1598
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1599
+ });
1600
+ union([
1601
+ object({
1602
+ id: zRequestId,
1603
+ result: union([
1604
+ zWriteTextFileResponse,
1605
+ zReadTextFileResponse,
1606
+ zRequestPermissionResponse,
1607
+ zCreateTerminalResponse,
1608
+ zTerminalOutputResponse,
1609
+ zReleaseTerminalResponse,
1610
+ zWaitForTerminalExitResponse,
1611
+ zKillTerminalResponse,
1612
+ zCreateElicitationResponse,
1613
+ zConnectMcpResponse,
1614
+ zDisconnectMcpResponse,
1615
+ zMessageMcpResponse,
1616
+ zExtResponse
1617
+ ])
1618
+ }),
1619
+ object({
1620
+ id: zRequestId,
1621
+ error: zError
1622
+ })
1623
+ ]);
1624
+ const zCancelNotification = object({
1625
+ sessionId: zSessionId,
1626
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1627
+ });
1628
+ const zDidOpenDocumentNotification = object({
1629
+ sessionId: zSessionId,
1630
+ uri: string(),
1631
+ languageId: string(),
1632
+ version: number(),
1633
+ text: string(),
1634
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1635
+ });
1636
+ const zTextDocumentContentChangeEvent = object({
1637
+ range: zRange.nullish(),
1638
+ text: string(),
1639
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1640
+ });
1641
+ const zDidChangeDocumentNotification = object({
1642
+ sessionId: zSessionId,
1643
+ uri: string(),
1644
+ version: number(),
1645
+ contentChanges: requiredDefaultOnError(vecSkipError(zTextDocumentContentChangeEvent), () => []),
1646
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1647
+ });
1648
+ const zDidCloseDocumentNotification = object({
1649
+ sessionId: zSessionId,
1650
+ uri: string(),
1651
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1652
+ });
1653
+ const zDidSaveDocumentNotification = object({
1654
+ sessionId: zSessionId,
1655
+ uri: string(),
1656
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1657
+ });
1658
+ const zDidFocusDocumentNotification = object({
1659
+ sessionId: zSessionId,
1660
+ uri: string(),
1661
+ version: number(),
1662
+ position: zPosition,
1663
+ visibleRange: zRange,
1664
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1665
+ });
1666
+ const zAcceptNesNotification = object({
1667
+ sessionId: zSessionId,
1668
+ id: zNesSuggestionId,
1669
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1670
+ });
1671
+ const zNesRejectReason = union([
1672
+ literal("rejected"),
1673
+ literal("ignored"),
1674
+ literal("replaced"),
1675
+ literal("cancelled")
1676
+ ]);
1677
+ const zRejectNesNotification = object({
1678
+ sessionId: zSessionId,
1679
+ id: zNesSuggestionId,
1680
+ reason: defaultOnError(zNesRejectReason.nullish(), () => void 0),
1681
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1682
+ });
1683
+ object({
1684
+ method: string(),
1685
+ params: union([
1686
+ zCancelNotification,
1687
+ zDidOpenDocumentNotification,
1688
+ zDidChangeDocumentNotification,
1689
+ zDidCloseDocumentNotification,
1690
+ zDidSaveDocumentNotification,
1691
+ zDidFocusDocumentNotification,
1692
+ zAcceptNesNotification,
1693
+ zRejectNesNotification,
1694
+ zMessageMcpNotification,
1695
+ zExtNotification
1696
+ ]).nullish()
1697
+ });
1698
+ object({
1699
+ requestId: zRequestId,
1700
+ _meta: defaultOnError(record(string(), unknown()).nullish(), () => void 0)
1701
+ });
1702
+ const CANCEL_REQUEST_METHOD = "$/cancel_request";
1703
+ function isRequestMessage(value) {
1704
+ return isJsonRpcEnvelope(value) && "id" in value && typeof value["method"] === "string" && isJsonRpcId(value["id"]);
1705
+ }
1706
+ function isResponseMessage(value) {
1707
+ if (!isJsonRpcEnvelope(value) || "method" in value) {
1708
+ return false;
1709
+ }
1710
+ if (!("id" in value) || !isJsonRpcId(value["id"])) {
1711
+ return false;
1712
+ }
1713
+ const hasResult = Object.hasOwn(value, "result");
1714
+ const hasError = Object.hasOwn(value, "error");
1715
+ if (hasResult === hasError) {
1716
+ return false;
1717
+ }
1718
+ return !hasError || isErrorResponse(value["error"]);
1719
+ }
1720
+ function isNotificationMessage(value) {
1721
+ return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
1722
+ }
1723
+ function isRecord(value) {
1724
+ return typeof value === "object" && value !== null;
1725
+ }
1726
+ function isJsonRpcEnvelope(value) {
1727
+ return isRecord(value) && value["jsonrpc"] === "2.0";
1728
+ }
1729
+ function isJsonRpcId(value) {
1730
+ return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
1731
+ }
1732
+ function isResponseShapedMessage(value) {
1733
+ return isRecord(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
1734
+ }
1735
+ function isResponseBatch(batch) {
1736
+ let hasValidCall = false;
1737
+ let hasValidResponse = false;
1738
+ let hasCallShape = false;
1739
+ let hasResponseShape = false;
1740
+ for (const entry of batch) {
1741
+ hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
1742
+ hasValidResponse ||= isResponseMessage(entry);
1743
+ if (!isRecord(entry)) {
1744
+ continue;
1745
+ }
1746
+ hasCallShape ||= "method" in entry;
1747
+ hasResponseShape ||= "result" in entry || "error" in entry;
1748
+ }
1749
+ if (hasValidCall) {
1750
+ return false;
1751
+ }
1752
+ if (hasValidResponse) {
1753
+ return true;
1754
+ }
1755
+ return hasResponseShape && !hasCallShape;
1756
+ }
1757
+ function cancelRequestId(params) {
1758
+ if (!isRecord(params) || !isJsonRpcId(params["requestId"])) {
1759
+ return void 0;
1760
+ }
1761
+ return params["requestId"];
1762
+ }
1763
+ function isErrorResponse(value) {
1764
+ return isRecord(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
1765
+ }
1766
+ const Handled = {
1767
+ /**
1768
+ * Marks a message as handled.
1769
+ */
1770
+ yes() {
1771
+ return { handled: true };
1772
+ },
1773
+ /**
1774
+ * Leaves a message unhandled so later handlers can process it.
1775
+ */
1776
+ no(message, retry = false) {
1777
+ return { handled: false, message, retry };
1778
+ }
1779
+ };
1780
+ function rejectedPromise(error) {
1781
+ const promise = Promise.reject(error);
1782
+ promise.catch(() => {
1783
+ });
1784
+ return promise;
1785
+ }
1786
+ function errorDetails(error) {
1787
+ if (error instanceof Error) {
1788
+ return error.message;
1789
+ }
1790
+ if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
1791
+ return error.message;
1792
+ }
1793
+ return void 0;
1794
+ }
1795
+ function isZodError(error) {
1796
+ return typeof error === "object" && error !== null && "name" in error && error.name === "ZodError" && "issues" in error && Array.isArray(error.issues) && "format" in error && typeof error.format === "function";
1797
+ }
1798
+ function errorToResult(error) {
1799
+ if (error instanceof RequestError) {
1800
+ return error.toResult();
1801
+ }
1802
+ if (isZodError(error)) {
1803
+ return RequestError.invalidParams(error.format()).toResult();
1804
+ }
1805
+ const details = errorDetails(error);
1806
+ try {
1807
+ return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
1808
+ } catch {
1809
+ return RequestError.internalError({ details }).toResult();
1810
+ }
1811
+ }
1812
+ function requestCancelledError(reason) {
1813
+ if (reason instanceof RequestError && reason.code === -32800) {
1814
+ return reason;
1815
+ }
1816
+ return RequestError.requestCancelled(reason);
1817
+ }
1818
+ function errorToRequestResult(error, signal) {
1819
+ const requestCancelled = abortErrorToRequestCancelled(error, signal);
1820
+ return requestCancelled ? requestCancelled.toResult() : errorToResult(error);
1821
+ }
1822
+ function abortErrorToRequestCancelled(error, signal) {
1823
+ if (!signal.aborted || !isAbortError(error)) {
1824
+ return void 0;
1825
+ }
1826
+ return requestCancelledError(signal.reason);
1827
+ }
1828
+ function isAbortError(error) {
1829
+ if (typeof error !== "object" || error === null) {
1830
+ return false;
1831
+ }
1832
+ const maybeAbortError = error;
1833
+ return maybeAbortError.name === "AbortError" || maybeAbortError.code === "ABORT_ERR";
1834
+ }
1835
+ class RequestResponder {
1836
+ id;
1837
+ sendResult;
1838
+ signal;
1839
+ finishRequest;
1840
+ didRespond = false;
1841
+ constructor(id, sendResult, signal = new AbortController().signal, finishRequest) {
1842
+ this.id = id;
1843
+ this.sendResult = sendResult;
1844
+ this.signal = signal;
1845
+ this.finishRequest = finishRequest;
1846
+ }
1847
+ /**
1848
+ * Whether this request has already received a response.
1849
+ */
1850
+ get responded() {
1851
+ return this.didRespond;
1852
+ }
1853
+ /**
1854
+ * Sends a successful JSON-RPC response.
1855
+ */
1856
+ respond(response) {
1857
+ return this.respondWithResult({ result: response ?? null });
1858
+ }
1859
+ /**
1860
+ * Sends an error JSON-RPC response.
1861
+ */
1862
+ respondWithError(error) {
1863
+ const errorResponse = error instanceof RequestError ? error.toErrorResponse() : error;
1864
+ return this.respondWithResult({ error: errorResponse });
1865
+ }
1866
+ /**
1867
+ * Sends a complete JSON-RPC result payload.
1868
+ */
1869
+ respondWithResult(result) {
1870
+ if (this.didRespond) {
1871
+ return rejectedPromise(new Error("JSON-RPC request already responded"));
1872
+ }
1873
+ this.didRespond = true;
1874
+ return this.sendResult(result).finally(() => {
1875
+ this.finishRequest?.();
1876
+ });
1877
+ }
1878
+ }
1879
+ class HandlerRegistration {
1880
+ disposeHandler;
1881
+ active = true;
1882
+ constructor(disposeHandler) {
1883
+ this.disposeHandler = disposeHandler;
1884
+ }
1885
+ /**
1886
+ * Unregisters the associated handler.
1887
+ */
1888
+ dispose() {
1889
+ if (!this.active) {
1890
+ return;
1891
+ }
1892
+ this.active = false;
1893
+ this.disposeHandler();
1894
+ }
1895
+ /**
1896
+ * Supports explicit resource management with `using`.
1897
+ */
1898
+ [Symbol.dispose]() {
1899
+ this.dispose();
1900
+ }
1901
+ /**
1902
+ * Returns this registration for call sites that intentionally keep it active.
1903
+ */
1904
+ runIndefinitely() {
1905
+ return this;
1906
+ }
1907
+ }
1908
+ class ConnectionContext {
1909
+ connection;
1910
+ constructor(connection) {
1911
+ this.connection = connection;
1912
+ }
1913
+ /**
1914
+ * Sends a request over the connection.
1915
+ */
1916
+ sendRequest(method, params, mapResponse, options) {
1917
+ return this.connection.sendRequest(method, params, mapResponse, options);
1918
+ }
1919
+ /**
1920
+ * Sends a notification over the connection.
1921
+ */
1922
+ sendNotification(method, params) {
1923
+ return this.connection.sendNotification(method, params);
1924
+ }
1925
+ /**
1926
+ * Sends a non-empty JSON-RPC batch in one transport message.
1927
+ */
1928
+ sendBatch(entries) {
1929
+ return this.connection.sendBatch(entries);
1930
+ }
1931
+ /**
1932
+ * Sends a protocol-level request cancellation notification.
1933
+ */
1934
+ sendCancelRequest(requestId) {
1935
+ return this.connection.sendCancelRequest(requestId);
1936
+ }
1937
+ /**
1938
+ * Registers a handler that can be disposed independently.
1939
+ */
1940
+ addDynamicHandler(handler) {
1941
+ return this.connection.addDynamicHandler(handler);
1942
+ }
1943
+ /**
1944
+ * AbortSignal that aborts when the connection closes.
1945
+ */
1946
+ get signal() {
1947
+ return this.connection.signal;
1948
+ }
1949
+ /**
1950
+ * Promise that resolves when the connection closes.
1951
+ */
1952
+ get closed() {
1953
+ return this.connection.closed;
1954
+ }
1955
+ }
1956
+ class Connection {
1957
+ pendingResponses = /* @__PURE__ */ new Map();
1958
+ incomingRequests = /* @__PURE__ */ new Map();
1959
+ nextRequestId = 0;
1960
+ staticHandlers = [];
1961
+ dynamicHandlers = /* @__PURE__ */ new Set();
1962
+ stream;
1963
+ writeQueue = Promise.resolve();
1964
+ abortController = new AbortController();
1965
+ closedPromise;
1966
+ retryQueue = [];
1967
+ context = new ConnectionContext(this);
1968
+ receiveReader;
1969
+ allowBatches = true;
1970
+ constructor(requestHandlerOrStream, notificationHandlerOrHandlers, streamOrOptions, options) {
1971
+ if (typeof requestHandlerOrStream === "function") {
1972
+ const requestHandler = requestHandlerOrStream;
1973
+ const notificationHandler = notificationHandlerOrHandlers;
1974
+ const stream2 = streamOrOptions;
1975
+ this.initialize(stream2, [
1976
+ ...options?.handlers ?? [],
1977
+ this.legacyHandler(requestHandler, notificationHandler)
1978
+ ], options);
1979
+ return;
1980
+ }
1981
+ const stream = requestHandlerOrStream;
1982
+ const handlers = notificationHandlerOrHandlers;
1983
+ const connectionOptions = streamOrOptions;
1984
+ this.initialize(stream, [...connectionOptions?.handlers ?? [], ...handlers], connectionOptions);
1985
+ }
1986
+ /**
1987
+ * Creates a builder for configuring a handler-based connection.
1988
+ */
1989
+ static builder() {
1990
+ return new ConnectionBuilder();
1991
+ }
1992
+ /**
1993
+ * Runs an operation while the connection is open, then closes the connection.
1994
+ *
1995
+ * If the stream closes before `op` settles, the returned promise rejects with
1996
+ * the connection close reason.
1997
+ */
1998
+ runUntil(op) {
1999
+ let opSettled = false;
2000
+ const opPromise = Promise.resolve().then(() => op(this.context)).finally(() => {
2001
+ opSettled = true;
2002
+ });
2003
+ const closedPromise = this.closed.then(() => {
2004
+ if (opSettled) {
2005
+ return new Promise(() => {
2006
+ });
2007
+ }
2008
+ throw this.closedReason();
2009
+ });
2010
+ return Promise.race([opPromise, closedPromise]).finally(() => {
2011
+ opSettled = true;
2012
+ this.close();
2013
+ });
2014
+ }
2015
+ /**
2016
+ * Adds a handler after the connection has started.
2017
+ *
2018
+ * Any messages queued with `Handled.no(message, true)` are retried after the
2019
+ * handler is added.
2020
+ */
2021
+ addDynamicHandler(handler) {
2022
+ this.dynamicHandlers.add(handler);
2023
+ if (this.retryQueue.length > 0) {
2024
+ for (const message of this.retryQueue.splice(0)) {
2025
+ void this.processIncomingMessage(message).catch((error) => this.close(error));
2026
+ }
2027
+ }
2028
+ return new HandlerRegistration(() => {
2029
+ this.dynamicHandlers.delete(handler);
2030
+ });
2031
+ }
2032
+ /**
2033
+ * AbortSignal that aborts when the connection closes.
2034
+ */
2035
+ get signal() {
2036
+ return this.abortController.signal;
2037
+ }
2038
+ /**
2039
+ * Promise that resolves when the connection closes.
2040
+ */
2041
+ get closed() {
2042
+ return this.closedPromise;
2043
+ }
2044
+ /** @internal */
2045
+ getContext() {
2046
+ return this.context;
2047
+ }
2048
+ /**
2049
+ * Sends a JSON-RPC request.
2050
+ *
2051
+ * `mapResponse` can convert the raw result before the returned promise
2052
+ * resolves.
2053
+ */
2054
+ sendRequest(method, params, mapResponse, options = {}) {
2055
+ if (this.abortController.signal.aborted) {
2056
+ return rejectedPromise(this.closedReason());
2057
+ }
2058
+ const request = this.prepareRequest(method, params, mapResponse, options);
2059
+ const requestSent = this.sendWireMessage(request.message);
2060
+ void requestSent.catch(() => {
2061
+ });
2062
+ if (options.cancellationSignal?.aborted) {
2063
+ request.cancel();
2064
+ }
2065
+ return request.response;
2066
+ }
2067
+ /**
2068
+ * Sends a non-empty JSON-RPC batch in one transport message.
2069
+ *
2070
+ * Requests and notifications are processed independently by the peer. The
2071
+ * returned tuple preserves the input order: request entries resolve to their
2072
+ * mapped response, while notification entries resolve to `undefined`.
2073
+ */
2074
+ sendBatch(entries) {
2075
+ if (this.abortController.signal.aborted) {
2076
+ return rejectedPromise(this.closedReason());
2077
+ }
2078
+ if (!this.allowBatches) {
2079
+ return rejectedPromise(new TypeError("JSON-RPC batches are not supported on this connection"));
2080
+ }
2081
+ if (entries.length === 0) {
2082
+ return rejectedPromise(new TypeError("JSON-RPC batch must contain at least one entry"));
2083
+ }
2084
+ const messages = [];
2085
+ const cancellations = [];
2086
+ const outputs = [];
2087
+ for (const entry of entries) {
2088
+ if (entry.kind === "notification") {
2089
+ messages.push({
2090
+ jsonrpc: "2.0",
2091
+ method: entry.method,
2092
+ params: entry.params
2093
+ });
2094
+ outputs.push(Promise.resolve(void 0));
2095
+ continue;
2096
+ }
2097
+ const request = this.prepareRequest(entry.method, entry.params, entry.mapResponse, entry.options);
2098
+ messages.push(request.message);
2099
+ outputs.push(request.response);
2100
+ cancellations.push({
2101
+ signal: entry.options?.cancellationSignal,
2102
+ cancel: request.cancel
2103
+ });
2104
+ }
2105
+ const batch = messages;
2106
+ const batchSent = this.sendWireMessage(batch);
2107
+ for (const cancellation of cancellations) {
2108
+ if (cancellation.signal?.aborted) {
2109
+ cancellation.cancel();
2110
+ }
2111
+ }
2112
+ const response = Promise.all([batchSent, ...outputs]).then(([, ...resolved]) => resolved);
2113
+ response.catch(() => {
2114
+ });
2115
+ return response;
2116
+ }
2117
+ /**
2118
+ * Sends a protocol-level request cancellation notification.
2119
+ */
2120
+ sendCancelRequest(requestId) {
2121
+ return this.sendNotification(CANCEL_REQUEST_METHOD, { requestId });
2122
+ }
2123
+ /**
2124
+ * Sends a JSON-RPC notification.
2125
+ */
2126
+ sendNotification(method, params) {
2127
+ if (this.abortController.signal.aborted) {
2128
+ return rejectedPromise(this.closedReason());
2129
+ }
2130
+ return this.sendWireMessage({ jsonrpc: "2.0", method, params });
2131
+ }
2132
+ prepareRequest(method, params, mapResponse, options = {}) {
2133
+ const id = this.nextRequestId++;
2134
+ let cancel = () => {
2135
+ };
2136
+ const response = new Promise((resolve, reject) => {
2137
+ const pendingResponse = {
2138
+ resolve: (value) => {
2139
+ try {
2140
+ resolve(mapResponse ? mapResponse(value) : value);
2141
+ } catch (error) {
2142
+ reject(error);
2143
+ }
2144
+ },
2145
+ reject
2146
+ };
2147
+ cancel = () => {
2148
+ if (pendingResponse.cancellationSent) {
2149
+ return;
2150
+ }
2151
+ pendingResponse.cancellationSent = true;
2152
+ pendingResponse.cleanup?.();
2153
+ void this.sendCancelRequest(id).catch(() => {
2154
+ });
2155
+ };
2156
+ options.cancellationSignal?.addEventListener("abort", cancel, {
2157
+ once: true
2158
+ });
2159
+ pendingResponse.cleanup = () => {
2160
+ options.cancellationSignal?.removeEventListener("abort", cancel);
2161
+ };
2162
+ this.pendingResponses.set(id, pendingResponse);
2163
+ });
2164
+ response.catch(() => {
2165
+ });
2166
+ return {
2167
+ message: { jsonrpc: "2.0", id, method, params },
2168
+ response,
2169
+ cancel: () => cancel()
2170
+ };
2171
+ }
2172
+ /**
2173
+ * Closes the connection and rejects pending requests.
2174
+ */
2175
+ close(error) {
2176
+ if (this.abortController.signal.aborted) {
2177
+ return;
2178
+ }
2179
+ const closeError = error ?? new Error("ACP connection closed");
2180
+ this.abortController.abort(closeError);
2181
+ for (const pendingResponse of this.pendingResponses.values()) {
2182
+ pendingResponse.cleanup?.();
2183
+ pendingResponse.reject(closeError);
2184
+ }
2185
+ this.pendingResponses.clear();
2186
+ for (const controller of this.incomingRequests.values()) {
2187
+ controller.abort(closeError);
2188
+ }
2189
+ this.incomingRequests.clear();
2190
+ void this.receiveReader?.cancel(closeError).catch(() => {
2191
+ });
2192
+ }
2193
+ initialize(stream, handlers, options) {
2194
+ this.stream = stream;
2195
+ this.staticHandlers = handlers;
2196
+ this.allowBatches = options?.allowBatches ?? true;
2197
+ this.closedPromise = new Promise((resolve) => {
2198
+ this.abortController.signal.addEventListener("abort", () => resolve());
2199
+ });
2200
+ void this.receive();
2201
+ }
2202
+ legacyHandler(requestHandler, notificationHandler) {
2203
+ return {
2204
+ handleMessage: async (message, cx) => {
2205
+ if (message.kind === "request") {
2206
+ const result = await requestHandler(message.method, message.params, cx);
2207
+ await message.responder.respond(result);
2208
+ } else {
2209
+ await notificationHandler(message.method, message.params, cx);
2210
+ }
2211
+ return Handled.yes();
2212
+ }
2213
+ };
2214
+ }
2215
+ async receive() {
2216
+ let closeError = void 0;
2217
+ try {
2218
+ const reader = this.stream.readable.getReader();
2219
+ this.receiveReader = reader;
2220
+ try {
2221
+ while (!this.abortController.signal.aborted) {
2222
+ const { value: message, done } = await reader.read();
2223
+ if (this.abortController.signal.aborted) {
2224
+ break;
2225
+ }
2226
+ if (done) {
2227
+ break;
2228
+ }
2229
+ if (!message) {
2230
+ continue;
2231
+ }
2232
+ this.receiveWireMessage(message);
2233
+ }
2234
+ } finally {
2235
+ if (this.receiveReader === reader) {
2236
+ this.receiveReader = void 0;
2237
+ }
2238
+ reader.releaseLock();
2239
+ }
2240
+ } catch (error) {
2241
+ closeError = error;
2242
+ } finally {
2243
+ this.close(closeError);
2244
+ }
2245
+ }
2246
+ receiveWireMessage(message) {
2247
+ if (Array.isArray(message)) {
2248
+ if (!this.allowBatches) {
2249
+ this.close(new TypeError("JSON-RPC batches are not supported on this connection"));
2250
+ return;
2251
+ }
2252
+ this.receiveBatch(message);
2253
+ return;
2254
+ }
2255
+ if (!isRecord(message)) {
2256
+ console.error("Invalid message", { message });
2257
+ return;
2258
+ }
2259
+ this.receiveMessage(message);
2260
+ }
2261
+ receiveBatch(batch) {
2262
+ if (batch.length === 0) {
2263
+ void this.sendWireMessage({
2264
+ jsonrpc: "2.0",
2265
+ id: null,
2266
+ error: RequestError.invalidRequest(batch).toErrorResponse()
2267
+ }).catch(() => {
2268
+ });
2269
+ return;
2270
+ }
2271
+ const responseBatch = isResponseBatch(batch);
2272
+ const responseCount = responseBatch ? 0 : batch.reduce((count, message) => count + (isNotificationMessage(message) ? 0 : 1), 0);
2273
+ let remaining = responseCount;
2274
+ let remainingNotifications = batch.reduce((count, message) => count + (isNotificationMessage(message) ? 1 : 0), 0);
2275
+ let responseSent = false;
2276
+ const responses = [];
2277
+ const sendResponsesIfReady = async () => {
2278
+ if (responseSent || remaining !== 0 || remainingNotifications !== 0 || responses.length === 0) {
2279
+ return;
2280
+ }
2281
+ responseSent = true;
2282
+ await this.sendWireMessage(responses);
2283
+ };
2284
+ const collectResponse = async (response) => {
2285
+ responses.push(response);
2286
+ remaining -= 1;
2287
+ await sendResponsesIfReady();
2288
+ };
2289
+ for (const message of batch) {
2290
+ if (responseBatch) {
2291
+ if (isResponseShapedMessage(message)) {
2292
+ this.receiveMessage(message);
2293
+ }
2294
+ continue;
2295
+ }
2296
+ if (!isRequestMessage(message) && !isNotificationMessage(message)) {
2297
+ void collectResponse({
2298
+ jsonrpc: "2.0",
2299
+ id: null,
2300
+ error: RequestError.invalidRequest(message).toErrorResponse()
2301
+ }).catch(() => {
2302
+ });
2303
+ continue;
2304
+ }
2305
+ const processing = this.receiveMessage(message, isRequestMessage(message) ? collectResponse : void 0);
2306
+ if (isNotificationMessage(message)) {
2307
+ void processing.finally(() => {
2308
+ remainingNotifications -= 1;
2309
+ void sendResponsesIfReady().catch((error) => this.close(error));
2310
+ });
2311
+ }
2312
+ }
2313
+ }
2314
+ receiveMessage(message, sendResponse) {
2315
+ if (this.abortController.signal.aborted) {
2316
+ return Promise.resolve();
2317
+ }
2318
+ if (!isRecord(message)) {
2319
+ console.error("Invalid message", { message });
2320
+ return Promise.resolve();
2321
+ }
2322
+ if ("method" in message) {
2323
+ if (!("id" in message)) {
2324
+ this.handleProtocolNotification(message);
2325
+ }
2326
+ return this.processIncomingMessage(this.toIncomingMessage(message, sendResponse)).catch((error) => this.close(error));
2327
+ } else if ("id" in message) {
2328
+ this.handleResponse(message);
2329
+ } else {
2330
+ console.error("Invalid message", { message });
2331
+ }
2332
+ return Promise.resolve();
2333
+ }
2334
+ async processIncomingMessage(message) {
2335
+ if (this.abortController.signal.aborted) {
2336
+ return;
2337
+ }
2338
+ let current = message;
2339
+ let retry = false;
2340
+ try {
2341
+ for (const handler of [
2342
+ ...this.staticHandlers,
2343
+ ...this.dynamicHandlers.values()
2344
+ ]) {
2345
+ if (this.abortController.signal.aborted) {
2346
+ return;
2347
+ }
2348
+ const result = await handler.handleMessage(current, this.context) ?? {
2349
+ handled: true
2350
+ };
2351
+ if (result.handled) {
2352
+ return;
2353
+ }
2354
+ current = result.message ?? current;
2355
+ retry = retry || Boolean(result.retry);
2356
+ }
2357
+ if (retry) {
2358
+ this.retryQueue.push(current);
2359
+ } else if (current.kind === "request") {
2360
+ await current.responder.respondWithError(RequestError.methodNotFound(current.method));
2361
+ }
2362
+ } catch (error) {
2363
+ if (this.abortController.signal.aborted) {
2364
+ return;
2365
+ }
2366
+ if (current.kind === "request" && !current.responder.responded) {
2367
+ await current.responder.respondWithResult(errorToRequestResult(error, current.responder.signal));
2368
+ } else {
2369
+ const response = errorToResult(error);
2370
+ if ("error" in response) {
2371
+ console.error("Error handling notification", message.raw, response.error);
2372
+ }
2373
+ }
2374
+ }
2375
+ }
2376
+ toIncomingMessage(message, sendResponse) {
2377
+ if ("id" in message) {
2378
+ const abortController = new AbortController();
2379
+ this.incomingRequests.set(message.id, abortController);
2380
+ const finishRequest = () => {
2381
+ if (this.incomingRequests.get(message.id) === abortController) {
2382
+ this.incomingRequests.delete(message.id);
2383
+ }
2384
+ };
2385
+ return {
2386
+ kind: "request",
2387
+ method: message.method,
2388
+ params: message.params,
2389
+ raw: message,
2390
+ signal: abortController.signal,
2391
+ responder: new RequestResponder(message.id, (result) => {
2392
+ const response = {
2393
+ jsonrpc: "2.0",
2394
+ id: message.id,
2395
+ ...result
2396
+ };
2397
+ return sendResponse ? sendResponse(response) : this.sendWireMessage(response);
2398
+ }, abortController.signal, finishRequest)
2399
+ };
2400
+ }
2401
+ return {
2402
+ kind: "notification",
2403
+ method: message.method,
2404
+ params: message.params,
2405
+ raw: message
2406
+ };
2407
+ }
2408
+ handleResponse(response) {
2409
+ const pendingResponse = this.pendingResponses.get(response.id);
2410
+ if (pendingResponse) {
2411
+ this.pendingResponses.delete(response.id);
2412
+ pendingResponse.cleanup?.();
2413
+ if (!isResponseMessage(response)) {
2414
+ pendingResponse.reject(RequestError.invalidRequest(response));
2415
+ } else if ("result" in response) {
2416
+ pendingResponse.resolve(response.result);
2417
+ } else {
2418
+ const { code, message, data } = response.error;
2419
+ pendingResponse.reject(new RequestError(code, message, data));
2420
+ }
2421
+ } else {
2422
+ console.error("Got response to unknown request", response.id);
2423
+ }
2424
+ }
2425
+ handleProtocolNotification(message) {
2426
+ if (message.method !== CANCEL_REQUEST_METHOD) {
2427
+ return;
2428
+ }
2429
+ const requestId = cancelRequestId(message.params);
2430
+ if (requestId === void 0) {
2431
+ return;
2432
+ }
2433
+ const controller = this.incomingRequests.get(requestId);
2434
+ if (!controller || controller.signal.aborted) {
2435
+ return;
2436
+ }
2437
+ controller.abort(RequestError.requestCancelled({ requestId }));
2438
+ }
2439
+ closedReason() {
2440
+ return this.abortController.signal.reason ?? new Error("ACP connection closed");
2441
+ }
2442
+ async sendWireMessage(message) {
2443
+ if (this.abortController.signal.aborted) {
2444
+ return rejectedPromise(this.closedReason());
2445
+ }
2446
+ this.writeQueue = this.writeQueue.then(async () => {
2447
+ if (this.abortController.signal.aborted) {
2448
+ throw this.closedReason();
2449
+ }
2450
+ const writer = this.stream.writable.getWriter();
2451
+ try {
2452
+ await writer.write(message);
2453
+ } finally {
2454
+ writer.releaseLock();
2455
+ }
2456
+ }).catch((error) => {
2457
+ this.close(error);
2458
+ throw error;
2459
+ });
2460
+ return this.writeQueue;
2461
+ }
2462
+ }
2463
+ class ConnectionBuilder {
2464
+ handlers = [];
2465
+ connectionName;
2466
+ /**
2467
+ * Sets a diagnostic name used by handlers created from this builder.
2468
+ */
2469
+ name(name2) {
2470
+ this.connectionName = name2;
2471
+ return this;
2472
+ }
2473
+ /**
2474
+ * Adds a raw JSON-RPC handler to the handler chain.
2475
+ */
2476
+ withHandler(handler) {
2477
+ this.handlers.push(handler);
2478
+ return this;
2479
+ }
2480
+ /**
2481
+ * Adds a handler that can inspect every incoming request or notification.
2482
+ *
2483
+ * Observer callbacks that return void pass the message through to later
2484
+ * handlers. Return `Handled.yes()` to stop dispatch explicitly.
2485
+ */
2486
+ onReceiveMessage(handler) {
2487
+ return this.withHandler({
2488
+ handleMessage: async (message, cx) => await handler(message, cx) ?? Handled.no(message),
2489
+ describe: () => this.connectionName ?? "onReceiveMessage"
2490
+ });
2491
+ }
2492
+ /**
2493
+ * Adds a typed request handler for one method.
2494
+ */
2495
+ onReceiveRequest(method, parse, handler) {
2496
+ return this.withHandler({
2497
+ handleMessage: async (message, cx) => {
2498
+ if (message.kind !== "request" || message.method !== method) {
2499
+ return Handled.no(message);
2500
+ }
2501
+ const request = parse(message.params);
2502
+ return await handler(request, message.responder, cx) ?? Handled.yes();
2503
+ },
2504
+ describe: () => `${this.connectionName ?? "request"}:${method}`
2505
+ });
2506
+ }
2507
+ /**
2508
+ * Adds a typed notification handler for one method.
2509
+ */
2510
+ onReceiveNotification(method, parse, handler) {
2511
+ return this.withHandler({
2512
+ handleMessage: async (message, cx) => {
2513
+ if (message.kind !== "notification" || message.method !== method) {
2514
+ return Handled.no(message);
2515
+ }
2516
+ const notification = parse(message.params);
2517
+ return await handler(notification, cx) ?? Handled.yes();
2518
+ },
2519
+ describe: () => `${this.connectionName ?? "notification"}:${method}`
2520
+ });
2521
+ }
2522
+ /**
2523
+ * Connects the configured handlers to a stream.
2524
+ */
2525
+ connect(stream, options) {
2526
+ return new Connection(stream, this.handlers, options);
2527
+ }
2528
+ /**
2529
+ * Connects to a stream for the lifetime of `op`, then closes the connection.
2530
+ */
2531
+ connectWith(stream, op, options) {
2532
+ return this.connect(stream, options).runUntil(op);
2533
+ }
2534
+ }
2535
+ class RequestError extends Error {
2536
+ code;
2537
+ /**
2538
+ * Additional JSON-RPC error data.
2539
+ */
2540
+ data;
2541
+ constructor(code, message, data) {
2542
+ super(message);
2543
+ this.code = code;
2544
+ this.name = "RequestError";
2545
+ this.data = data;
2546
+ }
2547
+ /**
2548
+ * Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
2549
+ */
2550
+ static parseError(data, additionalMessage) {
2551
+ return new RequestError(-32700, `Parse error${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
2552
+ }
2553
+ /**
2554
+ * The JSON sent is not a valid Request object.
2555
+ */
2556
+ static invalidRequest(data, additionalMessage) {
2557
+ return new RequestError(-32600, `Invalid request${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
2558
+ }
2559
+ /**
2560
+ * The method does not exist / is not available.
2561
+ */
2562
+ static methodNotFound(method) {
2563
+ return new RequestError(-32601, `"Method not found": ${method}`, {
2564
+ method
2565
+ });
2566
+ }
2567
+ /**
2568
+ * Invalid method parameter(s).
2569
+ */
2570
+ static invalidParams(data, additionalMessage) {
2571
+ return new RequestError(-32602, `Invalid params${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
2572
+ }
2573
+ /**
2574
+ * Internal JSON-RPC error.
2575
+ */
2576
+ static internalError(data, additionalMessage) {
2577
+ return new RequestError(-32603, `Internal error${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
2578
+ }
2579
+ /**
2580
+ * Execution of the request was aborted.
2581
+ */
2582
+ static requestCancelled(data, additionalMessage) {
2583
+ return new RequestError(-32800, `Request cancelled${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
2584
+ }
2585
+ /**
2586
+ * Authentication required.
2587
+ */
2588
+ static authRequired(data, additionalMessage) {
2589
+ return new RequestError(-32e3, `Authentication required${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
2590
+ }
2591
+ /**
2592
+ * Resource, such as a file, was not found
2593
+ */
2594
+ static resourceNotFound(uri) {
2595
+ return new RequestError(-32002, `Resource not found${uri ? `: ${uri}` : ""}`, uri && { uri });
2596
+ }
2597
+ /**
2598
+ * Converts this error to a JSON-RPC result object.
2599
+ */
2600
+ toResult() {
2601
+ return {
2602
+ error: {
2603
+ code: this.code,
2604
+ message: this.message,
2605
+ data: this.data
2606
+ }
2607
+ };
2608
+ }
2609
+ /**
2610
+ * Converts this error to a JSON-RPC error response payload.
2611
+ */
2612
+ toErrorResponse() {
2613
+ return {
2614
+ code: this.code,
2615
+ message: this.message,
2616
+ data: this.data
2617
+ };
2618
+ }
2619
+ }
2620
+ const newline = 10;
2621
+ class LineBuffer {
2622
+ /** Bytes of the current (incomplete) line, carried across chunks. */
2623
+ #pending = [];
2624
+ /**
2625
+ * Consumes a chunk, returning each complete line without its trailing
2626
+ * newline.
2627
+ */
2628
+ push(chunk) {
2629
+ const lines = [];
2630
+ let start = 0;
2631
+ let newlineIndex = chunk.indexOf(newline, start);
2632
+ while (newlineIndex !== -1) {
2633
+ lines.push(this.#takeLine(chunk.subarray(start, newlineIndex)));
2634
+ start = newlineIndex + 1;
2635
+ newlineIndex = chunk.indexOf(newline, start);
2636
+ }
2637
+ if (start < chunk.byteLength) {
2638
+ this.#pending.push(start === 0 ? chunk : new Uint8Array(chunk.subarray(start)));
2639
+ }
2640
+ return lines;
2641
+ }
2642
+ /**
2643
+ * Returns the trailing unterminated line and resets the buffer, or
2644
+ * undefined if no bytes are buffered.
2645
+ */
2646
+ flush() {
2647
+ if (this.#pending.length === 0) {
2648
+ return void 0;
2649
+ }
2650
+ return this.#takeLine(new Uint8Array(0));
2651
+ }
2652
+ #takeLine(tail) {
2653
+ if (this.#pending.length === 0) {
2654
+ return tail;
2655
+ }
2656
+ let total = tail.byteLength;
2657
+ for (const part of this.#pending) {
2658
+ total += part.byteLength;
2659
+ }
2660
+ const line = new Uint8Array(total);
2661
+ let offset = 0;
2662
+ for (const part of this.#pending) {
2663
+ line.set(part, offset);
2664
+ offset += part.byteLength;
2665
+ }
2666
+ line.set(tail, offset);
2667
+ this.#pending = [];
2668
+ return line;
2669
+ }
2670
+ }
2671
+ function ndJsonStream$1(output, input) {
2672
+ const textEncoder = new TextEncoder();
2673
+ const textDecoder = new TextDecoder();
2674
+ let cancelled = false;
2675
+ let inputReader;
2676
+ const readable = new ReadableStream({
2677
+ async start(controller) {
2678
+ const lines = new LineBuffer();
2679
+ const enqueueLine = (lineBytes) => {
2680
+ const trimmedLine = textDecoder.decode(lineBytes).trim();
2681
+ if (trimmedLine) {
2682
+ try {
2683
+ const message = JSON.parse(trimmedLine);
2684
+ if (isRecord(message) || Array.isArray(message)) {
2685
+ controller.enqueue(message);
2686
+ } else {
2687
+ console.warn("Skipping JSON line that is not an object:", trimmedLine);
2688
+ }
2689
+ } catch (err) {
2690
+ console.error("Failed to parse JSON message:", trimmedLine, err);
2691
+ }
2692
+ }
2693
+ };
2694
+ const reader = input.getReader();
2695
+ inputReader = reader;
2696
+ try {
2697
+ while (true) {
2698
+ const { value, done } = await reader.read();
2699
+ if (cancelled) {
2700
+ return;
2701
+ }
2702
+ if (done) {
2703
+ break;
2704
+ }
2705
+ if (!value) {
2706
+ continue;
2707
+ }
2708
+ for (const line of lines.push(value)) {
2709
+ enqueueLine(line);
2710
+ if (cancelled) {
2711
+ return;
2712
+ }
2713
+ }
2714
+ }
2715
+ if (cancelled) {
2716
+ return;
2717
+ }
2718
+ const lastLine = lines.flush();
2719
+ if (lastLine) {
2720
+ enqueueLine(lastLine);
2721
+ }
2722
+ } catch (err) {
2723
+ if (cancelled) {
2724
+ return;
2725
+ }
2726
+ controller.error(err);
2727
+ return;
2728
+ } finally {
2729
+ if (inputReader === reader) {
2730
+ inputReader = void 0;
2731
+ }
2732
+ reader.releaseLock();
2733
+ }
2734
+ if (cancelled) {
2735
+ return;
2736
+ }
2737
+ controller.close();
2738
+ },
2739
+ cancel(reason) {
2740
+ cancelled = true;
2741
+ return inputReader?.cancel(reason);
2742
+ }
2743
+ });
2744
+ const writable = new WritableStream({
2745
+ async write(message) {
2746
+ const content = JSON.stringify(message) + "\n";
2747
+ const writer = output.getWriter();
2748
+ try {
2749
+ await writer.write(textEncoder.encode(content));
2750
+ } finally {
2751
+ writer.releaseLock();
2752
+ }
2753
+ }
2754
+ });
2755
+ return { readable, writable };
2756
+ }
2757
+ function tagOf(value, key) {
2758
+ return typeof value === "object" && value !== null ? value[key] : void 0;
2759
+ }
2760
+ zElicitationFormMode.and(object({ mode: literal("form") })).and(object({ message: string() }));
2761
+ zElicitationUrlMode.and(object({ mode: literal("url") })).and(object({ message: string() }));
2762
+ union([zElicitationSessionScope, zElicitationRequestScope]).and(object({ message: string() }));
2763
+ zStringPropertySchema.and(object({ type: literal("string") }));
2764
+ zNumberPropertySchema.and(object({ type: literal("number") }));
2765
+ zIntegerPropertySchema.and(object({ type: literal("integer") }));
2766
+ zBooleanPropertySchema.and(object({ type: literal("boolean") }));
2767
+ zMultiSelectPropertySchema.and(object({ type: literal("array") }));
2768
+ zStringMultiSelectItems.and(object({ type: literal("string") }));
2769
+ const zGuardCreateElicitationResponseAccept = zElicitationAcceptAction.and(object({ action: literal("accept") }));
2770
+ const zGuardCreateElicitationResponseDecline = object({
2771
+ action: literal("decline")
2772
+ });
2773
+ const zGuardCreateElicitationResponseCancel = object({
2774
+ action: literal("cancel")
2775
+ });
2776
+ const CreateElicitationResponse = {
2777
+ /** Narrow to the `accept` variant, validating its payload. */
2778
+ isAccept(value) {
2779
+ return tagOf(value, "action") === "accept" && zGuardCreateElicitationResponseAccept.safeParse(value).success;
2780
+ },
2781
+ /** Narrow to the `decline` variant, validating its payload. */
2782
+ isDecline(value) {
2783
+ return tagOf(value, "action") === "decline" && zGuardCreateElicitationResponseDecline.safeParse(value).success;
2784
+ },
2785
+ /** Narrow to the `cancel` variant, validating its payload. */
2786
+ isCancel(value) {
2787
+ return tagOf(value, "action") === "cancel" && zGuardCreateElicitationResponseCancel.safeParse(value).success;
2788
+ },
2789
+ /**
2790
+ * Narrow to a custom or future variant: the `action` tag matches no known variant.
2791
+ *
2792
+ * TypeScript keeps the known variants in the narrowed union (they are
2793
+ * structural subtypes of the catch-all), so read vendor payload keys
2794
+ * via a widening cast: `(value as Record<string, unknown>).someKey`.
2795
+ */
2796
+ isCustom(value) {
2797
+ const tag = tagOf(value, "action");
2798
+ return typeof tag === "string" && !["accept", "cancel", "decline"].includes(tag);
2799
+ }
2800
+ };
2801
+ function ndJsonStream(output, input) {
2802
+ return ndJsonStream$1(output, input);
2803
+ }
2804
+ function emptyObjectResponse(response) {
2805
+ return response ?? {};
2806
+ }
2807
+ function isStream(value) {
2808
+ return typeof value === "object" && value !== null && "readable" in value && "writable" in value;
2809
+ }
2810
+ function memoryStreamPair() {
2811
+ const leftToRight = new TransformStream();
2812
+ const rightToLeft = new TransformStream();
2813
+ return [
2814
+ {
2815
+ readable: rightToLeft.readable,
2816
+ writable: leftToRight.writable
2817
+ },
2818
+ {
2819
+ readable: leftToRight.readable,
2820
+ writable: rightToLeft.writable
2821
+ }
2822
+ ];
2823
+ }
2824
+ const methods = {
2825
+ agent: {
2826
+ initialize: AGENT_METHODS.initialize,
2827
+ authenticate: AGENT_METHODS.authenticate,
2828
+ logout: AGENT_METHODS.logout,
2829
+ providers: {
2830
+ list: AGENT_METHODS.providers_list,
2831
+ set: AGENT_METHODS.providers_set,
2832
+ disable: AGENT_METHODS.providers_disable
2833
+ },
2834
+ session: {
2835
+ new: AGENT_METHODS.session_new,
2836
+ load: AGENT_METHODS.session_load,
2837
+ list: AGENT_METHODS.session_list,
2838
+ delete: AGENT_METHODS.session_delete,
2839
+ fork: AGENT_METHODS.session_fork,
2840
+ resume: AGENT_METHODS.session_resume,
2841
+ close: AGENT_METHODS.session_close,
2842
+ setMode: AGENT_METHODS.session_set_mode,
2843
+ setConfigOption: AGENT_METHODS.session_set_config_option,
2844
+ prompt: AGENT_METHODS.session_prompt,
2845
+ cancel: AGENT_METHODS.session_cancel
2846
+ }
2847
+ },
2848
+ client: {
2849
+ session: {
2850
+ requestPermission: CLIENT_METHODS.session_request_permission,
2851
+ update: CLIENT_METHODS.session_update
2852
+ },
2853
+ fs: {
2854
+ writeTextFile: CLIENT_METHODS.fs_write_text_file,
2855
+ readTextFile: CLIENT_METHODS.fs_read_text_file
2856
+ },
2857
+ elicitation: {
2858
+ create: CLIENT_METHODS.elicitation_create,
2859
+ complete: CLIENT_METHODS.elicitation_complete
2860
+ }
2861
+ }
2862
+ };
2863
+ const startActiveSession = Symbol("startActiveSession");
2864
+ class AcpContext {
2865
+ cx;
2866
+ currentRequestId;
2867
+ /** @internal */
2868
+ constructor(cx, currentRequestId) {
2869
+ this.cx = cx;
2870
+ this.currentRequestId = currentRequestId;
2871
+ }
2872
+ /**
2873
+ * JSON-RPC id of the request currently being handled.
2874
+ *
2875
+ * This is `undefined` for notification handlers and for contexts created
2876
+ * outside an inbound request, such as `connect(...)` and `connectWith(...)`.
2877
+ */
2878
+ get requestId() {
2879
+ return this.currentRequestId;
2880
+ }
2881
+ /** @internal */
2882
+ get connectionContext() {
2883
+ return this.cx;
2884
+ }
2885
+ /** @internal */
2886
+ sendRequest(method, params, mapResponse, options) {
2887
+ return this.cx.sendRequest(method, params, mapResponse, options);
2888
+ }
2889
+ /** @internal */
2890
+ sendNotification(method, params) {
2891
+ return this.cx.sendNotification(method, params);
2892
+ }
2893
+ /** @internal */
2894
+ addDynamicHandler(handler) {
2895
+ return this.cx.addDynamicHandler(handler);
2896
+ }
2897
+ }
2898
+ class AgentContext extends AcpContext {
2899
+ constructor(cx, requestId) {
2900
+ super(cx, requestId);
2901
+ }
2902
+ /** @internal */
2903
+ static create(cx, requestId) {
2904
+ return new AgentContext(cx, requestId);
2905
+ }
2906
+ request(method, params, options) {
2907
+ const spec = clientRequestSpecsByMethod[method];
2908
+ return this.sendRequest(method, params, spec?.mapResponse, options);
2909
+ }
2910
+ notify(method, params) {
2911
+ return this.sendNotification(method, params);
2912
+ }
2913
+ }
2914
+ class ClientContext extends AcpContext {
2915
+ constructor(cx, requestId) {
2916
+ super(cx, requestId);
2917
+ }
2918
+ /** @internal */
2919
+ static create(cx, requestId) {
2920
+ return new ClientContext(cx, requestId);
2921
+ }
2922
+ /** @internal */
2923
+ [startActiveSession](params, options) {
2924
+ return this.sendRequest(AGENT_METHODS.session_new, params, (response) => this.attachSession(response), options);
2925
+ }
2926
+ buildSession(cwdOrRequest) {
2927
+ if (typeof cwdOrRequest === "string") {
2928
+ return SessionBuilder.create(this, {
2929
+ cwd: cwdOrRequest,
2930
+ mcpServers: []
2931
+ });
2932
+ }
2933
+ return SessionBuilder.create(this, cwdOrRequest);
2934
+ }
2935
+ /**
2936
+ * Builds active-session helpers around a `session/new` response.
2937
+ */
2938
+ attachSession(response) {
2939
+ const updates = new AsyncQueue();
2940
+ const closeSignal = this.connectionContext.signal;
2941
+ const failUpdatesOnClose = () => {
2942
+ updates.fail(closeSignal.reason ?? new Error("ACP connection closed"));
2943
+ };
2944
+ if (closeSignal.aborted) {
2945
+ failUpdatesOnClose();
2946
+ } else {
2947
+ closeSignal.addEventListener("abort", failUpdatesOnClose);
2948
+ }
2949
+ const sessionRegistration = sessionUpdateRouter(this.connectionContext).attach(response, updates);
2950
+ const closeRegistration = new HandlerRegistration(() => {
2951
+ closeSignal.removeEventListener("abort", failUpdatesOnClose);
2952
+ });
2953
+ return ActiveSession.create(this, response, updates, [
2954
+ sessionRegistration,
2955
+ closeRegistration
2956
+ ]);
2957
+ }
2958
+ request(method, params, options) {
2959
+ const spec = agentRequestSpecsByMethod[method];
2960
+ return this.sendRequest(method, params, spec?.mapResponse, options);
2961
+ }
2962
+ notify(method, params) {
2963
+ return this.sendNotification(method, params);
2964
+ }
2965
+ }
2966
+ class AcpConnectionHandle {
2967
+ connection;
2968
+ constructor(connection) {
2969
+ this.connection = connection;
2970
+ }
2971
+ get signal() {
2972
+ return this.connection.signal;
2973
+ }
2974
+ get closed() {
2975
+ return this.connection.closed;
2976
+ }
2977
+ close(error) {
2978
+ this.connection.close(error);
2979
+ }
2980
+ }
2981
+ class AgentConnectionHandle extends AcpConnectionHandle {
2982
+ connectHandlers;
2983
+ client;
2984
+ didStartConnectHandlers = false;
2985
+ constructor(connection, connectHandlers = []) {
2986
+ super(connection);
2987
+ this.connectHandlers = connectHandlers;
2988
+ this.client = AgentContext.create(connection.getContext());
2989
+ }
2990
+ /** @internal */
2991
+ startConnectHandlers() {
2992
+ if (this.didStartConnectHandlers) {
2993
+ return;
2994
+ }
2995
+ this.didStartConnectHandlers = true;
2996
+ runConnectHandlers(this, this.connectHandlers);
2997
+ }
2998
+ }
2999
+ class ClientConnectionHandle extends AcpConnectionHandle {
3000
+ connectHandlers;
3001
+ agent;
3002
+ didStartConnectHandlers = false;
3003
+ constructor(connection, connectHandlers = []) {
3004
+ super(connection);
3005
+ this.connectHandlers = connectHandlers;
3006
+ this.agent = ClientContext.create(connection.getContext());
3007
+ }
3008
+ /** @internal */
3009
+ startConnectHandlers() {
3010
+ if (this.didStartConnectHandlers) {
3011
+ return;
3012
+ }
3013
+ this.didStartConnectHandlers = true;
3014
+ runConnectHandlers(this, this.connectHandlers);
3015
+ }
3016
+ }
3017
+ function agentConnection(connection, connectHandlers = []) {
3018
+ return new AgentConnectionHandle(connection, connectHandlers);
3019
+ }
3020
+ function clientConnection(connection, connectHandlers = []) {
3021
+ return new ClientConnectionHandle(connection, connectHandlers);
3022
+ }
3023
+ class AsyncQueue {
3024
+ values = [];
3025
+ waiters = [];
3026
+ failed = false;
3027
+ failure;
3028
+ enqueue(value) {
3029
+ if (this.failed) {
3030
+ return;
3031
+ }
3032
+ const waiter = this.waiters.shift();
3033
+ if (waiter) {
3034
+ waiter.resolve(value);
3035
+ } else {
3036
+ this.values.push({ kind: "value", value });
3037
+ }
3038
+ }
3039
+ reject(error) {
3040
+ if (this.failed) {
3041
+ return;
3042
+ }
3043
+ if (this.waiters.length > 0) {
3044
+ for (const waiter of this.waiters.splice(0)) {
3045
+ waiter.reject(error);
3046
+ }
3047
+ return;
3048
+ }
3049
+ this.values.push({ kind: "error", error });
3050
+ }
3051
+ clearErrors() {
3052
+ this.values = this.values.filter((entry) => entry.kind === "value");
3053
+ }
3054
+ fail(error) {
3055
+ if (this.failed) {
3056
+ return;
3057
+ }
3058
+ this.failed = true;
3059
+ this.failure = error;
3060
+ for (const waiter of this.waiters.splice(0)) {
3061
+ waiter.reject(error);
3062
+ }
3063
+ }
3064
+ next() {
3065
+ if (this.values.length > 0) {
3066
+ const entry = this.values.shift();
3067
+ if (entry.kind === "error") {
3068
+ return Promise.reject(entry.error);
3069
+ }
3070
+ return Promise.resolve(entry.value);
3071
+ }
3072
+ if (this.failed) {
3073
+ return Promise.reject(this.failure);
3074
+ }
3075
+ return new Promise((resolve, reject) => {
3076
+ this.waiters.push({ resolve, reject });
3077
+ });
3078
+ }
3079
+ }
3080
+ function cloneNewSessionRequest(request) {
3081
+ return {
3082
+ ...request,
3083
+ additionalDirectories: request.additionalDirectories ? [...request.additionalDirectories] : void 0,
3084
+ mcpServers: [...request.mcpServers]
3085
+ };
3086
+ }
3087
+ class SessionBuilder {
3088
+ cx;
3089
+ request;
3090
+ constructor(cx, request) {
3091
+ this.cx = cx;
3092
+ this.request = cloneNewSessionRequest(request);
3093
+ }
3094
+ /** @internal */
3095
+ static create(cx, request) {
3096
+ return new SessionBuilder(cx, request);
3097
+ }
3098
+ /**
3099
+ * Returns the `session/new` request that will be sent.
3100
+ *
3101
+ * The returned object is a defensive copy, so mutating it does not change the
3102
+ * builder.
3103
+ */
3104
+ toRequest() {
3105
+ return cloneNewSessionRequest(this.request);
3106
+ }
3107
+ /**
3108
+ * Replaces the additional workspace roots for this session.
3109
+ *
3110
+ * `additionalDirectories` expand the session's file-system scope without
3111
+ * changing `cwd`. Each path should be absolute.
3112
+ */
3113
+ withAdditionalDirectories(additionalDirectories) {
3114
+ this.request = {
3115
+ ...this.request,
3116
+ additionalDirectories: [...additionalDirectories]
3117
+ };
3118
+ return this;
3119
+ }
3120
+ /**
3121
+ * Adds one MCP server to the `session/new` request.
3122
+ */
3123
+ withMcpServer(mcpServer) {
3124
+ this.request = {
3125
+ ...this.request,
3126
+ mcpServers: [...this.request.mcpServers, mcpServer]
3127
+ };
3128
+ return this;
3129
+ }
3130
+ /**
3131
+ * Starts the session and returns an `ActiveSession` for prompting and reading
3132
+ * updates.
3133
+ *
3134
+ * Call `dispose()` on the returned session when you no longer need update
3135
+ * routing, or use `withSession(...)` to scope disposal automatically.
3136
+ */
3137
+ async start(options) {
3138
+ return this.cx[startActiveSession](this.toRequest(), options);
3139
+ }
3140
+ /**
3141
+ * Starts the session, runs `op`, and disposes the active-session update
3142
+ * routing when `op` finishes or throws.
3143
+ */
3144
+ async withSession(op) {
3145
+ const session = await this.start();
3146
+ try {
3147
+ return await op(session);
3148
+ } finally {
3149
+ session.dispose();
3150
+ }
3151
+ }
3152
+ }
3153
+ class ActiveSession {
3154
+ cx;
3155
+ sessionResponse;
3156
+ updates;
3157
+ registrations;
3158
+ constructor(cx, sessionResponse, updates, registrations) {
3159
+ this.cx = cx;
3160
+ this.sessionResponse = sessionResponse;
3161
+ this.updates = updates;
3162
+ this.registrations = registrations;
3163
+ }
3164
+ /** @internal */
3165
+ static create(cx, sessionResponse, updates, registrations) {
3166
+ return new ActiveSession(cx, sessionResponse, updates, registrations);
3167
+ }
3168
+ /**
3169
+ * Session ID returned by `session/new`.
3170
+ */
3171
+ get sessionId() {
3172
+ return this.sessionResponse.sessionId;
3173
+ }
3174
+ /**
3175
+ * Mode state returned when the session was created, if the agent provided it.
3176
+ */
3177
+ get modes() {
3178
+ return this.sessionResponse.modes;
3179
+ }
3180
+ /**
3181
+ * Metadata returned when the session was created.
3182
+ */
3183
+ get meta() {
3184
+ return this.sessionResponse._meta;
3185
+ }
3186
+ /**
3187
+ * Full response returned by `session/new`.
3188
+ */
3189
+ get newSessionResponse() {
3190
+ return this.sessionResponse;
3191
+ }
3192
+ /**
3193
+ * Sends a prompt to this session.
3194
+ *
3195
+ * Strings are converted to one text content block. A single content block is
3196
+ * wrapped in an array. The returned promise resolves with the final
3197
+ * `PromptResponse`, and the same completion is also queued as a `stop`
3198
+ * message for `nextUpdate()`.
3199
+ */
3200
+ prompt(prompt, options) {
3201
+ this.updates.clearErrors();
3202
+ const response = this.cx.request(AGENT_METHODS.session_prompt, {
3203
+ sessionId: this.sessionId,
3204
+ prompt: this.promptBlocks(prompt)
3205
+ }, options);
3206
+ void response.then((value) => {
3207
+ this.updates.enqueue({
3208
+ kind: "stop",
3209
+ response: value,
3210
+ stopReason: value.stopReason
3211
+ });
3212
+ }, (error) => {
3213
+ this.updates.reject(error);
3214
+ });
3215
+ return response;
3216
+ }
3217
+ /**
3218
+ * Reads the next update or stop message for this session.
3219
+ */
3220
+ nextUpdate() {
3221
+ return this.updates.next();
3222
+ }
3223
+ /**
3224
+ * Reads text chunks until the current prompt turn stops.
3225
+ *
3226
+ * Only `agent_message_chunk` updates with text content are appended. Other
3227
+ * update types are ignored by this helper; use `nextUpdate()` when you need
3228
+ * tool calls, plans, or the final `PromptResponse`.
3229
+ */
3230
+ async readText() {
3231
+ let output = "";
3232
+ for (; ; ) {
3233
+ const message = await this.nextUpdate();
3234
+ if (message.kind === "stop") {
3235
+ return output;
3236
+ }
3237
+ const { update } = message;
3238
+ if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
3239
+ output += update.content.text;
3240
+ }
3241
+ }
3242
+ }
3243
+ /**
3244
+ * Stops routing updates to this active-session helper.
3245
+ *
3246
+ * This does not close the ACP session on the agent. Use `ClientContext`
3247
+ * session lifecycle methods when the protocol session itself should be closed
3248
+ * or deleted.
3249
+ */
3250
+ dispose() {
3251
+ for (const registration of this.registrations.splice(0)) {
3252
+ registration.dispose();
3253
+ }
3254
+ this.updates.fail(new Error("Active session disposed"));
3255
+ }
3256
+ /**
3257
+ * Supports explicit resource management with `using`.
3258
+ */
3259
+ [Symbol.dispose]() {
3260
+ this.dispose();
3261
+ }
3262
+ promptBlocks(prompt) {
3263
+ if (typeof prompt === "string") {
3264
+ return [{ type: "text", text: prompt }];
3265
+ }
3266
+ if (Array.isArray(prompt)) {
3267
+ return prompt;
3268
+ }
3269
+ return [prompt];
3270
+ }
3271
+ }
3272
+ function parseParams(parser, params) {
3273
+ if (!parser) {
3274
+ return params;
3275
+ }
3276
+ if (typeof parser === "function") {
3277
+ return parser(params);
3278
+ }
3279
+ return parser.parse(params);
3280
+ }
3281
+ function requestSpec(method, params, mapResponse) {
3282
+ return { method, params, mapResponse };
3283
+ }
3284
+ function notificationSpec(method, params) {
3285
+ return { method, params };
3286
+ }
3287
+ function registerAppRequest(builder, spec, context, handler) {
3288
+ builder.onReceiveRequest(spec.method, (params) => parseParams(spec.params, params), async (params, responder, cx) => {
3289
+ const response = await handler(context(params, cx, responder.signal, responder.id));
3290
+ await responder.respond(spec.mapResponse ? spec.mapResponse(response) : response);
3291
+ });
3292
+ }
3293
+ function registerAppNotification(builder, spec, context, handler) {
3294
+ builder.onReceiveNotification(spec.method, (params) => parseParams(spec.params, params), (params, cx) => handler(context(params, cx, cx.signal)));
3295
+ }
3296
+ function specsByMethod(specs) {
3297
+ const byMethod = {};
3298
+ for (const spec of Object.values(specs)) {
3299
+ byMethod[spec.method] = spec;
3300
+ }
3301
+ return byMethod;
3302
+ }
3303
+ const agentRequestSpecs = {
3304
+ initialize: requestSpec(AGENT_METHODS.initialize, zInitializeRequest),
3305
+ newSession: requestSpec(AGENT_METHODS.session_new, zNewSessionRequest),
3306
+ loadSession: requestSpec(AGENT_METHODS.session_load, zLoadSessionRequest, emptyObjectResponse),
3307
+ unstable_forkSession: requestSpec(AGENT_METHODS.session_fork, zForkSessionRequest),
3308
+ listSessions: requestSpec(AGENT_METHODS.session_list, zListSessionsRequest),
3309
+ deleteSession: requestSpec(AGENT_METHODS.session_delete, zDeleteSessionRequest, emptyObjectResponse),
3310
+ resumeSession: requestSpec(AGENT_METHODS.session_resume, zResumeSessionRequest),
3311
+ closeSession: requestSpec(AGENT_METHODS.session_close, zCloseSessionRequest, emptyObjectResponse),
3312
+ setSessionMode: requestSpec(AGENT_METHODS.session_set_mode, zSetSessionModeRequest, emptyObjectResponse),
3313
+ setSessionConfigOption: requestSpec(AGENT_METHODS.session_set_config_option, zSetSessionConfigOptionRequest),
3314
+ authenticate: requestSpec(AGENT_METHODS.authenticate, zAuthenticateRequest, emptyObjectResponse),
3315
+ unstable_listProviders: requestSpec(AGENT_METHODS.providers_list, zListProvidersRequest),
3316
+ unstable_setProvider: requestSpec(AGENT_METHODS.providers_set, zSetProviderRequest, emptyObjectResponse),
3317
+ unstable_disableProvider: requestSpec(AGENT_METHODS.providers_disable, zDisableProviderRequest, emptyObjectResponse),
3318
+ logout: requestSpec(AGENT_METHODS.logout, zLogoutRequest, emptyObjectResponse),
3319
+ prompt: requestSpec(AGENT_METHODS.session_prompt, zPromptRequest),
3320
+ unstable_startNes: requestSpec(AGENT_METHODS.nes_start, zStartNesRequest),
3321
+ unstable_suggestNes: requestSpec(AGENT_METHODS.nes_suggest, zSuggestNesRequest),
3322
+ unstable_closeNes: requestSpec(AGENT_METHODS.nes_close, zCloseNesRequest, emptyObjectResponse)
3323
+ };
3324
+ const agentNotificationSpecs = {
3325
+ cancel: notificationSpec(AGENT_METHODS.session_cancel, zCancelNotification),
3326
+ unstable_didOpenDocument: notificationSpec(AGENT_METHODS.document_did_open, zDidOpenDocumentNotification),
3327
+ unstable_didChangeDocument: notificationSpec(AGENT_METHODS.document_did_change, zDidChangeDocumentNotification),
3328
+ unstable_didCloseDocument: notificationSpec(AGENT_METHODS.document_did_close, zDidCloseDocumentNotification),
3329
+ unstable_didSaveDocument: notificationSpec(AGENT_METHODS.document_did_save, zDidSaveDocumentNotification),
3330
+ unstable_didFocusDocument: notificationSpec(AGENT_METHODS.document_did_focus, zDidFocusDocumentNotification),
3331
+ unstable_acceptNes: notificationSpec(AGENT_METHODS.nes_accept, zAcceptNesNotification),
3332
+ unstable_rejectNes: notificationSpec(AGENT_METHODS.nes_reject, zRejectNesNotification)
3333
+ };
3334
+ const clientRequestSpecs = {
3335
+ requestPermission: requestSpec(CLIENT_METHODS.session_request_permission, zRequestPermissionRequest),
3336
+ writeTextFile: requestSpec(CLIENT_METHODS.fs_write_text_file, zWriteTextFileRequest, emptyObjectResponse),
3337
+ readTextFile: requestSpec(CLIENT_METHODS.fs_read_text_file, zReadTextFileRequest),
3338
+ createTerminal: requestSpec(CLIENT_METHODS.terminal_create, zCreateTerminalRequest),
3339
+ terminalOutput: requestSpec(CLIENT_METHODS.terminal_output, zTerminalOutputRequest),
3340
+ releaseTerminal: requestSpec(CLIENT_METHODS.terminal_release, zReleaseTerminalRequest, emptyObjectResponse),
3341
+ waitForTerminalExit: requestSpec(CLIENT_METHODS.terminal_wait_for_exit, zWaitForTerminalExitRequest),
3342
+ killTerminal: requestSpec(CLIENT_METHODS.terminal_kill, zKillTerminalRequest, emptyObjectResponse),
3343
+ unstable_createElicitation: requestSpec(CLIENT_METHODS.elicitation_create, zCreateElicitationRequest)
3344
+ };
3345
+ const clientNotificationSpecs = {
3346
+ sessionUpdate: notificationSpec(CLIENT_METHODS.session_update, zSessionNotification),
3347
+ unstable_completeElicitation: notificationSpec(CLIENT_METHODS.elicitation_complete, zCompleteElicitationNotification)
3348
+ };
3349
+ const agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs);
3350
+ const agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs);
3351
+ const clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs);
3352
+ const clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs);
3353
+ function agentRequestContext(params, client2, signal, requestId) {
3354
+ return {
3355
+ params,
3356
+ requestId,
3357
+ signal,
3358
+ client: client2
3359
+ };
3360
+ }
3361
+ function agentNotificationContext(params, client2, signal) {
3362
+ return {
3363
+ params,
3364
+ signal,
3365
+ client: client2
3366
+ };
3367
+ }
3368
+ function clientRequestContext(params, agent2, signal, requestId) {
3369
+ return {
3370
+ params,
3371
+ requestId,
3372
+ signal,
3373
+ agent: agent2
3374
+ };
3375
+ }
3376
+ function clientNotificationContext(params, agent2, signal) {
3377
+ return {
3378
+ params,
3379
+ signal,
3380
+ agent: agent2
3381
+ };
3382
+ }
3383
+ class SessionUpdateRouter {
3384
+ activeSessions = /* @__PURE__ */ new Map();
3385
+ handleMessage(message) {
3386
+ if (message.kind !== "notification" || message.method !== CLIENT_METHODS.session_update) {
3387
+ return Handled.no(message);
3388
+ }
3389
+ const notification = zSessionNotification.parse(message.params);
3390
+ const update = {
3391
+ kind: "session_update",
3392
+ notification,
3393
+ update: notification.update
3394
+ };
3395
+ const activeSessions = this.activeSessions.get(notification.sessionId);
3396
+ if (activeSessions && activeSessions.size > 0) {
3397
+ for (const session of activeSessions) {
3398
+ session.enqueue(update);
3399
+ }
3400
+ }
3401
+ return Handled.no(message);
3402
+ }
3403
+ attach(response, updates) {
3404
+ const sessions = this.activeSessions.get(response.sessionId) ?? /* @__PURE__ */ new Set();
3405
+ sessions.add(updates);
3406
+ this.activeSessions.set(response.sessionId, sessions);
3407
+ return new HandlerRegistration(() => {
3408
+ sessions.delete(updates);
3409
+ if (sessions.size === 0) {
3410
+ this.activeSessions.delete(response.sessionId);
3411
+ }
3412
+ });
3413
+ }
3414
+ }
3415
+ const sessionUpdateRouters = /* @__PURE__ */ new WeakMap();
3416
+ function sessionUpdateRouter(cx) {
3417
+ let router = sessionUpdateRouters.get(cx);
3418
+ if (!router) {
3419
+ router = new SessionUpdateRouter();
3420
+ sessionUpdateRouters.set(cx, router);
3421
+ }
3422
+ return router;
3423
+ }
3424
+ function runConnectHandlers(connection, handlers) {
3425
+ for (const handler of handlers) {
3426
+ let result;
3427
+ try {
3428
+ result = handler(connection);
3429
+ } catch (error) {
3430
+ connection.close(error);
3431
+ throw error;
3432
+ }
3433
+ void Promise.resolve(result).catch((error) => {
3434
+ connection.close(error);
3435
+ });
3436
+ }
3437
+ }
3438
+ const appBuilder = Symbol("appBuilder");
3439
+ const runAgentConnectHandlers = Symbol("runAgentConnectHandlers");
3440
+ const runClientConnectHandlers = Symbol("runClientConnectHandlers");
3441
+ const stableConnectionOptions = { allowBatches: false };
3442
+ function agent(options) {
3443
+ return new AgentApp(options);
3444
+ }
3445
+ class AgentApp {
3446
+ builder = Connection.builder();
3447
+ connectHandlers = [];
3448
+ constructor(options = {}) {
3449
+ if (options.name) {
3450
+ this.builder.name(options.name);
3451
+ }
3452
+ }
3453
+ /** @internal */
3454
+ [appBuilder]() {
3455
+ return this.builder;
3456
+ }
3457
+ /** @internal */
3458
+ [runAgentConnectHandlers](connection) {
3459
+ runConnectHandlers(connection, this.connectHandlers);
3460
+ }
3461
+ connect(target, options = {}) {
3462
+ return this.connectConnection(target, options).connection;
3463
+ }
3464
+ connectWith(target, op) {
3465
+ const { rawConnection, connection } = this.connectConnection(target);
3466
+ return rawConnection.runUntil(() => op(connection.client));
3467
+ }
3468
+ /**
3469
+ * Registers a handler that runs when this agent app opens a connection.
3470
+ *
3471
+ * Use this for connection-scoped work that needs to call client-side ACP
3472
+ * methods outside an inbound request handler.
3473
+ */
3474
+ onConnect(handler) {
3475
+ this.connectHandlers.push(handler);
3476
+ return this;
3477
+ }
3478
+ onRequest(method, handlerOrParams, handler) {
3479
+ if (handler) {
3480
+ return this.request({ method, params: handlerOrParams }, handler);
3481
+ }
3482
+ const spec = agentRequestSpecsByMethod[method];
3483
+ if (!spec) {
3484
+ throw new Error(`Unknown ACP request method '${method}'. Pass a params parser for custom methods.`);
3485
+ }
3486
+ return this.request(spec, handlerOrParams);
3487
+ }
3488
+ onNotification(method, handlerOrParams, handler) {
3489
+ if (handler) {
3490
+ return this.notification({ method, params: handlerOrParams }, handler);
3491
+ }
3492
+ const spec = agentNotificationSpecsByMethod[method];
3493
+ if (!spec) {
3494
+ throw new Error(`Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`);
3495
+ }
3496
+ return this.notification(spec, handlerOrParams);
3497
+ }
3498
+ request(spec, handler) {
3499
+ registerAppRequest(this.builder, spec, (params, cx, signal, requestId) => agentRequestContext(params, AgentContext.create(cx, requestId), signal, requestId), handler);
3500
+ return this;
3501
+ }
3502
+ notification(spec, handler) {
3503
+ registerAppNotification(this.builder, spec, (params, cx, signal) => agentNotificationContext(params, AgentContext.create(cx), signal), handler);
3504
+ return this;
3505
+ }
3506
+ connectConnection(target, options = {}) {
3507
+ if (isStream(target)) {
3508
+ const state2 = this.openStreamConnection(target);
3509
+ if (!options.deferConnectHandlers) {
3510
+ this[runAgentConnectHandlers](state2.connection);
3511
+ }
3512
+ return state2;
3513
+ }
3514
+ const [thisStream, peerStream] = memoryStreamPair();
3515
+ const peerRawConnection = target[appBuilder]().connect(peerStream, stableConnectionOptions);
3516
+ const peerConnection = clientConnection(peerRawConnection);
3517
+ const state = this.openStreamConnection(thisStream);
3518
+ void state.rawConnection.closed.then(() => peerConnection.close());
3519
+ void peerRawConnection.closed.then(() => state.connection.close());
3520
+ try {
3521
+ target[runClientConnectHandlers](peerConnection);
3522
+ this[runAgentConnectHandlers](state.connection);
3523
+ } catch (error) {
3524
+ peerConnection.close(error);
3525
+ state.connection.close(error);
3526
+ throw error;
3527
+ }
3528
+ return state;
3529
+ }
3530
+ openStreamConnection(stream) {
3531
+ const rawConnection = this.builder.connect(stream, stableConnectionOptions);
3532
+ return {
3533
+ rawConnection,
3534
+ connection: agentConnection(rawConnection, this.connectHandlers)
3535
+ };
3536
+ }
3537
+ }
3538
+ function client(options) {
3539
+ return new ClientApp(options);
3540
+ }
3541
+ class ClientApp {
3542
+ builder = Connection.builder();
3543
+ connectHandlers = [];
3544
+ constructor(options = {}) {
3545
+ if (options.name) {
3546
+ this.builder.name(options.name);
3547
+ }
3548
+ this.builder.withHandler({
3549
+ handleMessage: (message, cx) => sessionUpdateRouter(cx).handleMessage(message),
3550
+ describe: () => "client-session-update-router"
3551
+ });
3552
+ }
3553
+ /** @internal */
3554
+ [appBuilder]() {
3555
+ return this.builder;
3556
+ }
3557
+ /** @internal */
3558
+ [runClientConnectHandlers](connection) {
3559
+ runConnectHandlers(connection, this.connectHandlers);
3560
+ }
3561
+ connect(target) {
3562
+ return this.connectConnection(target).connection;
3563
+ }
3564
+ connectWith(target, op) {
3565
+ const { rawConnection, connection } = this.connectConnection(target);
3566
+ return rawConnection.runUntil(() => op(connection.agent));
3567
+ }
3568
+ /**
3569
+ * Registers a handler that runs when this client app opens a connection.
3570
+ *
3571
+ * Use this for connection-scoped work that needs to call agent-side ACP
3572
+ * methods outside an inbound request handler.
3573
+ */
3574
+ onConnect(handler) {
3575
+ this.connectHandlers.push(handler);
3576
+ return this;
3577
+ }
3578
+ onRequest(method, handlerOrParams, handler) {
3579
+ if (handler) {
3580
+ return this.request({ method, params: handlerOrParams }, handler);
3581
+ }
3582
+ const spec = clientRequestSpecsByMethod[method];
3583
+ if (!spec) {
3584
+ throw new Error(`Unknown ACP request method '${method}'. Pass a params parser for custom methods.`);
3585
+ }
3586
+ return this.request(spec, handlerOrParams);
3587
+ }
3588
+ onNotification(method, handlerOrParams, handler) {
3589
+ if (handler) {
3590
+ return this.notification({ method, params: handlerOrParams }, handler);
3591
+ }
3592
+ const spec = clientNotificationSpecsByMethod[method];
3593
+ if (!spec) {
3594
+ throw new Error(`Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`);
3595
+ }
3596
+ return this.notification(spec, handlerOrParams);
3597
+ }
3598
+ request(spec, handler) {
3599
+ registerAppRequest(this.builder, spec, (params, cx, signal, requestId) => clientRequestContext(params, ClientContext.create(cx, requestId), signal, requestId), handler);
3600
+ return this;
3601
+ }
3602
+ notification(spec, handler) {
3603
+ registerAppNotification(this.builder, spec, (params, cx, signal) => clientNotificationContext(params, ClientContext.create(cx), signal), handler);
3604
+ return this;
3605
+ }
3606
+ connectConnection(target) {
3607
+ if (isStream(target)) {
3608
+ const state2 = this.openStreamConnection(target);
3609
+ this[runClientConnectHandlers](state2.connection);
3610
+ return state2;
3611
+ }
3612
+ const [thisStream, peerStream] = memoryStreamPair();
3613
+ const peerRawConnection = target[appBuilder]().connect(peerStream, stableConnectionOptions);
3614
+ const peerConnection = agentConnection(peerRawConnection);
3615
+ const state = this.openStreamConnection(thisStream);
3616
+ void state.rawConnection.closed.then(() => peerConnection.close());
3617
+ void peerRawConnection.closed.then(() => state.connection.close());
3618
+ try {
3619
+ target[runAgentConnectHandlers](peerConnection);
3620
+ this[runClientConnectHandlers](state.connection);
3621
+ } catch (error) {
3622
+ peerConnection.close(error);
3623
+ state.connection.close(error);
3624
+ throw error;
3625
+ }
3626
+ return state;
3627
+ }
3628
+ openStreamConnection(stream) {
3629
+ const rawConnection = this.builder.connect(stream, stableConnectionOptions);
3630
+ return {
3631
+ rawConnection,
3632
+ connection: clientConnection(rawConnection, this.connectHandlers)
3633
+ };
3634
+ }
3635
+ }
3636
+ const legacyClientRequestMethods = /* @__PURE__ */ new Set([
3637
+ CLIENT_METHODS.session_request_permission,
3638
+ CLIENT_METHODS.fs_write_text_file,
3639
+ CLIENT_METHODS.fs_read_text_file,
3640
+ CLIENT_METHODS.terminal_create,
3641
+ CLIENT_METHODS.terminal_output,
3642
+ CLIENT_METHODS.terminal_release,
3643
+ CLIENT_METHODS.terminal_wait_for_exit,
3644
+ CLIENT_METHODS.terminal_kill,
3645
+ CLIENT_METHODS.elicitation_create
3646
+ ]);
3647
+ const legacyClientNotificationMethods = /* @__PURE__ */ new Set([
3648
+ CLIENT_METHODS.session_update,
3649
+ CLIENT_METHODS.elicitation_complete
3650
+ ]);
3651
+ function legacyClientApp(implementation) {
3652
+ const app = client().onRequest(CLIENT_METHODS.session_request_permission, (ctx) => implementation.requestPermission(ctx.params)).onNotification(CLIENT_METHODS.session_update, (ctx) => implementation.sessionUpdate(ctx.params)).onRequest(CLIENT_METHODS.fs_write_text_file, async (ctx) => await implementation.writeTextFile?.(ctx.params) ?? {}).onRequest(CLIENT_METHODS.fs_read_text_file, async (ctx) => await implementation.readTextFile?.(ctx.params)).onRequest(CLIENT_METHODS.terminal_create, async (ctx) => await implementation.createTerminal?.(ctx.params)).onRequest(CLIENT_METHODS.terminal_output, async (ctx) => await implementation.terminalOutput?.(ctx.params)).onRequest(CLIENT_METHODS.terminal_release, async (ctx) => await implementation.releaseTerminal?.(ctx.params) ?? {}).onRequest(CLIENT_METHODS.terminal_wait_for_exit, async (ctx) => await implementation.waitForTerminalExit?.(ctx.params)).onRequest(CLIENT_METHODS.terminal_kill, async (ctx) => await implementation.killTerminal?.(ctx.params) ?? {});
3653
+ if (implementation.unstable_createElicitation) {
3654
+ app.onRequest(CLIENT_METHODS.elicitation_create, (ctx) => implementation.unstable_createElicitation(ctx.params));
3655
+ }
3656
+ if (implementation.unstable_completeElicitation) {
3657
+ app.onNotification(CLIENT_METHODS.elicitation_complete, (ctx) => implementation.unstable_completeElicitation(ctx.params));
3658
+ }
3659
+ if (implementation.extMethod) {
3660
+ app[appBuilder]().withHandler({
3661
+ handleMessage: async (message) => {
3662
+ if (message.kind !== "request" || legacyClientRequestMethods.has(message.method)) {
3663
+ return Handled.no(message);
3664
+ }
3665
+ await message.responder.respond(await implementation.extMethod(message.method, message.params));
3666
+ return Handled.yes();
3667
+ },
3668
+ describe: () => "legacy-client-extension-request"
3669
+ });
3670
+ }
3671
+ if (implementation.extNotification) {
3672
+ app[appBuilder]().withHandler({
3673
+ handleMessage: async (message) => {
3674
+ if (message.kind !== "notification" || legacyClientNotificationMethods.has(message.method)) {
3675
+ return Handled.no(message);
3676
+ }
3677
+ await implementation.extNotification(message.method, message.params);
3678
+ return Handled.yes();
3679
+ },
3680
+ describe: () => "legacy-client-extension-notification"
3681
+ });
3682
+ }
3683
+ return app;
3684
+ }
3685
+ class ClientSideConnection {
3686
+ connection;
3687
+ /**
3688
+ * Creates a new client-side connection to an agent.
3689
+ *
3690
+ * This establishes the communication channel between a client and agent
3691
+ * following the ACP specification.
3692
+ *
3693
+ * @param toClient - A function that creates a Client handler to process incoming agent requests
3694
+ * @param stream - The bidirectional message stream for communication. Typically created using
3695
+ * {@link ndJsonStream} for stdio-based connections.
3696
+ *
3697
+ * See protocol docs: [Communication Model](https://agentclientprotocol.com/protocol/overview#communication-model)
3698
+ *
3699
+ * @deprecated Prefer `client({ name }).connectWith(stream, async (ctx) => ...)`.
3700
+ */
3701
+ constructor(toClient, stream) {
3702
+ this.connection = legacyClientApp(toClient(this))[appBuilder]().connect(stream, stableConnectionOptions);
3703
+ }
3704
+ /**
3705
+ * Establishes the connection with a client and negotiates protocol capabilities.
3706
+ *
3707
+ * This method is called once at the beginning of the connection to:
3708
+ * - Negotiate the protocol version to use
3709
+ * - Exchange capability information between client and agent
3710
+ * - Determine available authentication methods
3711
+ *
3712
+ * The agent should respond with its supported protocol version and capabilities.
3713
+ *
3714
+ * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
3715
+ */
3716
+ initialize(params) {
3717
+ return this.connection.sendRequest(AGENT_METHODS.initialize, params);
3718
+ }
3719
+ /**
3720
+ * Creates a new conversation session with the agent.
3721
+ *
3722
+ * Sessions represent independent conversation contexts with their own history and state.
3723
+ *
3724
+ * The agent should:
3725
+ * - Create a new session context
3726
+ * - Connect to any specified MCP servers
3727
+ * - Return a unique session ID for future requests
3728
+ *
3729
+ * The request may include `additionalDirectories` to expand the session's filesystem
3730
+ * scope beyond `cwd` without changing the base for relative paths.
3731
+ *
3732
+ * May return an `auth_required` error if the agent requires authentication.
3733
+ *
3734
+ * See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/session-setup)
3735
+ */
3736
+ newSession(params) {
3737
+ return this.connection.sendRequest(AGENT_METHODS.session_new, params);
3738
+ }
3739
+ /**
3740
+ * Loads an existing session to resume a previous conversation.
3741
+ *
3742
+ * This method is only available if the agent advertises the `loadSession` capability.
3743
+ *
3744
+ * The agent should:
3745
+ * - Restore the session context and conversation history
3746
+ * - Connect to the specified MCP servers
3747
+ * - Stream the entire conversation history back to the client via notifications
3748
+ *
3749
+ * The request may include `additionalDirectories` to set the complete list of
3750
+ * additional workspace roots for the loaded session.
3751
+ *
3752
+ * See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
3753
+ */
3754
+ loadSession(params) {
3755
+ return this.connection.sendRequest(AGENT_METHODS.session_load, params, emptyObjectResponse);
3756
+ }
3757
+ /**
3758
+ * **UNSTABLE**
3759
+ *
3760
+ * This capability is not part of the spec yet, and may be removed or changed at any point.
3761
+ *
3762
+ * Forks an existing session to create a new independent session.
3763
+ *
3764
+ * Creates a new session based on the context of an existing one, allowing
3765
+ * operations like generating summaries without affecting the original session's history.
3766
+ *
3767
+ * The request may include `additionalDirectories` to set the complete list of
3768
+ * additional workspace roots for the forked session.
3769
+ *
3770
+ * This method is only available if the agent advertises the `session.fork` capability.
3771
+ *
3772
+ * @experimental
3773
+ */
3774
+ unstable_forkSession(params) {
3775
+ return this.connection.sendRequest(AGENT_METHODS.session_fork, params);
3776
+ }
3777
+ /**
3778
+ * Lists existing sessions from the agent.
3779
+ *
3780
+ * This method is only available if the agent advertises the `listSessions` capability.
3781
+ *
3782
+ * Returns a list of sessions with metadata like session ID, working directory,
3783
+ * title, and last update time. Supports filtering by working directory,
3784
+ * `additionalDirectories`, and cursor-based pagination.
3785
+ */
3786
+ listSessions(params) {
3787
+ return this.connection.sendRequest(AGENT_METHODS.session_list, params);
3788
+ }
3789
+ /**
3790
+ * Deletes an existing session returned by `session/list`.
3791
+ *
3792
+ * This method is only available if the agent advertises the `sessionCapabilities.delete` capability.
3793
+ */
3794
+ deleteSession(params) {
3795
+ return this.connection.sendRequest(AGENT_METHODS.session_delete, params, emptyObjectResponse);
3796
+ }
3797
+ /**
3798
+ * Resumes an existing session without returning previous messages.
3799
+ *
3800
+ * This method is only available if the agent advertises the `session.resume` capability.
3801
+ *
3802
+ * The agent should resume the session context, allowing the conversation to continue
3803
+ * without replaying the message history (unlike `session/load`).
3804
+ *
3805
+ * The request may include `additionalDirectories` to set the complete list of
3806
+ * additional workspace roots for the resumed session.
3807
+ */
3808
+ resumeSession(params) {
3809
+ return this.connection.sendRequest(AGENT_METHODS.session_resume, params);
3810
+ }
3811
+ /**
3812
+ * Closes an active session and frees up any resources associated with it.
3813
+ *
3814
+ * This method is only available if the agent advertises the `session.close` capability.
3815
+ *
3816
+ * The agent must cancel any ongoing work (as if `session/cancel` was called)
3817
+ * and then free up any resources associated with the session.
3818
+ */
3819
+ closeSession(params) {
3820
+ return this.connection.sendRequest(AGENT_METHODS.session_close, params, emptyObjectResponse);
3821
+ }
3822
+ /**
3823
+ * Sets the operational mode for a session.
3824
+ *
3825
+ * Allows switching between different agent modes (e.g., "ask", "architect", "code")
3826
+ * that affect system prompts, tool availability, and permission behaviors.
3827
+ *
3828
+ * The mode must be one of the modes advertised in `availableModes` during session
3829
+ * creation or loading. Agents may also change modes autonomously and notify the
3830
+ * client via `current_mode_update` notifications.
3831
+ *
3832
+ * This method can be called at any time during a session, whether the Agent is
3833
+ * idle or actively generating a turn.
3834
+ *
3835
+ * See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
3836
+ */
3837
+ setSessionMode(params) {
3838
+ return this.connection.sendRequest(AGENT_METHODS.session_set_mode, params, emptyObjectResponse);
3839
+ }
3840
+ /**
3841
+ * Set a configuration option for a given session.
3842
+ *
3843
+ * The response contains the full set of configuration options and their current values,
3844
+ * as changing one option may affect the available values or state of other options.
3845
+ */
3846
+ setSessionConfigOption(params) {
3847
+ return this.connection.sendRequest(AGENT_METHODS.session_set_config_option, params);
3848
+ }
3849
+ /**
3850
+ * Authenticates the client using the specified authentication method.
3851
+ *
3852
+ * Called when the agent requires authentication before allowing session creation.
3853
+ * The client provides the authentication method ID that was advertised during initialization.
3854
+ *
3855
+ * After successful authentication, the client can proceed to create sessions with
3856
+ * `newSession` without receiving an `auth_required` error.
3857
+ *
3858
+ * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
3859
+ */
3860
+ authenticate(params) {
3861
+ return this.connection.sendRequest(AGENT_METHODS.authenticate, params, emptyObjectResponse);
3862
+ }
3863
+ /**
3864
+ * **UNSTABLE**
3865
+ *
3866
+ * This capability is not part of the spec yet, and may be removed or changed at any point.
3867
+ *
3868
+ * Lists providers that can be configured by the client.
3869
+ *
3870
+ * This method is only available if the agent advertises the `providers` capability.
3871
+ *
3872
+ * @experimental
3873
+ */
3874
+ unstable_listProviders(params) {
3875
+ return this.connection.sendRequest(AGENT_METHODS.providers_list, params);
3876
+ }
3877
+ /**
3878
+ * **UNSTABLE**
3879
+ *
3880
+ * This capability is not part of the spec yet, and may be removed or changed at any point.
3881
+ *
3882
+ * Replaces the configuration for a provider.
3883
+ *
3884
+ * This method is only available if the agent advertises the `providers` capability.
3885
+ *
3886
+ * @experimental
3887
+ */
3888
+ unstable_setProvider(params) {
3889
+ return this.connection.sendRequest(AGENT_METHODS.providers_set, params, emptyObjectResponse);
3890
+ }
3891
+ /**
3892
+ * **UNSTABLE**
3893
+ *
3894
+ * This capability is not part of the spec yet, and may be removed or changed at any point.
3895
+ *
3896
+ * Disables a provider.
3897
+ *
3898
+ * This method is only available if the agent advertises the `providers` capability.
3899
+ *
3900
+ * @experimental
3901
+ */
3902
+ unstable_disableProvider(params) {
3903
+ return this.connection.sendRequest(AGENT_METHODS.providers_disable, params, emptyObjectResponse);
3904
+ }
3905
+ /**
3906
+ * Logout of the current authentication method.
3907
+ */
3908
+ logout(params) {
3909
+ return this.connection.sendRequest(AGENT_METHODS.logout, params, emptyObjectResponse);
3910
+ }
3911
+ /**
3912
+ * Processes a user prompt within a session.
3913
+ *
3914
+ * This method handles the whole lifecycle of a prompt:
3915
+ * - Receives user messages with optional context (files, images, etc.)
3916
+ * - Processes the prompt using language models
3917
+ * - Reports language model content and tool calls to the Clients
3918
+ * - Requests permission to run tools
3919
+ * - Executes any requested tool calls
3920
+ * - Returns when the turn is complete with a stop reason
3921
+ *
3922
+ * See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/prompt-turn)
3923
+ */
3924
+ prompt(params) {
3925
+ return this.connection.sendRequest(AGENT_METHODS.session_prompt, params);
3926
+ }
3927
+ /**
3928
+ * Cancels ongoing operations for a session.
3929
+ *
3930
+ * This is a notification sent by the client to cancel an ongoing prompt turn.
3931
+ *
3932
+ * Upon receiving this notification, the Agent SHOULD:
3933
+ * - Stop all language model requests as soon as possible
3934
+ * - Abort all tool call invocations in progress
3935
+ * - Send any pending `session/update` notifications
3936
+ * - Respond to the original `session/prompt` request with `StopReason::Cancelled`
3937
+ *
3938
+ * See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
3939
+ */
3940
+ cancel(params) {
3941
+ return this.connection.sendNotification(AGENT_METHODS.session_cancel, params);
3942
+ }
3943
+ /**
3944
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
3945
+ *
3946
+ * Starts a NES (Next Edit Suggestions) session.
3947
+ *
3948
+ * @experimental
3949
+ */
3950
+ unstable_startNes(params) {
3951
+ return this.connection.sendRequest(AGENT_METHODS.nes_start, params);
3952
+ }
3953
+ /**
3954
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
3955
+ *
3956
+ * Sends a NES suggestion request.
3957
+ *
3958
+ * @experimental
3959
+ */
3960
+ unstable_suggestNes(params) {
3961
+ return this.connection.sendRequest(AGENT_METHODS.nes_suggest, params);
3962
+ }
3963
+ /**
3964
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
3965
+ *
3966
+ * Closes a NES session.
3967
+ *
3968
+ * @experimental
3969
+ */
3970
+ unstable_closeNes(params) {
3971
+ return this.connection.sendRequest(AGENT_METHODS.nes_close, params, emptyObjectResponse);
3972
+ }
3973
+ /**
3974
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
3975
+ *
3976
+ * Notifies the agent that a document was opened.
3977
+ *
3978
+ * @experimental
3979
+ */
3980
+ unstable_didOpenDocument(params) {
3981
+ return this.connection.sendNotification(AGENT_METHODS.document_did_open, params);
3982
+ }
3983
+ /**
3984
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
3985
+ *
3986
+ * Notifies the agent that a document was changed.
3987
+ *
3988
+ * @experimental
3989
+ */
3990
+ unstable_didChangeDocument(params) {
3991
+ return this.connection.sendNotification(AGENT_METHODS.document_did_change, params);
3992
+ }
3993
+ /**
3994
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
3995
+ *
3996
+ * Notifies the agent that a document was closed.
3997
+ *
3998
+ * @experimental
3999
+ */
4000
+ unstable_didCloseDocument(params) {
4001
+ return this.connection.sendNotification(AGENT_METHODS.document_did_close, params);
4002
+ }
4003
+ /**
4004
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
4005
+ *
4006
+ * Notifies the agent that a document was saved.
4007
+ *
4008
+ * @experimental
4009
+ */
4010
+ unstable_didSaveDocument(params) {
4011
+ return this.connection.sendNotification(AGENT_METHODS.document_did_save, params);
4012
+ }
4013
+ /**
4014
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
4015
+ *
4016
+ * Notifies the agent that a document received focus.
4017
+ *
4018
+ * @experimental
4019
+ */
4020
+ unstable_didFocusDocument(params) {
4021
+ return this.connection.sendNotification(AGENT_METHODS.document_did_focus, params);
4022
+ }
4023
+ /**
4024
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
4025
+ *
4026
+ * Notifies the agent that a NES suggestion was accepted.
4027
+ *
4028
+ * @experimental
4029
+ */
4030
+ unstable_acceptNes(params) {
4031
+ return this.connection.sendNotification(AGENT_METHODS.nes_accept, params);
4032
+ }
4033
+ /**
4034
+ * **UNSTABLE**: This capability is not part of the spec yet, and may be removed or changed at any point.
4035
+ *
4036
+ * Notifies the agent that a NES suggestion was rejected.
4037
+ *
4038
+ * @experimental
4039
+ */
4040
+ unstable_rejectNes(params) {
4041
+ return this.connection.sendNotification(AGENT_METHODS.nes_reject, params);
4042
+ }
4043
+ request(method, params, options) {
4044
+ const spec = agentRequestSpecsByMethod[method];
4045
+ return this.connection.sendRequest(method, params, spec?.mapResponse, options);
4046
+ }
4047
+ notify(method, params) {
4048
+ return this.connection.sendNotification(method, params);
4049
+ }
4050
+ /**
4051
+ * Extension method.
4052
+ *
4053
+ * @deprecated Use {@link request}.
4054
+ */
4055
+ extMethod(method, params) {
4056
+ return this.request(method, params);
4057
+ }
4058
+ /**
4059
+ * Extension notification.
4060
+ *
4061
+ * @deprecated Use {@link notify}.
4062
+ */
4063
+ extNotification(method, params) {
4064
+ return this.notify(method, params);
4065
+ }
4066
+ /**
4067
+ * AbortSignal that aborts when the connection closes.
4068
+ *
4069
+ * This signal can be used to:
4070
+ * - Listen for connection closure: `connection.signal.addEventListener('abort', () => {...})`
4071
+ * - Check connection status synchronously: `if (connection.signal.aborted) {...}`
4072
+ * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
4073
+ *
4074
+ * The connection closes when the underlying stream ends, either normally or due to an error.
4075
+ *
4076
+ * @example
4077
+ * ```typescript
4078
+ * const connection = new ClientSideConnection(client, stream);
4079
+ *
4080
+ * // Listen for closure
4081
+ * connection.signal.addEventListener('abort', () => {
4082
+ * console.log('Connection closed - performing cleanup');
4083
+ * });
4084
+ *
4085
+ * // Check status
4086
+ * if (connection.signal.aborted) {
4087
+ * console.log('Connection is already closed');
4088
+ * }
4089
+ *
4090
+ * // Pass to other APIs
4091
+ * fetch(url, { signal: connection.signal });
4092
+ * ```
4093
+ */
4094
+ get signal() {
4095
+ return this.connection.signal;
4096
+ }
4097
+ /**
4098
+ * Promise that resolves when the connection closes.
4099
+ *
4100
+ * The connection closes when the underlying stream ends, either normally or due to an error.
4101
+ * Once closed, the connection cannot send or receive any more messages.
4102
+ *
4103
+ * This is useful for async/await style cleanup:
4104
+ *
4105
+ * @example
4106
+ * ```typescript
4107
+ * const connection = new ClientSideConnection(client, stream);
4108
+ * await connection.closed;
4109
+ * console.log('Connection closed - performing cleanup');
4110
+ * ```
4111
+ */
4112
+ get closed() {
4113
+ return this.connection.closed;
4114
+ }
4115
+ }
4116
+ const name = "acp-extension-claude";
4117
+ const version = "0.62.0";
4118
+ const dependencies = { "@anthropic-ai/claude-agent-sdk": "0.3.220" };
4119
+ const packageJson = {
4120
+ name,
4121
+ version,
4122
+ dependencies
4123
+ };
4124
+ export {
4125
+ ClientSideConnection as C,
4126
+ PROTOCOL_VERSION as P,
4127
+ RequestError as R,
4128
+ CreateElicitationResponse as a,
4129
+ agent as b,
4130
+ methods as m,
4131
+ ndJsonStream as n,
4132
+ packageJson as p
4133
+ };