-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathCodexElicitationHandler.ts
More file actions
791 lines (725 loc) · 29.6 KB
/
Copy pathCodexElicitationHandler.ts
File metadata and controls
791 lines (725 loc) · 29.6 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
import * as acp from "@agentclientprotocol/sdk";
import type { SessionState } from "./CodexAcpServer";
import type { ElicitationHandler } from "./CodexAppServerClient";
import type { ServerNotification } from "./app-server";
import type {JsonValue} from "./app-server/serde_json/JsonValue";
import type {
ItemCompletedNotification,
ItemStartedNotification,
McpServerElicitationRequestParams,
McpServerElicitationRequestResponse,
ToolRequestUserInputParams,
ToolRequestUserInputResponse,
} from "./app-server/v2";
import { logger } from "./Logger";
import { McpApprovalOptionId } from "./McpApprovalOptionId";
import type {AcpClientConnection} from "./ACPSessionConnection";
import {
clientSupportsFormElicitation,
clientSupportsUrlElicitation,
} from "./ElicitationCapabilities";
// Standard elicitation options (non-tool-call approval).
const ELICITATION_OPTIONS: acp.PermissionOption[] = [
{ optionId: "accept", name: "Accept", kind: "allow_once" },
{ optionId: "decline", name: "Decline", kind: "reject_once" },
];
type PersistValue = "session" | "always";
type ToolApprovalPersistValue = PersistValue | "once";
type McpElicitationContext = {
isToolApproval: boolean;
persistOptions: Set<PersistValue>;
correlatedCallId: string | undefined;
};
type AcpBackedMcpElicitationParams = Extract<
McpServerElicitationRequestParams,
{ mode: "form" } | { mode: "url" }
>;
const USER_INPUT_OTHER_FIELD_SUFFIX = "__other";
/**
* Parses the `persist` field from the elicitation request `_meta`.
* Codex advertises which persistence options the client should show.
* Returns a set of supported persist values.
*/
function parsePersistOptions(meta: unknown): Set<PersistValue> {
const result = new Set<PersistValue>();
if (!meta || typeof meta !== "object") return result;
const persist = (meta as Record<string, unknown>)["persist"];
if (persist === "session") {
result.add("session");
} else if (persist === "always") {
result.add("always");
} else if (Array.isArray(persist)) {
if (persist.includes("session")) result.add("session");
if (persist.includes("always")) result.add("always");
}
return result;
}
function isMcpToolCallApproval(meta: unknown): boolean {
return (
meta !== null &&
typeof meta === "object" &&
(meta as Record<string, unknown>)["codex_approval_kind"] === "mcp_tool_call"
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function normalizeJsonValue(value: unknown): JsonValue {
if (value === null || value === undefined) {
return null;
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value;
}
if (typeof value === "bigint") {
return Number(value);
}
if (Array.isArray(value)) {
return value.map(normalizeJsonValue);
}
if (typeof value === "object") {
return Object.fromEntries(
Object.entries(value)
.filter(([, nested]) => nested !== undefined)
.map(([key, nested]) => [key, normalizeJsonValue(nested)])
);
}
return String(value);
}
function normalizeJsonObject(value: Record<string, unknown>): Record<string, JsonValue> {
return Object.fromEntries(
Object.entries(value)
.filter(([, nested]) => nested !== undefined)
.map(([key, nested]) => [key, normalizeJsonValue(nested)])
);
}
function normalizeElicitationSchema(value: unknown): acp.ElicitationSchema {
const normalized = normalizeElicitationSchemaValue(value);
if (!isRecord(normalized)) {
return { type: "object", properties: {} };
}
return {
...normalized,
type: "object",
} as acp.ElicitationSchema;
}
function normalizeElicitationSchemaValue(value: unknown): unknown {
if (typeof value === "bigint") {
return Number(value);
}
if (Array.isArray(value)) {
return value.map(normalizeElicitationSchemaValue);
}
if (!isRecord(value)) {
return value;
}
const result: Record<string, unknown> = Object.fromEntries(
Object.entries(value)
.filter(([, nested]) => nested !== undefined)
.map(([key, nested]) => [key, normalizeElicitationSchemaValue(nested)])
);
if (
result["type"] === "string" &&
Array.isArray(result["enum"]) &&
Array.isArray(result["enumNames"]) &&
!Array.isArray(result["oneOf"])
) {
const values = result["enum"];
const names = result["enumNames"];
result["oneOf"] = values.map((value, index) => ({
const: String(value),
title: String(names[index] ?? value),
}));
delete result["enum"];
delete result["enumNames"];
}
return result;
}
function metaRecord(meta: unknown): Record<string, unknown> | null {
return isRecord(meta) ? meta : null;
}
function persistChoiceOption(value: ToolApprovalPersistValue): acp.EnumOption {
switch (value) {
case "once":
return { const: "once", title: "Allow once" };
case "session":
return { const: "session", title: "Allow for this session" };
case "always":
return { const: "always", title: "Allow and don't ask again" };
}
}
function addPersistChoiceToSchema(
schema: acp.ElicitationSchema,
persistOptions: Set<PersistValue>
): acp.ElicitationSchema {
if (persistOptions.size === 0) {
return schema;
}
const choices: ToolApprovalPersistValue[] = ["once"];
if (persistOptions.has("session")) choices.push("session");
if (persistOptions.has("always")) choices.push("always");
return {
...schema,
properties: {
...schema.properties,
persist: {
type: "string",
title: "Approval scope",
oneOf: choices.map(persistChoiceOption),
default: "once",
},
},
required: Array.from(new Set([...(schema.required ?? []), "persist"])),
};
}
function contentRecord(content: unknown): Record<string, acp.ElicitationContentValue> {
return isRecord(content) ? content as Record<string, acp.ElicitationContentValue> : {};
}
function jsonObjectOrNull(
content: Record<string, acp.ElicitationContentValue>
): JsonValue | null {
const entries = Object.entries(content);
if (entries.length === 0) {
return null;
}
return Object.fromEntries(entries.map(([key, value]) => [key, normalizeJsonValue(value)]));
}
function elicitationResponseMeta(
response: acp.CreateElicitationResponse,
context: McpElicitationContext,
persist: unknown = undefined
): JsonValue | null {
const responseMeta = metaRecord(response._meta);
const meta = responseMeta ? normalizeJsonObject(responseMeta) : {};
if (context.isToolApproval) {
delete meta["persist"];
}
if (persist === "session" || persist === "always") {
meta["persist"] = persist;
}
return Object.keys(meta).length === 0 ? null : meta;
}
function userInputOtherFieldId(questionId: string, questionIds: Set<string>): string {
const base = `${questionId}${USER_INPUT_OTHER_FIELD_SUFFIX}`;
if (!questionIds.has(base)) {
return base;
}
let index = 1;
while (questionIds.has(`${base}${index}`)) {
index += 1;
}
return `${base}${index}`;
}
function userInputResponseValue(
content: Record<string, acp.ElicitationContentValue>,
fieldId: string
): acp.ElicitationContentValue | undefined {
const value = content[fieldId];
if (typeof value === "string" && value.trim() === "") {
return undefined;
}
if (Array.isArray(value) && value.length === 0) {
return undefined;
}
return value;
}
/**
* Builds the ACP permission options for an MCP tool call approval elicitation.
* Always includes "Allow Once"; adds session/always persist options when advertised.
*/
function buildToolApprovalOptions(persistOptions: Set<PersistValue>): acp.PermissionOption[] {
const options: acp.PermissionOption[] = [
{ optionId: McpApprovalOptionId.AllowOnce, name: "Allow", kind: "allow_once" },
];
if (persistOptions.has("session")) {
options.push({ optionId: McpApprovalOptionId.AllowSession, name: "Allow for This Session", kind: "allow_always" });
}
if (persistOptions.has("always")) {
options.push({ optionId: McpApprovalOptionId.AllowAlways, name: "Allow and Don't Ask Again", kind: "allow_always" });
}
options.push({ optionId: McpApprovalOptionId.Decline, name: "Decline", kind: "reject_once" });
return options;
}
export class CodexElicitationHandler implements ElicitationHandler {
private readonly connection: AcpClientConnection;
private readonly sessionState: SessionState;
private readonly clientCapabilities: acp.ClientCapabilities | null;
private readonly cancellationSignal: AbortSignal | undefined;
// In Rust, the MCP elicitation handler receives ElicitationRequestEvent directly from the MCP
// protocol layer, where id is set to "mcp_tool_call_approval_<call_id>" — the call ID is extracted
// by stripping that prefix.
//
// In TypeScript, Codex speaks the app-server JSON-RPC protocol (v2), where
// McpServerElicitationRequestParams omits elicitationId for form mode, so the MCP-level ID never
// reaches the client.
//
// Workaround: before requesting approval, Codex emits an item/started notification with an
// mcpToolCall item carrying the call id and server name. We store (threadId, serverName) → callId
// here so the elicitation request can correlate back to the already-rendered tool call item.
//
// Multiple calls are safe because Codex requests approval synchronously — it blocks on one tool
// call's elicitation before starting the next, so there is at most one pending approval per
// (threadId, serverName).
private readonly pendingMcpApprovals = new Map<string, string>();
// The app-server handler exposes URL elicitationId, while serverRequest/resolved only exposes
// threadId here, so accepted URL elicitations are completed at thread scope.
private readonly pendingUrlElicitations = new Map<string, Set<string>>();
constructor(
connection: AcpClientConnection,
sessionState: SessionState,
clientCapabilities: acp.ClientCapabilities | null = null,
cancellationSignal?: AbortSignal
) {
this.connection = connection;
this.sessionState = sessionState;
this.clientCapabilities = clientCapabilities;
this.cancellationSignal = cancellationSignal;
}
async handleNotification(notification: ServerNotification): Promise<void> {
switch (notification.method) {
case "item/started":
this.handleItemStarted(notification.params);
return;
case "item/completed":
this.handleItemCompleted(notification.params);
return;
case "serverRequest/resolved":
this.clearThread(notification.params.threadId);
await this.completeUrlElicitations(notification.params.threadId);
return;
default:
return;
}
}
async handleElicitation(
params: McpServerElicitationRequestParams
): Promise<McpServerElicitationRequestResponse> {
try {
const context = this.createMcpElicitationContext(params);
if (this.shouldUseAcpElicitation(params)) {
const response = await this.connection.request(
acp.methods.client.elicitation.create,
this.buildElicitationRequest(params, context),
this.requestOptions(),
);
const result = this.convertElicitationResponse(response, context);
if (params.mode === "url" && result.action === "accept") {
this.trackUrlElicitation(params.threadId, params.elicitationId);
}
await this.publishAcceptedMcpToolApproval(context, result.action === "accept");
return result;
}
const { request, correlatedCallId } = this.buildPermissionRequest(params, context);
const response = await this.connection.request(
acp.methods.client.session.requestPermission,
request,
this.requestOptions(),
);
if (correlatedCallId !== undefined && response.outcome.outcome !== "cancelled") {
const optionId = response.outcome.optionId;
if (optionId !== McpApprovalOptionId.Decline) {
await this.connection.notify(acp.methods.client.session.update, {
sessionId: this.sessionState.sessionId,
update: { sessionUpdate: "tool_call_update", toolCallId: correlatedCallId, status: "in_progress" },
});
}
}
return this.convertPermissionResponse(response);
} catch (error) {
logger.error("Error handling MCP elicitation request", error);
return { action: "cancel", content: null, _meta: null };
}
}
async handleUserInput(params: ToolRequestUserInputParams): Promise<ToolRequestUserInputResponse> {
if (!clientSupportsFormElicitation(this.clientCapabilities)) {
return { answers: {} };
}
try {
const response = await this.requestUserInputElicitation(params);
if (response === null) {
return { answers: {} };
}
return this.convertUserInputResponse(response, params);
} catch (error) {
logger.error("Error handling Codex user input request", error);
return { answers: {} };
}
}
private requestOptions(
cancellationSignal: AbortSignal | undefined = this.cancellationSignal
): acp.SendRequestOptions | undefined {
return cancellationSignal ? {cancellationSignal} : undefined;
}
private async requestUserInputElicitation(
params: ToolRequestUserInputParams
): Promise<acp.CreateElicitationResponse | null> {
const request = this.buildUserInputRequest(params);
if (params.autoResolutionMs === null) {
return await this.connection.request(
acp.methods.client.elicitation.create,
request,
this.requestOptions(),
);
}
const abortController = new AbortController();
let timeout: ReturnType<typeof setTimeout> | undefined;
let removeAbortListener: (() => void) | undefined;
const timeoutPromise = new Promise<null>((resolve) => {
const resolveWithoutInput = () => {
abortController.abort();
resolve(null);
};
timeout = setTimeout(resolveWithoutInput, Math.max(0, params.autoResolutionMs ?? 0));
if (this.cancellationSignal?.aborted) {
resolveWithoutInput();
return;
}
if (this.cancellationSignal) {
this.cancellationSignal.addEventListener("abort", resolveWithoutInput, { once: true });
removeAbortListener = () => {
this.cancellationSignal?.removeEventListener("abort", resolveWithoutInput);
};
}
});
const requestPromise = Promise.resolve(this.connection.request(
acp.methods.client.elicitation.create,
request,
this.requestOptions(abortController.signal),
));
void requestPromise.catch(() => {});
try {
return await Promise.race([requestPromise, timeoutPromise]);
} finally {
if (timeout) {
clearTimeout(timeout);
}
removeAbortListener?.();
}
}
private createMcpElicitationContext(params: McpServerElicitationRequestParams): McpElicitationContext {
const isToolApproval = isMcpToolCallApproval(params._meta);
const persistOptions = parsePersistOptions(params._meta);
const correlatedCallId = isToolApproval && (params.mode === "form" || params.mode === "openai/form")
? this.popPendingApproval(params.threadId, params.serverName)
: undefined;
return { isToolApproval, persistOptions, correlatedCallId };
}
private shouldUseAcpElicitation(
params: McpServerElicitationRequestParams
): params is AcpBackedMcpElicitationParams {
switch (params.mode) {
case "form":
return clientSupportsFormElicitation(this.clientCapabilities);
case "url":
return clientSupportsUrlElicitation(this.clientCapabilities);
case "openai/form":
return false;
}
}
private buildElicitationRequest(
params: AcpBackedMcpElicitationParams,
context: McpElicitationContext
): acp.CreateElicitationRequest {
const base = {
sessionId: this.sessionState.sessionId,
...(context.correlatedCallId ? { toolCallId: context.correlatedCallId } : {}),
message: params.message,
_meta: metaRecord(params._meta),
};
switch (params.mode) {
case "form": {
const requestedSchema = context.isToolApproval
? addPersistChoiceToSchema(
normalizeElicitationSchema(params.requestedSchema),
context.persistOptions,
)
: normalizeElicitationSchema(params.requestedSchema);
return {
...base,
mode: "form",
requestedSchema,
};
}
case "url":
return {
...base,
mode: "url",
url: params.url,
elicitationId: params.elicitationId,
};
}
}
private buildUserInputRequest(params: ToolRequestUserInputParams): acp.CreateElicitationRequest {
const properties: Record<string, acp.ElicitationPropertySchema> = {};
const required: string[] = [];
const questionIds = new Set(params.questions.map(question => question.id));
for (const question of params.questions) {
const options = question.options ?? [];
const hasOptions = options.length > 0;
const hasOtherAnswer = question.isOther && hasOptions;
const base = {
title: question.header || question.id,
description: question.question,
_meta: {
codex: {
isOther: question.isOther,
isSecret: question.isSecret,
},
},
};
if (!hasOtherAnswer) {
required.push(question.id);
}
properties[question.id] = hasOptions
? {
...base,
type: "string",
oneOf: options.map(option => ({
const: option.label,
title: option.label,
description: option.description,
})),
}
: {
...base,
type: "string",
};
if (hasOtherAnswer) {
properties[userInputOtherFieldId(question.id, questionIds)] = {
type: "string",
title: "Other",
description: "Type your own answer instead of choosing an option above.",
_meta: {
codex: {
questionId: question.id,
isOtherAnswer: true,
isSecret: question.isSecret,
},
},
};
}
}
const firstQuestion = params.questions[0];
return {
sessionId: this.sessionState.sessionId,
toolCallId: params.itemId,
mode: "form",
message: params.questions.length === 1 && firstQuestion
? firstQuestion.question
: "Input requested",
requestedSchema: {
type: "object",
properties,
required,
},
_meta: {
codex: {
autoResolutionMs: params.autoResolutionMs,
},
},
};
}
private buildPermissionRequest(
params: McpServerElicitationRequestParams,
context: McpElicitationContext
): { request: acp.RequestPermissionRequest; correlatedCallId: string | undefined } {
const sessionId = this.sessionState.sessionId;
const messageContent: acp.ToolCallContent = {
type: "content",
content: { type: "text", text: params.message },
};
const options = context.isToolApproval
? buildToolApprovalOptions(context.persistOptions)
: ELICITATION_OPTIONS;
if (params.mode === "form" || params.mode === "openai/form") {
if (context.correlatedCallId !== undefined) {
// The tool call item is already visible in the IDE conversation history because
// item/started was emitted before the elicitation request. Sending content or
// rawInput here would duplicate that information in the approval widget.
return {
request: {
sessionId,
toolCall: {
toolCallId: context.correlatedCallId,
kind: "execute",
status: "pending",
// content: [messageContent], — omitted: already rendered via item/started
// rawInput: { ... } — omitted: same reason
},
_meta: { is_mcp_tool_approval: true },
options,
},
correlatedCallId: context.correlatedCallId,
};
}
return {
request: {
sessionId,
toolCall: {
toolCallId: `elicitation-${params.serverName}`,
kind: context.isToolApproval ? "execute" : "other",
status: "pending",
content: [messageContent],
rawInput: { serverName: params.serverName, schema: params.requestedSchema },
},
...(context.isToolApproval ? { _meta: { is_mcp_tool_approval: true } } : {}),
options,
},
correlatedCallId: undefined,
};
} else {
return {
request: {
sessionId,
toolCall: {
toolCallId: `elicitation-${params.elicitationId}`,
kind: "fetch",
status: "pending",
content: [messageContent],
rawInput: { serverName: params.serverName, url: params.url },
},
options,
},
correlatedCallId: undefined,
};
}
}
private convertPermissionResponse(
response: acp.RequestPermissionResponse
): McpServerElicitationRequestResponse {
if (response.outcome.outcome === "cancelled") {
return { action: "cancel", content: null, _meta: null };
}
const optionId = response.outcome.optionId;
if (optionId === McpApprovalOptionId.AllowSession) {
return { action: "accept", content: null, _meta: { persist: "session" } };
}
if (optionId === McpApprovalOptionId.AllowAlways) {
return { action: "accept", content: null, _meta: { persist: "always" } };
}
if (optionId === McpApprovalOptionId.AllowOnce || optionId === "accept") {
return { action: "accept", content: null, _meta: null };
}
return { action: "decline", content: null, _meta: null };
}
private convertElicitationResponse(
response: acp.CreateElicitationResponse,
context: McpElicitationContext
): McpServerElicitationRequestResponse {
if (acp.CreateElicitationResponse.isAccept(response)) {
const content = contentRecord(response.content);
const persist = context.isToolApproval ? content["persist"] : undefined;
if (persist === "session" || persist === "always" || persist === "once") {
delete content["persist"];
}
return {
action: "accept",
content: jsonObjectOrNull(content),
_meta: elicitationResponseMeta(response, context, persist),
};
}
if (acp.CreateElicitationResponse.isDecline(response)) {
return { action: "decline", content: null, _meta: elicitationResponseMeta(response, context) };
}
if (acp.CreateElicitationResponse.isCancel(response)) {
return { action: "cancel", content: null, _meta: elicitationResponseMeta(response, context) };
}
if (acp.CreateElicitationResponse.isCustom(response)) {
return { action: "cancel", content: null, _meta: null };
}
// Malformed known variants match none of the SDK guards.
return { action: "cancel", content: null, _meta: null };
}
private convertUserInputResponse(
response: acp.CreateElicitationResponse,
params: ToolRequestUserInputParams
): ToolRequestUserInputResponse {
if (!acp.CreateElicitationResponse.isAccept(response)) {
return { answers: {} };
}
const answers: ToolRequestUserInputResponse["answers"] = {};
const content = contentRecord(response.content);
const questionIds = new Set(params.questions.map(question => question.id));
for (const question of params.questions) {
const value = question.isOther && question.options != null && question.options.length > 0
? userInputResponseValue(content, userInputOtherFieldId(question.id, questionIds))
?? userInputResponseValue(content, question.id)
: userInputResponseValue(content, question.id);
if (value === undefined) {
continue;
}
answers[question.id] = {
answers: Array.isArray(value)
? value.map(String)
: [String(value)],
};
}
return { answers };
}
private async publishAcceptedMcpToolApproval(
context: McpElicitationContext,
accepted: boolean
): Promise<void> {
if (!accepted || context.correlatedCallId === undefined) {
return;
}
await this.connection.notify(acp.methods.client.session.update, {
sessionId: this.sessionState.sessionId,
update: { sessionUpdate: "tool_call_update", toolCallId: context.correlatedCallId, status: "in_progress" },
});
}
private trackUrlElicitation(threadId: string, elicitationId: string): void {
const existing = this.pendingUrlElicitations.get(threadId);
if (existing) {
existing.add(elicitationId);
return;
}
this.pendingUrlElicitations.set(threadId, new Set([elicitationId]));
}
private async completeUrlElicitations(threadId: string): Promise<void> {
const elicitationIds = this.pendingUrlElicitations.get(threadId);
if (!elicitationIds) {
return;
}
this.pendingUrlElicitations.delete(threadId);
for (const elicitationId of elicitationIds) {
await this.connection.notify(acp.methods.client.elicitation.complete, {
elicitationId,
});
}
}
private handleItemStarted(event: ItemStartedNotification): void {
if (event.item.type !== "mcpToolCall") {
return;
}
this.pendingMcpApprovals.set(this.key(event.threadId, event.item.server), event.item.id);
}
private handleItemCompleted(event: ItemCompletedNotification): void {
if (event.item.type !== "mcpToolCall") {
return;
}
// This may run after the elicitation path already consumed the same entry.
// That double-pop is intentional: approvals pop on request correlation, while
// auto-approved or interrupted calls need completion-side cleanup.
this.popPendingApproval(event.threadId, event.item.server);
}
private popPendingApproval(threadId: string, serverName: string): string | undefined {
const key = this.key(threadId, serverName);
const callId = this.pendingMcpApprovals.get(key);
this.pendingMcpApprovals.delete(key);
return callId;
}
private clearThread(threadId: string): void {
for (const key of this.pendingMcpApprovals.keys()) {
if (this.belongsToThread(key, threadId)) {
this.pendingMcpApprovals.delete(key);
}
}
}
private key(threadId: string, serverName: string): string {
return `${threadId}:${serverName}`;
}
private belongsToThread(key: string, threadId: string): boolean {
return key.startsWith(`${threadId}:`);
}
}