-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathacp.ts
More file actions
4273 lines (3995 loc) · 128 KB
/
Copy pathacp.ts
File metadata and controls
4273 lines (3995 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as schema from "./schema/index.js";
import * as validate from "./schema/zod.gen.js";
import type { AnyMessage } from "./jsonrpc.js";
import { ndJsonStream as createJsonStream } from "./stream.js";
export type * from "./schema/types.gen.js";
// Runtime narrowing helpers for extensible unions, exposed as companion values
// that merge (declaration merging) with the like-named types — e.g.
// `CreateElicitationResponse.isAccept(response)`. See schema/guards.gen.ts.
//
// Listed explicitly (not `export *`) so each value+type pair merges rather than
// colliding with the `export type *` above. The guards.gen re-export test
// asserts this list stays in sync as new extensible unions are added.
export {
CreateElicitationRequest,
CreateElicitationResponse,
ElicitationPropertySchema,
MultiSelectItems,
StateUpdate,
} from "./schema/guards.gen.js";
export {
AGENT_METHODS,
CLIENT_METHODS,
PROTOCOL_METHODS,
PROTOCOL_VERSION,
} from "./schema/index.js";
/**
* Stream interface for stable ACP v1 connections.
*
* This type powers bidirectional communication for an ACP connection using
* individual JSON-RPC messages. The experimental v2 entry point exposes the
* batch-capable stream surface.
*
* The most common way to create a Stream is using {@link ndJsonStream}.
*/
export type Stream = {
/** Outgoing JSON-RPC messages written by this side of the connection. */
writable: WritableStream<AnyMessage>;
/** Incoming JSON-RPC messages read by this side of the connection. */
readable: ReadableStream<AnyMessage>;
};
/**
* Creates a stable ACP v1 stream from newline-delimited JSON streams.
*
* @param output - The writable stream to send encoded messages to
* @param input - The readable stream to receive encoded messages from
* @returns A stream for bidirectional ACP v1 communication
*/
export function ndJsonStream(
output: WritableStream<Uint8Array>,
input: ReadableStream<Uint8Array>,
options?: NdJsonStreamOptions,
): Stream {
return createJsonStream(output, input, options);
}
export { RequestError } from "./jsonrpc.js";
export {
DEFAULT_MAX_MESSAGE_BYTES,
MessageTooLargeError,
} from "./stream-limits.js";
export type { NdJsonStreamOptions } from "./stream.js";
export type {
AnyMessage,
AnyNotification,
AnyRequest,
AnyResponse,
ErrorResponse,
JsonRpcId,
MaybePromise,
Result,
SendRequestOptions,
} from "./jsonrpc.js";
import type { NdJsonStreamOptions, WireStream } from "./stream.js";
import { Connection, Handled, HandlerRegistration } from "./jsonrpc.js";
import type {
AnyWireMessage,
ConnectionBuilder,
ConnectionContext,
ConnectionOptions,
HandleResult,
IncomingMessage,
JsonRpcId,
JsonRpcHandler,
MaybePromise,
SendRequestOptions,
} from "./jsonrpc.js";
function emptyObjectResponse<T>(response: T | null | undefined | void): T {
return response ?? ({} as T);
}
function isStream(value: unknown): value is WireStream {
return (
typeof value === "object" &&
value !== null &&
"readable" in value &&
"writable" in value
);
}
function memoryStreamPair(): [WireStream, WireStream] {
const leftToRight = new TransformStream<AnyWireMessage>();
const rightToLeft = new TransformStream<AnyWireMessage>();
return [
{
readable: rightToLeft.readable,
writable: leftToRight.writable,
},
{
readable: leftToRight.readable,
writable: rightToLeft.writable,
},
];
}
/**
* ACP method-name constants.
*
* Use these with `onRequest(...)`, `onNotification(...)`, `request(...)`, and
* `notify(...)` when you want literal-string type inference without spelling
* protocol strings inline.
*/
export const methods = {
agent: {
initialize: schema.AGENT_METHODS.initialize,
authenticate: schema.AGENT_METHODS.authenticate,
logout: schema.AGENT_METHODS.logout,
providers: {
list: schema.AGENT_METHODS.providers_list,
set: schema.AGENT_METHODS.providers_set,
disable: schema.AGENT_METHODS.providers_disable,
},
session: {
new: schema.AGENT_METHODS.session_new,
load: schema.AGENT_METHODS.session_load,
list: schema.AGENT_METHODS.session_list,
delete: schema.AGENT_METHODS.session_delete,
fork: schema.AGENT_METHODS.session_fork,
resume: schema.AGENT_METHODS.session_resume,
close: schema.AGENT_METHODS.session_close,
setMode: schema.AGENT_METHODS.session_set_mode,
setConfigOption: schema.AGENT_METHODS.session_set_config_option,
prompt: schema.AGENT_METHODS.session_prompt,
cancel: schema.AGENT_METHODS.session_cancel,
},
nes: {
start: schema.AGENT_METHODS.nes_start,
suggest: schema.AGENT_METHODS.nes_suggest,
accept: schema.AGENT_METHODS.nes_accept,
reject: schema.AGENT_METHODS.nes_reject,
close: schema.AGENT_METHODS.nes_close,
},
document: {
didOpen: schema.AGENT_METHODS.document_did_open,
didChange: schema.AGENT_METHODS.document_did_change,
didClose: schema.AGENT_METHODS.document_did_close,
didSave: schema.AGENT_METHODS.document_did_save,
didFocus: schema.AGENT_METHODS.document_did_focus,
},
},
client: {
session: {
requestPermission: schema.CLIENT_METHODS.session_request_permission,
update: schema.CLIENT_METHODS.session_update,
},
fs: {
writeTextFile: schema.CLIENT_METHODS.fs_write_text_file,
readTextFile: schema.CLIENT_METHODS.fs_read_text_file,
},
terminal: {
create: schema.CLIENT_METHODS.terminal_create,
output: schema.CLIENT_METHODS.terminal_output,
release: schema.CLIENT_METHODS.terminal_release,
waitForExit: schema.CLIENT_METHODS.terminal_wait_for_exit,
kill: schema.CLIENT_METHODS.terminal_kill,
},
elicitation: {
create: schema.CLIENT_METHODS.elicitation_create,
complete: schema.CLIENT_METHODS.elicitation_complete,
},
},
protocol: {
cancelRequest: schema.PROTOCOL_METHODS.cancel_request,
},
} as const;
const startActiveSession = Symbol("startActiveSession");
/**
* Active ACP connection returned by `AgentApp.connect(...)` and
* `ClientApp.connect(...)`.
*
* Use this handle when you need a connection to stay open independently of a
* single `connectWith(...)` operation.
*/
export interface AcpConnection {
/**
* AbortSignal that aborts when the connection closes.
*/
readonly signal: AbortSignal;
/**
* Promise that resolves when the connection closes.
*/
readonly closed: Promise<void>;
/**
* Closes the connection and rejects pending requests.
*/
close(error?: unknown): void;
}
/**
* Agent-side connection returned by `AgentApp.connect(...)`.
*
* Use `client` to call client-side ACP methods for the lifetime of the
* connection.
*/
export interface AgentConnection extends AcpConnection {
/**
* Context for calling client-side ACP methods.
*/
readonly client: AgentContext;
}
/**
* Client-side connection returned by `ClientApp.connect(...)`.
*
* Use `agent` to call agent-side ACP methods and session helpers for the
* lifetime of the connection.
*/
export interface ClientConnection extends AcpConnection {
/**
* Context for calling agent-side ACP methods.
*/
readonly agent: ClientContext;
}
class AcpContext {
/** @internal */
constructor(
private readonly cx: ConnectionContext,
private readonly currentRequestId?: JsonRpcId,
) {}
/**
* JSON-RPC id of the request currently being handled.
*
* This is `undefined` for notification handlers and for contexts created
* outside an inbound request, such as `connect(...)` and `connectWith(...)`.
*/
get requestId(): JsonRpcId | undefined {
return this.currentRequestId;
}
/** @internal */
protected get connectionContext(): ConnectionContext {
return this.cx;
}
/** @internal */
protected sendRequest<Req, Resp, Output = Resp>(
method: string,
params?: Req,
mapResponse?: (response: Resp) => Output,
options?: SendRequestOptions,
): Promise<Output> {
return this.cx.sendRequest(method, params, mapResponse, options);
}
/** @internal */
protected sendNotification<N>(method: string, params?: N): Promise<void> {
return this.cx.sendNotification(method, params);
}
/** @internal */
protected addDynamicHandler(handler: JsonRpcHandler): HandlerRegistration {
return this.cx.addDynamicHandler(handler);
}
}
/**
* Context passed to agent-side handlers.
*
* Agents use this context to call client-side ACP methods while handling
* requests such as `session/prompt`.
*/
export class AgentContext extends AcpContext {
private constructor(cx: ConnectionContext, requestId?: JsonRpcId) {
super(cx, requestId);
}
/** @internal */
static create(cx: ConnectionContext, requestId?: JsonRpcId): AgentContext {
return new AgentContext(cx, requestId);
}
/**
* Sends a request to the client by ACP method name.
*
* Built-in method literals infer their params and response types. Custom
* methods can specify their response and params types with generics.
*/
request<Method extends ClientRequestMethod>(
method: Method,
params: ClientRequestParamsByMethod[Method],
options?: SendRequestOptions,
): Promise<ClientRequestResponsesByMethod[Method]>;
request<Response = unknown, Params = unknown>(
method: string,
params?: Params,
options?: SendRequestOptions,
): Promise<Response>;
request(
method: string,
params?: unknown,
options?: SendRequestOptions,
): Promise<unknown> {
const spec = clientRequestSpecsByMethod[method] as
AcpRequestSpec<unknown, unknown, unknown> | undefined;
return this.sendRequest(method, params, spec?.mapResponse, options);
}
/**
* Sends a notification to the client by ACP method name.
*
* Built-in method literals infer their params type. Custom notifications can
* specify their params type with a generic.
*/
notify<Method extends ClientNotificationMethod>(
method: Method,
params: ClientNotificationParamsByMethod[Method],
): Promise<void>;
notify<Params = unknown>(method: string, params?: Params): Promise<void>;
notify(method: string, params?: unknown): Promise<void> {
return this.sendNotification(method, params);
}
}
/**
* Context used by clients to call agent-side ACP methods.
*
* `connectWith` passes a `ClientContext` to the callback. Client handlers also
* receive one as `ctx.agent` when they need to call back into the agent.
*/
export class ClientContext extends AcpContext {
private constructor(cx: ConnectionContext, requestId?: JsonRpcId) {
super(cx, requestId);
}
/** @internal */
static create(cx: ConnectionContext, requestId?: JsonRpcId): ClientContext {
return new ClientContext(cx, requestId);
}
/** @internal */
[startActiveSession](
params: schema.NewSessionRequest,
options?: SendRequestOptions,
): Promise<ActiveSession> {
return this.sendRequest<
schema.NewSessionRequest,
schema.NewSessionResponse,
ActiveSession
>(
schema.AGENT_METHODS.session_new,
params,
(response) => this.attachSession(response),
options,
);
}
/**
* Creates a builder for starting and observing an ACP session.
*
* Pass a string for the common case where only `cwd` is needed, or pass a
* full `NewSessionRequest` when you need MCP servers, `_meta`, or additional
* session fields.
*/
buildSession(cwd: string): SessionBuilder;
buildSession(request: schema.NewSessionRequest): SessionBuilder;
buildSession(
cwdOrRequest: string | schema.NewSessionRequest,
): SessionBuilder {
if (typeof cwdOrRequest === "string") {
return SessionBuilder.create(this, {
cwd: cwdOrRequest,
mcpServers: [],
});
}
return SessionBuilder.create(this, cwdOrRequest);
}
/**
* Builds active-session helpers around a `session/new` response.
*/
private attachSession(response: schema.NewSessionResponse): ActiveSession {
const updates = new AsyncQueue<ActiveSessionMessage>();
const closeSignal = this.connectionContext.signal;
const failUpdatesOnClose = () => {
updates.fail(closeSignal.reason ?? new Error("ACP connection closed"));
};
if (closeSignal.aborted) {
failUpdatesOnClose();
} else {
closeSignal.addEventListener("abort", failUpdatesOnClose);
}
const sessionRegistration = sessionUpdateRouter(
this.connectionContext,
).attach(response, updates);
const closeRegistration = new HandlerRegistration(() => {
closeSignal.removeEventListener("abort", failUpdatesOnClose);
});
return ActiveSession.create(this, response, updates, [
sessionRegistration,
closeRegistration,
]);
}
/**
* Sends a request to the agent by ACP method name.
*
* Built-in method literals infer their params and response types. Custom
* methods can specify their response and params types with generics.
*/
request<Method extends AgentRequestMethod>(
method: Method,
params: AgentRequestParamsByMethod[Method],
options?: SendRequestOptions,
): Promise<AgentRequestResponsesByMethod[Method]>;
request<Response = unknown, Params = unknown>(
method: string,
params?: Params,
options?: SendRequestOptions,
): Promise<Response>;
request(
method: string,
params?: unknown,
options?: SendRequestOptions,
): Promise<unknown> {
const spec = agentRequestSpecsByMethod[method] as
AcpRequestSpec<unknown, unknown, unknown> | undefined;
return this.sendRequest(method, params, spec?.mapResponse, options);
}
/**
* Sends a notification to the agent by ACP method name.
*
* Built-in method literals infer their params type. Custom notifications can
* specify their params type with a generic.
*/
notify<Method extends AgentNotificationMethod>(
method: Method,
params: AgentNotificationParamsByMethod[Method],
): Promise<void>;
notify<Params = unknown>(method: string, params?: Params): Promise<void>;
notify(method: string, params?: unknown): Promise<void> {
return this.sendNotification(method, params);
}
}
class AcpConnectionHandle implements AcpConnection {
constructor(private readonly connection: Connection) {}
get signal(): AbortSignal {
return this.connection.signal;
}
get closed(): Promise<void> {
return this.connection.closed;
}
close(error?: unknown): void {
this.connection.close(error);
}
}
class AgentConnectionHandle
extends AcpConnectionHandle
implements AgentConnection
{
readonly client: AgentContext;
private didStartConnectHandlers = false;
constructor(
connection: Connection,
private readonly connectHandlers: readonly AgentConnectHandler[] = [],
) {
super(connection);
this.client = AgentContext.create(connection.getContext());
}
/** @internal */
startConnectHandlers(): void {
if (this.didStartConnectHandlers) {
return;
}
this.didStartConnectHandlers = true;
runConnectHandlers(this, this.connectHandlers);
}
}
class ClientConnectionHandle
extends AcpConnectionHandle
implements ClientConnection
{
readonly agent: ClientContext;
private didStartConnectHandlers = false;
constructor(
connection: Connection,
private readonly connectHandlers: readonly ClientConnectHandler[] = [],
) {
super(connection);
this.agent = ClientContext.create(connection.getContext());
}
/** @internal */
startConnectHandlers(): void {
if (this.didStartConnectHandlers) {
return;
}
this.didStartConnectHandlers = true;
runConnectHandlers(this, this.connectHandlers);
}
}
function agentConnection(
connection: Connection,
connectHandlers: readonly AgentConnectHandler[] = [],
): AgentConnection {
return new AgentConnectionHandle(connection, connectHandlers);
}
function clientConnection(
connection: Connection,
connectHandlers: readonly ClientConnectHandler[] = [],
): ClientConnection {
return new ClientConnectionHandle(connection, connectHandlers);
}
type AsyncQueueEntry<T> =
| {
kind: "value";
value: T;
}
| {
kind: "error";
error: unknown;
};
class AsyncQueue<T> {
private values: Array<AsyncQueueEntry<T>> = [];
private waiters: Array<{
resolve: (value: T) => void;
reject: (error: unknown) => void;
}> = [];
private failed = false;
private failure: unknown;
enqueue(value: T): void {
if (this.failed) {
return;
}
const waiter = this.waiters.shift();
if (waiter) {
waiter.resolve(value);
} else {
this.values.push({ kind: "value", value });
}
}
reject(error: unknown): void {
if (this.failed) {
return;
}
if (this.waiters.length > 0) {
for (const waiter of this.waiters.splice(0)) {
waiter.reject(error);
}
return;
}
this.values.push({ kind: "error", error });
}
clearErrors(): void {
this.values = this.values.filter((entry) => entry.kind === "value");
}
fail(error: unknown): void {
if (this.failed) {
return;
}
this.failed = true;
this.failure = error;
for (const waiter of this.waiters.splice(0)) {
waiter.reject(error);
}
}
next(): Promise<T> {
if (this.values.length > 0) {
const entry = this.values.shift() as AsyncQueueEntry<T>;
if (entry.kind === "error") {
return Promise.reject(entry.error);
}
return Promise.resolve(entry.value);
}
if (this.failed) {
return Promise.reject(this.failure);
}
return new Promise((resolve, reject) => {
this.waiters.push({ resolve, reject });
});
}
}
function cloneNewSessionRequest(
request: schema.NewSessionRequest,
): schema.NewSessionRequest {
return {
...request,
additionalDirectories: request.additionalDirectories
? [...request.additionalDirectories]
: undefined,
mcpServers: [...request.mcpServers],
};
}
/**
* Message produced by an `ActiveSession`.
*
* `session_update` messages expose the typed `session/update` notification and
* `stop` messages report the final `session/prompt` response. A prompt turn is
* complete once a `stop` message is returned.
*/
export type ActiveSessionMessage =
| {
/**
* Indicates that this message came from a `session/update` notification.
*/
kind: "session_update";
/**
* Full notification sent by the agent.
*/
notification: schema.SessionNotification;
/**
* Convenience alias for `notification.update`.
*/
update: schema.SessionUpdate;
}
| {
/**
* Indicates that the prompt turn has completed.
*/
kind: "stop";
/**
* Final response from `session/prompt`.
*/
response: schema.PromptResponse;
/**
* Convenience alias for `response.stopReason`.
*/
stopReason: schema.StopReason;
};
/**
* Builder for creating an `ActiveSession`.
*
* Start from `ctx.buildSession("/absolute/cwd")` for the common case, or
* pass a full `NewSessionRequest` to `ctx.buildSession(...)` when the session
* needs MCP servers, `_meta`, or additional request fields. All paths in ACP
* payloads should be absolute.
*/
export class SessionBuilder {
private request: schema.NewSessionRequest;
private constructor(
private cx: ClientContext,
request: schema.NewSessionRequest,
) {
this.request = cloneNewSessionRequest(request);
}
/** @internal */
static create(
cx: ClientContext,
request: schema.NewSessionRequest,
): SessionBuilder {
return new SessionBuilder(cx, request);
}
/**
* Returns the `session/new` request that will be sent.
*
* The returned object is a defensive copy, so mutating it does not change the
* builder.
*/
toRequest(): schema.NewSessionRequest {
return cloneNewSessionRequest(this.request);
}
/**
* Replaces the additional workspace roots for this session.
*
* `additionalDirectories` expand the session's file-system scope without
* changing `cwd`. Each path should be absolute.
*/
withAdditionalDirectories(additionalDirectories: string[]): this {
this.request = {
...this.request,
additionalDirectories: [...additionalDirectories],
};
return this;
}
/**
* Adds one MCP server to the `session/new` request.
*/
withMcpServer(mcpServer: schema.McpServer): this {
this.request = {
...this.request,
mcpServers: [...this.request.mcpServers, mcpServer],
};
return this;
}
/**
* Starts the session and returns an `ActiveSession` for prompting and reading
* updates.
*
* Call `dispose()` on the returned session when you no longer need update
* routing, or use `withSession(...)` to scope disposal automatically.
*/
async start(options?: SendRequestOptions): Promise<ActiveSession> {
return this.cx[startActiveSession](this.toRequest(), options);
}
/**
* Starts the session, runs `op`, and disposes the active-session update
* routing when `op` finishes or throws.
*/
async withSession<T>(
op: (session: ActiveSession) => MaybePromise<T>,
): Promise<T> {
const session = await this.start();
try {
return await op(session);
} finally {
session.dispose();
}
}
}
/**
* Convenience wrapper for an active ACP session.
*
* An active session routes `session/update` notifications for one session ID
* into an async queue. Use `prompt(...)` to send user content, then read updates
* with `nextUpdate()` until a `stop` message is returned.
*/
export class ActiveSession {
private constructor(
private cx: ClientContext,
private sessionResponse: schema.NewSessionResponse,
private updates: {
enqueue(value: ActiveSessionMessage): void;
reject(error: unknown): void;
clearErrors(): void;
fail(error: unknown): void;
next(): Promise<ActiveSessionMessage>;
},
private registrations: HandlerRegistration[],
) {}
/** @internal */
static create(
cx: ClientContext,
sessionResponse: schema.NewSessionResponse,
updates: {
enqueue(value: ActiveSessionMessage): void;
reject(error: unknown): void;
clearErrors(): void;
fail(error: unknown): void;
next(): Promise<ActiveSessionMessage>;
},
registrations: HandlerRegistration[],
): ActiveSession {
return new ActiveSession(cx, sessionResponse, updates, registrations);
}
/**
* Session ID returned by `session/new`.
*/
get sessionId(): schema.SessionId {
return this.sessionResponse.sessionId;
}
/**
* Mode state returned when the session was created, if the agent provided it.
*/
get modes(): schema.SessionModeState | null | undefined {
return this.sessionResponse.modes;
}
/**
* Metadata returned when the session was created.
*/
get meta(): { [key: string]: unknown } | null | undefined {
return this.sessionResponse._meta;
}
/**
* Full response returned by `session/new`.
*/
get newSessionResponse(): schema.NewSessionResponse {
return this.sessionResponse;
}
/**
* Sends a prompt to this session.
*
* Strings are converted to one text content block. A single content block is
* wrapped in an array. The returned promise resolves with the final
* `PromptResponse`, and the same completion is also queued as a `stop`
* message for `nextUpdate()`.
*/
prompt(
prompt: string | schema.ContentBlock | Array<schema.ContentBlock>,
options?: SendRequestOptions,
): Promise<schema.PromptResponse> {
this.updates.clearErrors();
const response = this.cx.request(
schema.AGENT_METHODS.session_prompt,
{
sessionId: this.sessionId,
prompt: this.promptBlocks(prompt),
},
options,
);
void response.then(
(value) => {
this.updates.enqueue({
kind: "stop",
response: value,
stopReason: value.stopReason,
});
},
(error) => {
this.updates.reject(error);
},
);
return response;
}
/**
* Reads the next update or stop message for this session.
*/
nextUpdate(): Promise<ActiveSessionMessage> {
return this.updates.next();
}
/**
* Reads text chunks until the current prompt turn stops.
*
* Only `agent_message_chunk` updates with text content are appended. Other
* update types are ignored by this helper; use `nextUpdate()` when you need
* tool calls, plans, or the final `PromptResponse`.
*/
async readText(): Promise<string> {
let output = "";
for (;;) {
const message = await this.nextUpdate();
if (message.kind === "stop") {
return output;
}
const { update } = message;
if (
update.sessionUpdate === "agent_message_chunk" &&
update.content.type === "text"
) {
output += update.content.text;
}
}
}
/**
* Stops routing updates to this active-session helper.
*
* This does not close the ACP session on the agent. Use `ClientContext`
* session lifecycle methods when the protocol session itself should be closed
* or deleted.
*/
dispose(): void {
for (const registration of this.registrations.splice(0)) {
registration.dispose();
}
this.updates.fail(new Error("Active session disposed"));
}
/**
* Supports explicit resource management with `using`.
*/
[Symbol.dispose](): void {
this.dispose();
}
private promptBlocks(
prompt: string | schema.ContentBlock | Array<schema.ContentBlock>,
): Array<schema.ContentBlock> {
if (typeof prompt === "string") {
return [{ type: "text", text: prompt }];
}
if (Array.isArray(prompt)) {
return prompt;
}
return [prompt];
}
}
/**
* Options used when creating an ACP app.
*/
export type AppOptions = {
/**
* Human-readable name used in JSON-RPC handler descriptions and diagnostics.
*/
name?: string;
};
/**
* Parser used by custom methods to validate or transform raw JSON-RPC params.
*
* A Zod schema can be passed directly because schemas expose a compatible
* `parse(...)` method.
*/
export type ParamsParser<Params> =
| {
/**
* Parses raw JSON-RPC params into the handler's typed params.
*/
parse: (params: unknown) => Params;
}
| ((params: unknown) => Params);
/**
* Common context passed to agent-side handlers.
*/
export type AgentHandlerContext<Params> = {
/**
* Parsed request or notification params.
*/
params: Params;
/**
* AbortSignal for the current request, or the connection signal for
* notifications.
*/
signal: AbortSignal;
/**
* Typed client context for calling client-side ACP methods.
*/
client: AgentContext;
};
/**
* Context passed to agent-side request handlers.
*/
export type AgentRequestContext<Params> = AgentHandlerContext<Params> & {
/**
* JSON-RPC id of the request currently being handled.
*/
requestId: JsonRpcId;
};
/**
* Context passed to agent-side notification handlers.
*
* Notifications do not have JSON-RPC request ids.
*/
export type AgentNotificationContext<Params> = AgentHandlerContext<Params>;
/**
* Common context passed to client-side handlers.
*/