@ycodium-ai/agent-acp 0.2.3608 → 0.2.3635

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.
package/dist/index.js CHANGED
@@ -98,6 +98,40 @@ var AcpExecutorTurnEndedError = class extends AcpExecutorError {
98
98
  this.name = "AcpExecutorTurnEndedError";
99
99
  }
100
100
  };
101
+ var AcpExecutorOptionRejectedError = class extends AcpExecutorError {
102
+ constructor(option, value, cause) {
103
+ const detail = acpErrorDetail(cause);
104
+ super(
105
+ "provider-rejected",
106
+ `The agent rejected the ${option}${value === void 0 ? "" : ` "${value}"`}${detail === void 0 ? "" : ` (${detail})`}. This turn was not sent.`
107
+ );
108
+ this.name = "AcpExecutorOptionRejectedError";
109
+ }
110
+ };
111
+ var AcpExecutorOptionTimeoutError = class extends AcpExecutorError {
112
+ constructor(option, value) {
113
+ super(
114
+ "provider-rejected",
115
+ `The agent did not answer the ${option} "${value}" change in time. This turn was not sent.`
116
+ );
117
+ this.name = "AcpExecutorOptionTimeoutError";
118
+ }
119
+ };
120
+ var AcpOptionWriteStoppedError = class extends Error {
121
+ constructor() {
122
+ super("option write stopped");
123
+ this.name = "AcpOptionWriteStoppedError";
124
+ }
125
+ };
126
+ function acpErrorDetail(cause) {
127
+ if (typeof cause !== "object" || cause === null) return void 0;
128
+ const message = cause.message;
129
+ const data = cause.data;
130
+ const parts = [message, data].filter(
131
+ (part) => typeof part === "string" && part.trim().length > 0
132
+ );
133
+ return parts.length === 0 ? void 0 : parts.join(": ");
134
+ }
101
135
  var AcpExecutorNotStartedError = class extends AcpExecutorError {
102
136
  constructor(message = "ACP session has not been started") {
103
137
  super("not-started", message);
@@ -211,10 +245,134 @@ var UnboundedEventStream = class {
211
245
  }
212
246
  };
213
247
 
214
- // ../../packages/ycodium-acp-executor/src/util.ts
248
+ // ../../packages/ycodium-acp-executor/src/config-options.ts
215
249
  function isRecord(value) {
216
250
  return typeof value === "object" && value !== null && !Array.isArray(value);
217
251
  }
252
+ function asString(value) {
253
+ return typeof value === "string" ? value : void 0;
254
+ }
255
+ function normalizedField(option, key) {
256
+ return asString(option[key])?.trim().toLowerCase() ?? "";
257
+ }
258
+ function looksLikeEffortOption(option) {
259
+ const id = normalizedField(option, "id");
260
+ const name = normalizedField(option, "name");
261
+ return id === "effort" || id === "reasoning" || name === "effort" || name === "reasoning" || name.includes("effort") || name.includes("reasoning") || normalizedField(option, "category") === "thought_level";
262
+ }
263
+ function flattenChoices(rawOptions, currentValue) {
264
+ if (!Array.isArray(rawOptions)) return [];
265
+ const out = [];
266
+ const seen = /* @__PURE__ */ new Set();
267
+ const push = (entry) => {
268
+ if (!isRecord(entry)) return;
269
+ const value = asString(entry["value"]);
270
+ if (value === void 0 || seen.has(value)) return;
271
+ seen.add(value);
272
+ const description = asString(entry["description"])?.trim();
273
+ const name = asString(entry["name"])?.trim();
274
+ out.push({
275
+ value,
276
+ ...name ? { name } : {},
277
+ label: name || value,
278
+ ...description ? { description } : {},
279
+ ...currentValue !== void 0 && currentValue === value ? { isDefault: true } : {}
280
+ });
281
+ };
282
+ for (const entry of rawOptions) {
283
+ if (isRecord(entry) && Array.isArray(entry["options"])) {
284
+ for (const nested of entry["options"]) push(nested);
285
+ continue;
286
+ }
287
+ push(entry);
288
+ }
289
+ return out;
290
+ }
291
+ function isConfigOption(entry, configId) {
292
+ return isRecord(entry) && asString(entry["id"])?.trim() === configId.trim();
293
+ }
294
+ function findConfigOptionEntry(configOptions, configId) {
295
+ return Array.isArray(configOptions) && configId.trim() !== "" ? configOptions.find(
296
+ (entry) => isConfigOption(entry, configId)
297
+ ) : void 0;
298
+ }
299
+ function withConfigOptionValue(configOptions, configId, value) {
300
+ if (!Array.isArray(configOptions)) return configOptions;
301
+ return configOptions.map(
302
+ (option) => isConfigOption(option, configId) ? { ...option, currentValue: value } : option
303
+ );
304
+ }
305
+ function pickEffortOption(configOptions) {
306
+ if (!Array.isArray(configOptions)) return void 0;
307
+ const candidates = configOptions.filter(isRecord).filter((option) => normalizedField(option, "type") === "select").filter(looksLikeEffortOption);
308
+ return candidates.find((option) => normalizedField(option, "category") === "model_option") ?? candidates.find((option) => normalizedField(option, "id") === "effort") ?? candidates.find((option) => normalizedField(option, "category") === "thought_level") ?? candidates[0];
309
+ }
310
+ function findAcpEffortConfig(configOptions) {
311
+ const picked = pickEffortOption(configOptions);
312
+ if (picked === void 0) return void 0;
313
+ const configId = asString(picked["id"])?.trim();
314
+ if (!configId) return void 0;
315
+ const currentValue = asString(picked["currentValue"])?.trim() || void 0;
316
+ const choices = flattenChoices(picked["options"], currentValue);
317
+ if (choices.length === 0) return void 0;
318
+ return {
319
+ configId,
320
+ label: asString(picked["name"])?.trim() ?? "",
321
+ choices,
322
+ ...currentValue === void 0 ? {} : { currentValue }
323
+ };
324
+ }
325
+ function choicesComplete(rawOptions) {
326
+ const leafOk = (entry) => isRecord(entry) && (asString(entry["value"])?.trim() ?? "") !== "";
327
+ return rawOptions.every(
328
+ (entry) => isRecord(entry) && Array.isArray(entry["options"]) ? entry["options"].every(leafOk) : leafOk(entry)
329
+ );
330
+ }
331
+ function acpEffortConfigState(configOptions) {
332
+ const picked = pickEffortOption(configOptions);
333
+ if (picked === void 0 || !asString(picked["id"])?.trim()) return "unknown";
334
+ const options = picked["options"];
335
+ if (!Array.isArray(options)) return "unknown";
336
+ if (options.length === 0) return "none";
337
+ return choicesComplete(options) ? "listed" : "unknown";
338
+ }
339
+ function acpModelChoicesFromConfigOptions(configOptions) {
340
+ if (!Array.isArray(configOptions)) return void 0;
341
+ const records = configOptions.filter(isRecord);
342
+ const modelOption = records.find((option) => normalizedField(option, "category") === "model") ?? records.find(
343
+ (option) => normalizedField(option, "id") === "model" && normalizedField(option, "type") === "select"
344
+ );
345
+ if (modelOption === void 0) return void 0;
346
+ if (!asString(modelOption["id"])?.trim()) return void 0;
347
+ return flattenChoices(modelOption["options"], asString(modelOption["currentValue"])?.trim());
348
+ }
349
+ function acpModelChoicesFromSessionModels(models) {
350
+ if (!isRecord(models) || !Array.isArray(models["availableModels"])) return void 0;
351
+ const currentModelId = asString(models["currentModelId"])?.trim();
352
+ const out = [];
353
+ const seen = /* @__PURE__ */ new Set();
354
+ for (const entry of models["availableModels"]) {
355
+ if (!isRecord(entry)) continue;
356
+ const value = asString(entry["modelId"])?.trim();
357
+ if (!value || seen.has(value)) continue;
358
+ seen.add(value);
359
+ const name = asString(entry["name"])?.trim();
360
+ const description = asString(entry["description"])?.trim();
361
+ out.push({
362
+ value,
363
+ ...name ? { name } : {},
364
+ label: name || value,
365
+ ...description ? { description } : {},
366
+ ...currentModelId !== void 0 && currentModelId === value ? { isDefault: true } : {}
367
+ });
368
+ }
369
+ return out;
370
+ }
371
+
372
+ // ../../packages/ycodium-acp-executor/src/util.ts
373
+ function isRecord2(value) {
374
+ return typeof value === "object" && value !== null && !Array.isArray(value);
375
+ }
218
376
  function asTrimmedString(value) {
219
377
  if (typeof value !== "string") {
220
378
  return void 0;
@@ -267,11 +425,11 @@ function extractCommandFromTitle(title) {
267
425
  return backtickMatch?.[1]?.trim() || void 0;
268
426
  }
269
427
  function extractToolCommand(data, title) {
270
- const item = isRecord(data?.["item"]) ? data["item"] : void 0;
271
- const itemInput = item && isRecord(item["input"]) ? item["input"] : void 0;
272
- const itemResult = item && isRecord(item["result"]) ? item["result"] : void 0;
273
- const rawInput = isRecord(data?.["rawInput"]) ? data["rawInput"] : void 0;
274
- const dataInput = isRecord(data?.["input"]) ? data["input"] : void 0;
428
+ const item = isRecord2(data?.["item"]) ? data["item"] : void 0;
429
+ const itemInput = item && isRecord2(item["input"]) ? item["input"] : void 0;
430
+ const itemResult = item && isRecord2(item["result"]) ? item["result"] : void 0;
431
+ const rawInput = isRecord2(data?.["rawInput"]) ? data["rawInput"] : void 0;
432
+ const dataInput = isRecord2(data?.["input"]) ? data["input"] : void 0;
275
433
  const candidates = [
276
434
  normalizeCommandValue(item?.["command"]),
277
435
  normalizeCommandValue(itemInput?.["command"]),
@@ -316,7 +474,7 @@ function collectPaths(value, paths, seen, depth) {
316
474
  }
317
475
  return;
318
476
  }
319
- if (!isRecord(value)) {
477
+ if (!isRecord2(value)) {
320
478
  return;
321
479
  }
322
480
  for (const key of ["path", "filePath", "relativePath", "filename", "newPath", "oldPath"]) {
@@ -394,7 +552,7 @@ function deriveToolActivityPresentation(input2) {
394
552
  const title = asTrimmedString(input2.title);
395
553
  const detail = stripTrailingExitCode(asTrimmedString(input2.detail));
396
554
  const fallbackSummary = asTrimmedString(input2.fallbackSummary) ?? "Tool";
397
- const data = isRecord(input2.data) ? input2.data : void 0;
555
+ const data = isRecord2(input2.data) ? input2.data : void 0;
398
556
  const command = extractToolCommand(data, title);
399
557
  const primaryPath = extractPrimaryPath(data);
400
558
  const action = classifyToolAction({
@@ -426,7 +584,7 @@ function deriveToolActivityPresentation(input2) {
426
584
  };
427
585
  }
428
586
  if (action === "search") {
429
- const rawInput = isRecord(data?.["rawInput"]) ? data["rawInput"] : void 0;
587
+ const rawInput = isRecord2(data?.["rawInput"]) ? data["rawInput"] : void 0;
430
588
  const query = asTrimmedString(rawInput?.["query"]) ?? asTrimmedString(rawInput?.["pattern"]) ?? asTrimmedString(rawInput?.["searchTerm"]);
431
589
  return {
432
590
  summary: "Searched files",
@@ -486,7 +644,7 @@ function extractCommandFromTitle2(title) {
486
644
  return match?.[1]?.trim() || void 0;
487
645
  }
488
646
  function extractToolCallCommand(rawInput, title) {
489
- if (isRecord(rawInput)) {
647
+ if (isRecord2(rawInput)) {
490
648
  const directCommand = normalizeCommandValue2(rawInput["command"]);
491
649
  if (directCommand) {
492
650
  return directCommand;
@@ -514,7 +672,7 @@ function boundTailText(text, limit = TOOL_CALL_CONTENT_MAX_CHARS) {
514
672
  var boundToolCallOutputText = (text) => boundTailText(text);
515
673
  var RAW_OUTPUT_TEXT_FIELDS = ["content", "stdout", "stderr", "output"];
516
674
  function boundToolCallRawOutput(rawOutput) {
517
- if (!isRecord(rawOutput)) {
675
+ if (!isRecord2(rawOutput)) {
518
676
  return rawOutput;
519
677
  }
520
678
  let changed = false;
@@ -695,14 +853,7 @@ function extractModelConfigId(sessionResponse) {
695
853
  return configOptions.find((opt) => opt.id.trim() === "model" && opt.type === "select") ? "model" : void 0;
696
854
  }
697
855
  function findSessionConfigOption(configOptions, configId) {
698
- if (!configOptions) {
699
- return void 0;
700
- }
701
- const normalizedConfigId = configId.trim();
702
- if (!normalizedConfigId) {
703
- return void 0;
704
- }
705
- return configOptions.find((option) => option.id.trim() === normalizedConfigId);
856
+ return findConfigOptionEntry(configOptions, configId);
706
857
  }
707
858
  function collectSessionConfigOptionValues(configOption) {
708
859
  if (configOption.type !== "select" || !configOption.options) {
@@ -713,11 +864,11 @@ function collectSessionConfigOptionValues(configOption) {
713
864
  );
714
865
  }
715
866
  function collectSessionModelIds(models) {
716
- if (!isRecord(models) || !Array.isArray(models["availableModels"])) {
867
+ if (!isRecord2(models) || !Array.isArray(models["availableModels"])) {
717
868
  return [];
718
869
  }
719
870
  return models["availableModels"].flatMap(
720
- (model) => isRecord(model) && typeof model["modelId"] === "string" ? [model["modelId"]] : []
871
+ (model) => isRecord2(model) && typeof model["modelId"] === "string" ? [model["modelId"]] : []
721
872
  );
722
873
  }
723
874
  function catalogModelLastSegment(value) {
@@ -789,7 +940,7 @@ function parseAvailableCommandsUpdate(params) {
789
940
  }
790
941
  const commands = [];
791
942
  for (const command of availableCommands) {
792
- if (!isRecord(command)) {
943
+ if (!isRecord2(command)) {
793
944
  continue;
794
945
  }
795
946
  const name = typeof command["name"] === "string" ? command["name"].trim() : "";
@@ -797,7 +948,7 @@ function parseAvailableCommandsUpdate(params) {
797
948
  continue;
798
949
  }
799
950
  const description = typeof command["description"] === "string" ? command["description"].trim() || void 0 : void 0;
800
- const input2 = isRecord(command["input"]) ? command["input"] : void 0;
951
+ const input2 = isRecord2(command["input"]) ? command["input"] : void 0;
801
952
  const inputHint = typeof input2?.["hint"] === "string" ? input2["hint"].trim() || void 0 : void 0;
802
953
  commands.push({
803
954
  name,
@@ -851,7 +1002,7 @@ function boundToolCallRawPayload(params, update, toolCall) {
851
1002
  }
852
1003
  function textFromContentBlocks(blocks) {
853
1004
  const parts = blocks.flatMap(
854
- (block) => isRecord(block) && block["type"] === "text" && typeof block["text"] === "string" ? [block["text"]] : []
1005
+ (block) => isRecord2(block) && block["type"] === "text" && typeof block["text"] === "string" ? [block["text"]] : []
855
1006
  );
856
1007
  const joined = parts.join("");
857
1008
  return joined.trim().length > 0 ? joined : void 0;
@@ -876,7 +1027,7 @@ function parseSessionUpdateEvent(params) {
876
1027
  const entries = Array.isArray(upd["entries"]) ? upd["entries"] : [];
877
1028
  const plan = entries.map((entry, index) => ({
878
1029
  step: readAcpText(entry, "content") ?? `Step ${index + 1}`,
879
- status: normalizePlanStepStatus(isRecord(entry) ? entry["status"] : void 0)
1030
+ status: normalizePlanStepStatus(isRecord2(entry) ? entry["status"] : void 0)
880
1031
  }));
881
1032
  if (plan.length > 0) {
882
1033
  events.push({
@@ -916,7 +1067,7 @@ function parseSessionUpdateEvent(params) {
916
1067
  }
917
1068
  case "agent_message_chunk":
918
1069
  case "agent_thought_chunk": {
919
- const content = isRecord(upd["content"]) ? upd["content"] : void 0;
1070
+ const content = isRecord2(upd["content"]) ? upd["content"] : void 0;
920
1071
  const contentType = content?.["type"];
921
1072
  const streamKind = kind === "agent_thought_chunk" ? "reasoning_text" : "assistant_text";
922
1073
  if (contentType === "text") {
@@ -956,7 +1107,7 @@ function parseSessionUpdateEvent(params) {
956
1107
  }
957
1108
  case "compaction_summary_chunk": {
958
1109
  const compactionId = readAcpText(upd, "compactionId");
959
- const content = isRecord(upd["content"]) ? upd["content"] : void 0;
1110
+ const content = isRecord2(upd["content"]) ? upd["content"] : void 0;
960
1111
  const text = content?.["type"] === "text" ? content["text"] : void 0;
961
1112
  if (compactionId === void 0 || typeof text !== "string" || text.length === 0) break;
962
1113
  events.push({ _tag: "CompactionSummaryChunk", compactionId, text });
@@ -22650,17 +22801,17 @@ function isResponseMessage(value) {
22650
22801
  function isNotificationMessage(value) {
22651
22802
  return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
22652
22803
  }
22653
- function isRecord2(value) {
22804
+ function isRecord3(value) {
22654
22805
  return typeof value === "object" && value !== null;
22655
22806
  }
22656
22807
  function isJsonRpcEnvelope(value) {
22657
- return isRecord2(value) && value["jsonrpc"] === "2.0";
22808
+ return isRecord3(value) && value["jsonrpc"] === "2.0";
22658
22809
  }
22659
22810
  function isJsonRpcId(value) {
22660
22811
  return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
22661
22812
  }
22662
22813
  function isResponseShapedMessage(value) {
22663
- return isRecord2(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
22814
+ return isRecord3(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
22664
22815
  }
22665
22816
  function isResponseBatch(batch) {
22666
22817
  let hasValidCall = false;
@@ -22670,7 +22821,7 @@ function isResponseBatch(batch) {
22670
22821
  for (const entry of batch) {
22671
22822
  hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
22672
22823
  hasValidResponse ||= isResponseMessage(entry);
22673
- if (!isRecord2(entry)) {
22824
+ if (!isRecord3(entry)) {
22674
22825
  continue;
22675
22826
  }
22676
22827
  hasCallShape ||= "method" in entry;
@@ -22685,13 +22836,13 @@ function isResponseBatch(batch) {
22685
22836
  return hasResponseShape && !hasCallShape;
22686
22837
  }
22687
22838
  function cancelRequestId(params) {
22688
- if (!isRecord2(params) || !isJsonRpcId(params["requestId"])) {
22839
+ if (!isRecord3(params) || !isJsonRpcId(params["requestId"])) {
22689
22840
  return void 0;
22690
22841
  }
22691
22842
  return params["requestId"];
22692
22843
  }
22693
22844
  function isErrorResponse(value) {
22694
- return isRecord2(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
22845
+ return isRecord3(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
22695
22846
  }
22696
22847
  var Handled = {
22697
22848
  /**
@@ -23236,7 +23387,7 @@ var Connection = class {
23236
23387
  if (this.abortController.signal.aborted) {
23237
23388
  return Promise.resolve();
23238
23389
  }
23239
- if (!isRecord2(message)) {
23390
+ if (!isRecord3(message)) {
23240
23391
  console.error("Invalid message", { message });
23241
23392
  return Promise.resolve();
23242
23393
  }
@@ -23639,7 +23790,7 @@ function ndJsonStream(output2, input2) {
23639
23790
  await writeJson(protocolErrorResponse(RequestError.parseError()));
23640
23791
  return;
23641
23792
  }
23642
- if (isRecord2(message) || Array.isArray(message)) {
23793
+ if (isRecord3(message) || Array.isArray(message)) {
23643
23794
  controller.enqueue(message);
23644
23795
  } else {
23645
23796
  await writeJson(protocolErrorResponse(RequestError.invalidRequest(message)));
@@ -24626,14 +24777,14 @@ var legacyClientNotificationMethods = /* @__PURE__ */ new Set([
24626
24777
  import * as NodeStream from "node:stream";
24627
24778
 
24628
24779
  // ../../packages/ycodium-acp-executor/src/jsonrpc.ts
24629
- function isRecord3(value) {
24780
+ function isRecord4(value) {
24630
24781
  return typeof value === "object" && value !== null;
24631
24782
  }
24632
24783
  function isJsonRpcId2(value) {
24633
24784
  return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
24634
24785
  }
24635
24786
  function isJsonRpcEnvelope2(value) {
24636
- return isRecord3(value) && value["jsonrpc"] === "2.0";
24787
+ return isRecord4(value) && value["jsonrpc"] === "2.0";
24637
24788
  }
24638
24789
  function isRequestMessage2(value) {
24639
24790
  return isJsonRpcEnvelope2(value) && "id" in value && typeof value["method"] === "string" && isJsonRpcId2(value["id"]);
@@ -24653,7 +24804,7 @@ function isNotificationMessage2(value) {
24653
24804
  return isJsonRpcEnvelope2(value) && !("id" in value) && typeof value["method"] === "string";
24654
24805
  }
24655
24806
  function readJsonRpcError(value) {
24656
- if (!isRecord3(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
24807
+ if (!isRecord4(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
24657
24808
  return void 0;
24658
24809
  }
24659
24810
  return {
@@ -24726,11 +24877,11 @@ var KNOWN_SESSION_UPDATES = /* @__PURE__ */ new Set([
24726
24877
  "compaction_summary_chunk"
24727
24878
  ]);
24728
24879
  function isSessionUpdateEnvelope(payload) {
24729
- if (!isRecord3(payload) || typeof payload["sessionId"] !== "string") {
24880
+ if (!isRecord4(payload) || typeof payload["sessionId"] !== "string") {
24730
24881
  return false;
24731
24882
  }
24732
24883
  const update = payload["update"];
24733
- return isRecord3(update) && typeof update["sessionUpdate"] === "string";
24884
+ return isRecord4(update) && typeof update["sessionUpdate"] === "string";
24734
24885
  }
24735
24886
  function hasKnownVariantShape(update) {
24736
24887
  const kind = update["sessionUpdate"];
@@ -24738,7 +24889,7 @@ function hasKnownVariantShape(update) {
24738
24889
  return false;
24739
24890
  }
24740
24891
  if (kind === "user_message_chunk" || kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
24741
- return isRecord3(update["content"]);
24892
+ return isRecord4(update["content"]);
24742
24893
  }
24743
24894
  return true;
24744
24895
  }
@@ -24927,6 +25078,10 @@ function createAcpConnection(options) {
24927
25078
  );
24928
25079
  } catch {
24929
25080
  }
25081
+ try {
25082
+ waiter.onArrival?.();
25083
+ } catch {
25084
+ }
24930
25085
  if (Object.hasOwn(message, "error")) {
24931
25086
  const rpcError = readJsonRpcError(message["error"]);
24932
25087
  waiter.reject(
@@ -25057,7 +25212,7 @@ function createAcpConnection(options) {
25057
25212
  options.readable.on("end", onEnd);
25058
25213
  options.readable.on("error", onError);
25059
25214
  options.writable.once("error", onWritableError);
25060
- const begin = (method, params, promptId) => {
25215
+ const begin = (method, params, promptId, onArrival) => {
25061
25216
  failIfClosed();
25062
25217
  const id = nextRequestId;
25063
25218
  nextRequestId += 1;
@@ -25065,6 +25220,7 @@ function createAcpConnection(options) {
25065
25220
  pending.set(String(id), {
25066
25221
  method,
25067
25222
  ...promptId === void 0 ? {} : { promptId },
25223
+ ...onArrival === void 0 ? {} : { onArrival },
25068
25224
  resolve: resolve2,
25069
25225
  reject
25070
25226
  });
@@ -25120,10 +25276,31 @@ function createAcpConnection(options) {
25120
25276
  function normalizeModelId(value) {
25121
25277
  return value?.trim() || void 0;
25122
25278
  }
25279
+ function adoptReportedConfigOptions(state, configOptions) {
25280
+ const option = state.modelConfigId === void 0 ? void 0 : findConfigOptionEntry(configOptions, state.modelConfigId);
25281
+ const value = option?.["currentValue"];
25282
+ const reported = typeof value === "string" ? normalizeModelId(value) : void 0;
25283
+ if (reported === void 0) return { ...state, configOptions };
25284
+ const { modelUnconfirmed: _confirmed, ...known } = state;
25285
+ return { ...known, configOptions, currentModelId: reported };
25286
+ }
25287
+ function forgetConfigOptionValue(state, configId) {
25288
+ const forgetsModel = configId === void 0 || configId === state.modelConfigId;
25289
+ const configOptions = configId !== void 0 && Array.isArray(state.configOptions) ? state.configOptions.map((option) => {
25290
+ if (!isRecord2(option) || option["id"] !== configId) return option;
25291
+ const { currentValue: _forgotten, ...rest } = option;
25292
+ return rest;
25293
+ }) : state.configOptions;
25294
+ return {
25295
+ ...state,
25296
+ configOptions,
25297
+ ...forgetsModel ? { currentModelId: void 0, modelUnconfirmed: true } : {}
25298
+ };
25299
+ }
25123
25300
  function modelSelectionStateFromSetup(setup) {
25124
- const sessionModels = isRecord(setup.models) ? setup.models : void 0;
25301
+ const sessionModels = isRecord2(setup.models) ? setup.models : void 0;
25125
25302
  const modelConfigId = extractModelConfigId(setup);
25126
- const strategy = sessionModels === void 0 && modelConfigId !== void 0 ? "config-option" : "session/set_model";
25303
+ const strategy = modelConfigId !== void 0 ? "config-option" : "session/set_model";
25127
25304
  const modelConfigOption = modelConfigId === void 0 ? void 0 : findSessionConfigOption(setup.configOptions, modelConfigId);
25128
25305
  const configModel = modelConfigOption?.currentValue;
25129
25306
  const currentModelId = strategy === "config-option" ? typeof configModel === "string" ? normalizeModelId(configModel) : void 0 : typeof sessionModels?.["currentModelId"] === "string" ? normalizeModelId(sessionModels["currentModelId"]) : void 0;
@@ -25133,7 +25310,8 @@ function modelSelectionStateFromSetup(setup) {
25133
25310
  modelConfigId,
25134
25311
  currentModelId,
25135
25312
  advertisedModelValues: strategy === "config-option" ? modelConfigOption === void 0 ? [] : collectSessionConfigOptionValues(modelConfigOption) : collectSessionModelIds(sessionModels),
25136
- configOptions: setup.configOptions
25313
+ configOptions: setup.configOptions,
25314
+ catalogSetup: setup
25137
25315
  };
25138
25316
  }
25139
25317
 
@@ -25231,6 +25409,10 @@ function createExecutorLifecycle({
25231
25409
  if (targetTurnId !== void 0) {
25232
25410
  interruptedTurnIds.add(targetTurnId);
25233
25411
  }
25412
+ const optionWrites = shared.optionWriteStop;
25413
+ if (optionWrites !== void 0 && (targetTurnId === void 0 || optionWrites.turnId === targetTurnId)) {
25414
+ optionWrites.stop();
25415
+ }
25234
25416
  settleAllApprovals("cancel");
25235
25417
  settleAllUserInputs();
25236
25418
  abortPendingSettlement("turn cancelled");
@@ -25443,6 +25625,41 @@ function isAcpRequestPermissionParams(value) {
25443
25625
  return Array.isArray(record2["options"]);
25444
25626
  }
25445
25627
 
25628
+ // ../../packages/ycodium-acp-executor/src/apply-effort.ts
25629
+ var alignRequestedEffort = async (input2) => {
25630
+ const unchanged = { configOptions: input2.configOptions };
25631
+ const effort = findAcpEffortConfig(input2.configOptions);
25632
+ if (effort === void 0) return unchanged;
25633
+ const values = new Set(effort.choices.map((choice) => choice.value));
25634
+ const current = effort.currentValue;
25635
+ const requested = input2.requestedEffort?.trim() || void 0;
25636
+ const unsupportedEffort = requested !== void 0 && !values.has(requested) ? requested : void 0;
25637
+ const staleCurrent = current !== void 0 && !values.has(current);
25638
+ const fallback = input2.modelDefaultEffort !== void 0 && values.has(input2.modelDefaultEffort) ? input2.modelDefaultEffort : void 0;
25639
+ const target = requested !== void 0 && unsupportedEffort === void 0 ? requested : unsupportedEffort !== void 0 || staleCurrent ? fallback : void 0;
25640
+ const written = target === void 0 || target === current ? void 0 : await input2.write(effort.configId, target);
25641
+ const configOptions = written === void 0 ? input2.configOptions : written.configOptions;
25642
+ if (unsupportedEffort === void 0) return { configOptions };
25643
+ const confirmed = fallback !== void 0 && written?.reported === true && findAcpEffortConfig(written.configOptions)?.currentValue === fallback;
25644
+ return { configOptions, unsupportedEffort, ...confirmed ? { appliedEffort: fallback } : {} };
25645
+ };
25646
+
25647
+ // ../../packages/ycodium-acp-executor/src/reasoning-level-fallback.ts
25648
+ var REASONING_LEVEL_FALLBACK_CODE = "reasoning-level-fallback";
25649
+ function reasoningLevelFallbackWarning(input2) {
25650
+ const model = input2.model ?? "This model";
25651
+ const outcome = input2.appliedEffort === void 0 ? "so the agent picks this turn's level" : `so this turn uses its default, "${input2.appliedEffort}"`;
25652
+ return {
25653
+ message: `${model} does not offer the "${input2.requestedEffort}" reasoning effort, ${outcome}. Your saved choice is unchanged.`,
25654
+ detail: {
25655
+ code: REASONING_LEVEL_FALLBACK_CODE,
25656
+ ...input2.model === void 0 ? {} : { model: input2.model },
25657
+ requestedEffort: input2.requestedEffort,
25658
+ ...input2.appliedEffort === void 0 ? {} : { appliedEffort: input2.appliedEffort }
25659
+ }
25660
+ };
25661
+ }
25662
+
25446
25663
  // ../../packages/ycodium-acp-executor/src/failureCategory.ts
25447
25664
  var ACP_FAILURE_CATEGORIES = [
25448
25665
  "quota",
@@ -25783,6 +26000,8 @@ function createExecutorPrompt({
25783
26000
  threadMutex,
25784
26001
  promptMutex,
25785
26002
  applyRequestedModel,
26003
+ modelDefaultEffort,
26004
+ writeConfigOptionReported,
25786
26005
  notifyPromptSettled,
25787
26006
  shared,
25788
26007
  promptResults,
@@ -25876,6 +26095,57 @@ function createExecutorPrompt({
25876
26095
  }
25877
26096
  }
25878
26097
  };
26098
+ const alignTurnOptions = async (input2, sessionId, generation, isStale, signal) => {
26099
+ const applied = await applyRequestedModel({
26100
+ state: shared.modelSelectionState,
26101
+ acpSessionId: sessionId,
26102
+ requestedModelId: input2.requestedModelId,
26103
+ expectedGeneration: generation,
26104
+ signal
26105
+ });
26106
+ shared.modelSelectionState = applied;
26107
+ if (isStale()) return;
26108
+ const switched = applied.configOptions;
26109
+ let aligned;
26110
+ try {
26111
+ aligned = await alignRequestedEffort({
26112
+ configOptions: switched,
26113
+ write: (configId, value) => writeConfigOptionReported(sessionId, switched, configId, value, {
26114
+ option: "reasoning level",
26115
+ signal
26116
+ }),
26117
+ requestedEffort: input2.requestedEffort,
26118
+ modelDefaultEffort: modelDefaultEffort(applied)
26119
+ });
26120
+ } catch (error62) {
26121
+ throw error62 instanceof RequestError ? new AcpExecutorOptionRejectedError(
26122
+ "reasoning level",
26123
+ input2.requestedEffort?.trim(),
26124
+ error62
26125
+ ) : error62;
26126
+ }
26127
+ if (!isLive(generation)) throw new AcpExecutorDisposedError();
26128
+ if (aligned.configOptions !== switched) {
26129
+ shared.modelSelectionState = adoptReportedConfigOptions(
26130
+ shared.modelSelectionState,
26131
+ aligned.configOptions
26132
+ );
26133
+ }
26134
+ if (aligned.unsupportedEffort !== void 0) {
26135
+ emit({
26136
+ type: "runtime.warning",
26137
+ ...stamp(),
26138
+ provider: options.provider,
26139
+ threadId: options.threadId,
26140
+ ...shared.activeTurnId === void 0 ? {} : { turnId: shared.activeTurnId },
26141
+ payload: reasoningLevelFallbackWarning({
26142
+ model: applied.currentModelId,
26143
+ requestedEffort: aligned.unsupportedEffort,
26144
+ appliedEffort: aligned.appliedEffort
26145
+ })
26146
+ });
26147
+ }
26148
+ };
25879
26149
  const failIfPromptUnavailable = () => {
25880
26150
  failIfDisposed();
25881
26151
  if (shared.connectionClosed) throw new AcpExecutorDisposedError();
@@ -25883,7 +26153,7 @@ function createExecutorPrompt({
25883
26153
  const prompt = async (input2) => {
25884
26154
  failIfPromptUnavailable();
25885
26155
  const started = requireStarted();
25886
- let sessionId = started.sessionId;
26156
+ const sessionId = started.sessionId;
25887
26157
  let record2;
25888
26158
  const settle2 = (rest) => settleTurn({
25889
26159
  expectedGeneration: started.generation,
@@ -25970,32 +26240,34 @@ function createExecutorPrompt({
25970
26240
  failIfDisposed();
25971
26241
  const queuedTurnId = turnId;
25972
26242
  const isStale = () => interruptedTurnIds.has(queuedTurnId) || input2.expectedActiveTurnId !== void 0 && shared.activeTurnId !== queuedTurnId;
25973
- if (!isStale()) {
26243
+ if (!isStale() && input2.expectedActiveTurnId === void 0) {
26244
+ const optionWrites = new AbortController();
26245
+ shared.optionWriteStop = { turnId, stop: () => optionWrites.abort() };
25974
26246
  try {
25975
- const applied = await applyRequestedModel({
25976
- state: shared.modelSelectionState,
25977
- acpSessionId: sessionId,
25978
- setup: shared.startResult?.sessionSetupResult ?? {},
25979
- requestedModelId: input2.requestedModelId,
25980
- expectedGeneration: started.generation
25981
- });
25982
- shared.modelSelectionState = applied.state;
25983
- sessionId = applied.sessionId;
25984
- record2.sessionId = applied.sessionId;
26247
+ await alignTurnOptions(
26248
+ input2,
26249
+ sessionId,
26250
+ started.generation,
26251
+ isStale,
26252
+ optionWrites.signal
26253
+ );
25985
26254
  } catch (error62) {
25986
- const failureCategory = readAcpFailureCategory(error62);
25987
- if (failureCategory === "model-unavailable") {
25988
- const errorMessage = error62 instanceof Error && error62.message.trim().length > 0 ? error62.message : "Requested model is not in this agent's catalog. This turn was not sent.";
25989
- settle2({
25990
- turnId,
25991
- stopReason: "error",
25992
- state: "failed",
25993
- errorMessage,
25994
- failureCategory
25995
- });
25996
- throw error62 instanceof Error ? withFailureCategory(error62, failureCategory) : error62;
26255
+ if (error62 instanceof AcpExecutorDisposedError) throw error62;
26256
+ if (isStale()) {
26257
+ settle2({ turnId, stopReason: "cancelled", state: "cancelled" });
26258
+ return { threadId: options.threadId, turnId, stopReason: "cancelled" };
25997
26259
  }
25998
- throw error62;
26260
+ const failureCategory = readAcpFailureCategory(error62);
26261
+ settle2({
26262
+ turnId,
26263
+ stopReason: "error",
26264
+ state: "failed",
26265
+ errorMessage: error62 instanceof Error && error62.message.trim() || "Switching the model or reasoning level failed. This turn was not sent.",
26266
+ ...failureCategory === void 0 ? {} : { failureCategory }
26267
+ });
26268
+ throw error62 instanceof Error ? withFailureCategory(error62, failureCategory) : error62;
26269
+ } finally {
26270
+ shared.optionWriteStop = void 0;
25999
26271
  }
26000
26272
  }
26001
26273
  failIfDisposed();
@@ -26378,7 +26650,7 @@ function createExecutorRequests({
26378
26650
  pendingUserInputs.delete(requestId);
26379
26651
  pending.resolve({
26380
26652
  kind: "answered",
26381
- answers: isRecord(answers) ? answers : {}
26653
+ answers: isRecord2(answers) ? answers : {}
26382
26654
  });
26383
26655
  };
26384
26656
  return {
@@ -26553,129 +26825,6 @@ function createExecutorRuntime({
26553
26825
  };
26554
26826
  }
26555
26827
 
26556
- // ../../packages/ycodium-acp-executor/src/config-options.ts
26557
- function isRecord4(value) {
26558
- return typeof value === "object" && value !== null && !Array.isArray(value);
26559
- }
26560
- function asString(value) {
26561
- return typeof value === "string" ? value : void 0;
26562
- }
26563
- function normalizedField(option, key) {
26564
- return asString(option[key])?.trim().toLowerCase() ?? "";
26565
- }
26566
- function looksLikeEffortOption(option) {
26567
- const id = normalizedField(option, "id");
26568
- const name = normalizedField(option, "name");
26569
- return id === "effort" || id === "reasoning" || name === "effort" || name === "reasoning" || name.includes("effort") || name.includes("reasoning") || normalizedField(option, "category") === "thought_level";
26570
- }
26571
- function flattenChoices(rawOptions, currentValue) {
26572
- if (!Array.isArray(rawOptions)) return [];
26573
- const out = [];
26574
- const seen = /* @__PURE__ */ new Set();
26575
- const push = (entry) => {
26576
- if (!isRecord4(entry)) return;
26577
- const value = asString(entry["value"]);
26578
- if (value === void 0 || seen.has(value)) return;
26579
- seen.add(value);
26580
- const description = asString(entry["description"])?.trim();
26581
- const name = asString(entry["name"])?.trim();
26582
- out.push({
26583
- value,
26584
- ...name ? { name } : {},
26585
- label: name || value,
26586
- ...description ? { description } : {},
26587
- ...currentValue !== void 0 && currentValue === value ? { isDefault: true } : {}
26588
- });
26589
- };
26590
- for (const entry of rawOptions) {
26591
- if (isRecord4(entry) && Array.isArray(entry["options"])) {
26592
- for (const nested of entry["options"]) push(nested);
26593
- continue;
26594
- }
26595
- push(entry);
26596
- }
26597
- return out;
26598
- }
26599
- function findAcpEffortConfig(configOptions) {
26600
- if (!Array.isArray(configOptions)) return void 0;
26601
- const candidates = configOptions.filter(isRecord4).filter((option) => normalizedField(option, "type") === "select").filter(looksLikeEffortOption);
26602
- if (candidates.length === 0) return void 0;
26603
- const picked = candidates.find((option) => normalizedField(option, "category") === "model_option") ?? candidates.find((option) => normalizedField(option, "id") === "effort") ?? candidates.find((option) => normalizedField(option, "category") === "thought_level") ?? candidates[0];
26604
- if (picked === void 0) return void 0;
26605
- const configId = asString(picked["id"])?.trim();
26606
- if (!configId) return void 0;
26607
- const choices = flattenChoices(picked["options"], asString(picked["currentValue"])?.trim());
26608
- if (choices.length === 0) return void 0;
26609
- return {
26610
- configId,
26611
- label: asString(picked["name"])?.trim() ?? "",
26612
- choices
26613
- };
26614
- }
26615
- function acpModelChoicesFromConfigOptions(configOptions) {
26616
- if (!Array.isArray(configOptions)) return void 0;
26617
- const records = configOptions.filter(isRecord4);
26618
- const modelOption = records.find((option) => normalizedField(option, "category") === "model") ?? records.find(
26619
- (option) => normalizedField(option, "id") === "model" && normalizedField(option, "type") === "select"
26620
- );
26621
- if (modelOption === void 0) return void 0;
26622
- if (!asString(modelOption["id"])?.trim()) return void 0;
26623
- return flattenChoices(modelOption["options"], asString(modelOption["currentValue"])?.trim());
26624
- }
26625
- function acpModelChoicesFromSessionModels(models) {
26626
- if (!isRecord4(models) || !Array.isArray(models["availableModels"])) return void 0;
26627
- const currentModelId = asString(models["currentModelId"])?.trim();
26628
- const out = [];
26629
- const seen = /* @__PURE__ */ new Set();
26630
- for (const entry of models["availableModels"]) {
26631
- if (!isRecord4(entry)) continue;
26632
- const value = asString(entry["modelId"])?.trim();
26633
- if (!value || seen.has(value)) continue;
26634
- seen.add(value);
26635
- const name = asString(entry["name"])?.trim();
26636
- const description = asString(entry["description"])?.trim();
26637
- out.push({
26638
- value,
26639
- ...name ? { name } : {},
26640
- label: name || value,
26641
- ...description ? { description } : {},
26642
- ...currentModelId !== void 0 && currentModelId === value ? { isDefault: true } : {}
26643
- });
26644
- }
26645
- return out;
26646
- }
26647
-
26648
- // ../../packages/ycodium-acp-executor/src/apply-effort.ts
26649
- var applyRequestedEffort = async (input2) => {
26650
- const requested = input2.requestedEffort?.trim();
26651
- if (!requested) return;
26652
- const effort = findAcpEffortConfig(input2.configOptions);
26653
- if (effort === void 0) return;
26654
- const matched = effort.choices.find((choice) => choice.value === requested);
26655
- if (matched === void 0) {
26656
- input2.log?.info("requested effort is not in the agent catalog; keeping its own", {
26657
- requestedEffort: requested,
26658
- advertised: effort.choices.map((choice) => choice.value)
26659
- });
26660
- return;
26661
- }
26662
- if (matched.isDefault === true) return;
26663
- if (!input2.isLive(input2.expectedGeneration)) return;
26664
- try {
26665
- await input2.connection.request("session/set_config_option", {
26666
- sessionId: input2.acpSessionId,
26667
- configId: effort.configId,
26668
- value: requested
26669
- });
26670
- } catch (error62) {
26671
- input2.log?.info("setting the effort level failed; the session keeps its own", {
26672
- requestedEffort: requested,
26673
- configId: effort.configId,
26674
- error: error62 instanceof Error ? error62.message : String(error62)
26675
- });
26676
- }
26677
- };
26678
-
26679
26828
  // ../../packages/ycodium-acp-executor/src/config-option-wiring.ts
26680
26829
  var VENDOR_CATEGORY_PREFIX = "_";
26681
26830
  var ACP_CONFIG_CATEGORY_HANDLING = {
@@ -26689,7 +26838,7 @@ var ACP_CONFIG_CATEGORY_HANDLING = {
26689
26838
  },
26690
26839
  thought_level: {
26691
26840
  consumed: true,
26692
- via: "config-options.ts:findAcpEffortConfig \u2192 apply-effort.ts:applyRequestedEffort"
26841
+ via: "config-options.ts:findAcpEffortConfig \u2192 apply-effort.ts:alignRequestedEffort"
26693
26842
  },
26694
26843
  model_option: {
26695
26844
  consumed: true,
@@ -26758,13 +26907,14 @@ function judgeRequestedModel(input2) {
26758
26907
  if (requested === void 0 || requested === current) return { kind: "keep" };
26759
26908
  const hasCatalog = input2.state.advertisedModelValues.length > 0;
26760
26909
  const hasCurrent = current !== void 0;
26761
- if (!hasCatalog && !hasCurrent) return { kind: "keep" };
26762
- const canSwitch = input2.state.strategy === "session/set_model" && input2.state.sessionModelsAdvertised || input2.state.strategy === "config-option" && input2.state.modelConfigId !== void 0;
26910
+ if (!hasCatalog && !hasCurrent && input2.state.modelUnconfirmed !== true) return { kind: "keep" };
26911
+ const canSwitch = canSwitchModel(input2.state);
26763
26912
  const value = hasCatalog ? matchAdvertisedModelValue(requested, input2.state.advertisedModelValues) : void 0;
26764
26913
  if (value !== void 0 && value === current) return { kind: "keep" };
26765
26914
  if (value !== void 0 && canSwitch) return { kind: "switch", value };
26766
- return input2.refreshed ? { kind: "unavailable" } : { kind: "refresh" };
26915
+ return { kind: "refresh" };
26767
26916
  }
26917
+ var canSwitchModel = (state) => state.strategy === "session/set_model" && state.sessionModelsAdvertised || state.strategy === "config-option" && state.modelConfigId !== void 0;
26768
26918
  function modelUnavailableError(requestedModelId, currentModelId) {
26769
26919
  const current = currentModelId ?? "its own model";
26770
26920
  return withFailureCategory(
@@ -26874,6 +27024,7 @@ function acpCurrentModeId(setup) {
26874
27024
  // ../../packages/ycodium-acp-executor/src/executor/session.ts
26875
27025
  function createExecutorSession({
26876
27026
  options,
27027
+ hooks,
26877
27028
  connection,
26878
27029
  isLive,
26879
27030
  emit,
@@ -26895,131 +27046,140 @@ function createExecutorSession({
26895
27046
  shared.sessionOpensInFlight -= 1;
26896
27047
  }
26897
27048
  };
26898
- const openFreshSession = async (expectedGeneration) => {
26899
- const initialized = shared.initializeResult;
26900
- if (initialized === void 0) {
26901
- throw new Error("no handshake");
27049
+ const optionDeadlineMs = () => options.modelCatalogRefreshTimeoutMs ?? MODEL_CATALOG_REFRESH_TIMEOUT_MS;
27050
+ const within = async (work, signal, onTimeout) => {
27051
+ void work.catch(() => void 0);
27052
+ let timer;
27053
+ let onStop;
27054
+ const bound = new Promise((_resolve, reject) => {
27055
+ timer = setTimeout(() => reject(onTimeout()), optionDeadlineMs());
27056
+ onStop = () => reject(new AcpOptionWriteStoppedError());
27057
+ if (signal?.aborted === true) onStop();
27058
+ else signal?.addEventListener("abort", onStop, { once: true });
27059
+ });
27060
+ try {
27061
+ return await Promise.race([work, bound]);
27062
+ } finally {
27063
+ clearTimeout(timer);
27064
+ if (onStop !== void 0) signal?.removeEventListener("abort", onStop);
26902
27065
  }
26903
- const mcpServers = filterMcpServersByAgentCapabilities(
26904
- options.mcpServers ?? [],
26905
- initialized.agentCapabilities
27066
+ };
27067
+ const awaitOptionReply = async (pending, configId, write) => {
27068
+ void pending.response.catch(() => void 0);
27069
+ try {
27070
+ return await within(
27071
+ pending.written.then(() => pending.response),
27072
+ write.signal,
27073
+ () => new AcpExecutorOptionTimeoutError(write.option, write.value)
27074
+ );
27075
+ } catch (error62) {
27076
+ if (error62 instanceof AcpExecutorOptionTimeoutError || error62 instanceof AcpOptionWriteStoppedError) {
27077
+ shared.modelSelectionState = forgetConfigOptionValue(shared.modelSelectionState, configId);
27078
+ }
27079
+ throw error62;
27080
+ }
27081
+ };
27082
+ const writeConfigOptionReported = async (sessionId, configOptions, configId, value, write) => {
27083
+ const issuedAt = shared.configUpdateSeq;
27084
+ let arrivedAt = Number.POSITIVE_INFINITY;
27085
+ const pending = connection.begin(
27086
+ "session/set_config_option",
27087
+ { sessionId, configId, value },
27088
+ void 0,
27089
+ () => {
27090
+ arrivedAt = shared.configUpdateSeq;
27091
+ }
26906
27092
  );
26907
- const additionalDirectories = options.additionalDirectories !== void 0 && options.additionalDirectories.length > 0 ? { additionalDirectories: options.additionalDirectories } : {};
26908
- const created = await requestSession("session/new", {
26909
- cwd: options.cwd,
26910
- mcpServers,
26911
- ...additionalDirectories
26912
- });
26913
- if (!isLive(expectedGeneration)) {
26914
- throw new AcpExecutorDisposedError();
27093
+ const reply = await awaitOptionReply(pending, configId, { ...write, value });
27094
+ await connection.awaitInboundIdle();
27095
+ const ours = shared.configOptionUpdates.get(sessionId);
27096
+ if (ours !== void 0 && ours.seq > arrivedAt) {
27097
+ return { configOptions: ours.configOptions, reported: true };
26915
27098
  }
26916
- if (created.sessionId === void 0 || created.sessionId.length === 0) {
26917
- throw new Error("session/new did not return a session id");
27099
+ if (reply?.configOptions !== void 0) {
27100
+ return { configOptions: reply.configOptions, reported: true };
26918
27101
  }
26919
- return { sessionId: created.sessionId, setup: created };
27102
+ const base = ours !== void 0 && ours.seq > issuedAt ? ours.configOptions : configOptions;
27103
+ return { configOptions: withConfigOptionValue(base, configId, value), reported: false };
26920
27104
  };
27105
+ const writeConfigOption = async (...args) => (await writeConfigOptionReported(...args)).configOptions;
26921
27106
  const switchModel = async (input2) => {
26922
27107
  let configOptions = input2.state.configOptions;
26923
- if (input2.state.strategy === "config-option") {
26924
- const switched = await connection.request(
26925
- "session/set_config_option",
26926
- { sessionId: input2.sessionId, configId: input2.state.modelConfigId, value: input2.value }
27108
+ const write = { option: "model", signal: input2.signal };
27109
+ if (input2.state.strategy === "config-option" && input2.state.modelConfigId !== void 0) {
27110
+ configOptions = await writeConfigOption(
27111
+ input2.sessionId,
27112
+ configOptions,
27113
+ input2.state.modelConfigId,
27114
+ input2.value,
27115
+ write
26927
27116
  );
26928
- configOptions = switched?.configOptions ?? configOptions;
26929
27117
  } else {
26930
- await connection.request("session/set_model", {
27118
+ const before = shared.configOptionUpdates.get(input2.sessionId);
27119
+ const pending = connection.begin("session/set_model", {
26931
27120
  sessionId: input2.sessionId,
26932
27121
  modelId: input2.value
26933
27122
  });
27123
+ await awaitOptionReply(pending, void 0, { ...write, value: input2.value });
27124
+ await connection.awaitInboundIdle();
27125
+ const reported = shared.configOptionUpdates.get(input2.sessionId);
27126
+ if (reported !== void 0 && reported !== before) {
27127
+ configOptions = reported.configOptions;
27128
+ }
26934
27129
  }
26935
27130
  if (!isLive(input2.expectedGeneration)) {
26936
27131
  throw new AcpExecutorDisposedError();
26937
27132
  }
26938
- return { ...input2.state, currentModelId: input2.value, configOptions };
26939
- };
26940
- const adoptReopenedSession = (applied) => {
26941
- if (shared.sessionId === void 0 && shared.startResult === void 0) return;
26942
- const setup = applied.setup;
26943
- shared.sessionId = applied.sessionId;
26944
- shared.modelSelectionState = applied.state;
26945
- shared.modeState = parseSessionModeState(setup);
26946
- if (shared.startResult !== void 0) {
26947
- shared.startResult = {
26948
- ...shared.startResult,
26949
- sessionId: applied.sessionId,
26950
- sessionSetupResult: setup,
26951
- modelConfigId: extractModelConfigId(setup),
26952
- modelId: applied.state.currentModelId
26953
- };
26954
- }
27133
+ const { modelUnconfirmed: _confirmed, ...known } = input2.state;
27134
+ return adoptReportedConfigOptions({ ...known, currentModelId: input2.value }, configOptions);
26955
27135
  };
26956
27136
  const applyRequestedModel = async (input2) => {
26957
- async function applyOnce(state, sessionId, setup, refreshed) {
26958
- const requestedModelId = normalizeModelId(input2.requestedModelId) ?? "";
27137
+ const requestedModelId = normalizeModelId(input2.requestedModelId) ?? "";
27138
+ const switchTo = (value) => switchModel({
27139
+ state: input2.state,
27140
+ sessionId: input2.acpSessionId,
27141
+ value,
27142
+ expectedGeneration: input2.expectedGeneration,
27143
+ signal: input2.signal
27144
+ });
27145
+ try {
26959
27146
  const judgment = judgeRequestedModel({
26960
- state,
26961
- requestedModelId: input2.requestedModelId,
26962
- refreshed
27147
+ state: input2.state,
27148
+ requestedModelId: input2.requestedModelId
26963
27149
  });
26964
- if (judgment.kind === "keep") return { state, sessionId, setup };
26965
- if (judgment.kind === "unavailable") {
26966
- throw modelUnavailableError(requestedModelId, state.currentModelId);
26967
- }
26968
- if (judgment.kind === "switch") {
26969
- return {
26970
- state: await switchModel({
26971
- state,
26972
- sessionId,
26973
- value: judgment.value,
26974
- expectedGeneration: input2.expectedGeneration
26975
- }),
26976
- sessionId,
26977
- setup
26978
- };
26979
- }
26980
- return refreshAndRejudge(requestedModelId);
26981
- }
26982
- async function refreshAndRejudge(requestedModelId) {
26983
- const timeoutMs = options.modelCatalogRefreshTimeoutMs ?? MODEL_CATALOG_REFRESH_TIMEOUT_MS;
26984
- let timedOut = false;
26985
- const timeoutError = new ModelCatalogRefreshTimeoutError();
26986
- let timer;
26987
- const work = (async () => {
26988
- await options.refreshCatalogForSend?.();
26989
- if (timedOut) throw timeoutError;
26990
- const reopened = await openFreshSession(input2.expectedGeneration);
26991
- if (timedOut) throw timeoutError;
26992
- const next = modelSelectionStateFromSetup(reopened.setup);
26993
- const applied = await applyOnce(next, reopened.sessionId, reopened.setup, true);
26994
- if (timedOut) throw timeoutError;
26995
- adoptReopenedSession(applied);
26996
- return applied;
26997
- })();
26998
- void work.then(
26999
- () => void 0,
27000
- () => void 0
27150
+ if (judgment.kind === "keep") return input2.state;
27151
+ if (judgment.kind === "switch") return await switchTo(judgment.value);
27152
+ await refreshCatalog(requestedModelId, input2.signal);
27153
+ if (!isLive(input2.expectedGeneration)) throw new AcpExecutorDisposedError();
27154
+ if (!canSwitchModel(input2.state)) {
27155
+ throw modelUnavailableError(requestedModelId, input2.state.currentModelId);
27156
+ }
27157
+ const switched = await switchTo(requestedModelId);
27158
+ return switched.advertisedModelValues.includes(requestedModelId) ? switched : {
27159
+ ...switched,
27160
+ advertisedModelValues: [...switched.advertisedModelValues, requestedModelId]
27161
+ };
27162
+ } catch (error62) {
27163
+ throw error62 instanceof RequestError ? withFailureCategory(
27164
+ new AcpExecutorOptionRejectedError("model", requestedModelId, error62),
27165
+ "model-unavailable"
27166
+ ) : error62;
27167
+ }
27168
+ };
27169
+ const refreshCatalog = async (requestedModelId, signal) => {
27170
+ try {
27171
+ await within(
27172
+ Promise.resolve(options.refreshCatalogForSend?.()),
27173
+ signal,
27174
+ () => new ModelCatalogRefreshTimeoutError()
27001
27175
  );
27002
- const deadline = new Promise((_resolve, reject) => {
27003
- timer = setTimeout(() => {
27004
- timedOut = true;
27005
- connection.abandonPending(timeoutError);
27006
- reject(timeoutError);
27007
- }, timeoutMs);
27008
- });
27009
- try {
27010
- return await Promise.race([work, deadline]);
27011
- } catch (error62) {
27012
- if (error62 instanceof AcpExecutorDisposedError) throw error62;
27013
- if (timedOut || error62 instanceof ModelCatalogRefreshTimeoutError) {
27014
- throw modelRefreshTimedOutError(requestedModelId);
27015
- }
27016
- if (readAcpFailureCategory(error62) === "model-unavailable") throw error62;
27017
- throw modelRefreshFailedError(requestedModelId, error62);
27018
- } finally {
27019
- if (timer !== void 0) clearTimeout(timer);
27176
+ } catch (error62) {
27177
+ if (error62 instanceof AcpOptionWriteStoppedError) throw error62;
27178
+ if (error62 instanceof ModelCatalogRefreshTimeoutError) {
27179
+ throw modelRefreshTimedOutError(requestedModelId);
27020
27180
  }
27181
+ throw modelRefreshFailedError(requestedModelId, error62);
27021
27182
  }
27022
- return applyOnce(input2.state, input2.acpSessionId, input2.setup, false);
27023
27183
  };
27024
27184
  const startOnce = async (expectedGeneration) => {
27025
27185
  const initializePayload = acpInitializePayload(
@@ -27094,26 +27254,45 @@ function createExecutorSession({
27094
27254
  categories: unhandledCategories
27095
27255
  });
27096
27256
  }
27097
- const openedSetup = setup;
27098
- const appliedModel = await applyRequestedModel({
27099
- state: modelSelectionStateFromSetup(openedSetup),
27257
+ let nextModelSelectionState = await applyRequestedModel({
27258
+ state: modelSelectionStateFromSetup(setup),
27100
27259
  acpSessionId: nextSessionId,
27101
- setup: openedSetup,
27102
27260
  requestedModelId: options.requestedModelId,
27103
27261
  expectedGeneration
27104
27262
  });
27105
- nextSessionId = appliedModel.sessionId;
27106
- setup = appliedModel.setup;
27107
- const nextModelSelectionState = appliedModel.state;
27108
- await applyRequestedEffort({
27109
- connection,
27110
- log: options.log,
27111
- isLive,
27112
- configOptions: nextModelSelectionState.configOptions,
27113
- acpSessionId: nextSessionId,
27114
- requestedEffort: options.requestedEffort,
27115
- expectedGeneration
27116
- });
27263
+ if (!isLive(expectedGeneration)) {
27264
+ throw new AcpExecutorDisposedError();
27265
+ }
27266
+ try {
27267
+ const opened = nextModelSelectionState.configOptions;
27268
+ const aligned = await alignRequestedEffort({
27269
+ configOptions: opened,
27270
+ write: (configId, value) => writeConfigOptionReported(nextSessionId, opened, configId, value, {
27271
+ option: "reasoning level"
27272
+ }),
27273
+ requestedEffort: options.requestedEffort,
27274
+ modelDefaultEffort: modelDefaultEffort(nextModelSelectionState)
27275
+ });
27276
+ nextModelSelectionState = adoptReportedConfigOptions(
27277
+ nextModelSelectionState,
27278
+ aligned.configOptions
27279
+ );
27280
+ if (aligned.unsupportedEffort !== void 0) {
27281
+ options.log?.info("requested effort is not offered by this model; using its default", {
27282
+ requestedEffort: aligned.unsupportedEffort,
27283
+ modelId: nextModelSelectionState.currentModelId
27284
+ });
27285
+ }
27286
+ } catch (error62) {
27287
+ const effortConfigId = findAcpEffortConfig(nextModelSelectionState.configOptions)?.configId;
27288
+ if (error62 instanceof AcpExecutorOptionTimeoutError && effortConfigId !== void 0) {
27289
+ nextModelSelectionState = forgetConfigOptionValue(nextModelSelectionState, effortConfigId);
27290
+ }
27291
+ options.log?.info("setting the effort level failed; the session keeps its own", {
27292
+ requestedEffort: options.requestedEffort,
27293
+ error: error62 instanceof Error ? error62.message : String(error62)
27294
+ });
27295
+ }
27117
27296
  if (options.beforeApplyResult) {
27118
27297
  await options.beforeApplyResult();
27119
27298
  }
@@ -27173,6 +27352,7 @@ function createExecutorSession({
27173
27352
  );
27174
27353
  return shared.startInFlight;
27175
27354
  };
27355
+ const modelDefaultEffort = (state) => state.currentModelId === void 0 ? void 0 : hooks.modelDefaultEffort?.({ setup: state.catalogSetup, modelId: state.currentModelId });
27176
27356
  const requireStarted = () => {
27177
27357
  failIfDisposed();
27178
27358
  if (!shared.sessionId || !shared.startResult) {
@@ -27200,7 +27380,14 @@ function createExecutorSession({
27200
27380
  modeId
27201
27381
  });
27202
27382
  };
27203
- return { applyRequestedModel, start, requireStarted, setNativeMode };
27383
+ return {
27384
+ applyRequestedModel,
27385
+ modelDefaultEffort,
27386
+ writeConfigOptionReported,
27387
+ start,
27388
+ requireStarted,
27389
+ setNativeMode
27390
+ };
27204
27391
  }
27205
27392
 
27206
27393
  // ../../packages/ycodium-acp-executor/src/executor/settlement.ts
@@ -27264,14 +27451,14 @@ function createExecutorSettlement({
27264
27451
 
27265
27452
  // ../../packages/ycodium-acp-executor/src/executor/subagent-sessions.ts
27266
27453
  function parseState(raw) {
27267
- if (!isRecord(raw)) return { status: void 0, error: void 0 };
27454
+ if (!isRecord2(raw)) return { status: void 0, error: void 0 };
27268
27455
  const state = raw["state"];
27269
27456
  if (state === "running") return { status: "running", error: void 0 };
27270
27457
  if (state === "requires_action") return { status: "waiting", error: void 0 };
27271
27458
  if (state !== "idle") return { status: void 0, error: void 0 };
27272
27459
  const stopReason = raw["stopReason"];
27273
- const error62 = isRecord(raw["error"]) ? asTrimmedString(raw["error"]["message"]) : void 0;
27274
- if (stopReason === "error" || isRecord(raw["error"])) return { status: "failed", error: error62 };
27460
+ const error62 = isRecord2(raw["error"]) ? asTrimmedString(raw["error"]["message"]) : void 0;
27461
+ if (stopReason === "error" || isRecord2(raw["error"])) return { status: "failed", error: error62 };
27275
27462
  if (stopReason === "cancelled") return { status: "cancelled", error: void 0 };
27276
27463
  return { status: "idle", error: void 0 };
27277
27464
  }
@@ -27287,7 +27474,7 @@ function childLinkage(childId, record2) {
27287
27474
  function createSubagentSessionTracker(registry2) {
27288
27475
  const observe = (notification, ctx) => {
27289
27476
  const update = notification.update;
27290
- if (!isRecord(update) || update["sessionUpdate"] !== "subagent_update") return [];
27477
+ if (!isRecord2(update) || update["sessionUpdate"] !== "subagent_update") return [];
27291
27478
  const childId = asTrimmedString(update["sessionId"]);
27292
27479
  if (childId === void 0 || ctx.ownSessionIds.has(childId)) return [];
27293
27480
  const outerId = notification.sessionId;
@@ -27513,6 +27700,21 @@ function createExecutorUpdates({
27513
27700
  markChildSession
27514
27701
  });
27515
27702
  const handleSessionUpdate = (params) => {
27703
+ const update = params.update;
27704
+ const reportedOptions = update["configOptions"];
27705
+ if (update["sessionUpdate"] === "config_option_update" && Array.isArray(reportedOptions)) {
27706
+ shared.configUpdateSeq += 1;
27707
+ shared.configOptionUpdates.set(params.sessionId, {
27708
+ configOptions: reportedOptions,
27709
+ seq: shared.configUpdateSeq
27710
+ });
27711
+ if (params.sessionId === shared.sessionId) {
27712
+ shared.modelSelectionState = adoptReportedConfigOptions(
27713
+ shared.modelSelectionState,
27714
+ reportedOptions
27715
+ );
27716
+ }
27717
+ }
27516
27718
  const parsed = parseSessionUpdateEvent(params);
27517
27719
  if (parsed.modeId && shared.modeState) {
27518
27720
  shared.modeState = {
@@ -27828,7 +28030,10 @@ function createAcpExecutor(options) {
27828
28030
  droppedReplayUpdates: 0,
27829
28031
  ownSessionIds: /* @__PURE__ */ new Set(),
27830
28032
  childSessions: createChildSessionRegistry(),
27831
- sessionOpensInFlight: 0
28033
+ sessionOpensInFlight: 0,
28034
+ configOptionUpdates: /* @__PURE__ */ new Map(),
28035
+ optionWriteStop: void 0,
28036
+ configUpdateSeq: 0
27832
28037
  };
27833
28038
  const interruptedTurnIds = /* @__PURE__ */ new Set();
27834
28039
  const approvals = createApprovalGate({
@@ -27977,8 +28182,16 @@ function createAcpExecutor(options) {
27977
28182
  };
27978
28183
  options.readable.once("end", onInputDead);
27979
28184
  options.readable.once("error", onInputDead);
27980
- const { applyRequestedModel, start, requireStarted, setNativeMode } = createExecutorSession({
28185
+ const {
28186
+ applyRequestedModel,
28187
+ modelDefaultEffort,
28188
+ writeConfigOptionReported,
28189
+ start,
28190
+ requireStarted,
28191
+ setNativeMode
28192
+ } = createExecutorSession({
27981
28193
  options,
28194
+ hooks,
27982
28195
  connection,
27983
28196
  isLive,
27984
28197
  emit,
@@ -28004,6 +28217,8 @@ function createAcpExecutor(options) {
28004
28217
  threadMutex,
28005
28218
  promptMutex,
28006
28219
  applyRequestedModel,
28220
+ modelDefaultEffort,
28221
+ writeConfigOptionReported,
28007
28222
  notifyPromptSettled,
28008
28223
  shared
28009
28224
  });
@@ -28293,9 +28508,9 @@ async function openAcpProbeHandshake(input2) {
28293
28508
  }
28294
28509
  }
28295
28510
  function acpAgentVersion(initializeResult) {
28296
- if (!isRecord(initializeResult)) return null;
28511
+ if (!isRecord2(initializeResult)) return null;
28297
28512
  const agentInfo = initializeResult["agentInfo"];
28298
- return isRecord(agentInfo) ? asTrimmedString(agentInfo["version"]) ?? null : null;
28513
+ return isRecord2(agentInfo) ? asTrimmedString(agentInfo["version"]) ?? null : null;
28299
28514
  }
28300
28515
  var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
28301
28516
 
@@ -28325,9 +28540,10 @@ var ACP_CARD = {
28325
28540
  verifiedSkills: false,
28326
28541
  everydayHarness: false,
28327
28542
  capabilities: {
28328
- sessionModelSwitch: "unsupported",
28329
- // 力度档只在建会话时经 `session/set_config_option` 发一次:中途换档,宿主带 resume cursor 重开。
28330
- sessionOptionSwitch: "unsupported",
28543
+ // 执行器发送前按 agent 宣告的通道在会话里切(`session/set_model` 或 `session/set_config_option`),
28544
+ // 不重开会话。agent 没宣告型号或档位时请求的值一样到不了它,重开也不会让它生效,只会关掉子 agent。
28545
+ sessionModelSwitch: "in-session",
28546
+ sessionOptionSwitch: "in-session",
28331
28547
  // **这一位仍是空头支票,切档走的是下面那位。** `setRuntimeMode` 在这里只改自己的
28332
28548
  // 会话记录,从不发 RPC——宿主四档发不到 CLI 上。它没删是因为编排还在读它(哪些手
28333
28549
  // 要重开会话),但用户真正切得动的是 `nativeModeSwitch` 那条:这只手自报几档、
@@ -28549,6 +28765,11 @@ function acpProbeModels(setup) {
28549
28765
  ...choice.name === void 0 ? {} : { name: choice.name },
28550
28766
  ...choice.isDefault === true ? { isDefault: true } : {}
28551
28767
  }));
28768
+ const effortState = acpEffortConfigState(rawOptions);
28769
+ if (effortState === "unknown") return models;
28770
+ if (effortState === "none") {
28771
+ return models.map((model) => ({ ...model, capabilities: { optionDescriptors: [] } }));
28772
+ }
28552
28773
  const effort = findAcpEffortConfig(rawOptions);
28553
28774
  if (effort === void 0) return models;
28554
28775
  const capabilities = {
@@ -28979,10 +29200,15 @@ var createAcpInstance = (config2, host) => {
28979
29200
  signal?.addEventListener("abort", onAbort);
28980
29201
  try {
28981
29202
  const requestedModelId = modelIdFromSelection(input2.modelSelection);
29203
+ const requestedEffort = modelSelectionStringOption(
29204
+ input2.modelSelection,
29205
+ ACP_EFFORT_OPTION_ID
29206
+ );
28982
29207
  const turn = await dispatchAcpPrompt(booked.executor, {
28983
29208
  text: input2.input ?? "",
28984
29209
  expectedActiveTurnId: input2.expectedTurnId,
28985
- ...requestedModelId === void 0 ? {} : { requestedModelId }
29210
+ ...requestedModelId === void 0 ? {} : { requestedModelId },
29211
+ ...requestedEffort === void 0 ? {} : { requestedEffort }
28986
29212
  });
28987
29213
  booked.turns.push({ id: turn.turnId, items: [] });
28988
29214
  return {
@@ -29064,7 +29290,7 @@ var executors = [
29064
29290
  ];
29065
29291
  var index_default = definePlugin({
29066
29292
  id: "agent-acp",
29067
- apiVersion: 49,
29293
+ apiVersion: 50,
29068
29294
  executors,
29069
29295
  activate(ctx) {
29070
29296
  ctx.log.info("generic ACP executor ready");