@ycodium-ai/agent-kimi 0.2.5029 → 0.2.5093

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 +848 -524
  2. package/package.json +6 -4
package/dist/index.js CHANGED
@@ -8,10 +8,10 @@ var __export = (target, all) => {
8
8
  import { definePlugin } from "@ycodium-ai/plugin-api";
9
9
 
10
10
  // ../../packages/plugin-api/src/version.ts
11
- var PLUGIN_API_VERSION = 143;
11
+ var PLUGIN_API_VERSION = 147;
12
12
 
13
13
  // src/index.ts
14
- import * as NodeOS6 from "node:os";
14
+ import * as NodeOS7 from "node:os";
15
15
  import * as NodePath8 from "node:path";
16
16
  import {
17
17
  EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
@@ -19,6 +19,62 @@ import {
19
19
  readExecutorEffectiveRequest
20
20
  } from "@ycodium-ai/plugin-api/executor";
21
21
 
22
+ // ../../packages/ycodium-instance-config/src/homePath.ts
23
+ import * as NodeOS from "node:os";
24
+ import * as NodePath from "node:path";
25
+ import { mergeLaunchEnv } from "@ycodium-ai/plugin-api/executor";
26
+ function expandHomePath(value) {
27
+ if (value === "~") return NodeOS.homedir();
28
+ if (value.startsWith("~/") || value.startsWith("~\\")) {
29
+ return NodePath.join(NodeOS.homedir(), value.slice(2));
30
+ }
31
+ return value;
32
+ }
33
+ function homeLaunchEnv(recipe, configuredHomePath) {
34
+ const homePath = configuredHomePath.trim();
35
+ const homeEnvVar = recipe.homeEnvVar.trim();
36
+ const homeInjection = homePath.length > 0 && homeEnvVar.length > 0 ? { [homeEnvVar]: expandHomePath(homePath) } : {};
37
+ return mergeLaunchEnv({ accountHome: homeInjection, instanceTable: recipe.environment });
38
+ }
39
+ function homeContinuationKey(kind, recipe) {
40
+ const homePath = recipe.homePath.trim();
41
+ const resolvedHomePath = homePath.length > 0 ? NodePath.resolve(expandHomePath(homePath)) : "";
42
+ return `${kind}:home:${recipe.binaryPath.trim()}\0${resolvedHomePath}`;
43
+ }
44
+
45
+ // ../../packages/ycodium-instance-config/src/programHomeSchema.ts
46
+ function programAndHomeConfigSchema(binaryPath) {
47
+ const binaryForm = {
48
+ titleKey: "form.binaryPath.title",
49
+ descriptionKey: "form.binaryPath.description",
50
+ placeholderKey: "form.binaryPath.placeholder",
51
+ control: binaryPath.control
52
+ };
53
+ if (binaryPath.machineLocal === true) binaryForm["machineLocal"] = true;
54
+ return {
55
+ type: "object",
56
+ "x-ycodium-form-order": ["binaryPath", "homePath"],
57
+ properties: {
58
+ binaryPath: { type: "string", "x-ycodium-form": binaryForm },
59
+ homePath: {
60
+ type: "string",
61
+ "x-ycodium-form": {
62
+ titleKey: "form.homePath.title",
63
+ machineLocal: true,
64
+ descriptionKey: "form.homePath.description",
65
+ placeholderKey: "form.homePath.placeholder"
66
+ }
67
+ },
68
+ enabled: { type: "boolean" },
69
+ customModels: { type: "array" },
70
+ driver: { type: "string" },
71
+ config: { type: "object" },
72
+ environment: { type: "array" }
73
+ },
74
+ additionalProperties: true
75
+ };
76
+ }
77
+
22
78
  // src/card.ts
23
79
  var KIMI_DRIVER_KIND = "kimiCode";
24
80
  var KIMI_CARD = {
@@ -72,38 +128,7 @@ var KIMI_CARD = {
72
128
  },
73
129
  credentialSources: [],
74
130
  diagnostics: [],
75
- // 设置表单照这份画:带 x-ycodium-form 的属性才进表单(enabled、customModels 等另有入口,不在此列),
76
- // 顺序看 x-ycodium-form-order;文案键在本插件 locales/<locale>.json 里解析,宿主不兜底。
77
- configSchema: {
78
- type: "object",
79
- "x-ycodium-form-order": ["binaryPath", "homePath"],
80
- properties: {
81
- binaryPath: {
82
- type: "string",
83
- "x-ycodium-form": {
84
- titleKey: "form.binaryPath.title",
85
- descriptionKey: "form.binaryPath.description",
86
- placeholderKey: "form.binaryPath.placeholder",
87
- control: "executable-path"
88
- }
89
- },
90
- homePath: {
91
- type: "string",
92
- "x-ycodium-form": {
93
- titleKey: "form.homePath.title",
94
- machineLocal: true,
95
- descriptionKey: "form.homePath.description",
96
- placeholderKey: "form.homePath.placeholder"
97
- }
98
- },
99
- enabled: { type: "boolean" },
100
- customModels: { type: "array" },
101
- driver: { type: "string" },
102
- config: { type: "object" },
103
- environment: { type: "array" }
104
- },
105
- additionalProperties: true
106
- },
131
+ configSchema: programAndHomeConfigSchema({ control: "executable-path" }),
107
132
  modelConnectivity: {
108
133
  dialects: [],
109
134
  acceptsExternalEndpoints: false
@@ -111,14 +136,7 @@ var KIMI_CARD = {
111
136
  };
112
137
 
113
138
  // src/kimiInstance.ts
114
- import * as NodeOS5 from "node:os";
115
- import * as NodePath7 from "node:path";
116
- import {
117
- mergeLaunchEnv,
118
- modelSelectionStringOption,
119
- raceAbort
120
- } from "@ycodium-ai/plugin-api/executor";
121
- import { nodeStreamsFromHandle } from "@ycodium-ai/plugin-api/process-stdin";
139
+ import { raceAbort as raceAbort2 } from "@ycodium-ai/plugin-api/executor";
122
140
 
123
141
  // ../../packages/ycodium-acp-executor/src/executor.ts
124
142
  import * as NodeCrypto from "node:crypto";
@@ -180,6 +198,24 @@ function approvalOutcomeForDecision(decision, optionId) {
180
198
  return decision !== "cancel" && optionId !== void 0 ? { outcome: "selected", optionId } : { outcome: "cancelled" };
181
199
  }
182
200
 
201
+ // ../../packages/ycodium-executor-common/src/stderrTail.ts
202
+ var REDACTION_MARKERS = ["[redacted]", "[pairing-url]"];
203
+ function lastStderrTail(text, maxChars) {
204
+ if (text.length <= maxChars) return text;
205
+ let start = text.length - maxChars;
206
+ if (text[start - 1] !== "\n") {
207
+ const lineEnd = text.indexOf("\n", start);
208
+ if (lineEnd !== -1 && lineEnd < text.length - 1) return text.slice(lineEnd + 1);
209
+ const code = text.charCodeAt(start);
210
+ if (code >= 56320 && code <= 57343) start += 1;
211
+ for (const marker of REDACTION_MARKERS) {
212
+ const at = text.lastIndexOf(marker, start);
213
+ if (at !== -1 && at < start && start < at + marker.length) start = at + marker.length;
214
+ }
215
+ }
216
+ return text.slice(start);
217
+ }
218
+
183
219
  // ../../packages/ycodium-acp-executor/src/errors.ts
184
220
  var AcpExecutorError = class extends Error {
185
221
  code;
@@ -284,22 +320,6 @@ var AcpAgentExitedError = class extends AcpConnectionClosedError {
284
320
  this.exitCode = exitCode;
285
321
  }
286
322
  };
287
- var REDACTION_MARKERS = ["[redacted]", "[pairing-url]"];
288
- var lastLines = (text, maxChars) => {
289
- if (text.length <= maxChars) return text;
290
- let start = text.length - maxChars;
291
- if (text[start - 1] !== "\n") {
292
- const lineEnd = text.indexOf("\n", start);
293
- if (lineEnd !== -1 && lineEnd < text.length - 1) return text.slice(lineEnd + 1);
294
- const code = text.charCodeAt(start);
295
- if (code >= 56320 && code <= 57343) start += 1;
296
- for (const marker of REDACTION_MARKERS) {
297
- const at = text.lastIndexOf(marker, start);
298
- if (at !== -1 && at < start && start < at + marker.length) start = at + marker.length;
299
- }
300
- }
301
- return text.slice(start);
302
- };
303
323
  var settledExitCode = async (exited) => {
304
324
  if (exited === void 0) return void 0;
305
325
  let timer;
@@ -320,7 +340,7 @@ async function describeAgentExit(input2) {
320
340
  input2.stderrTail === void 0 ? "" : Promise.resolve().then(input2.stderrTail).catch(() => "")
321
341
  ]);
322
342
  const head = exitCode === void 0 ? "The agent closed its connection." : exitCode === null ? "The agent process exited without an exit code." : `The agent process exited with code ${exitCode}.`;
323
- const excerpt = lastLines(tail.trim(), AGENT_EXIT_STDERR_MAX_CHARS);
343
+ const excerpt = lastStderrTail(tail.trim(), AGENT_EXIT_STDERR_MAX_CHARS);
324
344
  return new AcpAgentExitedError(
325
345
  excerpt.length === 0 ? head : `${head}
326
346
  Agent stderr (last lines):
@@ -505,9 +525,17 @@ var selectPromptTurnId = (input2, activeTurnId, freshTurnId) => {
505
525
  return target;
506
526
  };
507
527
 
508
- // ../../packages/ycodium-acp-executor/src/tool-presentation.ts
528
+ // ../../packages/ycodium-executor-common/src/toolPresentation.ts
529
+ function isRecord3(value) {
530
+ return typeof value === "object" && value !== null && !Array.isArray(value);
531
+ }
532
+ function asTrimmedString2(value) {
533
+ if (typeof value !== "string") return void 0;
534
+ const trimmed2 = value.trim();
535
+ return trimmed2.length > 0 ? trimmed2 : void 0;
536
+ }
509
537
  function normalizeCommandValue(value) {
510
- const direct = asTrimmedString(value);
538
+ const direct = asTrimmedString2(value);
511
539
  if (direct) {
512
540
  return direct;
513
541
  }
@@ -516,7 +544,7 @@ function normalizeCommandValue(value) {
516
544
  }
517
545
  const parts = [];
518
546
  for (const entry of value) {
519
- const part = asTrimmedString(entry);
547
+ const part = asTrimmedString2(entry);
520
548
  if (part !== void 0) {
521
549
  parts.push(part);
522
550
  }
@@ -540,11 +568,11 @@ function extractCommandFromTitle(title) {
540
568
  return backtickMatch?.[1]?.trim() || void 0;
541
569
  }
542
570
  function extractToolCommand(data, title) {
543
- const item = isRecord2(data?.["item"]) ? data["item"] : void 0;
544
- const itemInput = item && isRecord2(item["input"]) ? item["input"] : void 0;
545
- const itemResult = item && isRecord2(item["result"]) ? item["result"] : void 0;
546
- const rawInput = isRecord2(data?.["rawInput"]) ? data["rawInput"] : void 0;
547
- const dataInput = isRecord2(data?.["input"]) ? data["input"] : void 0;
571
+ const item = isRecord3(data?.["item"]) ? data["item"] : void 0;
572
+ const itemInput = item && isRecord3(item["input"]) ? item["input"] : void 0;
573
+ const itemResult = item && isRecord3(item["result"]) ? item["result"] : void 0;
574
+ const rawInput = isRecord3(data?.["rawInput"]) ? data["rawInput"] : void 0;
575
+ const dataInput = isRecord3(data?.["input"]) ? data["input"] : void 0;
548
576
  const candidates = [
549
577
  normalizeCommandValue(item?.["command"]),
550
578
  normalizeCommandValue(itemInput?.["command"]),
@@ -557,7 +585,7 @@ function extractToolCommand(data, title) {
557
585
  if (direct) {
558
586
  return direct;
559
587
  }
560
- const executable = asTrimmedString(rawInput?.["executable"]);
588
+ const executable = asTrimmedString2(rawInput?.["executable"]);
561
589
  const args = normalizeCommandValue(rawInput?.["args"]);
562
590
  if (executable && args) {
563
591
  return `${executable} ${args}`;
@@ -589,11 +617,11 @@ function collectPaths(value, paths, seen, depth) {
589
617
  }
590
618
  return;
591
619
  }
592
- if (!isRecord2(value)) {
620
+ if (!isRecord3(value)) {
593
621
  return;
594
622
  }
595
623
  for (const key of ["path", "filePath", "relativePath", "filename", "newPath", "oldPath"]) {
596
- const candidate = maybePathLike(asTrimmedString(value[key]));
624
+ const candidate = maybePathLike(asTrimmedString2(value[key]));
597
625
  if (!candidate || seen.has(candidate)) {
598
626
  continue;
599
627
  }
@@ -619,7 +647,7 @@ function extractPrimaryPath(data) {
619
647
  return paths[0];
620
648
  }
621
649
  function normalizeEquivalentValue(value) {
622
- const trimmed2 = asTrimmedString(value);
650
+ const trimmed2 = asTrimmedString2(value);
623
651
  if (!trimmed2) {
624
652
  return void 0;
625
653
  }
@@ -632,8 +660,8 @@ function isEquivalent(left, right) {
632
660
  }
633
661
  function classifyToolAction(input2) {
634
662
  const itemType = input2.itemType ?? void 0;
635
- const kind = asTrimmedString(input2.data?.["kind"])?.toLowerCase();
636
- const title = asTrimmedString(input2.title)?.toLowerCase();
663
+ const kind = asTrimmedString2(input2.data?.["kind"])?.toLowerCase();
664
+ const title = asTrimmedString2(input2.title)?.toLowerCase();
637
665
  if (itemType === "command_execution" || kind === "execute" || title === "terminal") {
638
666
  return "command";
639
667
  }
@@ -648,26 +676,11 @@ function classifyToolAction(input2) {
648
676
  }
649
677
  return "other";
650
678
  }
651
- function canonicalItemTypeFromAcpToolKind(kind) {
652
- switch (kind) {
653
- case "execute":
654
- return "command_execution";
655
- case "edit":
656
- case "delete":
657
- case "move":
658
- return "file_change";
659
- case "search":
660
- case "fetch":
661
- return "web_search";
662
- default:
663
- return "dynamic_tool_call";
664
- }
665
- }
666
679
  function deriveToolActivityPresentation(input2) {
667
- const title = asTrimmedString(input2.title);
668
- const detail = stripTrailingExitCode(asTrimmedString(input2.detail));
669
- const fallbackSummary = asTrimmedString(input2.fallbackSummary) ?? "Tool";
670
- const data = isRecord2(input2.data) ? input2.data : void 0;
680
+ const title = asTrimmedString2(input2.title);
681
+ const detail = stripTrailingExitCode(asTrimmedString2(input2.detail));
682
+ const fallbackSummary = asTrimmedString2(input2.fallbackSummary) ?? "Tool";
683
+ const data = isRecord3(input2.data) ? input2.data : void 0;
671
684
  const command = extractToolCommand(data, title);
672
685
  const primaryPath = extractPrimaryPath(data);
673
686
  const action = classifyToolAction({
@@ -699,8 +712,8 @@ function deriveToolActivityPresentation(input2) {
699
712
  };
700
713
  }
701
714
  if (action === "search") {
702
- const rawInput = isRecord2(data?.["rawInput"]) ? data["rawInput"] : void 0;
703
- const query = asTrimmedString(rawInput?.["query"]) ?? asTrimmedString(rawInput?.["pattern"]) ?? asTrimmedString(rawInput?.["searchTerm"]);
715
+ const rawInput = isRecord3(data?.["rawInput"]) ? data["rawInput"] : void 0;
716
+ const query = asTrimmedString2(rawInput?.["query"]) ?? asTrimmedString2(rawInput?.["pattern"]) ?? asTrimmedString2(rawInput?.["searchTerm"]);
704
717
  return {
705
718
  summary: "Searched files",
706
719
  ...query ? { detail: query } : {}
@@ -717,6 +730,23 @@ function deriveToolActivityPresentation(input2) {
717
730
  };
718
731
  }
719
732
 
733
+ // ../../packages/ycodium-acp-executor/src/tool-presentation.ts
734
+ function canonicalItemTypeFromAcpToolKind(kind) {
735
+ switch (kind) {
736
+ case "execute":
737
+ return "command_execution";
738
+ case "edit":
739
+ case "delete":
740
+ case "move":
741
+ return "file_change";
742
+ case "search":
743
+ case "fetch":
744
+ return "web_search";
745
+ default:
746
+ return "dynamic_tool_call";
747
+ }
748
+ }
749
+
720
750
  // ../../packages/ycodium-acp-executor/src/tool-call-state.ts
721
751
  function normalizeToolCallStatus(raw, fallback) {
722
752
  switch (raw) {
@@ -945,6 +975,30 @@ function decideToolCallUpdateEmission(input2) {
945
975
  return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
946
976
  }
947
977
 
978
+ // ../../packages/ycodium-executor-common/src/catalogModel.ts
979
+ function catalogModelLastSegment(value) {
980
+ if (value.startsWith("[")) {
981
+ let parsed;
982
+ try {
983
+ parsed = JSON.parse(value);
984
+ } catch {
985
+ return void 0;
986
+ }
987
+ if (!Array.isArray(parsed) || parsed.length < 2) return void 0;
988
+ const last = parsed[parsed.length - 1];
989
+ return typeof last === "string" ? last : void 0;
990
+ }
991
+ const separator = value.indexOf("/");
992
+ return separator > 0 && separator < value.length - 1 ? value.slice(separator + 1) : void 0;
993
+ }
994
+ function matchCatalogModel(requested, catalog) {
995
+ const wanted = requested?.trim();
996
+ if (!wanted) return void 0;
997
+ if (catalog.includes(wanted)) return wanted;
998
+ const byLastSegment = catalog.filter((value) => catalogModelLastSegment(value) === wanted);
999
+ return byLastSegment.length === 1 ? byLastSegment[0] : void 0;
1000
+ }
1001
+
948
1002
  // ../../packages/ycodium-acp-executor/src/runtime-model.ts
949
1003
  function normalizePlanStepStatus(raw) {
950
1004
  switch (raw) {
@@ -986,30 +1040,6 @@ function collectSessionModelIds(models) {
986
1040
  (model) => isRecord2(model) && typeof model["modelId"] === "string" ? [model["modelId"]] : []
987
1041
  );
988
1042
  }
989
- function catalogModelLastSegment(value) {
990
- if (value.startsWith("[")) {
991
- let parsed;
992
- try {
993
- parsed = JSON.parse(value);
994
- } catch {
995
- return void 0;
996
- }
997
- if (!Array.isArray(parsed) || parsed.length < 2) return void 0;
998
- const last = parsed[parsed.length - 1];
999
- return typeof last === "string" ? last : void 0;
1000
- }
1001
- const separator = value.indexOf("/");
1002
- return separator > 0 && separator < value.length - 1 ? value.slice(separator + 1) : void 0;
1003
- }
1004
- function matchAdvertisedModelValue(requestedModelId, advertisedValues) {
1005
- const wanted = requestedModelId.trim();
1006
- if (!wanted) return void 0;
1007
- if (advertisedValues.includes(wanted)) return wanted;
1008
- const byLastSegment = advertisedValues.filter(
1009
- (value) => catalogModelLastSegment(value) === wanted
1010
- );
1011
- return byLastSegment.length === 1 ? byLastSegment[0] : void 0;
1012
- }
1013
1043
  function parseSessionModeState(sessionResponse) {
1014
1044
  const modes = sessionResponse.modes;
1015
1045
  if (!modes) return void 0;
@@ -22925,17 +22955,17 @@ function isResponseMessage(value) {
22925
22955
  function isNotificationMessage(value) {
22926
22956
  return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
22927
22957
  }
22928
- function isRecord3(value) {
22958
+ function isRecord4(value) {
22929
22959
  return typeof value === "object" && value !== null;
22930
22960
  }
22931
22961
  function isJsonRpcEnvelope(value) {
22932
- return isRecord3(value) && value["jsonrpc"] === "2.0";
22962
+ return isRecord4(value) && value["jsonrpc"] === "2.0";
22933
22963
  }
22934
22964
  function isJsonRpcId(value) {
22935
22965
  return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
22936
22966
  }
22937
22967
  function isResponseShapedMessage(value) {
22938
- return isRecord3(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
22968
+ return isRecord4(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
22939
22969
  }
22940
22970
  function isResponseBatch(batch) {
22941
22971
  let hasValidCall = false;
@@ -22945,7 +22975,7 @@ function isResponseBatch(batch) {
22945
22975
  for (const entry of batch) {
22946
22976
  hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
22947
22977
  hasValidResponse ||= isResponseMessage(entry);
22948
- if (!isRecord3(entry)) {
22978
+ if (!isRecord4(entry)) {
22949
22979
  continue;
22950
22980
  }
22951
22981
  hasCallShape ||= "method" in entry;
@@ -22960,13 +22990,13 @@ function isResponseBatch(batch) {
22960
22990
  return hasResponseShape && !hasCallShape;
22961
22991
  }
22962
22992
  function cancelRequestId(params) {
22963
- if (!isRecord3(params) || !isJsonRpcId(params["requestId"])) {
22993
+ if (!isRecord4(params) || !isJsonRpcId(params["requestId"])) {
22964
22994
  return void 0;
22965
22995
  }
22966
22996
  return params["requestId"];
22967
22997
  }
22968
22998
  function isErrorResponse(value) {
22969
- return isRecord3(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
22999
+ return isRecord4(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
22970
23000
  }
22971
23001
  var Handled = {
22972
23002
  /**
@@ -23511,7 +23541,7 @@ var Connection = class {
23511
23541
  if (this.abortController.signal.aborted) {
23512
23542
  return Promise.resolve();
23513
23543
  }
23514
- if (!isRecord3(message)) {
23544
+ if (!isRecord4(message)) {
23515
23545
  console.error("Invalid message", { message });
23516
23546
  return Promise.resolve();
23517
23547
  }
@@ -23914,7 +23944,7 @@ function ndJsonStream(output2, input2) {
23914
23944
  await writeJson(protocolErrorResponse(RequestError.parseError()));
23915
23945
  return;
23916
23946
  }
23917
- if (isRecord3(message) || Array.isArray(message)) {
23947
+ if (isRecord4(message) || Array.isArray(message)) {
23918
23948
  controller.enqueue(message);
23919
23949
  } else {
23920
23950
  await writeJson(protocolErrorResponse(RequestError.invalidRequest(message)));
@@ -24901,14 +24931,14 @@ var legacyClientNotificationMethods = /* @__PURE__ */ new Set([
24901
24931
  import * as NodeStream from "node:stream";
24902
24932
 
24903
24933
  // ../../packages/ycodium-acp-executor/src/jsonrpc.ts
24904
- function isRecord4(value) {
24934
+ function isRecord5(value) {
24905
24935
  return typeof value === "object" && value !== null;
24906
24936
  }
24907
24937
  function isJsonRpcId2(value) {
24908
24938
  return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
24909
24939
  }
24910
24940
  function isJsonRpcEnvelope2(value) {
24911
- return isRecord4(value) && value["jsonrpc"] === "2.0";
24941
+ return isRecord5(value) && value["jsonrpc"] === "2.0";
24912
24942
  }
24913
24943
  function isRequestMessage2(value) {
24914
24944
  return isJsonRpcEnvelope2(value) && "id" in value && typeof value["method"] === "string" && isJsonRpcId2(value["id"]);
@@ -24928,7 +24958,7 @@ function isNotificationMessage2(value) {
24928
24958
  return isJsonRpcEnvelope2(value) && !("id" in value) && typeof value["method"] === "string";
24929
24959
  }
24930
24960
  function readJsonRpcError(value) {
24931
- if (!isRecord4(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
24961
+ if (!isRecord5(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
24932
24962
  return void 0;
24933
24963
  }
24934
24964
  return {
@@ -25001,11 +25031,11 @@ var KNOWN_SESSION_UPDATES = /* @__PURE__ */ new Set([
25001
25031
  "compaction_summary_chunk"
25002
25032
  ]);
25003
25033
  function isSessionUpdateEnvelope(payload) {
25004
- if (!isRecord4(payload) || typeof payload["sessionId"] !== "string") {
25034
+ if (!isRecord5(payload) || typeof payload["sessionId"] !== "string") {
25005
25035
  return false;
25006
25036
  }
25007
25037
  const update = payload["update"];
25008
- return isRecord4(update) && typeof update["sessionUpdate"] === "string";
25038
+ return isRecord5(update) && typeof update["sessionUpdate"] === "string";
25009
25039
  }
25010
25040
  function hasKnownVariantShape(update) {
25011
25041
  const kind = update["sessionUpdate"];
@@ -25013,7 +25043,7 @@ function hasKnownVariantShape(update) {
25013
25043
  return false;
25014
25044
  }
25015
25045
  if (kind === "user_message_chunk" || kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
25016
- return isRecord4(update["content"]);
25046
+ return isRecord5(update["content"]);
25017
25047
  }
25018
25048
  return true;
25019
25049
  }
@@ -25781,7 +25811,7 @@ var alignRequestedEffort = async (input2) => {
25781
25811
  return { configOptions, unsupportedEffort, ...confirmed ? { appliedEffort: fallback } : {} };
25782
25812
  };
25783
25813
 
25784
- // ../../packages/ycodium-acp-executor/src/reasoning-level-fallback.ts
25814
+ // ../../packages/ycodium-executor-common/src/reasoningLevelFallback.ts
25785
25815
  var REASONING_LEVEL_FALLBACK_CODE = "reasoning-level-fallback";
25786
25816
  function reasoningLevelFallbackWarning(input2) {
25787
25817
  const model = input2.model ?? "This model";
@@ -26877,7 +26907,7 @@ function createExecutorRequests({
26877
26907
  }
26878
26908
 
26879
26909
  // ../../packages/ycodium-acp-executor/src/artifacts.ts
26880
- import * as NodePath from "node:path";
26910
+ import * as NodePath2 from "node:path";
26881
26911
  import * as NodeURL from "node:url";
26882
26912
  function resourceLinkArtifacts(content) {
26883
26913
  if (content["type"] !== "resource_link" || typeof content["uri"] !== "string") return [];
@@ -26888,7 +26918,7 @@ function resourceLinkArtifacts(content) {
26888
26918
  } catch {
26889
26919
  return [];
26890
26920
  }
26891
- if (!NodePath.isAbsolute(path)) return [];
26921
+ if (!NodePath2.isAbsolute(path)) return [];
26892
26922
  const name = typeof content["name"] === "string" ? content["name"].trim() : "";
26893
26923
  const mimeType = typeof content["mimeType"] === "string" ? content["mimeType"].trim() : "";
26894
26924
  return [
@@ -26933,7 +26963,7 @@ function makeArtifactEmitter(input2) {
26933
26963
  // ../../packages/ycodium-acp-executor/src/executor/runtime.ts
26934
26964
  function createExecutorRuntime({
26935
26965
  randomId,
26936
- nowIso: nowIso2,
26966
+ nowIso: nowIso3,
26937
26967
  eventStream,
26938
26968
  options,
26939
26969
  assistantItemRuntimeId,
@@ -26942,7 +26972,7 @@ function createExecutorRuntime({
26942
26972
  }) {
26943
26973
  const stamp = () => ({
26944
26974
  eventId: randomId(),
26945
- createdAt: nowIso2()
26975
+ createdAt: nowIso3()
26946
26976
  });
26947
26977
  const isLive = (expectedGeneration) => !shared.disposed && shared.generation === expectedGeneration;
26948
26978
  const publish = (event) => {
@@ -27120,7 +27150,7 @@ function judgeRequestedModel(input2) {
27120
27150
  const hasCurrent = current !== void 0;
27121
27151
  if (!hasCatalog && !hasCurrent && input2.state.modelUnconfirmed !== true) return { kind: "keep" };
27122
27152
  const canSwitch = canSwitchModel(input2.state);
27123
- const value = hasCatalog ? matchAdvertisedModelValue(requested, input2.state.advertisedModelValues) : void 0;
27153
+ const value = hasCatalog ? matchCatalogModel(requested, input2.state.advertisedModelValues) : void 0;
27124
27154
  if (value !== void 0 && value === current) return { kind: "keep" };
27125
27155
  if (value !== void 0 && canSwitch) return { kind: "switch", value };
27126
27156
  return { kind: "refresh" };
@@ -27160,18 +27190,18 @@ function modelRefreshFailedError(requestedModelId, error62) {
27160
27190
  }
27161
27191
 
27162
27192
  // ../../packages/ycodium-acp-executor/src/runtime-mode.ts
27163
- function isRecord5(value) {
27193
+ function isRecord6(value) {
27164
27194
  return typeof value === "object" && value !== null && !Array.isArray(value);
27165
27195
  }
27166
27196
  function asString2(value) {
27167
27197
  return typeof value === "string" ? value : void 0;
27168
27198
  }
27169
27199
  function acpModeConfigId(setup) {
27170
- if (!isRecord5(setup)) return void 0;
27200
+ if (!isRecord6(setup)) return void 0;
27171
27201
  const configOptions = setup["configOptions"];
27172
27202
  if (!Array.isArray(configOptions)) return void 0;
27173
27203
  for (const option of configOptions) {
27174
- if (!isRecord5(option)) continue;
27204
+ if (!isRecord6(option)) continue;
27175
27205
  if (asString2(option["category"])?.trim().toLowerCase() !== "mode") continue;
27176
27206
  const id = asString2(option["id"])?.trim();
27177
27207
  if (id) return id;
@@ -27179,16 +27209,16 @@ function acpModeConfigId(setup) {
27179
27209
  return void 0;
27180
27210
  }
27181
27211
  function acpCurrentModeId(setup) {
27182
- if (!isRecord5(setup)) return void 0;
27212
+ if (!isRecord6(setup)) return void 0;
27183
27213
  const modes = setup["modes"];
27184
- if (isRecord5(modes)) {
27214
+ if (isRecord6(modes)) {
27185
27215
  const current = asString2(modes["currentModeId"])?.trim();
27186
27216
  if (current) return current;
27187
27217
  }
27188
27218
  const configOptions = setup["configOptions"];
27189
27219
  if (Array.isArray(configOptions)) {
27190
27220
  for (const option of configOptions) {
27191
- if (!isRecord5(option)) continue;
27221
+ if (!isRecord6(option)) continue;
27192
27222
  if (asString2(option["category"])?.trim().toLowerCase() !== "mode") continue;
27193
27223
  const current = asString2(option["currentValue"])?.trim();
27194
27224
  if (current) return current;
@@ -28102,8 +28132,8 @@ function readOpenToolCalls(toolCalls, turnId) {
28102
28132
 
28103
28133
  // ../../packages/ycodium-acp-executor/src/protocol-log.ts
28104
28134
  import * as NodeFS from "node:fs";
28105
- import * as NodeOS from "node:os";
28106
- import * as NodePath2 from "node:path";
28135
+ import * as NodeOS2 from "node:os";
28136
+ import * as NodePath3 from "node:path";
28107
28137
  var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
28108
28138
  var UNSAFE_FILE_CHARS = /[^A-Za-z0-9._-]+/gu;
28109
28139
  function safeFileName(value) {
@@ -28112,7 +28142,7 @@ function safeFileName(value) {
28112
28142
  function createAcpProtocolLogFile(input2) {
28113
28143
  const maxBytes = input2.maxBytes ?? DEFAULT_MAX_BYTES;
28114
28144
  NodeFS.mkdirSync(input2.directory, { recursive: true });
28115
- const filePath = NodePath2.join(
28145
+ const filePath = NodePath3.join(
28116
28146
  input2.directory,
28117
28147
  `${safeFileName(input2.provider)}-${safeFileName(input2.threadId)}-${Date.now().toString(36)}.ndjson`
28118
28148
  );
@@ -28168,7 +28198,7 @@ function createAcpProtocolLogFromEnv(input2) {
28168
28198
  const flag = process.env.YCODIUM_ACP_PROTOCOL_LOG;
28169
28199
  if (flag !== "1" && flag?.toLowerCase() !== "true") return void 0;
28170
28200
  const configured = process.env.YCODIUM_ACP_PROTOCOL_LOG_DIR?.trim();
28171
- const directory = configured && configured.length > 0 ? configured : NodePath2.join(NodeOS.tmpdir(), "ycodium-acp-protocol");
28201
+ const directory = configured && configured.length > 0 ? configured : NodePath3.join(NodeOS2.tmpdir(), "ycodium-acp-protocol");
28172
28202
  try {
28173
28203
  const sink = createAcpProtocolLogFile({
28174
28204
  directory,
@@ -28197,7 +28227,7 @@ function defaultRandomId() {
28197
28227
  function createAcpExecutor(options) {
28198
28228
  const hooks = { ...defaultVendorHooks, ...options.hooks };
28199
28229
  const cancelGraceMs = options.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
28200
- const nowIso2 = options.nowIso ?? defaultNowIso;
28230
+ const nowIso3 = options.nowIso ?? defaultNowIso;
28201
28231
  const randomId = options.randomId ?? defaultRandomId;
28202
28232
  const eventStream = new UnboundedEventStream();
28203
28233
  const threadMutex = new Mutex();
@@ -28258,7 +28288,7 @@ function createAcpExecutor(options) {
28258
28288
  waitForPromptIdle
28259
28289
  } = createExecutorRuntime({
28260
28290
  randomId,
28261
- nowIso: nowIso2,
28291
+ nowIso: nowIso3,
28262
28292
  eventStream,
28263
28293
  options,
28264
28294
  assistantItemRuntimeId,
@@ -28502,7 +28532,7 @@ function createAcpExecutor(options) {
28502
28532
  }
28503
28533
 
28504
28534
  // ../../packages/ycodium-acp-executor/src/session-registry.ts
28505
- function createAcpSessionRegistry(threads, stopBooked2, log) {
28535
+ function createAcpSessionRegistry(threads, stopBooked, log) {
28506
28536
  const exits = /* @__PURE__ */ new WeakMap();
28507
28537
  const requireThread = (threadId) => {
28508
28538
  const booked = threads.get(threadId);
@@ -28513,7 +28543,7 @@ function createAcpSessionRegistry(threads, stopBooked2, log) {
28513
28543
  const stopSession = (threadId, booked = threads.get(threadId)) => {
28514
28544
  if (!booked) return Promise.resolve();
28515
28545
  const close = { exitCode: exits.get(booked), hasExited: () => exits.has(booked) };
28516
- booked.closing ??= Promise.resolve().then(() => stopBooked2(booked, close)).then(() => {
28546
+ booked.closing ??= Promise.resolve().then(() => stopBooked(booked, close)).then(() => {
28517
28547
  if (threads.get(threadId) === booked) threads.delete(threadId);
28518
28548
  }).catch((cause) => {
28519
28549
  if (threads.get(threadId) === booked) delete booked.closing;
@@ -28630,22 +28660,225 @@ var dispatchAcpPrompt = (executor, input2) => {
28630
28660
  ]);
28631
28661
  };
28632
28662
 
28633
- // ../../packages/ycodium-acp-executor/src/start-abort.ts
28634
- function throwIfStartAborted(signal) {
28635
- if (signal?.aborted) throw new Error("aborted");
28663
+ // ../../packages/ycodium-acp-executor/src/thread-operations.ts
28664
+ var yieldTick = () => new Promise((resolve4) => {
28665
+ setImmediate(resolve4);
28666
+ });
28667
+ var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
28668
+ function createAcpThreadOperations(options) {
28669
+ const { threads, requireThread } = options;
28670
+ return {
28671
+ sendTurn: async (input2, signal) => {
28672
+ if (options.isDisposed()) throw new Error("instance disposed");
28673
+ const booked = requireThread(input2.threadId);
28674
+ if (signal?.aborted) throw new Error("aborted");
28675
+ options.beforeSendTurn?.(booked);
28676
+ const onAbort = () => {
28677
+ void booked.executor.cancel(input2.expectedTurnId).catch(() => void 0);
28678
+ };
28679
+ signal?.addEventListener("abort", onAbort);
28680
+ try {
28681
+ const { requestedModelId, requestedEffort } = options.turnSelection?.(input2.modelSelection) ?? {};
28682
+ const turn = await dispatchAcpPrompt(booked.executor, {
28683
+ text: input2.input ?? "",
28684
+ expectedActiveTurnId: input2.expectedTurnId,
28685
+ ...requestedModelId === void 0 ? {} : { requestedModelId },
28686
+ ...requestedEffort === void 0 ? {} : { requestedEffort }
28687
+ });
28688
+ booked.turns.push({ id: turn.turnId, items: [] });
28689
+ return {
28690
+ threadId: input2.threadId,
28691
+ turnId: turn.turnId,
28692
+ ...booked.session.resumeCursor === void 0 ? {} : { resumeCursor: booked.session.resumeCursor }
28693
+ };
28694
+ } finally {
28695
+ signal?.removeEventListener("abort", onAbort);
28696
+ }
28697
+ },
28698
+ interruptTurn: async (threadId, turnId) => {
28699
+ const booked = threads.get(threadId);
28700
+ if (booked === void 0 || booked.closing) return;
28701
+ options.log.info("interrupt turn", { threadId, turnId });
28702
+ await booked.executor.cancel(turnId);
28703
+ await yieldTick();
28704
+ },
28705
+ respondToRequest: async (threadId, requestId, decision, reason) => {
28706
+ const booked = requireThread(threadId);
28707
+ await booked.executor.respondToRequest(
28708
+ requestId,
28709
+ decision === "allow" ? "accept" : "decline",
28710
+ reason
28711
+ );
28712
+ },
28713
+ respondToUserInput: async (threadId, requestId, answers) => {
28714
+ const booked = requireThread(threadId);
28715
+ await booked.executor.respondToUserInput(requestId, answers);
28716
+ },
28717
+ /**
28718
+ * 切这只手自报的审批档。`nativeModeId` 是它自己报的 id(探测时原样上报的那些),
28719
+ * 一路不翻译成宿主四档。
28720
+ *
28721
+ * 这是 `setRuntimeMode` 做不到的那一半:那个只改插件自己的会话记录,CLI 收不到
28722
+ * (`runtime-mode-never-reaches-cli` 记的那族缺陷)。
28723
+ */
28724
+ setNativeMode: async (threadId, nativeModeId) => {
28725
+ const booked = requireThread(threadId);
28726
+ await booked.executor.setNativeMode(nativeModeId);
28727
+ booked.session = { ...booked.session, nativeModeId, updatedAt: nowIso() };
28728
+ },
28729
+ setRuntimeMode: async (threadId, runtimeMode) => {
28730
+ const booked = requireThread(threadId);
28731
+ booked.session = { ...booked.session, runtimeMode, updatedAt: nowIso() };
28732
+ },
28733
+ readThread: async (threadId) => {
28734
+ const booked = requireThread(threadId);
28735
+ return { threadId, turns: booked.turns };
28736
+ }
28737
+ };
28636
28738
  }
28637
- async function raceStartAbort(promise2, signal) {
28638
- void promise2.catch(() => void 0);
28639
- throwIfStartAborted(signal);
28640
- if (signal === void 0) return promise2;
28641
- const aborted2 = Promise.withResolvers();
28642
- const onAbort = () => aborted2.reject(new Error("aborted"));
28643
- signal.addEventListener("abort", onAbort, { once: true });
28644
- try {
28645
- return await Promise.race([promise2, aborted2.promise]);
28646
- } finally {
28647
- signal.removeEventListener("abort", onAbort);
28739
+
28740
+ // ../../packages/ycodium-executor-common/src/modelSelection.ts
28741
+ function modelSelectionStringOption(selection, optionId) {
28742
+ if (typeof selection !== "object" || selection === null || Array.isArray(selection)) {
28743
+ return void 0;
28744
+ }
28745
+ const options = selection["options"];
28746
+ if (!Array.isArray(options)) return void 0;
28747
+ for (const entry of options) {
28748
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
28749
+ const record2 = entry;
28750
+ if (record2["id"] !== optionId) continue;
28751
+ const value = record2["value"];
28752
+ return typeof value === "string" ? value.trim() || void 0 : void 0;
28648
28753
  }
28754
+ return void 0;
28755
+ }
28756
+
28757
+ // ../../packages/ycodium-executor-common/src/nodeStreams.ts
28758
+ import * as NodeOS3 from "node:os";
28759
+ import * as NodeStream2 from "node:stream";
28760
+ var PEER_CLOSED_STDIN_CODES = /* @__PURE__ */ new Set([
28761
+ "EPIPE",
28762
+ "ECONNRESET",
28763
+ "EOF",
28764
+ "ERR_STREAM_DESTROYED",
28765
+ "ERR_STREAM_WRITE_AFTER_END",
28766
+ "ERR_STREAM_ALREADY_FINISHED"
28767
+ ]);
28768
+ function errorCode(value) {
28769
+ if (typeof value !== "object" || value === null) return void 0;
28770
+ const code = value.code;
28771
+ return typeof code === "string" ? code : void 0;
28772
+ }
28773
+ function asError(value) {
28774
+ return value instanceof Error ? value : new Error(String(value));
28775
+ }
28776
+ function isPeerClosedStdinError(error62) {
28777
+ const code = errorCode(error62);
28778
+ return code !== void 0 && PEER_CLOSED_STDIN_CODES.has(code);
28779
+ }
28780
+ var PeerClosedStdinError = class extends Error {
28781
+ name = "PeerClosedStdinError";
28782
+ code;
28783
+ constructor(operation, cause) {
28784
+ super(
28785
+ `Child process stdin is closed; the ${operation} did not reach the peer.`,
28786
+ cause === void 0 ? void 0 : { cause }
28787
+ );
28788
+ this.code = errorCode(cause) ?? "ERR_STREAM_DESTROYED";
28789
+ }
28790
+ };
28791
+ var ownErrors = {
28792
+ isPeerClosed: isPeerClosedStdinError,
28793
+ peerClosed: (operation, cause) => new PeerClosedStdinError(operation, cause)
28794
+ };
28795
+ function toStreamError(errors, operation, error62) {
28796
+ if (errors.isPeerClosed(error62)) return errors.peerClosed(operation, error62);
28797
+ return asError(error62);
28798
+ }
28799
+ function nodeWritableFromHandle(handle, errors = ownErrors) {
28800
+ return new NodeStream2.Writable({
28801
+ write(chunk, _encoding, callback) {
28802
+ const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
28803
+ handle.writeStdin(bytes).then(
28804
+ () => callback(),
28805
+ (error62) => callback(toStreamError(errors, "write", error62))
28806
+ );
28807
+ },
28808
+ final(callback) {
28809
+ handle.closeStdin().then(
28810
+ () => callback(),
28811
+ // 关一条对端已经没了的流是正常收尾,不是失败;真异常照旧交出去。
28812
+ (error62) => callback(errors.isPeerClosed(error62) ? void 0 : toStreamError(errors, "close", error62))
28813
+ );
28814
+ }
28815
+ });
28816
+ }
28817
+ var STDERR_TAIL_MAX_CHARS = 4096;
28818
+ var STDERR_SETTLE_MS = 500;
28819
+ var PAIRING_URL_PATTERN = /https?:\/\/[^\s]*\/pair#[^\s]*/gi;
28820
+ var BEARER_TOKEN_PATTERN = /\bBearer\s+[A-Za-z0-9._\-+=/]+/gi;
28821
+ var BASIC_AUTH_PATTERN = /\bAuthorization:\s*Basic\s+\S+/gi;
28822
+ var API_KEY_HEADER_PATTERN = /\bx-api-key:\s*\S+/gi;
28823
+ var SECRET_TOKEN_PATTERN = /\b(?:sk-[A-Za-z0-9][A-Za-z0-9-]{7,}|ghp_[A-Za-z0-9]+|xox[a-zA-Z]-[A-Za-z0-9-]+)\b/g;
28824
+ function redactStderrExcerpt(text, environment = process.env) {
28825
+ let result = text.replaceAll("\0", "");
28826
+ const homes = [environment["HOME"], environment["USERPROFILE"], NodeOS3.homedir()].filter(
28827
+ (value) => typeof value === "string" && value.length > 1
28828
+ );
28829
+ for (const home of new Set(homes)) {
28830
+ result = result.split(home).join("~");
28831
+ }
28832
+ return result.replace(PAIRING_URL_PATTERN, "[pairing-url]").replace(BEARER_TOKEN_PATTERN, "Bearer [redacted]").replace(BASIC_AUTH_PATTERN, "Authorization: Basic [redacted]").replace(API_KEY_HEADER_PATTERN, "x-api-key: [redacted]").replace(SECRET_TOKEN_PATTERN, "[redacted]").trim();
28833
+ }
28834
+ function drainStderrTail(stderr) {
28835
+ let tail = "";
28836
+ const decoder = new TextDecoder();
28837
+ const drained = (async () => {
28838
+ for await (const chunk of stderr) {
28839
+ const next = tail + decoder.decode(chunk, { stream: true });
28840
+ tail = next.length <= STDERR_TAIL_MAX_CHARS ? next : next.slice(-STDERR_TAIL_MAX_CHARS);
28841
+ }
28842
+ })().catch(() => void 0);
28843
+ return async () => {
28844
+ let timer;
28845
+ await Promise.race([
28846
+ drained,
28847
+ new Promise((resolve4) => {
28848
+ timer = setTimeout(resolve4, STDERR_SETTLE_MS);
28849
+ })
28850
+ ]);
28851
+ clearTimeout(timer);
28852
+ return redactStderrExcerpt(tail);
28853
+ };
28854
+ }
28855
+ function nodeStreamsFromHandle(handle, errors = ownErrors) {
28856
+ const readable = new NodeStream2.PassThrough();
28857
+ void (async () => {
28858
+ try {
28859
+ for await (const chunk of handle.stdout) {
28860
+ if (!readable.writable) return;
28861
+ if (!readable.write(chunk)) {
28862
+ await new Promise((resolve4) => {
28863
+ const onDone = () => {
28864
+ readable.off("drain", onDone);
28865
+ readable.off("close", onDone);
28866
+ resolve4();
28867
+ };
28868
+ readable.once("drain", onDone);
28869
+ readable.once("close", onDone);
28870
+ });
28871
+ }
28872
+ }
28873
+ } catch (error62) {
28874
+ readable.destroy(asError(error62));
28875
+ return;
28876
+ }
28877
+ if (readable.writable) readable.end();
28878
+ })();
28879
+ const settledStderrTail = drainStderrTail(handle.stderr);
28880
+ const writable = nodeWritableFromHandle(handle, errors);
28881
+ return { readable, writable, stderrTail: settledStderrTail };
28649
28882
  }
28650
28883
 
28651
28884
  // ../../packages/ycodium-acp-executor/src/mcp-servers.ts
@@ -28668,57 +28901,238 @@ function toAcpMcpServers(entries) {
28668
28901
  );
28669
28902
  }
28670
28903
 
28671
- // ../../packages/ycodium-acp-executor/src/probe.ts
28672
- var CLI_VERSION_PATTERN = /(?<![\d.])(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)/;
28673
- function parseCliVersion(output2) {
28674
- return CLI_VERSION_PATTERN.exec(output2)?.[1] ?? null;
28904
+ // ../../packages/ycodium-acp-executor/src/start-abort.ts
28905
+ function throwIfStartAborted(signal) {
28906
+ if (signal?.aborted) throw new Error("aborted");
28907
+ }
28908
+ async function raceStartAbort(promise2, signal) {
28909
+ void promise2.catch(() => void 0);
28910
+ throwIfStartAborted(signal);
28911
+ if (signal === void 0) return promise2;
28912
+ const aborted2 = Promise.withResolvers();
28913
+ const onAbort = () => aborted2.reject(new Error("aborted"));
28914
+ signal.addEventListener("abort", onAbort, { once: true });
28915
+ try {
28916
+ return await Promise.race([promise2, aborted2.promise]);
28917
+ } finally {
28918
+ signal.removeEventListener("abort", onAbort);
28919
+ }
28675
28920
  }
28676
- var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
28677
28921
 
28678
- // src/config.ts
28679
- function isRecord6(value) {
28680
- return typeof value === "object" && value !== null && !Array.isArray(value);
28922
+ // ../../packages/ycodium-acp-executor/src/instance-kit.ts
28923
+ var yieldTick2 = () => new Promise((resolve4) => {
28924
+ setImmediate(resolve4);
28925
+ });
28926
+ var nowIso2 = () => (/* @__PURE__ */ new Date()).toISOString();
28927
+ function createAcpThreadTable(log, beforeStopAll) {
28928
+ const threads = /* @__PURE__ */ new Map();
28929
+ const registry2 = createAcpSessionRegistry(
28930
+ threads,
28931
+ (booked, processExit) => cleanupAcpSession({
28932
+ executor: booked.executor,
28933
+ stopProcess: () => booked.handle.kill("SIGTERM"),
28934
+ forwarding: booked.forwarding,
28935
+ processExit
28936
+ }),
28937
+ log
28938
+ );
28939
+ const disposeOnce = createRetryableClose(async () => {
28940
+ await beforeStopAll?.();
28941
+ await registry2.stopAll();
28942
+ });
28943
+ return { threads, ...registry2, disposeOnce };
28681
28944
  }
28682
- function readString(value) {
28683
- return typeof value === "string" ? value : "";
28945
+ function bindAcpInstanceThreads(input2) {
28946
+ const table = createAcpThreadTable(input2.log);
28947
+ const { threads, requireThread, registerSession, stopSession, disposeOnce } = table;
28948
+ const threadOps = createAcpThreadOperations({
28949
+ threads,
28950
+ requireThread,
28951
+ isDisposed: input2.isDisposed,
28952
+ log: input2.log,
28953
+ ...input2.turnSelection === void 0 ? {} : { turnSelection: input2.turnSelection },
28954
+ ...input2.beforeSendTurn === void 0 ? {} : { beforeSendTurn: input2.beforeSendTurn }
28955
+ });
28956
+ return { table, threads, requireThread, registerSession, stopSession, disposeOnce, threadOps };
28684
28957
  }
28685
- function readTrimmed(value) {
28686
- return readString(value).trim();
28958
+ function acpProgramNotConfigured(detail) {
28959
+ return {
28960
+ installed: false,
28961
+ version: null,
28962
+ readiness: "not-installed",
28963
+ auth: { status: "unknown" },
28964
+ detail
28965
+ };
28687
28966
  }
28688
- function readEnvironment(value) {
28689
- if (!Array.isArray(value)) return {};
28690
- const env = {};
28691
- for (const entry of value) {
28692
- if (!isRecord6(entry)) continue;
28693
- const name = readTrimmed(entry["name"]);
28694
- if (name.length === 0) continue;
28695
- env[name] = readString(entry["value"]);
28696
- }
28697
- return env;
28967
+ function acpOwnedSpawnSpec(input2) {
28968
+ return {
28969
+ program: input2.program,
28970
+ args: [...input2.args],
28971
+ cwd: input2.cwd,
28972
+ owner: { bindingId: input2.bindingId },
28973
+ ...Object.keys(input2.env).length > 0 ? { env: { ...input2.env } } : {}
28974
+ };
28975
+ }
28976
+ function acpLaunchFromHandle(input2) {
28977
+ const { readable, writable, stderrTail } = nodeStreamsFromHandle(input2.handle);
28978
+ const resume = acpResumeFrom(input2.start, input2.resumeSchemaVersion);
28979
+ const requestedModelId = input2.modelIdFromSelection(input2.modelSelection);
28980
+ const requestedEffort = modelSelectionStringOption(input2.modelSelection, input2.effortOptionId);
28981
+ return { readable, writable, stderrTail, resume, requestedModelId, requestedEffort };
28982
+ }
28983
+ async function stopExistingAcpThread(table, threadId, isDisposed, signal) {
28984
+ const existing = table.threads.get(threadId);
28985
+ if (existing === void 0) return;
28986
+ await table.stopSession(threadId, existing);
28987
+ if (isDisposed()) throw new Error("instance disposed");
28988
+ throwIfStartAborted(signal);
28698
28989
  }
28699
- function parseKimiInstanceConfig(config2) {
28700
- if (!isRecord6(config2)) {
28701
- return {
28702
- binaryPath: "",
28703
- launchArgs: KIMI_CARD.launchArgs,
28704
- homePath: "",
28705
- homeEnvVar: KIMI_CARD.homeEnvVar,
28706
- environment: {},
28707
- envelopeDriver: void 0
28708
- };
28990
+ function acpResumeFrom(input2, schemaVersion) {
28991
+ return input2.discardResumeCursor === true ? void 0 : parseAcpResumeCursor(input2.resumeCursor, schemaVersion);
28992
+ }
28993
+ function acpStartedSession(input2, started) {
28994
+ const createdAt = nowIso2();
28995
+ return {
28996
+ provider: input2.provider,
28997
+ providerInstanceId: input2.providerInstanceId,
28998
+ status: "idle",
28999
+ runtimeMode: input2.runtimeMode,
29000
+ ...input2.nativeModeId === void 0 ? {} : { nativeModeId: input2.nativeModeId },
29001
+ cwd: input2.cwd,
29002
+ threadId: input2.threadId,
29003
+ createdAt,
29004
+ updatedAt: createdAt,
29005
+ resumeCursor: { schemaVersion: input2.resumeSchemaVersion, sessionId: started.sessionId },
29006
+ ...started.modelId === void 0 ? {} : {
29007
+ model: started.modelId,
29008
+ // agent 在握手里报的才是读回的;切型号走 session/set_model 时回包不带型号,那只是请求值。
29009
+ modelSource: started.modelReported ? "reported" : "echo"
29010
+ },
29011
+ ...input2.bindingGeneration === void 0 ? {} : { bindingGeneration: input2.bindingGeneration }
29012
+ };
29013
+ }
29014
+ async function openAcpThread(input2) {
29015
+ const { executor, handle, signal, threadId } = input2;
29016
+ const forwarding = (async () => {
29017
+ for await (const event of executor.events) {
29018
+ const forwarded = input2.forward(event);
29019
+ if (forwarded !== void 0) await forwarded;
29020
+ }
29021
+ })();
29022
+ try {
29023
+ throwIfStartAborted(signal);
29024
+ const started = await raceStartAbort(executor.start(), signal);
29025
+ const after = input2.afterStart?.(started);
29026
+ if (after !== void 0) await after;
29027
+ await yieldTick2();
29028
+ throwIfStartAborted(signal);
29029
+ const session = input2.session(started);
29030
+ input2.registerSession(
29031
+ threadId,
29032
+ input2.booked({ session, turns: [], executor, handle, forwarding })
29033
+ );
29034
+ input2.log.info("session started", { threadId, sessionId: started.sessionId });
29035
+ input2.afterRegister?.();
29036
+ return session;
29037
+ } catch (error62) {
29038
+ await cleanupAcpStartup({
29039
+ executor,
29040
+ stopProcess: () => handle.kill("SIGTERM"),
29041
+ forwarding,
29042
+ log: input2.log,
29043
+ threadId
29044
+ });
29045
+ throw error62;
28709
29046
  }
28710
- const nested = isRecord6(config2["config"]) ? config2["config"] : void 0;
28711
- const settings = nested ?? config2;
29047
+ }
29048
+ function acpLaunchMcpFields(input2) {
29049
+ const omit2 = input2.omitWhenEmpty === true && (input2.mcpServers === void 0 || input2.mcpServers.length === 0);
28712
29050
  return {
28713
- binaryPath: readTrimmed(settings["binaryPath"]),
28714
- launchArgs: readString(settings["launchArgs"]) || KIMI_CARD.launchArgs,
28715
- homePath: readTrimmed(settings["homePath"]) || readTrimmed(config2["homePath"]),
28716
- homeEnvVar: KIMI_CARD.homeEnvVar,
28717
- environment: readEnvironment(config2["environment"]),
28718
- envelopeDriver: readTrimmed(config2["driver"]) || void 0
29051
+ ...omit2 ? {} : { mcpServers: toAcpMcpServers(input2.mcpServers) },
29052
+ ...input2.resumeSessionId === void 0 ? {} : { resumeSessionId: input2.resumeSessionId }
28719
29053
  };
28720
29054
  }
28721
- function tokenizeLaunchArgs(value) {
29055
+ function openAcpThreadSession(input2) {
29056
+ return openAcpThread({
29057
+ registerSession: input2.registerSession,
29058
+ threadId: input2.threadId,
29059
+ executor: input2.executor,
29060
+ handle: input2.handle,
29061
+ ...input2.signal === void 0 ? {} : { signal: input2.signal },
29062
+ log: input2.log,
29063
+ forward: input2.emit,
29064
+ ...input2.afterStart === void 0 ? {} : { afterStart: input2.afterStart },
29065
+ session: (started) => {
29066
+ input2.beforeSession?.(started);
29067
+ return acpStartedSession({ ...input2.session, threadId: input2.threadId }, started);
29068
+ },
29069
+ booked: input2.booked,
29070
+ ...input2.afterRegister === void 0 ? {} : { afterRegister: input2.afterRegister }
29071
+ });
29072
+ }
29073
+ function openRequestedAcpThread(input2) {
29074
+ return openAcpThreadSession({
29075
+ registerSession: input2.registerSession,
29076
+ threadId: input2.threadId,
29077
+ executor: input2.executor,
29078
+ handle: input2.handle,
29079
+ ...input2.signal === void 0 ? {} : { signal: input2.signal },
29080
+ log: input2.log,
29081
+ emit: input2.emit,
29082
+ afterStart: (started) => applyRequestedAcpMode(input2.executor, {
29083
+ requestedNativeModeId: input2.requestedNativeModeId,
29084
+ started,
29085
+ resumed: input2.resumed,
29086
+ ...input2.signal === void 0 ? {} : { signal: input2.signal }
29087
+ }),
29088
+ session: input2.session,
29089
+ booked: input2.booked,
29090
+ ...input2.afterRegister === void 0 ? {} : { afterRegister: input2.afterRegister }
29091
+ });
29092
+ }
29093
+ function acpSessionModeToApply(requestedNativeModeId, startedModeId, isResuming) {
29094
+ return requestedNativeModeId !== void 0 && (isResuming || requestedNativeModeId !== startedModeId) ? requestedNativeModeId : void 0;
29095
+ }
29096
+ async function applyRequestedAcpMode(executor, input2) {
29097
+ const modeId = acpSessionModeToApply(
29098
+ input2.requestedNativeModeId,
29099
+ acpCurrentModeId(input2.started.sessionSetupResult),
29100
+ input2.resumed
29101
+ );
29102
+ if (modeId === void 0) return;
29103
+ await raceStartAbort(executor.setNativeMode(modeId), input2.signal);
29104
+ }
29105
+ function acpNotStartedProbeResult(outcome) {
29106
+ return {
29107
+ installed: false,
29108
+ version: null,
29109
+ readiness: outcome.readiness,
29110
+ auth: { status: "unknown" },
29111
+ ...outcome.detail === void 0 ? {} : { detail: outcome.detail }
29112
+ };
29113
+ }
29114
+ function acpFailedProbeResult(outcome, auth) {
29115
+ return {
29116
+ installed: true,
29117
+ version: outcome.version,
29118
+ readiness: "error",
29119
+ auth,
29120
+ ...outcome.detail === void 0 ? {} : { detail: outcome.detail }
29121
+ };
29122
+ }
29123
+
29124
+ // ../../packages/ycodium-acp-executor/src/probe-session.ts
29125
+ var acpProbeFailureDetail = (error62) => (error62 instanceof Error ? error62.message : String(error62)).trim() || void 0;
29126
+
29127
+ // ../../packages/ycodium-acp-executor/src/probe.ts
29128
+ var CLI_VERSION_PATTERN = /(?<![\d.])(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)/;
29129
+ function parseCliVersion(output2) {
29130
+ return CLI_VERSION_PATTERN.exec(output2)?.[1] ?? null;
29131
+ }
29132
+ var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
29133
+
29134
+ // ../../packages/ycodium-instance-config/src/launchArgs.ts
29135
+ function tokenizeShellWords(value) {
28722
29136
  const input2 = value.trim();
28723
29137
  if (!input2) return [];
28724
29138
  const tokens = [];
@@ -28770,23 +29184,92 @@ function tokenizeLaunchArgs(value) {
28770
29184
  return tokens;
28771
29185
  }
28772
29186
 
29187
+ // ../../packages/ycodium-instance-config/src/instanceConfig.ts
29188
+ import { modelSelectionStringOption as modelSelectionStringOption2 } from "@ycodium-ai/plugin-api/executor";
29189
+ function isRecord7(value) {
29190
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29191
+ }
29192
+ function readString(value) {
29193
+ return typeof value === "string" ? value : "";
29194
+ }
29195
+ function readTrimmed(value) {
29196
+ return readString(value).trim();
29197
+ }
29198
+ function modelIdFromSelection(selection) {
29199
+ if (!isRecord7(selection)) return void 0;
29200
+ const model = selection["model"];
29201
+ return typeof model === "string" ? model.trim() || void 0 : void 0;
29202
+ }
29203
+ function readTurnSelection(selection, effortOptionId) {
29204
+ const requestedModelId = modelIdFromSelection(selection);
29205
+ const requestedEffort = modelSelectionStringOption2(selection, effortOptionId);
29206
+ return {
29207
+ ...requestedModelId === void 0 ? {} : { requestedModelId },
29208
+ ...requestedEffort === void 0 ? {} : { requestedEffort }
29209
+ };
29210
+ }
29211
+ function readEnvironment(value) {
29212
+ if (!Array.isArray(value)) return {};
29213
+ const env = {};
29214
+ for (const entry of value) {
29215
+ if (!isRecord7(entry)) continue;
29216
+ const name = readTrimmed(entry["name"]);
29217
+ if (name.length === 0) continue;
29218
+ env[name] = readString(entry["value"]);
29219
+ }
29220
+ return env;
29221
+ }
29222
+ function instanceSettings(config2) {
29223
+ if (!isRecord7(config2)) return {};
29224
+ return isRecord7(config2["config"]) ? config2["config"] : config2;
29225
+ }
29226
+ function readInstanceEnvelope(config2) {
29227
+ const envelope = isRecord7(config2) ? config2 : {};
29228
+ const settings = instanceSettings(config2);
29229
+ return {
29230
+ settings,
29231
+ settingOrEnvelope: (key) => readTrimmed(settings[key]) || readTrimmed(envelope[key]),
29232
+ environment: readEnvironment(envelope["environment"]),
29233
+ envelopeDriver: readTrimmed(envelope["driver"]) || void 0
29234
+ };
29235
+ }
29236
+ function readLaunchInstanceRecipe(config2, defaultLaunchArgs = "") {
29237
+ const envelope = readInstanceEnvelope(config2);
29238
+ return {
29239
+ binaryPath: readTrimmed(envelope.settings["binaryPath"]),
29240
+ launchArgs: readString(envelope.settings["launchArgs"]) || defaultLaunchArgs,
29241
+ homePath: envelope.settingOrEnvelope("homePath"),
29242
+ homeEnvVar: envelope.settingOrEnvelope("homeEnvVar"),
29243
+ environment: envelope.environment,
29244
+ envelopeDriver: envelope.envelopeDriver
29245
+ };
29246
+ }
29247
+
29248
+ // src/config.ts
29249
+ function parseKimiInstanceConfig(config2) {
29250
+ return {
29251
+ ...readLaunchInstanceRecipe(config2, KIMI_CARD.launchArgs),
29252
+ homeEnvVar: KIMI_CARD.homeEnvVar
29253
+ };
29254
+ }
29255
+
28773
29256
  // src/kimi.ts
28774
29257
  import * as NodeFS2 from "node:fs";
28775
- import * as NodePath3 from "node:path";
29258
+ import * as NodePath4 from "node:path";
28776
29259
  var KIMI_USER_INPUT_TITLES = /* @__PURE__ */ new Set(["AskUserQuestion", "ExitPlanMode"]);
28777
29260
  var KIMI_PLAN_ACTIONS = {
28778
29261
  plan_approve: "approve",
28779
29262
  plan_revise: "revise",
28780
29263
  plan_reject_and_exit: "stop"
28781
29264
  };
28782
- var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29265
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
28783
29266
  function questionTextFromContent(content) {
28784
29267
  if (!Array.isArray(content)) return "";
28785
29268
  const parts = [];
28786
29269
  for (const entry of content) {
28787
- if (!isRecord7(entry) || entry["type"] !== "content") continue;
29270
+ if (!isRecord8(entry) || entry["type"] !== "content") continue;
28788
29271
  const inner = entry["content"];
28789
- if (!isRecord7(inner) || inner["type"] !== "text") continue;
29272
+ if (!isRecord8(inner) || inner["type"] !== "text") continue;
28790
29273
  const text = inner["text"];
28791
29274
  if (typeof text === "string") parts.push(text);
28792
29275
  }
@@ -28838,7 +29321,7 @@ function parseKimiContextWindow(contents) {
28838
29321
  } catch {
28839
29322
  continue;
28840
29323
  }
28841
- if (!isRecord7(record2)) continue;
29324
+ if (!isRecord8(record2)) continue;
28842
29325
  const type = record2["type"];
28843
29326
  if (type === "token_counting.turn_recorded" || type === "token_counting.measured") {
28844
29327
  usedTokens = positiveInt(record2["tokens"]) ?? usedTokens;
@@ -28873,7 +29356,7 @@ function readTail(filePath) {
28873
29356
  }
28874
29357
  }
28875
29358
  function findKimiSessionWireLog(input2) {
28876
- const sessionsRoot = NodePath3.join(input2.homePath, SESSIONS_DIR);
29359
+ const sessionsRoot = NodePath4.join(input2.homePath, SESSIONS_DIR);
28877
29360
  let workspaces;
28878
29361
  try {
28879
29362
  workspaces = NodeFS2.readdirSync(sessionsRoot);
@@ -28881,7 +29364,7 @@ function findKimiSessionWireLog(input2) {
28881
29364
  return void 0;
28882
29365
  }
28883
29366
  for (const workspace of workspaces) {
28884
- const candidate = NodePath3.join(
29367
+ const candidate = NodePath4.join(
28885
29368
  sessionsRoot,
28886
29369
  workspace,
28887
29370
  input2.acpSessionId,
@@ -28901,19 +29384,71 @@ function readKimiContextWindow(input2) {
28901
29384
 
28902
29385
  // src/kimiQuota.ts
28903
29386
  import * as NodeFS4 from "node:fs";
28904
- import * as NodeOS3 from "node:os";
28905
- import * as NodePath5 from "node:path";
28906
- import {
28907
- parseRetryAfterMs
28908
- } from "@ycodium-ai/plugin-api/usage";
29387
+ import * as NodeOS5 from "node:os";
29388
+ import * as NodePath6 from "node:path";
29389
+ import "@ycodium-ai/plugin-api/usage";
29390
+
29391
+ // ../../packages/ycodium-credential-account/src/quotaRequest.ts
29392
+ import { parseRetryAfterMs } from "@ycodium-ai/plugin-api/usage";
29393
+
29394
+ // ../../packages/ycodium-credential-account/src/credentialAccount.ts
29395
+ var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29396
+
29397
+ // ../../packages/ycodium-credential-account/src/quotaRequest.ts
29398
+ async function requestQuotaJson(input2) {
29399
+ let response;
29400
+ try {
29401
+ response = await input2.fetch(input2.url, {
29402
+ headers: input2.headers,
29403
+ signal: AbortSignal.any([
29404
+ ...input2.signal === void 0 ? [] : [input2.signal],
29405
+ AbortSignal.timeout(input2.timeoutMs)
29406
+ ])
29407
+ });
29408
+ } catch {
29409
+ return { status: "unavailable", reason: "unreachable" };
29410
+ }
29411
+ if (response.status === 401 || response.status === 403) {
29412
+ return { status: "unavailable", reason: "authRejected" };
29413
+ }
29414
+ if (response.status === 429) {
29415
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), input2.now());
29416
+ return {
29417
+ status: "unavailable",
29418
+ reason: "rateLimited",
29419
+ ...retryAfterMs === null ? {} : { retryAfterMs }
29420
+ };
29421
+ }
29422
+ if (!response.ok) return { status: "unavailable", reason: "unreachable" };
29423
+ let body;
29424
+ try {
29425
+ body = JSON.parse(await response.text());
29426
+ } catch {
29427
+ return { status: "unavailable", reason: "unreachable" };
29428
+ }
29429
+ if (!isRecord9(body)) return { status: "unavailable", reason: "unreachable" };
29430
+ return { body };
29431
+ }
29432
+
29433
+ // ../../packages/ycodium-credential-account/src/quotaJson.ts
29434
+ var asObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
29435
+ var asString3 = (value) => typeof value === "string" && value.length > 0 ? value : null;
29436
+ var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
29437
+ var parseJson = (raw) => {
29438
+ try {
29439
+ return JSON.parse(raw);
29440
+ } catch {
29441
+ return null;
29442
+ }
29443
+ };
28909
29444
 
28910
29445
  // src/kimiAccount.ts
28911
29446
  import * as NodeFS3 from "node:fs";
28912
- import * as NodeOS2 from "node:os";
28913
- import * as NodePath4 from "node:path";
29447
+ import * as NodeOS4 from "node:os";
29448
+ import * as NodePath5 from "node:path";
28914
29449
  function kimiCredentialsPath(resolvedHomePath) {
28915
- const home = resolvedHomePath.trim().length > 0 ? resolvedHomePath : NodePath4.join(NodeOS2.homedir(), ".kimi-code");
28916
- return NodePath4.join(home, "credentials", "kimi-code.json");
29450
+ const home = resolvedHomePath.trim().length > 0 ? resolvedHomePath : NodePath5.join(NodeOS4.homedir(), ".kimi-code");
29451
+ return NodePath5.join(home, "credentials", "kimi-code.json");
28917
29452
  }
28918
29453
  var nonEmptyString = (value) => typeof value === "string" && value.length > 0;
28919
29454
  function readKimiAuthState(resolvedHomePath) {
@@ -28940,9 +29475,6 @@ var KIMI_DEFAULT_BASE_URL = "https://api.kimi.com/coding/v1";
28940
29475
  var KIMI_USAGES_PATH = "/usages";
28941
29476
  var QUOTA_TIMEOUT_MS = 1e4;
28942
29477
  var TOKEN_EXPIRY_SKEW_MS = 3e4;
28943
- var asObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
28944
- var asString3 = (value) => typeof value === "string" && value.length > 0 ? value : null;
28945
- var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
28946
29478
  var asCount = (value) => {
28947
29479
  const direct = asNumber(value);
28948
29480
  if (direct !== null) return direct;
@@ -28951,13 +29483,6 @@ var asCount = (value) => {
28951
29483
  const parsed = Number(text);
28952
29484
  return Number.isFinite(parsed) ? parsed : null;
28953
29485
  };
28954
- var parseJson = (raw) => {
28955
- try {
28956
- return JSON.parse(raw);
28957
- } catch {
28958
- return null;
28959
- }
28960
- };
28961
29486
  var clampPercent = (value) => Math.min(100, Math.max(0, value));
28962
29487
  var expiryMs = (value) => {
28963
29488
  const raw = asNumber(value);
@@ -29084,12 +29609,12 @@ var kimiEffectiveHome = (resolvedHomePath, processEnvHome) => {
29084
29609
  var createKimiUsage = (input2) => {
29085
29610
  const now = input2.now ?? Date.now;
29086
29611
  const processEnv = input2.processEnv ?? process.env;
29087
- const home = input2.homePath.trim().length > 0 ? input2.homePath : NodePath5.join(NodeOS3.homedir(), ".kimi-code");
29612
+ const home = input2.homePath.trim().length > 0 ? input2.homePath : NodePath6.join(NodeOS5.homedir(), ".kimi-code");
29088
29613
  const credentialsPath = kimiCredentialsPath(input2.homePath);
29089
29614
  const readQuota = async (request) => {
29090
29615
  let configToml = null;
29091
29616
  try {
29092
- configToml = NodeFS4.readFileSync(NodePath5.join(home, "config.toml"), "utf8");
29617
+ configToml = NodeFS4.readFileSync(NodePath6.join(home, "config.toml"), "utf8");
29093
29618
  } catch (error62) {
29094
29619
  if (error62.code !== "ENOENT") {
29095
29620
  return { status: "unavailable", reason: "unreachable" };
@@ -29107,37 +29632,16 @@ var createKimiUsage = (input2) => {
29107
29632
  token = null;
29108
29633
  }
29109
29634
  if (token === null) return { status: "unavailable", reason: "missingCredentials" };
29110
- let response;
29111
- try {
29112
- response = await input2.fetch(endpoint.usagesUrl, {
29113
- headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
29114
- signal: AbortSignal.any([
29115
- ...request.signal === void 0 ? [] : [request.signal],
29116
- AbortSignal.timeout(QUOTA_TIMEOUT_MS)
29117
- ])
29118
- });
29119
- } catch {
29120
- return { status: "unavailable", reason: "unreachable" };
29121
- }
29122
- if (response.status === 401 || response.status === 403) {
29123
- return { status: "unavailable", reason: "authRejected" };
29124
- }
29125
- if (response.status === 429) {
29126
- const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), now());
29127
- return {
29128
- status: "unavailable",
29129
- reason: "rateLimited",
29130
- ...retryAfterMs === null ? {} : { retryAfterMs }
29131
- };
29132
- }
29133
- if (!response.ok) return { status: "unavailable", reason: "unreachable" };
29134
- let body;
29135
- try {
29136
- body = parseJson(await response.text());
29137
- } catch {
29138
- return { status: "unavailable", reason: "unreachable" };
29139
- }
29140
- if (asObject(body) === null) return { status: "unavailable", reason: "unreachable" };
29635
+ const answer = await requestQuotaJson({
29636
+ fetch: input2.fetch,
29637
+ url: endpoint.usagesUrl,
29638
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
29639
+ ...request.signal === void 0 ? {} : { signal: request.signal },
29640
+ timeoutMs: QUOTA_TIMEOUT_MS,
29641
+ now
29642
+ });
29643
+ if (!("body" in answer)) return answer;
29644
+ const { body } = answer;
29141
29645
  const plan = kimiPlanName(body);
29142
29646
  return {
29143
29647
  status: "available",
@@ -29152,11 +29656,11 @@ var createKimiUsage = (input2) => {
29152
29656
 
29153
29657
  // src/kimiTokens.ts
29154
29658
  import * as NodeFS5 from "node:fs";
29155
- import * as NodeOS4 from "node:os";
29156
- import * as NodePath6 from "node:path";
29659
+ import * as NodeOS6 from "node:os";
29660
+ import * as NodePath7 from "node:path";
29157
29661
  var MTIME_SLACK_MS = 36 * 60 * 60 * 1e3;
29158
29662
  var GUARD_LENGTH = 64;
29159
- var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29663
+ var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29160
29664
  var count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
29161
29665
  var parseKimiUsageLine = (line) => {
29162
29666
  if (!line.includes('"usage.record"')) return void 0;
@@ -29166,11 +29670,11 @@ var parseKimiUsageLine = (line) => {
29166
29670
  } catch {
29167
29671
  return "malformed";
29168
29672
  }
29169
- if (!isRecord8(parsed) || parsed["type"] !== "usage.record") return void 0;
29673
+ if (!isRecord10(parsed) || parsed["type"] !== "usage.record") return void 0;
29170
29674
  const usage = parsed["usage"];
29171
29675
  const model = typeof parsed["model"] === "string" ? parsed["model"].trim() : "";
29172
29676
  const timeMs = parsed["time"];
29173
- if (!isRecord8(usage) || model.length === 0 || typeof timeMs !== "number" || !Number.isFinite(timeMs)) {
29677
+ if (!isRecord10(usage) || model.length === 0 || typeof timeMs !== "number" || !Number.isFinite(timeMs)) {
29174
29678
  return "malformed";
29175
29679
  }
29176
29680
  const totals = {
@@ -29198,10 +29702,10 @@ var readDirs = (dir) => {
29198
29702
  var listWireLogs = (sessionsRoot) => {
29199
29703
  const found = [];
29200
29704
  for (const workspace of readDirs(sessionsRoot)) {
29201
- for (const session of readDirs(NodePath6.join(sessionsRoot, workspace))) {
29202
- const agentsDir = NodePath6.join(sessionsRoot, workspace, session, "agents");
29705
+ for (const session of readDirs(NodePath7.join(sessionsRoot, workspace))) {
29706
+ const agentsDir = NodePath7.join(sessionsRoot, workspace, session, "agents");
29203
29707
  for (const agent of readDirs(agentsDir)) {
29204
- found.push({ file: NodePath6.join(agentsDir, agent, "wire.jsonl"), sessionId: session });
29708
+ found.push({ file: NodePath7.join(agentsDir, agent, "wire.jsonl"), sessionId: session });
29205
29709
  }
29206
29710
  }
29207
29711
  }
@@ -29225,8 +29729,8 @@ var readRange = (file2, from, to) => {
29225
29729
  };
29226
29730
  var guardOf = (file2, size) => readRange(file2, 0, Math.min(size, GUARD_LENGTH)).toString("base64");
29227
29731
  var createKimiTokenReader = (input2) => {
29228
- const home = input2.homePath.trim().length > 0 ? NodePath6.resolve(input2.homePath) : NodePath6.join(NodeOS4.homedir(), ".kimi-code");
29229
- const sessionsRoot = NodePath6.join(home, "sessions");
29732
+ const home = input2.homePath.trim().length > 0 ? NodePath7.resolve(input2.homePath) : NodePath7.join(NodeOS6.homedir(), ".kimi-code");
29733
+ const sessionsRoot = NodePath7.join(home, "sessions");
29230
29734
  const memos = /* @__PURE__ */ new Map();
29231
29735
  const refresh = (file2, size) => {
29232
29736
  const guard = guardOf(file2, size);
@@ -29332,13 +29836,12 @@ import {
29332
29836
 
29333
29837
  // src/probeModels.ts
29334
29838
  var ACP_EFFORT_OPTION_ID = "reasoning";
29335
- var probeFailureDetail = (error62) => (error62 instanceof Error ? error62.message : String(error62)).trim() || void 0;
29336
29839
 
29337
29840
  // src/kimiModels.ts
29338
29841
  var PROBE_TIMEOUT_MS = 15e3;
29339
29842
  var MAX_OUTPUT_BYTES = 1024 * 1024;
29340
29843
  var KIMI_MODEL_LIST_ARGS = ["provider", "list", "--json"];
29341
- function isRecord9(value) {
29844
+ function isRecord11(value) {
29342
29845
  return typeof value === "object" && value !== null && !Array.isArray(value);
29343
29846
  }
29344
29847
  function asString4(value) {
@@ -29376,13 +29879,13 @@ function kimiProbeModels(stdout) {
29376
29879
  } catch {
29377
29880
  return void 0;
29378
29881
  }
29379
- if (!isRecord9(parsed)) return void 0;
29882
+ if (!isRecord11(parsed)) return void 0;
29380
29883
  const models = parsed["models"];
29381
- if (!isRecord9(models)) return void 0;
29884
+ if (!isRecord11(models)) return void 0;
29382
29885
  const out = [];
29383
29886
  for (const [slug, entry] of Object.entries(models)) {
29384
29887
  const trimmed2 = slug.trim();
29385
- if (trimmed2.length === 0 || !isRecord9(entry)) continue;
29888
+ if (trimmed2.length === 0 || !isRecord11(entry)) continue;
29386
29889
  const name = asString4(entry["displayName"]);
29387
29890
  const contextWindow = positiveInt2(entry["maxContextSize"]);
29388
29891
  const effort = kimiEffortDescriptor(entry);
@@ -29437,7 +29940,7 @@ async function probeKimiModels(input2) {
29437
29940
  if (error62 instanceof ExecutorSpawnRefusedError || error62 instanceof ExecutorSpawnAbortedError || error62 instanceof OperationCleanupError || input2.signal?.aborted)
29438
29941
  throw error62;
29439
29942
  if (!spawned) return { kind: "not-started", ...describeExecutorSpawnFailure(error62) };
29440
- return { kind: "failed", detail: probeFailureDetail(error62) };
29943
+ return { kind: "failed", detail: acpProbeFailureDetail(error62) };
29441
29944
  }
29442
29945
  }
29443
29946
  async function probeKimiVersion(input2) {
@@ -29552,9 +30055,6 @@ function acpRuntimeModeAutoApproves(runtimeMode, toolKind, toolName, nativeMode
29552
30055
  return false;
29553
30056
  }
29554
30057
  }
29555
- function acpSessionModeToApply(requestedNativeModeId, startedModeId, isResuming) {
29556
- return requestedNativeModeId !== void 0 && (isResuming || requestedNativeModeId !== startedModeId) ? requestedNativeModeId : void 0;
29557
- }
29558
30058
 
29559
30059
  // src/subagents.ts
29560
30060
  var SUBAGENT_TITLE = "Kimi subagent";
@@ -29563,7 +30063,7 @@ var FOREGROUND_ENDED_DESCRIPTION = "Turn ended before Kimi reported this agent's
29563
30063
  var BACKGROUND_ENDED_DESCRIPTION = "Running in the background. Kimi does not report when it finishes.";
29564
30064
  var SINGLE_TITLE = /^Launching (background )?(\S+) agent: ([\s\S]*)$/u;
29565
30065
  var SWARM_TITLE_PREFIX = "Launching agent swarm: ";
29566
- var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30066
+ var isRecord12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29567
30067
  var trimmed = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
29568
30068
  function classify(input2) {
29569
30069
  if (input2.kind !== void 0 && input2.kind !== "other") return void 0;
@@ -29577,7 +30077,7 @@ function requestedModel(value) {
29577
30077
  return model === "primary" ? void 0 : model;
29578
30078
  }
29579
30079
  function describe3(kind, input2, previous) {
29580
- const raw = isRecord10(input2.rawInput) ? input2.rawInput : {};
30080
+ const raw = isRecord12(input2.rawInput) ? input2.rawInput : {};
29581
30081
  if (kind === "swarm") {
29582
30082
  const fromTitle = input2.title?.startsWith(SWARM_TITLE_PREFIX) ? trimmed(input2.title.slice(SWARM_TITLE_PREFIX.length)) : void 0;
29583
30083
  return {
@@ -29678,7 +30178,7 @@ var kimiToolSubagents = {
29678
30178
  announce: "started",
29679
30179
  resolve: (call, kind) => resolveOutcome(call, asKind(kind)),
29680
30180
  resumes: (call, kind) => {
29681
- if (asKind(kind) !== "subagent" || !isRecord10(call.rawInput)) return void 0;
30181
+ if (asKind(kind) !== "subagent" || !isRecord12(call.rawInput)) return void 0;
29682
30182
  return trimmed(call.rawInput["resume"]);
29683
30183
  },
29684
30184
  endNote: ({ background }) => background ? { description: BACKGROUND_ENDED_DESCRIPTION, timelineBypass: true } : { description: FOREGROUND_ENDED_DESCRIPTION }
@@ -29712,40 +30212,6 @@ var kimiPermissionStatement = ({
29712
30212
  // src/kimiInstance.ts
29713
30213
  var RESUME_SCHEMA_VERSION = 1;
29714
30214
  var CLIENT_INFO = { name: "ycodium-agent-kimi", version: "0.1.0" };
29715
- var yieldTick = () => new Promise((resolve4) => {
29716
- setImmediate(resolve4);
29717
- });
29718
- function expandHomePath(value) {
29719
- if (value === "~") return NodeOS5.homedir();
29720
- if (value.startsWith("~/") || value.startsWith("~\\")) {
29721
- return NodePath7.join(NodeOS5.homedir(), value.slice(2));
29722
- }
29723
- return value;
29724
- }
29725
- function modelIdFromSelection(selection) {
29726
- if (typeof selection !== "object" || selection === null || Array.isArray(selection)) {
29727
- return void 0;
29728
- }
29729
- const model = selection["model"];
29730
- return typeof model === "string" ? model.trim() || void 0 : void 0;
29731
- }
29732
- function buildSpawnEnv(recipe, configuredHomePath) {
29733
- const homePath = configuredHomePath.trim();
29734
- const homeEnvVar = recipe.homeEnvVar.trim();
29735
- const homeInjection = homePath.length > 0 && homeEnvVar.length > 0 ? { [homeEnvVar]: expandHomePath(homePath) } : {};
29736
- return mergeLaunchEnv({
29737
- accountHome: homeInjection,
29738
- instanceTable: recipe.environment
29739
- });
29740
- }
29741
- function nowIso() {
29742
- return (/* @__PURE__ */ new Date()).toISOString();
29743
- }
29744
- function kimiContinuationKey(recipe) {
29745
- const homePath = recipe.homePath.trim();
29746
- const resolvedHomePath = homePath.length > 0 ? NodePath7.resolve(expandHomePath(homePath)) : "";
29747
- return `kimiCode:home:${recipe.binaryPath.trim()}\0${resolvedHomePath}`;
29748
- }
29749
30215
  function resolveHomePath(recipe) {
29750
30216
  const envVar = recipe.homeEnvVar.trim();
29751
30217
  const fromEnvironment = envVar.length > 0 ? recipe.environment[envVar]?.trim() : void 0;
@@ -29764,41 +30230,23 @@ function kimiHooks(recipe) {
29764
30230
  readContextWindow: ({ sessionId }) => readKimiContextWindow({ homePath, acpSessionId: sessionId })
29765
30231
  };
29766
30232
  }
29767
- async function stopBooked(booked, processExit) {
29768
- await cleanupAcpSession({
29769
- executor: booked.executor,
29770
- stopProcess: () => booked.handle.kill("SIGTERM"),
29771
- forwarding: booked.forwarding,
29772
- processExit
29773
- });
29774
- }
29775
30233
  var createKimiInstance = (config2, host) => {
29776
30234
  const recipe = parseKimiInstanceConfig(config2);
29777
- const threads = /* @__PURE__ */ new Map();
29778
30235
  let disposed = false;
29779
- const usageHome = kimiEffectiveHome(resolveHomePath(recipe), process.env[recipe.homeEnvVar]);
29780
- const { requireThread, registerSession, stopSession, stopAll } = createAcpSessionRegistry(
29781
- threads,
29782
- stopBooked,
29783
- host.log
29784
- );
29785
- const disposeOnce = createRetryableClose(async () => {
29786
- await stopAll();
30236
+ const { table, threads, requireThread, registerSession, stopSession, disposeOnce, threadOps } = bindAcpInstanceThreads({
30237
+ log: host.log,
30238
+ isDisposed: () => disposed,
30239
+ turnSelection: (selection) => readTurnSelection(selection, ACP_EFFORT_OPTION_ID)
29787
30240
  });
30241
+ const usageHome = kimiEffectiveHome(resolveHomePath(recipe), process.env[recipe.homeEnvVar]);
29788
30242
  const instance = {
29789
30243
  probe: async (signal) => {
29790
30244
  if (recipe.binaryPath.length === 0) {
29791
- return {
29792
- installed: false,
29793
- version: null,
29794
- readiness: "not-installed",
29795
- auth: { status: "unknown" },
29796
- detail: "Kimi Code program path is not configured"
29797
- };
30245
+ return acpProgramNotConfigured("Kimi Code program path is not configured");
29798
30246
  }
29799
30247
  if (signal?.aborted) throw new Error("aborted");
29800
- const env = buildSpawnEnv(recipe, recipe.homePath);
29801
- const outcome = await raceAbort(
30248
+ const env = homeLaunchEnv(recipe, recipe.homePath);
30249
+ const outcome = await raceAbort2(
29802
30250
  probeKimi({ recipe, host, env, ...signal === void 0 ? {} : { signal } }),
29803
30251
  signal
29804
30252
  );
@@ -29814,21 +30262,9 @@ var createKimiInstance = (config2, host) => {
29814
30262
  };
29815
30263
  switch (outcome.kind) {
29816
30264
  case "not-started":
29817
- return {
29818
- installed: false,
29819
- version: null,
29820
- readiness: outcome.readiness,
29821
- auth: { status: "unknown" },
29822
- ...outcome.detail === void 0 ? {} : { detail: outcome.detail }
29823
- };
30265
+ return acpNotStartedProbeResult(outcome);
29824
30266
  case "failed":
29825
- return {
29826
- installed: true,
29827
- version: outcome.version,
29828
- readiness: "error",
29829
- auth: auth(),
29830
- ...outcome.detail === void 0 ? {} : { detail: outcome.detail }
29831
- };
30267
+ return acpFailedProbeResult(outcome, auth());
29832
30268
  case "auth-required":
29833
30269
  return {
29834
30270
  installed: true,
@@ -29850,7 +30286,7 @@ var createKimiInstance = (config2, host) => {
29850
30286
  readCliVersion: (signal) => recipe.binaryPath.length === 0 ? Promise.resolve(null) : probeKimiVersion({
29851
30287
  recipe,
29852
30288
  host,
29853
- env: buildSpawnEnv(recipe, recipe.homePath),
30289
+ env: homeLaunchEnv(recipe, recipe.homePath),
29854
30290
  ...signal === void 0 ? {} : { signal }
29855
30291
  }),
29856
30292
  // 暂不处理 input.readOnlyDirectories(有意为之):kimi 经共享的 ycodium-acp-executor 起会话,
@@ -29863,13 +30299,8 @@ var createKimiInstance = (config2, host) => {
29863
30299
  }
29864
30300
  const cwd = input2.cwd ?? host.workspacePath(input2.threadId);
29865
30301
  if (cwd.trim() === "") throw new Error("workspace path missing");
29866
- const existing = threads.get(input2.threadId);
29867
- if (existing !== void 0) {
29868
- await stopSession(input2.threadId, existing);
29869
- if (disposed) throw new Error("instance disposed");
29870
- throwIfStartAborted(signal);
29871
- }
29872
- const env = buildSpawnEnv(recipe, recipe.homePath);
30302
+ await stopExistingAcpThread(table, input2.threadId, () => disposed, signal);
30303
+ const env = homeLaunchEnv(recipe, recipe.homePath);
29873
30304
  const toolTimeouts = (input2.mcpServers ?? []).flatMap(
29874
30305
  (server) => server.toolTimeoutSeconds === void 0 ? [] : [server.toolTimeoutSeconds]
29875
30306
  );
@@ -29877,21 +30308,24 @@ var createKimiInstance = (config2, host) => {
29877
30308
  env.KIMI_MCP_TOOL_TIMEOUT_MS = String(Math.max(...toolTimeouts) * 1e3);
29878
30309
  const spawned = {
29879
30310
  program: recipe.binaryPath,
29880
- args: tokenizeLaunchArgs(recipe.launchArgs),
30311
+ args: tokenizeShellWords(recipe.launchArgs),
29881
30312
  cwd
29882
30313
  };
29883
- const handle = await host.process.spawn({
29884
- ...spawned,
29885
- owner: { bindingId: host.bindingId },
29886
- ...Object.keys(env).length > 0 ? { env } : {}
29887
- });
29888
- const { readable, writable, stderrTail } = nodeStreamsFromHandle(handle);
29889
- const resume = input2.discardResumeCursor === true ? void 0 : parseAcpResumeCursor(input2.resumeCursor, RESUME_SCHEMA_VERSION);
29890
- const requestedModelId = modelIdFromSelection(input2.modelSelection);
29891
- const requestedEffort = modelSelectionStringOption(
29892
- input2.modelSelection,
29893
- ACP_EFFORT_OPTION_ID
30314
+ const handle = await host.process.spawn(
30315
+ acpOwnedSpawnSpec({
30316
+ ...spawned,
30317
+ bindingId: host.bindingId,
30318
+ env
30319
+ })
29894
30320
  );
30321
+ const { readable, writable, stderrTail, resume, requestedModelId, requestedEffort } = acpLaunchFromHandle({
30322
+ handle,
30323
+ start: input2,
30324
+ modelSelection: input2.modelSelection,
30325
+ resumeSchemaVersion: RESUME_SCHEMA_VERSION,
30326
+ effortOptionId: ACP_EFFORT_OPTION_ID,
30327
+ modelIdFromSelection
30328
+ });
29895
30329
  const hooks = kimiHooks(recipe);
29896
30330
  const autoApprove = (request) => {
29897
30331
  const session = threads.get(input2.threadId)?.session ?? input2;
@@ -29925,112 +30359,37 @@ var createKimiInstance = (config2, host) => {
29925
30359
  // 不重放历史(0.31.1 真机实测上下文还在);session/load 要把整段历史重放一遍,会话越长越慢。
29926
30360
  resumeMethod: "session/resume",
29927
30361
  autoApprove,
29928
- // 内置编排那一条排第一,后面跟用户在插件中心配的;缺了这一栏,
29929
- // `mcp__ycodium__*` 整套工具(浏览器等)在这只手的会话里都不存在。
29930
- // http / sse 由执行器按握手里的 `mcpCapabilities` 再筛。
29931
- mcpServers: toAcpMcpServers(input2.mcpServers),
29932
- ...resume === void 0 ? {} : { resumeSessionId: resume.sessionId }
30362
+ // 内置编排在前、插件中心配的在后(缺了就没有 `mcp__ycodium__*`);http / sse 由执行器按握手再筛。
30363
+ // 空数组也传。
30364
+ ...acpLaunchMcpFields({
30365
+ mcpServers: input2.mcpServers,
30366
+ resumeSessionId: resume?.sessionId
30367
+ })
29933
30368
  });
29934
- const forwarding = (async () => {
29935
- for await (const event of executor.events) input2.events.emit(event);
29936
- })();
29937
- try {
29938
- throwIfStartAborted(signal);
29939
- const started = await raceStartAbort(executor.start(), signal);
29940
- const modeToApply = acpSessionModeToApply(
29941
- input2.nativeModeId,
29942
- acpCurrentModeId(started.sessionSetupResult),
29943
- resume !== void 0
29944
- );
29945
- if (modeToApply !== void 0) {
29946
- await raceStartAbort(executor.setNativeMode(modeToApply), signal);
29947
- }
29948
- await yieldTick();
29949
- throwIfStartAborted(signal);
29950
- const createdAt = nowIso();
29951
- const resumeCursor = {
29952
- schemaVersion: RESUME_SCHEMA_VERSION,
29953
- sessionId: started.sessionId
29954
- };
29955
- const session = {
30369
+ return openRequestedAcpThread({
30370
+ registerSession,
30371
+ threadId: input2.threadId,
30372
+ executor,
30373
+ handle,
30374
+ signal,
30375
+ log: host.log,
30376
+ emit: (event) => input2.events.emit(event),
30377
+ requestedNativeModeId: input2.nativeModeId,
30378
+ resumed: resume !== void 0,
30379
+ session: {
29956
30380
  provider: KIMI_DRIVER_KIND,
29957
30381
  providerInstanceId: host.instanceId,
29958
- status: "idle",
29959
30382
  runtimeMode: input2.runtimeMode,
29960
- ...input2.nativeModeId === void 0 ? {} : { nativeModeId: input2.nativeModeId },
30383
+ nativeModeId: input2.nativeModeId,
29961
30384
  cwd,
29962
- threadId: input2.threadId,
29963
- createdAt,
29964
- updatedAt: createdAt,
29965
- resumeCursor,
29966
- ...started.modelId === void 0 ? {} : {
29967
- model: started.modelId,
29968
- // agent 在握手里报的才是读回的;切型号走 session/set_model 时回包不带型号,那只是请求值。
29969
- modelSource: started.modelReported ? "reported" : "echo"
29970
- },
29971
- ...input2.bindingGeneration === void 0 ? {} : { bindingGeneration: input2.bindingGeneration }
29972
- };
29973
- registerSession(input2.threadId, {
29974
- session,
29975
- turns: [],
29976
- executor,
29977
- handle,
29978
- forwarding,
29979
- spawned
29980
- });
29981
- host.log.info("session started", {
29982
- threadId: input2.threadId,
29983
- sessionId: started.sessionId
29984
- });
29985
- return session;
29986
- } catch (error62) {
29987
- await cleanupAcpStartup({
29988
- executor,
29989
- stopProcess: () => handle.kill("SIGTERM"),
29990
- forwarding,
29991
- log: host.log,
29992
- threadId: input2.threadId
29993
- });
29994
- throw error62;
29995
- }
29996
- },
29997
- sendTurn: async (input2, signal) => {
29998
- if (disposed) throw new Error("instance disposed");
29999
- const booked = requireThread(input2.threadId);
30000
- if (signal?.aborted) throw new Error("aborted");
30001
- const onAbort = () => {
30002
- void booked.executor.cancel(input2.expectedTurnId).catch(() => void 0);
30003
- };
30004
- signal?.addEventListener("abort", onAbort);
30005
- try {
30006
- const requestedModelId = modelIdFromSelection(input2.modelSelection);
30007
- const requestedEffort = modelSelectionStringOption(
30008
- input2.modelSelection,
30009
- ACP_EFFORT_OPTION_ID
30010
- );
30011
- const turn = await dispatchAcpPrompt(booked.executor, {
30012
- text: input2.input ?? "",
30013
- expectedActiveTurnId: input2.expectedTurnId,
30014
- ...requestedModelId === void 0 ? {} : { requestedModelId },
30015
- ...requestedEffort === void 0 ? {} : { requestedEffort }
30016
- });
30017
- booked.turns.push({ id: turn.turnId, items: [] });
30018
- return {
30019
- threadId: input2.threadId,
30020
- turnId: turn.turnId,
30021
- ...booked.session.resumeCursor === void 0 ? {} : { resumeCursor: booked.session.resumeCursor }
30022
- };
30023
- } finally {
30024
- signal?.removeEventListener("abort", onAbort);
30025
- }
30026
- },
30027
- interruptTurn: async (threadId, turnId) => {
30028
- const booked = threads.get(threadId);
30029
- if (booked === void 0 || booked.closing) return;
30030
- host.log.info("interrupt turn", { threadId, turnId });
30031
- await booked.executor.cancel(turnId);
30032
- await yieldTick();
30385
+ bindingGeneration: input2.bindingGeneration,
30386
+ resumeSchemaVersion: RESUME_SCHEMA_VERSION
30387
+ },
30388
+ booked: (base) => ({ ...base, spawned })
30389
+ });
30033
30390
  },
30391
+ sendTurn: threadOps.sendTurn,
30392
+ interruptTurn: threadOps.interruptTurn,
30034
30393
  openCommandProcesses: async (threadId) => {
30035
30394
  const booked = threads.get(threadId);
30036
30395
  if (booked === void 0) return void 0;
@@ -30040,47 +30399,12 @@ var createKimiInstance = (config2, host) => {
30040
30399
  openToolCalls: booked.executor.openToolCalls()
30041
30400
  });
30042
30401
  },
30043
- respondToRequest: async (threadId, requestId, decision, reason) => {
30044
- const booked = requireThread(threadId);
30045
- await booked.executor.respondToRequest(
30046
- requestId,
30047
- decision === "allow" ? "accept" : "decline",
30048
- reason
30049
- );
30050
- },
30051
- respondToUserInput: async (threadId, requestId, answers) => {
30052
- const booked = requireThread(threadId);
30053
- await booked.executor.respondToUserInput(requestId, answers);
30054
- },
30055
- /**
30056
- * 切这只手自报的审批档。`nativeModeId` 是它自己报的 id(探测时原样上报的那些),
30057
- * 一路不翻译成宿主四档。
30058
- *
30059
- * 这是 `setRuntimeMode` 做不到的那一半:那个只改插件自己的会话记录,CLI 收不到
30060
- * (`runtime-mode-never-reaches-cli` 记的那族缺陷)。
30061
- */
30062
- setNativeMode: async (threadId, nativeModeId) => {
30063
- const booked = requireThread(threadId);
30064
- await booked.executor.setNativeMode(nativeModeId);
30065
- booked.session = {
30066
- ...booked.session,
30067
- nativeModeId,
30068
- updatedAt: nowIso()
30069
- };
30070
- },
30071
- setRuntimeMode: async (threadId, runtimeMode) => {
30072
- const booked = requireThread(threadId);
30073
- booked.session = {
30074
- ...booked.session,
30075
- runtimeMode,
30076
- updatedAt: nowIso()
30077
- };
30078
- },
30402
+ respondToRequest: threadOps.respondToRequest,
30403
+ respondToUserInput: threadOps.respondToUserInput,
30404
+ setNativeMode: threadOps.setNativeMode,
30405
+ setRuntimeMode: threadOps.setRuntimeMode,
30079
30406
  stopSession: (threadId) => stopSession(threadId),
30080
- readThread: async (threadId) => {
30081
- const booked = requireThread(threadId);
30082
- return { threadId, turns: booked.turns };
30083
- },
30407
+ readThread: threadOps.readThread,
30084
30408
  // 额度与 token 都读这个实例自己的账号目录(与它的 CLI 同一个)。
30085
30409
  usage: {
30086
30410
  ...createKimiUsage({
@@ -30090,7 +30414,7 @@ var createKimiInstance = (config2, host) => {
30090
30414
  }),
30091
30415
  ...createKimiTokenReader({ homePath: usageHome })
30092
30416
  },
30093
- continuationKey: kimiContinuationKey(recipe),
30417
+ continuationKey: homeContinuationKey("kimiCode", recipe),
30094
30418
  dispose: () => {
30095
30419
  disposed = true;
30096
30420
  return disposeOnce();
@@ -30127,7 +30451,7 @@ var index_default = definePlugin({
30127
30451
  "KIMI_CODE_HOME",
30128
30452
  request,
30129
30453
  process.env,
30130
- (value) => value === void 0 ? NodePath8.join(NodeOS6.homedir(), ".kimi-code") : NodePath8.resolve(expandHomePath(value))
30454
+ (value) => value === void 0 ? NodePath8.join(NodeOS7.homedir(), ".kimi-code") : NodePath8.resolve(expandHomePath(value))
30131
30455
  )
30132
30456
  };
30133
30457
  }