@agentclientprotocol/codex-acp 2.5.1-preview.3 → 2.5.1-preview.4

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.
Files changed (2) hide show
  1. package/dist/index.js +401 -490
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -25039,6 +25039,8 @@ var zSubagentUpdate = object({
25039
25039
  description: defaultOnError(string2().nullish(), () => void 0),
25040
25040
  capabilities: defaultOnError(zSubagentSessionCapabilities.nullish(), () => void 0),
25041
25041
  state: defaultOnError(zStateUpdate.nullish(), () => void 0),
25042
+ cwd: string2().nullish(),
25043
+ additionalDirectories: array(string2()).nullish(),
25042
25044
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
25043
25045
  });
25044
25046
  var zSessionMessage = object({
@@ -25501,6 +25503,17 @@ var zCancelRequestNotification = object({
25501
25503
 
25502
25504
  // node_modules/@agentclientprotocol/sdk/dist/core/jsonrpc.js
25503
25505
  var CANCEL_REQUEST_METHOD = "$/cancel_request";
25506
+ function treatSessionNotFoundAsSuccess(method, response, success2) {
25507
+ if (method !== "session/close" && method !== "session/delete") {
25508
+ return response;
25509
+ }
25510
+ return response.catch((error62) => {
25511
+ if (error62 instanceof RequestError && error62.code === -32002) {
25512
+ return success2();
25513
+ }
25514
+ throw error62;
25515
+ });
25516
+ }
25504
25517
  function isRequestMessage(value) {
25505
25518
  return isJsonRpcEnvelope(value) && "id" in value && typeof value["method"] === "string" && isJsonRpcId(value["id"]);
25506
25519
  }
@@ -25533,28 +25546,6 @@ function isJsonRpcId(value) {
25533
25546
  function isResponseShapedMessage(value) {
25534
25547
  return isRecord(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
25535
25548
  }
25536
- function isResponseBatch(batch) {
25537
- let hasValidCall = false;
25538
- let hasValidResponse = false;
25539
- let hasCallShape = false;
25540
- let hasResponseShape = false;
25541
- for (const entry of batch) {
25542
- hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
25543
- hasValidResponse ||= isResponseMessage(entry);
25544
- if (!isRecord(entry)) {
25545
- continue;
25546
- }
25547
- hasCallShape ||= "method" in entry;
25548
- hasResponseShape ||= "result" in entry || "error" in entry;
25549
- }
25550
- if (hasValidCall) {
25551
- return false;
25552
- }
25553
- if (hasValidResponse) {
25554
- return true;
25555
- }
25556
- return hasResponseShape && !hasCallShape;
25557
- }
25558
25549
  function cancelRequestId(params) {
25559
25550
  if (!isRecord(params) || !isJsonRpcId(params["requestId"])) {
25560
25551
  return void 0;
@@ -25686,7 +25677,6 @@ var RequestResponder = class {
25686
25677
  });
25687
25678
  }
25688
25679
  };
25689
- var requestBatchSizes = /* @__PURE__ */ new WeakMap();
25690
25680
  var nullIdResponders = /* @__PURE__ */ new WeakSet();
25691
25681
  function isV2RequestId(value) {
25692
25682
  return typeof value === "string" || Number.isInteger(value);
@@ -25695,9 +25685,6 @@ function respondWithNullId(responder, error62) {
25695
25685
  nullIdResponders.add(responder);
25696
25686
  return responder.respondWithError(error62);
25697
25687
  }
25698
- function requestBatchSize(responder) {
25699
- return requestBatchSizes.get(responder);
25700
- }
25701
25688
  var HandlerRegistration = class {
25702
25689
  disposeHandler;
25703
25690
  active = true;
@@ -25744,12 +25731,6 @@ var ConnectionContext = class {
25744
25731
  sendNotification(method, params) {
25745
25732
  return this.connection.sendNotification(method, params);
25746
25733
  }
25747
- /**
25748
- * Sends a non-empty JSON-RPC batch in one transport message.
25749
- */
25750
- sendBatch(entries) {
25751
- return this.connection.sendBatch(entries);
25752
- }
25753
25734
  /**
25754
25735
  * Sends a protocol-level request cancellation notification.
25755
25736
  */
@@ -25789,7 +25770,6 @@ var Connection = class {
25789
25770
  retryQueue = [];
25790
25771
  context = new ConnectionContext(this);
25791
25772
  receiveReader;
25792
- allowBatches = true;
25793
25773
  constructor(requestHandlerOrStream, notificationHandlerOrHandlers, streamOrOptions, options) {
25794
25774
  if (typeof requestHandlerOrStream === "function") {
25795
25775
  const requestHandler = requestHandlerOrStream;
@@ -25879,7 +25859,7 @@ var Connection = class {
25879
25859
  return rejectedPromise(this.closedReason());
25880
25860
  }
25881
25861
  const request = this.prepareRequest(method, params, mapResponse, options);
25882
- const requestSent = this.sendWireMessage(request.message);
25862
+ const requestSent = this.sendMessage(request.message);
25883
25863
  void requestSent.catch(() => {
25884
25864
  });
25885
25865
  if (options.cancellationSignal?.aborted) {
@@ -25887,60 +25867,6 @@ var Connection = class {
25887
25867
  }
25888
25868
  return request.response;
25889
25869
  }
25890
- /**
25891
- * Sends a non-empty JSON-RPC batch in one transport message.
25892
- *
25893
- * Requests and notifications are processed independently by the peer, and
25894
- * array position does not establish processing order. Callers **MUST NOT**
25895
- * batch messages whose correctness depends on their relative order, such as
25896
- * two `session/update` notifications for the same entity; send those as
25897
- * separate messages instead. The returned tuple preserves the input order:
25898
- * request entries resolve to their mapped response, while notification
25899
- * entries resolve to `undefined`.
25900
- */
25901
- sendBatch(entries) {
25902
- if (this.abortController.signal.aborted) {
25903
- return rejectedPromise(this.closedReason());
25904
- }
25905
- if (!this.allowBatches) {
25906
- return rejectedPromise(new TypeError("JSON-RPC batches are not supported on this connection"));
25907
- }
25908
- if (entries.length === 0) {
25909
- return rejectedPromise(new TypeError("JSON-RPC batch must contain at least one entry"));
25910
- }
25911
- const messages = [];
25912
- const cancellations = [];
25913
- const outputs = [];
25914
- for (const entry of entries) {
25915
- if (entry.kind === "notification") {
25916
- messages.push({
25917
- jsonrpc: "2.0",
25918
- method: entry.method,
25919
- params: entry.params
25920
- });
25921
- outputs.push(Promise.resolve(void 0));
25922
- continue;
25923
- }
25924
- const request = this.prepareRequest(entry.method, entry.params, entry.mapResponse, entry.options);
25925
- messages.push(request.message);
25926
- outputs.push(request.response);
25927
- cancellations.push({
25928
- signal: entry.options?.cancellationSignal,
25929
- cancel: request.cancel
25930
- });
25931
- }
25932
- const batch = messages;
25933
- const batchSent = this.sendWireMessage(batch);
25934
- for (const cancellation of cancellations) {
25935
- if (cancellation.signal?.aborted) {
25936
- cancellation.cancel();
25937
- }
25938
- }
25939
- const response = Promise.all([batchSent, ...outputs]).then(([, ...resolved]) => resolved);
25940
- response.catch(() => {
25941
- });
25942
- return response;
25943
- }
25944
25870
  /**
25945
25871
  * Sends a protocol-level request cancellation notification.
25946
25872
  */
@@ -25954,7 +25880,7 @@ var Connection = class {
25954
25880
  if (this.abortController.signal.aborted) {
25955
25881
  return rejectedPromise(this.closedReason());
25956
25882
  }
25957
- return this.sendWireMessage({ jsonrpc: "2.0", method, params });
25883
+ return this.sendMessage({ jsonrpc: "2.0", method, params });
25958
25884
  }
25959
25885
  prepareRequest(method, params, mapResponse, options = {}) {
25960
25886
  const id = this.nextRequestId++;
@@ -26021,7 +25947,6 @@ var Connection = class {
26021
25947
  this.stream = stream;
26022
25948
  this.staticHandlers = handlers;
26023
25949
  this.fallbackHandlers = [...options?.fallbackHandlers ?? []];
26024
- this.allowBatches = options?.allowBatches ?? true;
26025
25950
  this.closedPromise = new Promise((resolve) => {
26026
25951
  this.abortController.signal.addEventListener("abort", () => resolve());
26027
25952
  });
@@ -26054,7 +25979,7 @@ var Connection = class {
26054
25979
  if (done) {
26055
25980
  break;
26056
25981
  }
26057
- this.receiveWireMessage(message);
25982
+ this.receiveUnvalidatedMessage(message);
26058
25983
  }
26059
25984
  } finally {
26060
25985
  if (this.receiveReader === reader) {
@@ -26068,68 +25993,20 @@ var Connection = class {
26068
25993
  this.close(closeError);
26069
25994
  }
26070
25995
  }
26071
- receiveWireMessage(message) {
25996
+ receiveUnvalidatedMessage(message) {
26072
25997
  if (Array.isArray(message)) {
26073
- if (!this.allowBatches) {
26074
- this.close(new TypeError("JSON-RPC batches are not supported on this connection"));
26075
- return;
26076
- }
26077
- this.receiveBatch(message);
25998
+ void this.sendMessage(protocolErrorResponse(RequestError.invalidRequest(void 0, "JSON-RPC batches are not supported"))).catch(() => {
25999
+ });
26078
26000
  return;
26079
26001
  }
26080
26002
  if (!isRequestMessage(message) && !isNotificationMessage(message) && !isResponseShapedMessage(message)) {
26081
- void this.sendWireMessage(protocolErrorResponse(RequestError.invalidRequest(message))).catch(() => {
26003
+ void this.sendMessage(protocolErrorResponse(RequestError.invalidRequest(message))).catch(() => {
26082
26004
  });
26083
26005
  return;
26084
26006
  }
26085
26007
  this.receiveMessage(message);
26086
26008
  }
26087
- receiveBatch(batch) {
26088
- if (batch.length === 0) {
26089
- void this.sendWireMessage(protocolErrorResponse(RequestError.invalidRequest(batch))).catch(() => {
26090
- });
26091
- return;
26092
- }
26093
- const responseBatch = isResponseBatch(batch);
26094
- const responseCount = responseBatch ? 0 : batch.reduce((count, message) => count + (isNotificationMessage(message) ? 0 : 1), 0);
26095
- let remaining = responseCount;
26096
- let remainingNotifications = batch.reduce((count, message) => count + (isNotificationMessage(message) ? 1 : 0), 0);
26097
- let responseSent = false;
26098
- const responses = [];
26099
- const sendResponsesIfReady = async () => {
26100
- if (responseSent || remaining !== 0 || remainingNotifications !== 0 || responses.length === 0) {
26101
- return;
26102
- }
26103
- responseSent = true;
26104
- await this.sendWireMessage(responses);
26105
- };
26106
- const collectResponse = async (response) => {
26107
- responses.push(response);
26108
- remaining -= 1;
26109
- await sendResponsesIfReady();
26110
- };
26111
- for (const message of batch) {
26112
- if (responseBatch) {
26113
- if (isResponseShapedMessage(message)) {
26114
- this.receiveMessage(message);
26115
- }
26116
- continue;
26117
- }
26118
- if (!isRequestMessage(message) && !isNotificationMessage(message)) {
26119
- void collectResponse(protocolErrorResponse(RequestError.invalidRequest(message))).catch(() => {
26120
- });
26121
- continue;
26122
- }
26123
- const processing = this.receiveMessage(message, isRequestMessage(message) ? collectResponse : void 0, batch.length);
26124
- if (isNotificationMessage(message)) {
26125
- void processing.finally(() => {
26126
- remainingNotifications -= 1;
26127
- void sendResponsesIfReady().catch((error62) => this.close(error62));
26128
- });
26129
- }
26130
- }
26131
- }
26132
- receiveMessage(message, sendResponse, batchSize) {
26009
+ receiveMessage(message) {
26133
26010
  if (this.abortController.signal.aborted) {
26134
26011
  return Promise.resolve();
26135
26012
  }
@@ -26141,7 +26018,7 @@ var Connection = class {
26141
26018
  if (!("id" in message)) {
26142
26019
  this.handleProtocolNotification(message);
26143
26020
  }
26144
- return this.processIncomingMessage(this.toIncomingMessage(message, sendResponse, batchSize)).catch((error62) => this.close(error62));
26021
+ return this.processIncomingMessage(this.toIncomingMessage(message)).catch((error62) => this.close(error62));
26145
26022
  } else if ("id" in message) {
26146
26023
  this.handleResponse(message);
26147
26024
  } else {
@@ -26196,7 +26073,7 @@ var Connection = class {
26196
26073
  }
26197
26074
  }
26198
26075
  }
26199
- toIncomingMessage(message, sendResponse, batchSize) {
26076
+ toIncomingMessage(message) {
26200
26077
  if ("id" in message) {
26201
26078
  const abortController = new AbortController();
26202
26079
  this.incomingRequests.set(message.id, abortController);
@@ -26211,11 +26088,8 @@ var Connection = class {
26211
26088
  id: nullIdResponders.has(responder) ? null : message.id,
26212
26089
  ...result
26213
26090
  };
26214
- return sendResponse ? sendResponse(response) : this.sendWireMessage(response);
26091
+ return this.sendMessage(response);
26215
26092
  }, abortController.signal, finishRequest);
26216
- if (batchSize !== void 0) {
26217
- requestBatchSizes.set(responder, batchSize);
26218
- }
26219
26093
  return {
26220
26094
  kind: "request",
26221
26095
  method: message.method,
@@ -26266,7 +26140,7 @@ var Connection = class {
26266
26140
  closedReason() {
26267
26141
  return this.abortController.signal.reason ?? new Error("ACP connection closed");
26268
26142
  }
26269
- async sendWireMessage(message) {
26143
+ async sendMessage(message) {
26270
26144
  if (this.abortController.signal.aborted) {
26271
26145
  return rejectedPromise(this.closedReason());
26272
26146
  }
@@ -26678,7 +26552,9 @@ function ndJsonStream(output2, input2, options = {}) {
26678
26552
  await writeJson(protocolErrorResponse(RequestError.parseError()));
26679
26553
  return;
26680
26554
  }
26681
- if (isRecord(message) || Array.isArray(message)) {
26555
+ if (Array.isArray(message)) {
26556
+ await writeJson(protocolErrorResponse(RequestError.invalidRequest(void 0, "JSON-RPC batches are not supported")));
26557
+ } else if (isRecord(message)) {
26682
26558
  controller.enqueue(message);
26683
26559
  } else {
26684
26560
  await writeJson(protocolErrorResponse(RequestError.invalidRequest(message)));
@@ -27080,7 +26956,7 @@ var ClientContext = class _ClientContext extends AcpContext {
27080
26956
  }
27081
26957
  request(method, params, options) {
27082
26958
  const spec = agentRequestSpecsByMethod[method];
27083
- return this.sendRequest(method, params, spec?.mapResponse, options);
26959
+ return treatSessionNotFoundAsSuccess(method, this.sendRequest(method, params, spec?.mapResponse, options), () => spec?.mapResponse ? spec.mapResponse({}) : {});
27084
26960
  }
27085
26961
  notify(method, params) {
27086
26962
  return this.sendNotification(method, params);
@@ -27544,7 +27420,6 @@ function runConnectHandlers(connection, handlers) {
27544
27420
  var appBuilder = /* @__PURE__ */ Symbol("appBuilder");
27545
27421
  var runAgentConnectHandlers = /* @__PURE__ */ Symbol("runAgentConnectHandlers");
27546
27422
  var runClientConnectHandlers = /* @__PURE__ */ Symbol("runClientConnectHandlers");
27547
- var stableConnectionOptions = { allowBatches: false };
27548
27423
  function agent(options) {
27549
27424
  return new AgentApp(options);
27550
27425
  }
@@ -27660,7 +27535,7 @@ var AgentApp = class {
27660
27535
  return state2;
27661
27536
  }
27662
27537
  const [thisStream, peerStream] = memoryStreamPair();
27663
- const peerRawConnection = target[appBuilder]().connect(peerStream, stableConnectionOptions);
27538
+ const peerRawConnection = target[appBuilder]().connect(peerStream);
27664
27539
  const peerConnection = clientConnection(peerRawConnection);
27665
27540
  const state = this.openStreamConnection(thisStream);
27666
27541
  void state.rawConnection.closed.then(() => peerConnection.close());
@@ -27676,7 +27551,7 @@ var AgentApp = class {
27676
27551
  return state;
27677
27552
  }
27678
27553
  openStreamConnection(stream) {
27679
- const rawConnection = this.builder.connect(stream, stableConnectionOptions);
27554
+ const rawConnection = this.builder.connect(stream);
27680
27555
  return {
27681
27556
  rawConnection,
27682
27557
  connection: agentConnection(rawConnection, this.connectHandlers)
@@ -27778,7 +27653,7 @@ var ClientApp = class {
27778
27653
  return state2;
27779
27654
  }
27780
27655
  const [thisStream, peerStream] = memoryStreamPair();
27781
- const peerRawConnection = target[appBuilder]().connect(peerStream, stableConnectionOptions);
27656
+ const peerRawConnection = target[appBuilder]().connect(peerStream);
27782
27657
  const peerConnection = agentConnection(peerRawConnection);
27783
27658
  const state = this.openStreamConnection(thisStream);
27784
27659
  void state.rawConnection.closed.then(() => peerConnection.close());
@@ -27794,7 +27669,7 @@ var ClientApp = class {
27794
27669
  return state;
27795
27670
  }
27796
27671
  openStreamConnection(stream) {
27797
- const rawConnection = this.builder.connect(stream, stableConnectionOptions);
27672
+ const rawConnection = this.builder.connect(stream);
27798
27673
  return {
27799
27674
  rawConnection,
27800
27675
  connection: clientConnection(rawConnection, this.connectHandlers)
@@ -28201,7 +28076,7 @@ var zRole2 = union([
28201
28076
  ]);
28202
28077
  var zAnnotations2 = object({
28203
28078
  audience: defaultOnError(vecSkipError(zRole2).nullish(), () => void 0),
28204
- lastModified: defaultOnError(iso_exports.datetime({ offset: true }).nullish(), () => void 0),
28079
+ lastModified: defaultOnError(string2().nullish(), () => void 0),
28205
28080
  priority: defaultOnError(number2().gte(0).lte(1).nullish(), () => void 0),
28206
28081
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
28207
28082
  });
@@ -28530,9 +28405,9 @@ var zElicitationPropertySchema2 = preserveCustomPayload(union([
28530
28405
  }), "type", ["array", "boolean", "integer", "number", "string"])
28531
28406
  ]), "type", ["array", "boolean", "integer", "number", "string"]);
28532
28407
  var zElicitationSchema2 = object({
28533
- type: zElicitationSchemaType2.optional().default("object"),
28408
+ type: zElicitationSchemaType2,
28534
28409
  title: defaultOnError(string2().nullish(), () => void 0),
28535
- properties: record(string2(), zElicitationPropertySchema2).optional().default({}),
28410
+ properties: record(string2(), zElicitationPropertySchema2),
28536
28411
  required: array(string2()).nullish(),
28537
28412
  description: defaultOnError(string2().nullish(), () => void 0),
28538
28413
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
@@ -28757,8 +28632,8 @@ var zSessionConfigSelectGroup2 = object({
28757
28632
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
28758
28633
  });
28759
28634
  var zSessionConfigSelectOptions2 = union([
28760
- array(zSessionConfigSelectOption2),
28761
- array(zSessionConfigSelectGroup2)
28635
+ array(zSessionConfigSelectOption2).min(1),
28636
+ array(zSessionConfigSelectGroup2).min(1)
28762
28637
  ]);
28763
28638
  var zSessionConfigSelect2 = object({
28764
28639
  currentValue: zSessionConfigValueId2,
@@ -28821,7 +28696,7 @@ var zNewSessionResponse2 = object({
28821
28696
  var zSessionInfo2 = object({
28822
28697
  sessionId: zSessionId2,
28823
28698
  cwd: zAbsolutePath,
28824
- additionalDirectories: array(zAbsolutePath).optional(),
28699
+ additionalDirectories: defaultOnNull(array(zAbsolutePath), () => []).optional(),
28825
28700
  title: defaultOnError(string2().nullish(), () => void 0),
28826
28701
  updatedAt: defaultOnError(iso_exports.datetime({ offset: true }).nullish(), () => void 0),
28827
28702
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
@@ -28875,10 +28750,24 @@ var zErrorCode2 = union([
28875
28750
  error: "Invalid value: Expected int32 to be <= 2147483647"
28876
28751
  })
28877
28752
  ]);
28753
+ var zUnsupportedProtocolVersionErrorData = object({
28754
+ requested: zProtocolVersion2,
28755
+ supported: array(zProtocolVersion2),
28756
+ _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
28757
+ });
28758
+ var zSessionNotFoundErrorData = object({
28759
+ sessionId: zSessionId2,
28760
+ _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
28761
+ });
28762
+ var zErrorData = union([
28763
+ zUnsupportedProtocolVersionErrorData,
28764
+ zSessionNotFoundErrorData,
28765
+ unknown()
28766
+ ]);
28878
28767
  var zError2 = object({
28879
28768
  code: zErrorCode2,
28880
28769
  message: string2(),
28881
- data: defaultOnError(unknown().optional(), () => void 0)
28770
+ data: defaultOnError(zErrorData.nullish(), () => void 0)
28882
28771
  });
28883
28772
  var zAgentResponse2 = union([
28884
28773
  object({
@@ -28902,7 +28791,7 @@ var zAgentResponse2 = union([
28902
28791
  ])
28903
28792
  }),
28904
28793
  object({
28905
- id: union([wideInt(), string2()]),
28794
+ id: union([wideInt(), string2()]).nullable(),
28906
28795
  error: zError2
28907
28796
  })
28908
28797
  ]);
@@ -29114,7 +29003,7 @@ var zSessionInfoUpdate2 = object({
29114
29003
  });
29115
29004
  var zCost2 = object({
29116
29005
  amount: number2(),
29117
- currency: string2().regex(/^[A-Z]{3}$/),
29006
+ currency: string2(),
29118
29007
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
29119
29008
  });
29120
29009
  var zUsageUpdate2 = object({
@@ -29168,6 +29057,8 @@ var zSubagentUpdate2 = object({
29168
29057
  description: defaultOnError(string2().nullish(), () => void 0),
29169
29058
  capabilities: defaultOnError(zSubagentSessionCapabilities2.nullish(), () => void 0),
29170
29059
  state: defaultOnError(zStateUpdate2.nullish(), () => void 0),
29060
+ cwd: zAbsolutePath.nullish(),
29061
+ additionalDirectories: array(zAbsolutePath).nullish(),
29171
29062
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
29172
29063
  });
29173
29064
  var zSessionMessage2 = object({
@@ -29489,7 +29380,7 @@ var zSetSessionConfigOptionRequest2 = preserveCustomPayload(intersection(union([
29489
29380
  })), "type", ["boolean", "id"]);
29490
29381
  var zPromptRequest2 = object({
29491
29382
  sessionId: zSessionId2,
29492
- prompt: array(zContentBlock2),
29383
+ prompt: array(zContentBlock2).min(1),
29493
29384
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
29494
29385
  });
29495
29386
  var zClientRequest2 = object({
@@ -29540,7 +29431,8 @@ var zElicitationContentValue2 = union([
29540
29431
  wideInt(),
29541
29432
  number2(),
29542
29433
  boolean2(),
29543
- array(string2())
29434
+ array(string2()),
29435
+ unknown()
29544
29436
  ]);
29545
29437
  var zElicitationAcceptAction2 = object({
29546
29438
  content: record(string2(), zElicitationContentValue2).nullish()
@@ -29591,7 +29483,7 @@ var zClientResponse2 = union([
29591
29483
  ])
29592
29484
  }),
29593
29485
  object({
29594
- id: union([wideInt(), string2()]),
29486
+ id: union([wideInt(), string2()]).nullable(),
29595
29487
  error: zError2
29596
29488
  })
29597
29489
  ]);
@@ -29618,10 +29510,6 @@ var zCancelRequestNotification2 = object({
29618
29510
  requestId: zRequestId2,
29619
29511
  _meta: defaultOnError(record(string2(), unknown()).nullish(), () => void 0)
29620
29512
  });
29621
- var zProtocolLevelNotification = object({
29622
- method: string2(),
29623
- params: zCancelRequestNotification2.nullish()
29624
- });
29625
29513
 
29626
29514
  // node_modules/@agentclientprotocol/sdk/dist/v2/unstable/schema/guards.gen.js
29627
29515
  function tagOf2(value, key) {
@@ -29955,6 +29843,31 @@ var StateUpdate2 = {
29955
29843
  return typeof tag === "string" && !["idle", "requires_action", "running", "unknown"].includes(tag);
29956
29844
  }
29957
29845
  };
29846
+ var CreateElicitationResponse2 = {
29847
+ /** Narrow to the `accept` variant, validating its payload. */
29848
+ isAccept(value) {
29849
+ return tagOf2(value, "action") === "accept" && zGuardCreateElicitationResponseAccept2.safeParse(value).success;
29850
+ },
29851
+ /** Narrow to the `decline` variant, validating its payload. */
29852
+ isDecline(value) {
29853
+ return tagOf2(value, "action") === "decline" && zGuardCreateElicitationResponseDecline2.safeParse(value).success;
29854
+ },
29855
+ /** Narrow to the `cancel` variant, validating its payload. */
29856
+ isCancel(value) {
29857
+ return tagOf2(value, "action") === "cancel" && zGuardCreateElicitationResponseCancel2.safeParse(value).success;
29858
+ },
29859
+ /**
29860
+ * Narrow to a custom or future variant: the `action` tag matches no known variant.
29861
+ *
29862
+ * TypeScript keeps the known variants in the narrowed union (they are
29863
+ * structural subtypes of the catch-all), so read vendor payload keys
29864
+ * via a widening cast: `(value as Record<string, unknown>).someKey`.
29865
+ */
29866
+ isCustom(value) {
29867
+ const tag = tagOf2(value, "action");
29868
+ return typeof tag === "string" && !["accept", "cancel", "decline"].includes(tag);
29869
+ }
29870
+ };
29958
29871
 
29959
29872
  // node_modules/@agentclientprotocol/sdk/dist/protocol-router.js
29960
29873
  var INITIALIZE_METHOD = "initialize";
@@ -30002,104 +29915,127 @@ var AgentProtocolRouter = class {
30002
29915
  }
30003
29916
  async route(stream, lifecycle) {
30004
29917
  const reader = stream.readable.getReader();
30005
- let first;
30006
- try {
30007
- first = await reader.read();
30008
- } catch (error62) {
30009
- reader.releaseLock();
30010
- throw error62;
30011
- }
30012
- if (first.done) {
30013
- reader.releaseLock();
30014
- await closeWritable(stream.writable);
30015
- lifecycle.finish();
30016
- return;
30017
- }
30018
- const firstMessage = first.value;
30019
- if (shouldCloseWithoutResponse(firstMessage)) {
30020
- await closeWithoutResponse(reader, stream.writable, RequestError.invalidRequest("first ACP message must be an initialize request"));
30021
- lifecycle.finish();
30022
- return;
30023
- }
30024
- let batchedInitialize = false;
30025
- let message = firstMessage;
30026
- if (Array.isArray(firstMessage)) {
30027
- if (firstMessage.length === 1 && isRequestMessage(firstMessage[0]) && firstMessage[0].method === INITIALIZE_METHOD) {
30028
- batchedInitialize = true;
30029
- message = firstMessage[0];
30030
- } else {
30031
- await rejectInitialize(reader, stream.writable, null, RequestError.invalidRequest("first ACP message must be an initialize request"));
29918
+ for (; ; ) {
29919
+ let next;
29920
+ try {
29921
+ next = await reader.read();
29922
+ } catch (error62) {
29923
+ reader.releaseLock();
29924
+ throw error62;
29925
+ }
29926
+ if (next.done) {
29927
+ reader.releaseLock();
29928
+ await closeWritable(stream.writable);
30032
29929
  lifecycle.finish();
30033
29930
  return;
30034
29931
  }
29932
+ const routed = this.routeInitialize(next.value);
29933
+ if ("reject" in routed) {
29934
+ if (routed.reject) {
29935
+ await writeMessage(stream.writable, {
29936
+ jsonrpc: "2.0",
29937
+ id: routed.reject.id,
29938
+ error: errorResponse(routed.reject.error)
29939
+ });
29940
+ }
29941
+ continue;
29942
+ }
29943
+ const { selected, initialize } = routed;
29944
+ const routedStream = {
29945
+ readable: routedReadable(reader, initialize, lifecycle),
29946
+ writable: stream.writable
29947
+ };
29948
+ const agent3 = selected === PROTOCOL_V2 ? this.v2 : this.v1;
29949
+ if (!agent3) {
29950
+ throw new Error("selected ACP protocol implementation is not configured");
29951
+ }
29952
+ try {
29953
+ const connection = agent3.connect(routedStream, {
29954
+ deferConnectHandlers: true
29955
+ });
29956
+ lifecycle.attach(connection);
29957
+ } catch (error62) {
29958
+ try {
29959
+ await reader.cancel(error62);
29960
+ } catch {
29961
+ } finally {
29962
+ reader.releaseLock();
29963
+ }
29964
+ throw error62;
29965
+ }
29966
+ return;
29967
+ }
29968
+ }
29969
+ /**
29970
+ * Decides how to handle a message received before initialization: route a
29971
+ * valid `initialize`, ignore notifications and responses, or reject it.
29972
+ */
29973
+ routeInitialize(message) {
29974
+ if (Array.isArray(message)) {
29975
+ return {
29976
+ reject: {
29977
+ id: null,
29978
+ error: RequestError.invalidRequest(void 0, "JSON-RPC batches are not supported")
29979
+ }
29980
+ };
29981
+ }
29982
+ if (isNotificationMessage(message) || isResponseShapedMessage(message)) {
29983
+ return { reject: void 0 };
30035
29984
  }
30036
29985
  if (!isRequestMessage(message)) {
30037
- await rejectInitialize(reader, stream.writable, null, RequestError.invalidRequest("first ACP message must be an initialize request"));
30038
- lifecycle.finish();
30039
- return;
29986
+ return {
29987
+ reject: {
29988
+ id: null,
29989
+ error: RequestError.invalidRequest("first ACP message must be an initialize request")
29990
+ }
29991
+ };
30040
29992
  }
30041
29993
  if (message.method !== INITIALIZE_METHOD) {
30042
- await rejectInitialize(reader, stream.writable, message.id, RequestError.invalidRequest("first ACP request must be initialize"), batchedInitialize);
30043
- lifecycle.finish();
30044
- return;
29994
+ return {
29995
+ reject: {
29996
+ id: message.id,
29997
+ error: RequestError.invalidRequest("first ACP request must be initialize")
29998
+ }
29999
+ };
30045
30000
  }
30046
30001
  if (!isJsonObject(message.params)) {
30047
- await rejectInitialize(reader, stream.writable, message.id, invalidProtocolVersion(), batchedInitialize);
30048
- lifecycle.finish();
30049
- return;
30002
+ return { reject: { id: message.id, error: invalidProtocolVersion() } };
30050
30003
  }
30051
30004
  const requested = message.params["protocolVersion"];
30052
30005
  if (!isProtocolVersion(requested)) {
30053
- await rejectInitialize(reader, stream.writable, message.id, invalidProtocolVersion(), batchedInitialize);
30054
- lifecycle.finish();
30055
- return;
30006
+ return { reject: { id: message.id, error: invalidProtocolVersion() } };
30056
30007
  }
30057
30008
  const selected = this.selectProtocol(requested);
30058
30009
  if (!selected) {
30059
- await rejectInitialize(reader, stream.writable, message.id, RequestError.unsupportedProtocolVersion(requested, [
30060
- ...this.v1 ? [PROTOCOL_V1] : [],
30061
- ...this.v2 ? [PROTOCOL_V2] : []
30062
- ]), batchedInitialize);
30063
- lifecycle.finish();
30064
- return;
30010
+ return {
30011
+ reject: {
30012
+ id: message.id,
30013
+ error: RequestError.unsupportedProtocolVersion(requested, [
30014
+ ...this.v1 ? [PROTOCOL_V1] : [],
30015
+ ...this.v2 ? [PROTOCOL_V2] : []
30016
+ ])
30017
+ }
30018
+ };
30065
30019
  }
30066
30020
  if (selected === PROTOCOL_V2 && !isV2RequestId(message.id)) {
30067
- await rejectInitialize(reader, stream.writable, null, RequestError.invalidRequest(void 0, "ACP v2 request IDs must be strings or integers"), batchedInitialize);
30068
- lifecycle.finish();
30069
- return;
30021
+ return {
30022
+ reject: {
30023
+ id: null,
30024
+ error: RequestError.invalidRequest(void 0, "ACP v2 request IDs must be strings or integers")
30025
+ }
30026
+ };
30070
30027
  }
30071
- let params;
30072
30028
  try {
30073
- params = rewriteInitializeParams(message.params, requested, selected);
30029
+ const params = rewriteInitializeParams(message.params, requested, selected);
30030
+ return { selected, initialize: { ...message, params } };
30074
30031
  } catch (error62) {
30075
30032
  const detail = error62 instanceof Error ? error62.message : String(error62);
30076
- await rejectInitialize(reader, stream.writable, message.id, RequestError.invalidParams(`invalid initialize params: ${detail}`), batchedInitialize);
30077
- lifecycle.finish();
30078
- return;
30079
- }
30080
- const initialize = { ...message, params };
30081
- const routedInitialize = batchedInitialize && selected === PROTOCOL_V2 ? [initialize] : initialize;
30082
- const routedStream = {
30083
- readable: routedReadable(reader, routedInitialize, lifecycle),
30084
- writable: batchedInitialize && selected === PROTOCOL_V1 ? batchInitializeResponseWritable(stream.writable, message.id) : stream.writable
30085
- };
30086
- const agent3 = selected === PROTOCOL_V2 ? this.v2 : this.v1;
30087
- if (!agent3) {
30088
- throw new Error("selected ACP protocol implementation is not configured");
30089
- }
30090
- try {
30091
- const connection = agent3.connect(routedStream, {
30092
- deferConnectHandlers: true
30093
- });
30094
- lifecycle.attach(connection);
30095
- } catch (error62) {
30096
- try {
30097
- await reader.cancel(error62);
30098
- } catch {
30099
- } finally {
30100
- reader.releaseLock();
30101
- }
30102
- throw error62;
30033
+ return {
30034
+ reject: {
30035
+ id: message.id,
30036
+ error: RequestError.invalidParams(`invalid initialize params: ${detail}`)
30037
+ }
30038
+ };
30103
30039
  }
30104
30040
  }
30105
30041
  selectProtocol(requested) {
@@ -30115,12 +30051,6 @@ var AgentProtocolRouter = class {
30115
30051
  return void 0;
30116
30052
  }
30117
30053
  };
30118
- function shouldCloseWithoutResponse(message) {
30119
- if (!Array.isArray(message)) {
30120
- return isNotificationMessage(message) || isResponseShapedMessage(message);
30121
- }
30122
- return message.length > 0 && (isResponseBatch(message) || message.every((item) => isNotificationMessage(item) || isResponseMessage(item)));
30123
- }
30124
30054
  function agentProtocolRouter() {
30125
30055
  return new AgentProtocolRouter();
30126
30056
  }
@@ -30216,56 +30146,12 @@ function routedReadable(source, initialize, lifecycle) {
30216
30146
  }
30217
30147
  });
30218
30148
  }
30219
- function batchInitializeResponseWritable(destination, initializeId) {
30220
- let responseFramed = false;
30221
- return new WritableStream({
30222
- async write(message) {
30223
- let outgoing = message;
30224
- if (!responseFramed && !Array.isArray(message) && isResponseShapedMessage(message) && "id" in message && message.id === initializeId) {
30225
- responseFramed = true;
30226
- outgoing = [message];
30227
- }
30228
- const writer = destination.getWriter();
30229
- try {
30230
- await writer.write(outgoing);
30231
- } finally {
30232
- writer.releaseLock();
30233
- }
30234
- },
30235
- close: () => closeWritable(destination),
30236
- abort: (reason) => abortWritable(destination, reason)
30237
- });
30238
- }
30239
- async function rejectInitialize(reader, writable, id, error62, batched = false) {
30240
- const response = {
30241
- jsonrpc: "2.0",
30242
- id,
30243
- error: errorResponse(error62)
30244
- };
30149
+ async function writeMessage(writable, message) {
30245
30150
  const writer = writable.getWriter();
30246
30151
  try {
30247
- await writer.write(batched ? [response] : response);
30248
- await writer.close();
30152
+ await writer.write(message);
30249
30153
  } finally {
30250
30154
  writer.releaseLock();
30251
- try {
30252
- await reader.cancel(error62);
30253
- } finally {
30254
- reader.releaseLock();
30255
- }
30256
- }
30257
- }
30258
- async function closeWithoutResponse(reader, writable, reason) {
30259
- const writer = writable.getWriter();
30260
- try {
30261
- await writer.close();
30262
- } finally {
30263
- writer.releaseLock();
30264
- try {
30265
- await reader.cancel(reason);
30266
- } finally {
30267
- reader.releaseLock();
30268
- }
30269
30155
  }
30270
30156
  }
30271
30157
  function errorResponse(error62) {
@@ -30405,11 +30291,6 @@ function assertUnrecognizedV2Method(method, kind) {
30405
30291
  throw new TypeError(`Cannot replace the built-in ACP v2 ${kind} parser for '${method}'`);
30406
30292
  }
30407
30293
  }
30408
- function assertV2BatchMethods(entries, requestMethods, notificationMethods) {
30409
- for (const entry of entries) {
30410
- assertV2MethodDirection(entry.method, entry.kind === "request" ? requestMethods : notificationMethods, entry.kind, entry.kind === "notification");
30411
- }
30412
- }
30413
30294
  var UNKNOWN_IMPLEMENTATION2 = {
30414
30295
  name: "unknown",
30415
30296
  version: "unknown"
@@ -30530,14 +30411,32 @@ var InitializationState = class {
30530
30411
  this.attempt.resolve();
30531
30412
  }
30532
30413
  /**
30533
- * Fails the initialize attempt in progress, or the connection before it has
30534
- * been initialized. A failed repeat keeps the previous initialization.
30414
+ * Whether an `initialize` exchange has completed, including while a repeat
30415
+ * is in progress.
30416
+ */
30417
+ get hasInitialized() {
30418
+ return this.snapshot !== void 0 && this.phase !== "failed";
30419
+ }
30420
+ /**
30421
+ * Fails the initialize attempt in progress. A failed repeat keeps the
30422
+ * previous initialization; a failed first attempt leaves the connection
30423
+ * uninitialized so `initialize` can be sent again.
30424
+ */
30425
+ failAttempt() {
30426
+ if (this.phase !== "initializing") {
30427
+ return;
30428
+ }
30429
+ this.phase = this.snapshot ? "initialized" : "uninitialized";
30430
+ this.request = void 0;
30431
+ this.attempt.resolve();
30432
+ }
30433
+ /**
30434
+ * Fails initialization for good, such as when the connection closes before
30435
+ * it was initialized. A failed repeat keeps the previous initialization.
30535
30436
  */
30536
30437
  fail(error62) {
30537
30438
  if (this.phase === "initializing" && this.snapshot) {
30538
- this.phase = "initialized";
30539
- this.request = void 0;
30540
- this.attempt.resolve();
30439
+ this.failAttempt();
30541
30440
  return;
30542
30441
  }
30543
30442
  if (this.phase === "uninitialized" || this.phase === "initializing") {
@@ -30561,7 +30460,10 @@ var InitializationState = class {
30561
30460
  return Promise.resolve();
30562
30461
  }
30563
30462
  if (this.phase === "initializing") {
30564
- return this.snapshot ? this.attempt.promise.then(() => this.waitUntilInitialized(method)) : this.barrier.promise.then(() => {
30463
+ return this.attempt.promise.then(() => this.waitUntilInitialized(method));
30464
+ }
30465
+ if (this.phase === "failed") {
30466
+ return this.barrier.promise.then(() => {
30565
30467
  });
30566
30468
  }
30567
30469
  return Promise.reject(initializationUnavailable(method));
@@ -30586,10 +30488,8 @@ function initializationState(cx) {
30586
30488
  function initializationUnavailable(method) {
30587
30489
  return RequestError.invalidRequest(`ACP v2 connection must be initialized before '${method}'`);
30588
30490
  }
30589
- async function blockUninitializedIncoming(message, state) {
30590
- const error62 = initializationUnavailable(message.method);
30591
- state.fail(error62);
30592
- return rejectIncoming(message, error62);
30491
+ async function blockUninitializedIncoming(message) {
30492
+ return rejectIncoming(message, initializationUnavailable(message.method));
30593
30493
  }
30594
30494
  async function rejectIncoming(message, error62) {
30595
30495
  if (message.kind === "request") {
@@ -30609,10 +30509,14 @@ async function waitUntilInitializedIncoming(message, state) {
30609
30509
  return Handled.no(message);
30610
30510
  }
30611
30511
  if (state.status === "initializing") {
30612
- await state.waitUntilInitialized(message.method);
30512
+ try {
30513
+ await state.waitUntilInitialized(message.method);
30514
+ } catch {
30515
+ return blockUninitializedIncoming(message);
30516
+ }
30613
30517
  return Handled.no(message);
30614
30518
  }
30615
- return blockUninitializedIncoming(message, state);
30519
+ return blockUninitializedIncoming(message);
30616
30520
  }
30617
30521
  function agentInitializationGuard() {
30618
30522
  return {
@@ -30623,8 +30527,8 @@ function agentInitializationGuard() {
30623
30527
  }
30624
30528
  const state = initializationState(cx);
30625
30529
  if (message.kind === "notification") {
30626
- if (message.method === PROTOCOL_METHODS2.cancel_request) {
30627
- return state.status === "initializing" || state.status === "initialized" ? Handled.yes() : blockUninitializedIncoming(message, state);
30530
+ if (message.method === PROTOCOL_METHODS2.cancel_request || !state.hasInitialized) {
30531
+ return Handled.yes();
30628
30532
  }
30629
30533
  return waitUntilInitializedIncoming(message, state);
30630
30534
  }
@@ -30633,33 +30537,17 @@ function agentInitializationGuard() {
30633
30537
  if (beginError) {
30634
30538
  return rejectIncoming(message, beginError);
30635
30539
  }
30636
- const batchSize = requestBatchSize(message.responder);
30637
- if (batchSize !== void 0 && batchSize !== 1) {
30638
- const error62 = RequestError.invalidRequest("ACP v2 initialize must be the only entry in its batch");
30639
- state.fail(error62);
30640
- return rejectIncoming(message, error62);
30641
- }
30642
- let request;
30643
- try {
30644
- if (state.status === "initialized" && readInitializeProtocolVersion(message.params) < PROTOCOL_VERSION2) {
30645
- return rejectIncoming(message, RequestError.invalidRequest(void 0, `a repeated initialize must request protocol version ${PROTOCOL_VERSION2} or later`));
30646
- }
30647
- request = parseV2InitializeRequest(message.params);
30648
- } catch (error62) {
30649
- state.fail(error62);
30650
- throw error62;
30540
+ if (state.status === "initialized" && readInitializeProtocolVersion(message.params) < PROTOCOL_VERSION2) {
30541
+ return rejectIncoming(message, RequestError.invalidRequest(void 0, `a repeated initialize must request protocol version ${PROTOCOL_VERSION2} or later`));
30651
30542
  }
30652
- state.begin(request);
30543
+ state.begin(parseV2InitializeRequest(message.params));
30653
30544
  return Handled.no(message);
30654
30545
  }
30655
30546
  if (state.status === "initialized") {
30656
30547
  state.noteRequest();
30657
30548
  return Handled.no(message);
30658
30549
  }
30659
- if (state.status === "initializing") {
30660
- return rejectIncoming(message, initializationUnavailable(message.method));
30661
- }
30662
- return blockUninitializedIncoming(message, state);
30550
+ return blockUninitializedIncoming(message);
30663
30551
  },
30664
30552
  describe: () => "agent-initialization"
30665
30553
  };
@@ -30673,7 +30561,7 @@ function clientInitializationGuard() {
30673
30561
  }
30674
30562
  const state = initializationState(cx);
30675
30563
  if (message.kind === "notification" && message.method === PROTOCOL_METHODS2.cancel_request) {
30676
- return state.status === "initializing" || state.status === "initialized" ? Handled.yes() : blockUninitializedIncoming(message, state);
30564
+ return Handled.yes();
30677
30565
  }
30678
30566
  return waitUntilInitializedIncoming(message, state);
30679
30567
  },
@@ -30683,25 +30571,6 @@ function clientInitializationGuard() {
30683
30571
  function parseRequestResponse(spec, response) {
30684
30572
  return parseParams(spec.response, response);
30685
30573
  }
30686
- function normalizeV2Batch(entries, requestSpecs, onInitializeResponse) {
30687
- return entries.map((entry) => {
30688
- if (entry.kind !== "request") {
30689
- return entry;
30690
- }
30691
- const spec = requestSpecs[entry.method];
30692
- const mapResponse = entry.mapResponse;
30693
- return {
30694
- ...entry,
30695
- mapResponse: spec ? (response) => {
30696
- const parsed = parseRequestResponse(spec, response);
30697
- if (onInitializeResponse && entry.method === AGENT_METHODS2.initialize) {
30698
- onInitializeResponse(parsed);
30699
- }
30700
- return mapResponse ? mapResponse(parsed) : parsed;
30701
- } : mapResponse
30702
- };
30703
- });
30704
- }
30705
30574
  function isStream2(value) {
30706
30575
  return typeof value === "object" && value !== null && "readable" in value && "writable" in value;
30707
30576
  }
@@ -30719,6 +30588,7 @@ function memoryStreamPair2() {
30719
30588
  }
30720
30589
  ];
30721
30590
  }
30591
+ var MCP_TRANSPORT_CAPABILITIES = Object.keys(zMcpCapabilities2.shape).filter((key) => key !== "_meta");
30722
30592
  var methods2 = {
30723
30593
  agent: {
30724
30594
  initialize: AGENT_METHODS2.initialize,
@@ -30764,6 +30634,7 @@ var methods2 = {
30764
30634
  }
30765
30635
  };
30766
30636
  var startActiveSession2 = /* @__PURE__ */ Symbol("startActiveSession");
30637
+ var routeActiveSessionUpdate = /* @__PURE__ */ Symbol("routeActiveSessionUpdate");
30767
30638
  var AcpContext2 = class {
30768
30639
  cx;
30769
30640
  currentRequestId;
@@ -30808,10 +30679,6 @@ var AcpContext2 = class {
30808
30679
  return this.cx.sendNotification(method, params);
30809
30680
  }
30810
30681
  /** @internal */
30811
- sendBatch(entries) {
30812
- return this.cx.sendBatch(entries);
30813
- }
30814
- /** @internal */
30815
30682
  addDynamicHandler(handler) {
30816
30683
  return this.cx.addDynamicHandler(handler);
30817
30684
  }
@@ -30833,13 +30700,6 @@ var AgentContext2 = class _AgentContext extends AcpContext2 {
30833
30700
  assertV2MethodDirection(method, clientNotificationSpecsByMethod2, "notification", true);
30834
30701
  return this.initializationLifecycle.waitUntilInitialized(method).then(() => this.sendNotification(method, params));
30835
30702
  }
30836
- /**
30837
- * Sends requests and notifications to the client as one JSON-RPC batch.
30838
- */
30839
- batch(entries) {
30840
- assertV2BatchMethods(entries, clientRequestSpecsByMethod2, clientNotificationSpecsByMethod2);
30841
- return this.initializationLifecycle.waitUntilInitialized("batch").then(() => this.sendBatch(normalizeV2Batch(entries, clientRequestSpecsByMethod2)));
30842
- }
30843
30703
  };
30844
30704
  var ClientContext2 = class _ClientContext extends AcpContext2 {
30845
30705
  closeOnInitializationFailure;
@@ -30878,14 +30738,14 @@ var ClientContext2 = class _ClientContext extends AcpContext2 {
30878
30738
  } else {
30879
30739
  closeSignal.addEventListener("abort", failUpdatesOnClose);
30880
30740
  }
30881
- const sessionRegistration = sessionUpdateRouter2(this.connectionContext).attach(response, updates);
30882
- const closeRegistration = new HandlerRegistration(() => {
30741
+ const registrations = [];
30742
+ const session = ActiveSession2.create(this, response, updates, registrations);
30743
+ registrations.push(sessionUpdateRouter2(this.connectionContext).attach(response, {
30744
+ enqueue: (message) => session[routeActiveSessionUpdate](message)
30745
+ }), new HandlerRegistration(() => {
30883
30746
  closeSignal.removeEventListener("abort", failUpdatesOnClose);
30884
- });
30885
- return ActiveSession2.create(this, response, updates, [
30886
- sessionRegistration,
30887
- closeRegistration
30888
- ]);
30747
+ }));
30748
+ return session;
30889
30749
  }
30890
30750
  request(method, params, options) {
30891
30751
  assertV2MethodDirection(method, agentRequestSpecsByMethod2, "request");
@@ -30895,25 +30755,36 @@ var ClientContext2 = class _ClientContext extends AcpContext2 {
30895
30755
  const { wire: request, parsed } = normalizeOutgoingV2InitializeRequest(params);
30896
30756
  state.begin(parsed);
30897
30757
  let response;
30758
+ let unusableResponse = false;
30898
30759
  try {
30899
30760
  response = this.sendRequest(method, request, (value) => {
30900
- const parsed2 = parseRequestResponse(spec, value);
30901
- state.complete(parsed2);
30902
- return parsed2;
30761
+ try {
30762
+ const parsed2 = parseRequestResponse(spec, value);
30763
+ state.complete(parsed2);
30764
+ return parsed2;
30765
+ } catch (error62) {
30766
+ unusableResponse = true;
30767
+ throw error62;
30768
+ }
30903
30769
  }, options);
30904
30770
  } catch (error62) {
30905
30771
  this.failInitialization(error62);
30906
30772
  throw error62;
30907
30773
  }
30908
30774
  void response.catch((error62) => {
30909
- if (state.status !== "initialized") {
30910
- this.failInitialization(error62);
30775
+ if (state.status === "initializing") {
30776
+ if (unusableResponse) {
30777
+ this.failInitialization(error62);
30778
+ } else {
30779
+ state.failAttempt();
30780
+ }
30911
30781
  }
30912
30782
  });
30913
30783
  return response;
30914
30784
  }
30915
30785
  state.noteRequest();
30916
- return state.waitUntilInitialized(method).then(() => this.sendRequest(method, params, spec ? (response) => parseRequestResponse(spec, response) : void 0, options));
30786
+ const mapResponse = spec ? (response) => parseRequestResponse(spec, response) : void 0;
30787
+ return state.waitUntilInitialized(method).then(() => treatSessionNotFoundAsSuccess(method, this.sendRequest(method, params, mapResponse, options), () => mapResponse ? mapResponse({}) : {}));
30917
30788
  }
30918
30789
  /**
30919
30790
  * Fails an initialize attempt. Closes the connection unless a previous
@@ -30930,41 +30801,6 @@ var ClientContext2 = class _ClientContext extends AcpContext2 {
30930
30801
  assertV2MethodDirection(method, agentNotificationSpecsByMethod2, "notification", true);
30931
30802
  return this.initializationLifecycle.waitUntilInitialized(method).then(() => this.sendNotification(method, params));
30932
30803
  }
30933
- /**
30934
- * Sends requests and notifications to the agent as one JSON-RPC batch.
30935
- */
30936
- batch(entries) {
30937
- assertV2BatchMethods(entries, agentRequestSpecsByMethod2, agentNotificationSpecsByMethod2);
30938
- const initializeEntries = entries.filter((entry) => entry.kind === "request" && entry.method === AGENT_METHODS2.initialize);
30939
- if (initializeEntries.length > 0) {
30940
- if (entries.length !== 1 || initializeEntries.length !== 1) {
30941
- return Promise.reject(RequestError.invalidRequest("ACP v2 initialize must be the only entry in its batch"));
30942
- }
30943
- const state = this.initializationLifecycle;
30944
- const { wire: request, parsed } = normalizeOutgoingV2InitializeRequest(initializeEntries[0].params);
30945
- state.begin(parsed);
30946
- const normalizedEntries = [
30947
- { ...initializeEntries[0], params: request }
30948
- ];
30949
- let response;
30950
- try {
30951
- response = this.sendBatch(normalizeV2Batch(normalizedEntries, agentRequestSpecsByMethod2, (value) => state.complete(value)));
30952
- } catch (error62) {
30953
- this.failInitialization(error62);
30954
- throw error62;
30955
- }
30956
- void response.catch((error62) => {
30957
- if (state.status !== "initialized") {
30958
- this.failInitialization(error62);
30959
- }
30960
- });
30961
- return response;
30962
- }
30963
- if (entries.some((entry) => entry.kind === "request")) {
30964
- this.initializationLifecycle.noteRequest();
30965
- }
30966
- return this.initializationLifecycle.waitUntilInitialized("batch").then(() => this.sendBatch(normalizeV2Batch(entries, agentRequestSpecsByMethod2)));
30967
- }
30968
30804
  };
30969
30805
  var AcpConnectionHandle2 = class {
30970
30806
  connection;
@@ -31168,11 +31004,13 @@ var ActiveSession2 = class _ActiveSession {
31168
31004
  sessionResponse;
31169
31005
  updates;
31170
31006
  registrations;
31007
+ currentConfigOptions;
31171
31008
  constructor(cx, sessionResponse, updates, registrations) {
31172
31009
  this.cx = cx;
31173
31010
  this.sessionResponse = sessionResponse;
31174
31011
  this.updates = updates;
31175
31012
  this.registrations = registrations;
31013
+ this.currentConfigOptions = sessionResponse.configOptions ?? void 0;
31176
31014
  }
31177
31015
  /** @internal */
31178
31016
  static create(cx, sessionResponse, updates, registrations) {
@@ -31185,10 +31023,16 @@ var ActiveSession2 = class _ActiveSession {
31185
31023
  return this.sessionResponse.sessionId;
31186
31024
  }
31187
31025
  /**
31188
- * Configuration options returned when the session was created, if provided.
31026
+ * Current configuration options for this session, if the agent provided any.
31027
+ *
31028
+ * Starts with the `configOptions` from `session/new`. It is replaced with the
31029
+ * full list from each `config_option_update` routed to this session (applied
31030
+ * when the notification arrives, before it is read with `nextUpdate()`) and
31031
+ * from each `setConfigOption(...)` response. Updates stop after `dispose()`.
31032
+ * `newSessionResponse.configOptions` keeps the original `session/new` value.
31189
31033
  */
31190
31034
  get configOptions() {
31191
- return this.sessionResponse.configOptions;
31035
+ return this.currentConfigOptions;
31192
31036
  }
31193
31037
  /**
31194
31038
  * Metadata returned when the session was created.
@@ -31206,18 +31050,45 @@ var ActiveSession2 = class _ActiveSession {
31206
31050
  * Sends a prompt to this session.
31207
31051
  *
31208
31052
  * Strings are converted to one text content block. A single content block is
31209
- * wrapped in an array. The returned promise resolves with the inserted user
31210
- * message's ID once the agent inserts it into the ACP conversation, not when
31211
- * processing finishes. Session updates remain independent of this request;
31212
- * an idle `state_update` does not establish that this message was processed.
31213
- * Rejection is reported only by this promise, not by the session update queue.
31053
+ * wrapped in an array. A prompt must contain at least one block. The returned
31054
+ * promise resolves with the inserted user message's ID once the agent
31055
+ * inserts it into the ACP conversation, not when processing finishes.
31056
+ *
31057
+ * A prompt may be sent while the agent is working. The agent inserts it
31058
+ * right away or holds it and inserts it later, in the order received; the
31059
+ * promise stays pending until then. Aborting `options.cancellationSignal`
31060
+ * withdraws a held prompt, and `session/cancel` or `session/close` answer
31061
+ * held prompts with `-32800`. `session/cancel` does not affect a prompt sent
31062
+ * after it.
31063
+ *
31064
+ * Session updates remain independent of this request and have no fixed
31065
+ * order relative to its response; an idle `state_update` does not establish
31066
+ * that this message was processed. Rejection is reported only by this
31067
+ * promise, not by the session update queue.
31214
31068
  */
31215
31069
  prompt(prompt, options) {
31070
+ const blocks = this.promptBlocks(prompt);
31071
+ if (blocks.length === 0) {
31072
+ return Promise.reject(new TypeError("A prompt must contain at least one content block"));
31073
+ }
31216
31074
  return this.cx.request(AGENT_METHODS2.session_prompt, {
31217
31075
  sessionId: this.sessionId,
31218
- prompt: this.promptBlocks(prompt)
31076
+ prompt: blocks
31219
31077
  }, options);
31220
31078
  }
31079
+ /**
31080
+ * Sets a configuration option for this session with
31081
+ * `session/set_config_option`.
31082
+ *
31083
+ * The response carries the agent's complete `configOptions` list, which
31084
+ * replaces `configOptions` on this session. For example,
31085
+ * `session.setConfigOption({ configId: "model", type: "id", value: "fast" })`.
31086
+ */
31087
+ async setConfigOption(request, options) {
31088
+ const response = await this.cx.request(AGENT_METHODS2.session_set_config_option, { ...request, sessionId: this.sessionId }, options);
31089
+ this.currentConfigOptions = response.configOptions;
31090
+ return response;
31091
+ }
31221
31092
  /**
31222
31093
  * Reads the next update or stop message for this session.
31223
31094
  *
@@ -31269,6 +31140,13 @@ var ActiveSession2 = class _ActiveSession {
31269
31140
  }
31270
31141
  }
31271
31142
  }
31143
+ /** @internal */
31144
+ [routeActiveSessionUpdate](message) {
31145
+ if (SessionUpdate.isConfigOptionUpdate(message.update)) {
31146
+ this.currentConfigOptions = message.update.configOptions;
31147
+ }
31148
+ this.updates.enqueue(message);
31149
+ }
31272
31150
  /**
31273
31151
  * Stops routing updates to this active-session helper.
31274
31152
  *
@@ -31570,7 +31448,7 @@ var AgentApp2 = class {
31570
31448
  beforeResponse: (_params, response, cx) => {
31571
31449
  initializationState(cx).complete(mapV2InitializeResponse(response));
31572
31450
  },
31573
- onError: (cx, error62) => initializationState(cx).fail(error62)
31451
+ onError: (cx) => initializationState(cx).failAttempt()
31574
31452
  } : void 0);
31575
31453
  return this;
31576
31454
  }
@@ -32166,6 +32044,9 @@ function toV2CreateElicitationRequest(request) {
32166
32044
  function toV1CreateElicitationResponse(response) {
32167
32045
  return response;
32168
32046
  }
32047
+ function toV2CreateElicitationResponse(response) {
32048
+ return response;
32049
+ }
32169
32050
  function elicitationSessionId(request) {
32170
32051
  const sessionId = request.sessionId;
32171
32052
  return typeof sessionId === "string" ? sessionId : void 0;
@@ -33469,58 +33350,62 @@ var BINARY_PROBE_LENGTH = 8e3;
33469
33350
  var NO_NEWLINE_MARKER = "\";
33470
33351
  var HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
33471
33352
  var REGULAR_FILE_MODE = "100644";
33472
- function createUpdateGitPatch(oldPath, newPath, diff) {
33353
+ function createUpdateGitPatch(oldPath, newPath, diff, style = "relative") {
33473
33354
  const hunks = hunkText(diff);
33474
33355
  if (hunks === null || isBinary(hunks)) return null;
33475
- const oldName = gitPath(oldPath);
33476
- const newName = gitPath(newPath);
33477
- const headers = [`diff --git ${quotedGitName("a/", oldName)} ${quotedGitName("b/", newName)}`];
33356
+ const oldName = gitPath(oldPath, style);
33357
+ const newName = gitPath(newPath, style);
33358
+ const oldPrefix = style === "absolute" ? "" : "a/";
33359
+ const newPrefix = style === "absolute" ? "" : "b/";
33360
+ const headers = [`diff --git ${quotedGitName(oldPrefix, oldName)} ${quotedGitName(newPrefix, newName)}`];
33478
33361
  if (oldName !== newName) {
33479
33362
  headers.push(`rename from ${quotedGitName("", oldName)}`, `rename to ${quotedGitName("", newName)}`);
33480
33363
  }
33481
- headers.push(fileHeader("---", "a/", oldName), fileHeader("+++", "b/", newName));
33364
+ headers.push(fileHeader("---", oldPrefix, oldName), fileHeader("+++", newPrefix, newName));
33482
33365
  return limited(`${headers.join("\n")}
33483
33366
  ${hunks}`);
33484
33367
  }
33485
- function createRenameGitPatch(oldPath, newPath) {
33486
- const oldName = gitPath(oldPath);
33487
- const newName = gitPath(newPath);
33368
+ function createRenameGitPatch(oldPath, newPath, style = "relative") {
33369
+ const oldName = gitPath(oldPath, style);
33370
+ const newName = gitPath(newPath, style);
33488
33371
  if (oldName === newName) return null;
33489
33372
  return limited([
33490
- `diff --git ${quotedGitName("a/", oldName)} ${quotedGitName("b/", newName)}`,
33373
+ `diff --git ${quotedGitName(style === "absolute" ? "" : "a/", oldName)} ${quotedGitName(style === "absolute" ? "" : "b/", newName)}`,
33491
33374
  "similarity index 100%",
33492
33375
  `rename from ${quotedGitName("", oldName)}`,
33493
33376
  `rename to ${quotedGitName("", newName)}`,
33494
33377
  ""
33495
33378
  ].join("\n"));
33496
33379
  }
33497
- function createAddedFileGitPatch(filePath, text) {
33498
- return createWholeFilePatch(filePath, text, "added");
33380
+ function createAddedFileGitPatch(filePath, text, style = "relative") {
33381
+ return createWholeFilePatch(filePath, text, "added", style);
33499
33382
  }
33500
- function createDeletedFileGitPatch(filePath, text) {
33501
- return createWholeFilePatch(filePath, text, "deleted");
33383
+ function createDeletedFileGitPatch(filePath, text, style = "relative") {
33384
+ return createWholeFilePatch(filePath, text, "deleted", style);
33502
33385
  }
33503
- function createEmptyFileGitPatch(filePath, change) {
33504
- const name = gitPath(filePath);
33386
+ function createEmptyFileGitPatch(filePath, change, style = "relative") {
33387
+ const name = gitPath(filePath, style);
33505
33388
  return [
33506
- `diff --git ${quotedGitName("a/", name)} ${quotedGitName("b/", name)}`,
33389
+ `diff --git ${quotedGitName(style === "absolute" ? "" : "a/", name)} ${quotedGitName(style === "absolute" ? "" : "b/", name)}`,
33507
33390
  `${change === "added" ? "new" : "deleted"} file mode ${REGULAR_FILE_MODE}`,
33508
33391
  ""
33509
33392
  ].join("\n");
33510
33393
  }
33511
- function createWholeFilePatch(filePath, text, change) {
33394
+ function createWholeFilePatch(filePath, text, change, style) {
33512
33395
  if (text.length === 0 || isBinary(text)) return null;
33513
- const name = gitPath(filePath);
33396
+ const name = gitPath(filePath, style);
33397
+ const oldPrefix = style === "absolute" ? "" : "a/";
33398
+ const newPrefix = style === "absolute" ? "" : "b/";
33514
33399
  const lines = text.split("\n");
33515
33400
  const endsWithNewline = lines.at(-1) === "";
33516
33401
  if (endsWithNewline) lines.pop();
33517
33402
  const sign = change === "added" ? "+" : "-";
33518
33403
  const range = `1${lines.length === 1 ? "" : `,${lines.length}`}`;
33519
33404
  const patch = [
33520
- `diff --git ${quotedGitName("a/", name)} ${quotedGitName("b/", name)}`,
33405
+ `diff --git ${quotedGitName(oldPrefix, name)} ${quotedGitName(newPrefix, name)}`,
33521
33406
  `${change === "added" ? "new" : "deleted"} file mode ${REGULAR_FILE_MODE}`,
33522
- change === "added" ? "--- /dev/null" : fileHeader("---", "a/", name),
33523
- change === "added" ? fileHeader("+++", "b/", name) : "+++ /dev/null",
33407
+ change === "added" ? "--- /dev/null" : fileHeader("---", oldPrefix, name),
33408
+ change === "added" ? fileHeader("+++", newPrefix, name) : "+++ /dev/null",
33524
33409
  change === "added" ? `@@ -0,0 +${range} @@` : `@@ -${range} +0,0 @@`,
33525
33410
  ...lines.map((line) => `${sign}${line}`),
33526
33411
  ...endsWithNewline ? [] : [NO_NEWLINE_MARKER],
@@ -33595,7 +33480,8 @@ function isBinary(text) {
33595
33480
  function limited(patch) {
33596
33481
  return Buffer.byteLength(patch, "utf8") <= DIFF_PATCH_MAX_BYTES ? patch : null;
33597
33482
  }
33598
- function gitPath(filePath) {
33483
+ function gitPath(filePath, style) {
33484
+ if (style === "absolute") return filePath;
33599
33485
  const slashed = /^[A-Za-z]:\\/.test(filePath) ? filePath.replace(/\\/g, "/") : filePath;
33600
33486
  return slashed.replace(/^\/+/, "");
33601
33487
  }
@@ -33751,13 +33637,13 @@ function createAcpV2Content(change) {
33751
33637
  let patch;
33752
33638
  switch (kind.type) {
33753
33639
  case "add":
33754
- patch = diff.length === 0 ? createEmptyFileGitPatch(path16, "added") : createAddedFileGitPatch(path16, diff);
33640
+ patch = diff.length === 0 ? createEmptyFileGitPatch(path16, "added", "absolute") : createAddedFileGitPatch(path16, diff, "absolute");
33755
33641
  break;
33756
33642
  case "delete":
33757
- patch = diff.length === 0 ? createEmptyFileGitPatch(path16, "deleted") : createDeletedFileGitPatch(path16, diff);
33643
+ patch = diff.length === 0 ? createEmptyFileGitPatch(path16, "deleted", "absolute") : createDeletedFileGitPatch(path16, diff, "absolute");
33758
33644
  break;
33759
33645
  case "update":
33760
- patch = kind.move_path !== null && diff.trim().length === 0 ? createRenameGitPatch(oldPath, path16) : createUpdateGitPatch(oldPath, path16, diff);
33646
+ patch = kind.move_path !== null && diff.trim().length === 0 ? createRenameGitPatch(oldPath, path16, "absolute") : createUpdateGitPatch(oldPath, path16, diff, "absolute");
33761
33647
  break;
33762
33648
  }
33763
33649
  if (patch === null) {
@@ -38960,13 +38846,13 @@ function typedChoiceAnswer(value, question) {
38960
38846
  }
38961
38847
  function userInputResponseValue(content, fieldId) {
38962
38848
  const value = content[fieldId];
38963
- if (typeof value === "string" && value.trim() === "") {
38964
- return void 0;
38849
+ if (typeof value === "string") {
38850
+ return value.trim() === "" ? void 0 : value;
38965
38851
  }
38966
- if (Array.isArray(value) && value.length === 0) {
38967
- return void 0;
38852
+ if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
38853
+ return value;
38968
38854
  }
38969
- return value;
38855
+ return void 0;
38970
38856
  }
38971
38857
  function buildUserInputSchema(questions, clientCapabilities, answersRequired) {
38972
38858
  const properties = {};
@@ -39044,8 +38930,9 @@ function buildUserInputRequest(params, clientCapabilities) {
39044
38930
  }
39045
38931
  };
39046
38932
  }
39047
- function userInputAnswers(response, questions, clientCapabilities) {
39048
- if (!CreateElicitationResponse.isAccept(response)) {
38933
+ function userInputAnswers(rawResponse, questions, clientCapabilities) {
38934
+ const response = toV2CreateElicitationResponse(rawResponse);
38935
+ if (!CreateElicitationResponse2.isAccept(response)) {
39049
38936
  return {};
39050
38937
  }
39051
38938
  const answers = {};
@@ -39299,8 +39186,12 @@ var CodexElicitationHandler = class {
39299
39186
  };
39300
39187
  }
39301
39188
  }
39302
- convertElicitationResponse(response, context) {
39303
- if (CreateElicitationResponse.isAccept(response)) {
39189
+ convertElicitationResponse(rawResponse, context) {
39190
+ if (AcpV2Connection.of(this.connection) === null && rawResponse.action === "accept" && !CreateElicitationResponse.isAccept(rawResponse)) {
39191
+ return { action: "cancel", content: null, _meta: null };
39192
+ }
39193
+ const response = toV2CreateElicitationResponse(rawResponse);
39194
+ if (CreateElicitationResponse2.isAccept(response)) {
39304
39195
  const content = contentRecord(response.content);
39305
39196
  const persist = context.isToolApproval ? content["persist"] : void 0;
39306
39197
  if (context.isToolApproval && !this.isAllowedToolApprovalPersist(persist, context.persistOptions)) {
@@ -39315,13 +39206,13 @@ var CodexElicitationHandler = class {
39315
39206
  _meta: elicitationResponseMeta(response, context, persist)
39316
39207
  };
39317
39208
  }
39318
- if (CreateElicitationResponse.isDecline(response)) {
39209
+ if (CreateElicitationResponse2.isDecline(response)) {
39319
39210
  return context.isToolApproval ? { action: "cancel", content: null, _meta: elicitationResponseMeta(response, context) } : { action: "decline", content: null, _meta: elicitationResponseMeta(response, context) };
39320
39211
  }
39321
- if (CreateElicitationResponse.isCancel(response)) {
39212
+ if (CreateElicitationResponse2.isCancel(response)) {
39322
39213
  return { action: "cancel", content: null, _meta: elicitationResponseMeta(response, context) };
39323
39214
  }
39324
- if (CreateElicitationResponse.isCustom(response)) {
39215
+ if (CreateElicitationResponse2.isCustom(response)) {
39325
39216
  return { action: "cancel", content: null, _meta: null };
39326
39217
  }
39327
39218
  return { action: "cancel", content: null, _meta: null };
@@ -39510,6 +39401,15 @@ function sanitizeMcpServerName(name) {
39510
39401
  function getMcpServerName(server) {
39511
39402
  return typeof server.name === "string" ? server.name : "";
39512
39403
  }
39404
+ function normalizeMcpServers(servers) {
39405
+ const names = /* @__PURE__ */ new Set();
39406
+ return servers.map((server) => {
39407
+ const name = sanitizeMcpServerName(getMcpServerName(server));
39408
+ if (names.has(name)) throw RequestError.invalidParams({ name: getMcpServerName(server) }, "MCP server names must be unique");
39409
+ names.add(name);
39410
+ return { ...normalizeMcpServer(server), name };
39411
+ });
39412
+ }
39513
39413
  function normalizeMcpServer(server) {
39514
39414
  if (!("type" in server)) {
39515
39415
  return { type: "stdio", name: server.name, command: server.command, args: server.args, env: server.env };
@@ -40575,7 +40475,7 @@ var package_default = {
40575
40475
  publishConfig: {
40576
40476
  access: "public"
40577
40477
  },
40578
- version: "2.5.1-preview.3",
40478
+ version: "2.5.1-preview.4",
40579
40479
  description: "",
40580
40480
  main: "dist/index.js",
40581
40481
  bin: {
@@ -40640,7 +40540,7 @@ var package_default = {
40640
40540
  vitest: "^5.0.1"
40641
40541
  },
40642
40542
  dependencies: {
40643
- "@agentclientprotocol/sdk": "~2.1.0",
40543
+ "@agentclientprotocol/sdk": "~2.2.0",
40644
40544
  "@openai/codex": "^0.165.0",
40645
40545
  "cross-spawn": "^7.0.6",
40646
40546
  diff: "^9.0.0",
@@ -40687,9 +40587,11 @@ function createCodexCollaborationMode(mode, currentModelId) {
40687
40587
 
40688
40588
  // src/PathUtils.ts
40689
40589
  import path9 from "node:path";
40590
+ function isAbsoluteProtocolPath(value) {
40591
+ return !value.includes("\0") && (path9.posix.isAbsolute(value) || isWindowsAbsolutePath2(value));
40592
+ }
40690
40593
  function isAbsolutePathLike(value) {
40691
- const trimmed = value.trim();
40692
- return path9.isAbsolute(trimmed) || isWindowsAbsolutePath2(trimmed);
40594
+ return isAbsoluteProtocolPath(value.trim());
40693
40595
  }
40694
40596
  function arePathsEqual(left, right) {
40695
40597
  return normalizePathForComparison(left) === normalizePathForComparison(right);
@@ -41159,6 +41061,7 @@ var CodexAcpClient = class _CodexAcpClient {
41159
41061
  version: `${package_default.version}`
41160
41062
  };
41161
41063
  async initialize(request) {
41064
+ if (this.isInitialized) return;
41162
41065
  const response = await this.codexClient.initialize({
41163
41066
  capabilities: {
41164
41067
  experimentalApi: true,
@@ -41944,10 +41847,7 @@ var CodexAcpClient = class _CodexAcpClient {
41944
41847
  if (mcpServers.length === 0) {
41945
41848
  return { config: configWithWorkspaceRoots, skippedMcpServers: [] };
41946
41849
  }
41947
- const requestedServers = mcpServers.map((mcp) => ({
41948
- name: sanitizeMcpServerName(getMcpServerName(mcp)),
41949
- server: normalizeMcpServer(mcp)
41950
- }));
41850
+ const requestedServers = normalizeMcpServers(mcpServers).map((server) => ({ name: server.name, server }));
41951
41851
  let serversToConfigure = requestedServers;
41952
41852
  if (shouldDeduplicateMcpConflicts()) {
41953
41853
  const existingNames = await this.getConfigMcpServerNames(projectPath);
@@ -42378,7 +42278,7 @@ function readAdditionalDirectories(cwd, additionalDirectories, meta3) {
42378
42278
  if (directory.length === 0) {
42379
42279
  throw RequestError.invalidParams(void 0, "additionalDirectories entries must not be empty");
42380
42280
  }
42381
- if (!path10.isAbsolute(directory)) {
42281
+ if (!isAbsoluteProtocolPath(directory)) {
42382
42282
  throw RequestError.invalidParams(void 0, "additionalDirectories entries must be absolute paths");
42383
42283
  }
42384
42284
  if (!seen.has(directory)) {
@@ -49927,16 +49827,16 @@ var CodexAcpServer = class {
49927
49827
  }
49928
49828
  async initialize(_params) {
49929
49829
  logger.log("Initialize request received");
49830
+ const appServer = this.ensureAppServer();
49831
+ if (appServer) await appServer;
49832
+ await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
49930
49833
  this.clientInfo = _params.clientInfo ?? null;
49931
49834
  this.clientCapabilities = _params.clientCapabilities ?? null;
49932
49835
  this.initializeRequest = _params;
49933
49836
  this.capabilities = ClientCapabilities.from(_params.clientCapabilities);
49934
- const appServer = this.ensureAppServer();
49935
- if (appServer) await appServer;
49936
49837
  this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
49937
49838
  this.booleanConfigOptionsSupported = clientSupportsBooleanConfigOptions(_params.clientCapabilities);
49938
49839
  this.sessionIndex.configure(_params.clientCapabilities);
49939
- await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
49940
49840
  this.sessionIndex.observe(this.codexAcpClient);
49941
49841
  this.publishFirstAuthStatusAfterResponse();
49942
49842
  const sessionCapabilities = {
@@ -49985,16 +49885,16 @@ var CodexAcpServer = class {
49985
49885
  async initializeV2(params) {
49986
49886
  logger.log("Initialize request received", { protocolVersion: params.protocolVersion });
49987
49887
  const clientCapabilities = toV1ClientCapabilitiesView(params.capabilities);
49888
+ const appServer = this.ensureAppServer();
49889
+ if (appServer) await appServer;
49890
+ await this.runWithProcessCheck(() => this.codexAcpClient.initialize({ clientInfo: params.info }));
49988
49891
  this.clientInfo = params.info;
49989
49892
  this.clientCapabilities = clientCapabilities;
49990
49893
  this.initializeRequest = { clientInfo: params.info };
49991
49894
  this.capabilities = ClientCapabilities.fromV2(clientCapabilities);
49992
- const appServer = this.ensureAppServer();
49993
- if (appServer) await appServer;
49994
49895
  this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
49995
49896
  this.booleanConfigOptionsSupported = true;
49996
49897
  this.sessionIndex.configure(clientCapabilities);
49997
- await this.runWithProcessCheck(() => this.codexAcpClient.initialize({ clientInfo: params.info }));
49998
49898
  this.sessionIndex.observe(this.codexAcpClient);
49999
49899
  this.publishFirstAuthStatusAfterResponse();
50000
49900
  return {
@@ -51581,6 +51481,10 @@ You have been logged out. Please try again.`);
51581
51481
  };
51582
51482
  }
51583
51483
  async setSessionConfigOptionV2(params) {
51484
+ const option = this.createSessionConfigOptions(this.getSessionState(params.sessionId)).find((option2) => option2.id === params.configId);
51485
+ if (!option || params.type !== (option.type === "boolean" ? "boolean" : "id")) {
51486
+ throw RequestError.invalidParams();
51487
+ }
51584
51488
  const response = await this.setSessionConfigOption(toV1SetSessionConfigOptionRequest(params));
51585
51489
  return { configOptions: toV2ConfigOptions(response.configOptions) };
51586
51490
  }
@@ -54308,12 +54212,10 @@ var AcpResponseDelivery = class {
54308
54212
  } finally {
54309
54213
  writer.releaseLock();
54310
54214
  }
54311
- for (const entry of Array.isArray(message) ? message : [message]) {
54312
- if ("method" in entry || entry.id === null) continue;
54313
- const callback = this.callbacks.get(entry.id);
54314
- this.callbacks.delete(entry.id);
54315
- callback?.();
54316
- }
54215
+ if ("method" in message || message.id === null) return;
54216
+ const callback = this.callbacks.get(message.id);
54217
+ this.callbacks.delete(message.id);
54218
+ callback?.();
54317
54219
  },
54318
54220
  close: async () => {
54319
54221
  const writer = stream.writable.getWriter();
@@ -54394,6 +54296,15 @@ function createRouter(createAgent, responses) {
54394
54296
  if (typeof params?.sessionId === "string") codexAcpServer.assertSessionMutationAllowed(params.sessionId);
54395
54297
  return codexAcpServer;
54396
54298
  };
54299
+ const getAgentForPaths = (params) => {
54300
+ if (params.cwd != null && !isAbsoluteProtocolPath(params.cwd)) {
54301
+ throw RequestError.invalidParams(void 0, "cwd must be an absolute path");
54302
+ }
54303
+ if (params.additionalDirectories?.some((directory) => !isAbsoluteProtocolPath(directory))) {
54304
+ throw RequestError.invalidParams(void 0, "additionalDirectories entries must be absolute paths");
54305
+ }
54306
+ return getAgent(params);
54307
+ };
54397
54308
  const setups = /* @__PURE__ */ new Map();
54398
54309
  const setup = (sessionId, requestId, operation, signal) => {
54399
54310
  const agent3 = getAgent({ sessionId });
@@ -54450,8 +54361,8 @@ function createRouter(createAgent, responses) {
54450
54361
  }
54451
54362
  });
54452
54363
  };
54453
- const v1Agent = agent({ name: package_default.name }).onConnect((connection) => attachAgent(createAgent(connection.client), connection.signal)).onRequest(methods.agent.initialize, (ctx) => getAgent().initialize(ctx.params)).onRequest(methods.agent.session.new, (ctx) => getAgent().newSession(ctx.params)).onRequest(methods.agent.session.load, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgent(ctx.params).loadSession(ctx.params), ctx.signal)).onRequest(methods.agent.session.fork, (ctx) => getAgent(ctx.params).forkSession(ctx.params)).onRequest(methods.agent.session.list, (ctx) => getAgent().listSessions(ctx.params)).onRequest(methods.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params)).onRequest(methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgent(ctx.params).resumeSession(ctx.params), ctx.signal)).onRequest(methods.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params)).onRequest(methods.agent.session.setMode, (ctx) => getAgent(ctx.params).setSessionMode(ctx.params)).onRequest(methods.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOption(ctx.params)).onRequest(methods.agent.authenticate, (ctx) => getAgent().authenticate(ctx.params, ctx.requestId)).onRequest(methods.agent.logout, (ctx) => getAgent().logout(ctx.params)).onRequest(methods.agent.providers.list, (ctx) => getAgent().listProviders(ctx.params)).onRequest(methods.agent.providers.set, (ctx) => getAgent().setProvider(ctx.params)).onRequest(methods.agent.providers.disable, (ctx) => getAgent().disableProvider(ctx.params)).onRequest(methods.agent.session.prompt, (ctx) => getAgent(ctx.params).prompt(ctx.params, ctx.signal)).onNotification(methods.agent.session.cancel, (ctx) => getAgent().cancel(ctx.params)).onRequest("authentication/status", emptyExtensionParamsParser, (ctx) => getAgent().extMethod("authentication/status", ctx.params)).onRequest("authentication/logout", emptyExtensionParamsParser, (ctx) => getAgent().extMethod("authentication/logout", ctx.params)).onRequest(LEGACY_SET_SESSION_MODEL_METHOD, legacySetSessionModelParamsParser, (ctx) => getAgent(ctx.params).extMethod(LEGACY_SET_SESSION_MODEL_METHOD, ctx.params)).onRequest(SESSION_STEERING_METHOD, sessionSteerParamsParser, (ctx) => getAgent(ctx.params).extMethod(SESSION_STEERING_METHOD, ctx.params)).onRequest(ASYNC_TASK_STOP_METHOD, asyncTaskStopParamsParser, (ctx) => getAgent(ctx.params).extMethod(ASYNC_TASK_STOP_METHOD, ctx.params)).onRequest(CODEX_HOOKS_LIST_METHOD, hooksListParamsParser, (ctx) => getAgent().listHooks(ctx.params.cwd)).onRequest(CODEX_HOOKS_TRUST_METHOD, hooksTrustParamsParser, (ctx) => getAgent().trustHooks(ctx.params.cwd, ctx.params.hooks)).onRequest(GOAL_CONTROL_METHOD, goalControlParamsParser, (ctx) => getAgent(ctx.params).extMethod(GOAL_CONTROL_METHOD, ctx.params)).onRequest(SESSION_RENAME_METHOD, sessionRenameParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.rename(ctx.params)).onRequest(SESSION_BATCH_GET_METHOD, sessionBatchGetParamsParser, (ctx) => getAgent().sessionIndex.batchGet(ctx.params)).onRequest(SESSION_ARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, true)).onRequest(SESSION_UNARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, false)).onRequest(SESSION_LIST_SUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.subscribeList(ctx.params)).onRequest(SESSION_LIST_UNSUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.unsubscribeList(ctx.params));
54454
- const v2Agent = agent2({ name: package_default.name }).onConnect((connection) => attachAgent(createAgent(new AcpV2Connection(connection.client)), connection.signal)).onRequest(methods2.agent.initialize, (ctx) => getAgent().initializeV2(ctx.params)).onRequest(methods2.agent.session.new, (ctx) => getAgent().newSessionV2(ctx.params)).onRequest(methods2.agent.session.list, (ctx) => getAgent().listSessions(ctx.params)).onRequest(methods2.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params)).onRequest(methods2.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgent(ctx.params).resumeSessionV2(ctx.params), ctx.signal)).onRequest(methods2.agent.session.fork, (ctx) => getAgent(ctx.params).forkSessionV2(ctx.params)).onRequest(methods2.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params)).onRequest(methods2.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOptionV2(ctx.params)).onRequest(methods2.agent.auth.login, (ctx) => getAgent().authenticateV2(ctx.params, ctx.requestId)).onRequest(methods2.agent.auth.logout, (ctx) => getAgent().logoutV2(ctx.params)).onRequest(methods2.agent.session.prompt, (ctx) => getAgent(ctx.params).promptV2(ctx.params, ctx.signal)).onNotification(methods2.agent.session.cancel, (ctx) => getAgent().cancel(ctx.params)).onRequest(methods2.agent.providers.list, (ctx) => getAgent().listProviders(ctx.params)).onRequest(methods2.agent.providers.set, (ctx) => getAgent().setProvider(ctx.params)).onRequest(methods2.agent.providers.disable, (ctx) => getAgent().disableProvider(ctx.params)).onRequest(SESSION_STEERING_METHOD, sessionSteerParamsParser, (ctx) => getAgent(ctx.params).extMethod(SESSION_STEERING_METHOD, ctx.params)).onRequest(GOAL_CONTROL_METHOD, goalControlParamsParser, (ctx) => getAgent(ctx.params).extMethod(GOAL_CONTROL_METHOD, ctx.params)).onRequest(ASYNC_TASK_STOP_METHOD, asyncTaskStopParamsParser, (ctx) => getAgent(ctx.params).extMethod(ASYNC_TASK_STOP_METHOD, ctx.params)).onRequest(SESSION_RENAME_METHOD, sessionRenameParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.rename(ctx.params)).onRequest(SESSION_BATCH_GET_METHOD, sessionBatchGetParamsParser, (ctx) => getAgent().sessionIndex.batchGet(ctx.params)).onRequest(SESSION_ARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, true)).onRequest(SESSION_UNARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, false)).onRequest(SESSION_LIST_SUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.subscribeList(ctx.params)).onRequest(SESSION_LIST_UNSUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.unsubscribeList(ctx.params));
54364
+ const v1Agent = agent({ name: package_default.name }).onConnect((connection) => attachAgent(createAgent(connection.client), connection.signal)).onRequest(methods.agent.initialize, (ctx) => getAgent().initialize(ctx.params)).onRequest(methods.agent.session.new, (ctx) => getAgentForPaths(ctx.params).newSession(ctx.params)).onRequest(methods.agent.session.load, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).loadSession(ctx.params), ctx.signal)).onRequest(methods.agent.session.fork, (ctx) => getAgentForPaths(ctx.params).forkSession(ctx.params)).onRequest(methods.agent.session.list, (ctx) => getAgentForPaths({ cwd: ctx.params.cwd ?? null }).listSessions(ctx.params)).onRequest(methods.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params)).onRequest(methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).resumeSession(ctx.params), ctx.signal)).onRequest(methods.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params)).onRequest(methods.agent.session.setMode, (ctx) => getAgent(ctx.params).setSessionMode(ctx.params)).onRequest(methods.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOption(ctx.params)).onRequest(methods.agent.authenticate, (ctx) => getAgent().authenticate(ctx.params, ctx.requestId)).onRequest(methods.agent.logout, (ctx) => getAgent().logout(ctx.params)).onRequest(methods.agent.providers.list, (ctx) => getAgent().listProviders(ctx.params)).onRequest(methods.agent.providers.set, (ctx) => getAgent().setProvider(ctx.params)).onRequest(methods.agent.providers.disable, (ctx) => getAgent().disableProvider(ctx.params)).onRequest(methods.agent.session.prompt, (ctx) => getAgent(ctx.params).prompt(ctx.params, ctx.signal)).onNotification(methods.agent.session.cancel, (ctx) => getAgent().cancel(ctx.params)).onRequest("authentication/status", emptyExtensionParamsParser, (ctx) => getAgent().extMethod("authentication/status", ctx.params)).onRequest("authentication/logout", emptyExtensionParamsParser, (ctx) => getAgent().extMethod("authentication/logout", ctx.params)).onRequest(LEGACY_SET_SESSION_MODEL_METHOD, legacySetSessionModelParamsParser, (ctx) => getAgent(ctx.params).extMethod(LEGACY_SET_SESSION_MODEL_METHOD, ctx.params)).onRequest(SESSION_STEERING_METHOD, sessionSteerParamsParser, (ctx) => getAgent(ctx.params).extMethod(SESSION_STEERING_METHOD, ctx.params)).onRequest(ASYNC_TASK_STOP_METHOD, asyncTaskStopParamsParser, (ctx) => getAgent(ctx.params).extMethod(ASYNC_TASK_STOP_METHOD, ctx.params)).onRequest(CODEX_HOOKS_LIST_METHOD, hooksListParamsParser, (ctx) => getAgent().listHooks(ctx.params.cwd)).onRequest(CODEX_HOOKS_TRUST_METHOD, hooksTrustParamsParser, (ctx) => getAgent().trustHooks(ctx.params.cwd, ctx.params.hooks)).onRequest(GOAL_CONTROL_METHOD, goalControlParamsParser, (ctx) => getAgent(ctx.params).extMethod(GOAL_CONTROL_METHOD, ctx.params)).onRequest(SESSION_RENAME_METHOD, sessionRenameParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.rename(ctx.params)).onRequest(SESSION_BATCH_GET_METHOD, sessionBatchGetParamsParser, (ctx) => getAgent().sessionIndex.batchGet(ctx.params)).onRequest(SESSION_ARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, true)).onRequest(SESSION_UNARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, false)).onRequest(SESSION_LIST_SUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.subscribeList(ctx.params)).onRequest(SESSION_LIST_UNSUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.unsubscribeList(ctx.params));
54365
+ const v2Agent = agent2({ name: package_default.name }).onConnect((connection) => attachAgent(createAgent(new AcpV2Connection(connection.client)), connection.signal)).onRequest(methods2.agent.initialize, (ctx) => getAgent().initializeV2(ctx.params)).onRequest(methods2.agent.session.new, (ctx) => getAgentForPaths(ctx.params).newSessionV2(ctx.params)).onRequest(methods2.agent.session.list, (ctx) => getAgentForPaths({ cwd: ctx.params.cwd ?? null }).listSessions(ctx.params)).onRequest(methods2.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params)).onRequest(methods2.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).resumeSessionV2(ctx.params), ctx.signal)).onRequest(methods2.agent.session.fork, (ctx) => getAgentForPaths(ctx.params).forkSessionV2(ctx.params)).onRequest(methods2.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params)).onRequest(methods2.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOptionV2(ctx.params)).onRequest(methods2.agent.auth.login, (ctx) => getAgent().authenticateV2(ctx.params, ctx.requestId)).onRequest(methods2.agent.auth.logout, (ctx) => getAgent().logoutV2(ctx.params)).onRequest(methods2.agent.session.prompt, (ctx) => getAgent(ctx.params).promptV2(ctx.params, ctx.signal)).onNotification(methods2.agent.session.cancel, (ctx) => getAgent().cancel(ctx.params)).onRequest(methods2.agent.providers.list, (ctx) => getAgent().listProviders(ctx.params)).onRequest(methods2.agent.providers.set, (ctx) => getAgent().setProvider(ctx.params)).onRequest(methods2.agent.providers.disable, (ctx) => getAgent().disableProvider(ctx.params)).onRequest(SESSION_STEERING_METHOD, sessionSteerParamsParser, (ctx) => getAgent(ctx.params).extMethod(SESSION_STEERING_METHOD, ctx.params)).onRequest(GOAL_CONTROL_METHOD, goalControlParamsParser, (ctx) => getAgent(ctx.params).extMethod(GOAL_CONTROL_METHOD, ctx.params)).onRequest(ASYNC_TASK_STOP_METHOD, asyncTaskStopParamsParser, (ctx) => getAgent(ctx.params).extMethod(ASYNC_TASK_STOP_METHOD, ctx.params)).onRequest(SESSION_RENAME_METHOD, sessionRenameParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.rename(ctx.params)).onRequest(SESSION_BATCH_GET_METHOD, sessionBatchGetParamsParser, (ctx) => getAgent().sessionIndex.batchGet(ctx.params)).onRequest(SESSION_ARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, true)).onRequest(SESSION_UNARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.setArchived(ctx.params, false)).onRequest(SESSION_LIST_SUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.subscribeList(ctx.params)).onRequest(SESSION_LIST_UNSUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.unsubscribeList(ctx.params));
54455
54366
  return agentProtocolRouter().withV1(v1Agent).withV2(v2Agent);
54456
54367
  }
54457
54368