@ycodium-ai/agent-kimi 0.2.5557 → 0.2.5634

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
@@ -8,21 +8,48 @@ 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 = 175;
11
+ var PLUGIN_API_VERSION = 178;
12
12
 
13
13
  // src/index.ts
14
14
  import * as NodeOS7 from "node:os";
15
- import * as NodePath9 from "node:path";
16
- import {
17
- EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
18
- executorHomeEffectiveValue,
19
- readExecutorEffectiveRequest
20
- } from "@ycodium-ai/plugin-api/executor";
15
+ import * as NodePath10 from "node:path";
21
16
 
22
17
  // ../../packages/ycodium-instance-config/src/homePath.ts
18
+ import * as NodeCrypto from "node:crypto";
23
19
  import * as NodeOS from "node:os";
24
20
  import * as NodePath from "node:path";
25
- import { mergeLaunchEnv } from "@ycodium-ai/plugin-api/executor";
21
+ import {
22
+ EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
23
+ executorHomeEffectiveValue,
24
+ readExecutorEffectiveRequest,
25
+ mergeLaunchEnv
26
+ } from "@ycodium-ai/plugin-api/executor";
27
+ function instanceAccountDirectory(pluginDataDir, instanceId) {
28
+ return NodePath.join(
29
+ pluginDataDir,
30
+ "profiles",
31
+ NodeCrypto.createHash("sha256").update(instanceId).digest("hex")
32
+ );
33
+ }
34
+ function privateHomeFor(config2, env, variable, dataDir, id) {
35
+ if (config2.privateAccount !== true || typeof config2.homePath === "string" && config2.homePath.trim() || env[variable]?.trim() || !id)
36
+ return void 0;
37
+ if (!dataDir) throw new Error("Executor plugin data directory unavailable");
38
+ return instanceAccountDirectory(dataDir, id);
39
+ }
40
+ function applyPrivateAccountHome(recipe, settings, variable, dataDir, id, credentialVariables) {
41
+ const home = privateHomeFor(
42
+ { ...settings, homePath: recipe.homePath },
43
+ recipe.environment,
44
+ variable,
45
+ dataDir,
46
+ id
47
+ );
48
+ if (!home) return { recipe, home };
49
+ const environment = { ...recipe.environment, [variable]: home };
50
+ for (const key of credentialVariables) environment[key] ??= "";
51
+ return { recipe: { ...recipe, homePath: home, environment }, home };
52
+ }
26
53
  function expandHomePath(value) {
27
54
  if (value === "~") return NodeOS.homedir();
28
55
  if (value.startsWith("~/") || value.startsWith("~\\")) {
@@ -41,35 +68,70 @@ function homeContinuationKey(kind, recipe) {
41
68
  const resolvedHomePath = homePath.length > 0 ? NodePath.resolve(expandHomePath(homePath)) : "";
42
69
  return `${kind}:home:${recipe.binaryPath.trim()}\0${resolvedHomePath}`;
43
70
  }
71
+ function registerEffectiveHomeCommand(ctx, homeEnvVar, resolve5, profileDataDir2) {
72
+ ctx.command({
73
+ name: "effectiveConfig",
74
+ description: "Settings form: the account directory an empty path resolves to on this machine.",
75
+ scope: "read",
76
+ payloadSchema: EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
77
+ handle: async (payload) => {
78
+ const req = readExecutorEffectiveRequest(payload);
79
+ if (profileDataDir2 && req.config.privateAccount === true && !req.instanceId && !req.environment[homeEnvVar]?.trim() && !req.config.homePath)
80
+ return {};
81
+ const home = profileDataDir2 && privateHomeFor(req.config, req.environment, homeEnvVar, profileDataDir2, req.instanceId);
82
+ return {
83
+ homePath: home ? { value: home, detailKey: "form.effective.default" } : executorHomeEffectiveValue(homeEnvVar, req, process.env, resolve5)
84
+ };
85
+ }
86
+ });
87
+ }
44
88
 
45
89
  // ../../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
90
+ var executorEnvelopeFields = {
91
+ enabled: { type: "boolean" },
92
+ customModels: { type: "array" },
93
+ driver: { type: "string" },
94
+ config: { type: "object" },
95
+ environment: { type: "array" }
96
+ };
97
+ function executorProgramField(name, options = {}) {
98
+ return {
99
+ type: "string",
100
+ "x-ycodium-form": {
101
+ titleKey: `form.${name}.title`,
102
+ ...options.description === false ? {} : { descriptionKey: `form.${name}.description` },
103
+ ...options.placeholder === false ? {} : { placeholderKey: `form.${name}.placeholder` },
104
+ ...name === "binaryPath" ? { control: options.control ?? "executable-path" } : {},
105
+ ...name === "homePath" || options.machineLocal ? { machineLocal: true } : {}
106
+ }
52
107
  };
53
- if (binaryPath.machineLocal === true) binaryForm["machineLocal"] = true;
108
+ }
109
+ function programAndHomeConfigSchema(binaryPath) {
54
110
  return {
55
111
  type: "object",
56
- "x-ycodium-form-order": ["binaryPath", "homePath"],
112
+ ...binaryPath.privateAccountOption ? { "x-ycodium-new-instance-defaults": { privateAccount: true } } : {},
113
+ "x-ycodium-form-order": [
114
+ "binaryPath",
115
+ "homePath",
116
+ ...binaryPath.privateAccountOption ? ["privateAccount"] : []
117
+ ],
57
118
  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"
119
+ ...executorEnvelopeFields,
120
+ binaryPath: executorProgramField("binaryPath", {
121
+ control: binaryPath.control,
122
+ machineLocal: binaryPath.machineLocal === true
123
+ }),
124
+ homePath: executorProgramField("homePath"),
125
+ ...binaryPath.privateAccountOption ? {
126
+ privateAccount: {
127
+ type: "boolean",
128
+ default: false,
129
+ "x-ycodium-form": {
130
+ titleKey: "form.privateAccount.title",
131
+ descriptionKey: "form.privateAccount.description"
132
+ }
66
133
  }
67
- },
68
- enabled: { type: "boolean" },
69
- customModels: { type: "array" },
70
- driver: { type: "string" },
71
- config: { type: "object" },
72
- environment: { type: "array" }
134
+ } : {}
73
135
  },
74
136
  additionalProperties: true
75
137
  };
@@ -130,18 +192,118 @@ var KIMI_CARD = {
130
192
  },
131
193
  credentialSources: [],
132
194
  diagnostics: [],
133
- configSchema: programAndHomeConfigSchema({ control: "executable-path" }),
195
+ configSchema: programAndHomeConfigSchema({
196
+ control: "executable-path",
197
+ privateAccountOption: true
198
+ }),
134
199
  modelConnectivity: {
135
200
  dialects: [],
136
201
  acceptsExternalEndpoints: false
137
202
  }
138
203
  };
139
204
 
205
+ // ../../packages/ycodium-instance-config/src/instanceConfig.ts
206
+ import { modelSelectionStringOption } from "@ycodium-ai/plugin-api/executor";
207
+ function isRecord(value) {
208
+ return typeof value === "object" && value !== null && !Array.isArray(value);
209
+ }
210
+ function readString(value) {
211
+ return typeof value === "string" ? value : "";
212
+ }
213
+ function readTrimmed(value) {
214
+ return readString(value).trim();
215
+ }
216
+ function modelIdFromSelection(selection) {
217
+ if (!isRecord(selection)) return void 0;
218
+ const model = selection["model"];
219
+ return typeof model === "string" ? model.trim() || void 0 : void 0;
220
+ }
221
+ function readTurnSelection(selection, effortOptionId) {
222
+ const requestedModelId = modelIdFromSelection(selection);
223
+ const requestedEffort = modelSelectionStringOption(selection, effortOptionId);
224
+ return {
225
+ ...requestedModelId === void 0 ? {} : { requestedModelId },
226
+ ...requestedEffort === void 0 ? {} : { requestedEffort }
227
+ };
228
+ }
229
+ function readEnvironment(value) {
230
+ if (!Array.isArray(value)) return {};
231
+ const entries = [];
232
+ for (const entry of value) {
233
+ if (!isRecord(entry)) continue;
234
+ const name = readTrimmed(entry["name"]);
235
+ if (name.length === 0) continue;
236
+ entries.push([name, readString(entry["value"])]);
237
+ }
238
+ return Object.fromEntries(entries);
239
+ }
240
+ function instanceSettings(config2) {
241
+ if (!isRecord(config2)) return {};
242
+ return isRecord(config2["config"]) ? config2["config"] : config2;
243
+ }
244
+ function readInstanceEnvelope(config2) {
245
+ const envelope = isRecord(config2) ? config2 : {};
246
+ const settings = instanceSettings(config2);
247
+ return {
248
+ settings,
249
+ settingOrEnvelope: (key) => readTrimmed(settings[key]) || readTrimmed(envelope[key]),
250
+ environment: readEnvironment(envelope["environment"]),
251
+ envelopeDriver: readTrimmed(envelope["driver"]) || void 0
252
+ };
253
+ }
254
+ function readLaunchInstanceRecipe(config2, defaultLaunchArgs = "") {
255
+ const envelope = readInstanceEnvelope(config2);
256
+ return {
257
+ binaryPath: readTrimmed(envelope.settings["binaryPath"]),
258
+ launchArgs: readString(envelope.settings["launchArgs"]) || defaultLaunchArgs,
259
+ homePath: envelope.settingOrEnvelope("homePath"),
260
+ homeEnvVar: envelope.settingOrEnvelope("homeEnvVar"),
261
+ environment: envelope.environment,
262
+ envelopeDriver: envelope.envelopeDriver
263
+ };
264
+ }
265
+
266
+ // ../../packages/ycodium-jsonl-stream/src/sessionTranscript.ts
267
+ var SESSION_IMPORT_ACTIVITY_TEXT_LIMIT = 32e3;
268
+ function bounded(value, tail = false) {
269
+ if (value.length <= SESSION_IMPORT_ACTIVITY_TEXT_LIMIT) return { text: value, truncated: false };
270
+ const offset = tail ? value.length - SESSION_IMPORT_ACTIVITY_TEXT_LIMIT : SESSION_IMPORT_ACTIVITY_TEXT_LIMIT;
271
+ const character = value.charCodeAt(offset);
272
+ const previous = value.charCodeAt(offset - 1);
273
+ const splitPair = character >= 56320 && character <= 57343 && previous >= 55296 && previous <= 56319;
274
+ return {
275
+ text: tail ? value.slice(offset + (splitPair ? 1 : 0)) : value.slice(0, offset - (splitPair ? 1 : 0)),
276
+ truncated: true
277
+ };
278
+ }
279
+ function inputPayload(input2) {
280
+ if (input2 === void 0) return {};
281
+ const result = bounded(input2);
282
+ return { input: result.text, ...result.truncated ? { inputTruncated: true } : {} };
283
+ }
284
+ function outputPayload(output2) {
285
+ if (output2 === void 0) return {};
286
+ const result = bounded(output2, true);
287
+ return { output: result.text, ...result.truncated ? { outputTruncated: true } : {} };
288
+ }
289
+ function sessionReadFromImport(nativeSessionId, imported) {
290
+ return {
291
+ nativeSessionId,
292
+ model: imported.model,
293
+ resumeCursor: imported.resumeCursor,
294
+ messages: imported.messages.map(({ role, text: text2, createdAt }) => ({
295
+ role,
296
+ text: text2,
297
+ createdAt: Date.parse(createdAt)
298
+ }))
299
+ };
300
+ }
301
+
140
302
  // src/kimiInstance.ts
141
303
  import { raceAbort as raceAbort2 } from "@ycodium-ai/plugin-api/executor";
142
304
 
143
305
  // ../../packages/ycodium-acp-executor/src/executor.ts
144
- import * as NodeCrypto from "node:crypto";
306
+ import * as NodeCrypto2 from "node:crypto";
145
307
 
146
308
  // ../../packages/ycodium-acp-executor/src/approvals.ts
147
309
  function createApprovalGate(input2) {
@@ -277,7 +439,7 @@ var UnboundedEventStream = class {
277
439
  };
278
440
 
279
441
  // ../../packages/ycodium-acp-executor/src/config-options.ts
280
- function isRecord(value) {
442
+ function isRecord2(value) {
281
443
  return typeof value === "object" && value !== null && !Array.isArray(value);
282
444
  }
283
445
  function asString(value) {
@@ -296,7 +458,7 @@ function flattenChoices(rawOptions, currentValue) {
296
458
  const out = [];
297
459
  const seen = /* @__PURE__ */ new Set();
298
460
  const push = (entry) => {
299
- if (!isRecord(entry)) return;
461
+ if (!isRecord2(entry)) return;
300
462
  const value = asString(entry["value"]);
301
463
  if (value === void 0 || seen.has(value)) return;
302
464
  seen.add(value);
@@ -311,7 +473,7 @@ function flattenChoices(rawOptions, currentValue) {
311
473
  });
312
474
  };
313
475
  for (const entry of rawOptions) {
314
- if (isRecord(entry) && Array.isArray(entry["options"])) {
476
+ if (isRecord2(entry) && Array.isArray(entry["options"])) {
315
477
  for (const nested of entry["options"]) push(nested);
316
478
  continue;
317
479
  }
@@ -320,7 +482,7 @@ function flattenChoices(rawOptions, currentValue) {
320
482
  return out;
321
483
  }
322
484
  function isConfigOption(entry, configId) {
323
- return isRecord(entry) && asString(entry["id"])?.trim() === configId.trim();
485
+ return isRecord2(entry) && asString(entry["id"])?.trim() === configId.trim();
324
486
  }
325
487
  function findConfigOptionEntry(configOptions, configId) {
326
488
  return Array.isArray(configOptions) && configId.trim() !== "" ? configOptions.find(
@@ -335,7 +497,7 @@ function withConfigOptionValue(configOptions, configId, value) {
335
497
  }
336
498
  function pickEffortOption(configOptions) {
337
499
  if (!Array.isArray(configOptions)) return void 0;
338
- const candidates = configOptions.filter(isRecord).filter((option) => normalizedField(option, "type") === "select").filter(looksLikeEffortOption);
500
+ const candidates = configOptions.filter(isRecord2).filter((option) => normalizedField(option, "type") === "select").filter(looksLikeEffortOption);
339
501
  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];
340
502
  }
341
503
  function findAcpEffortConfig(configOptions) {
@@ -507,7 +669,7 @@ ${excerpt}`,
507
669
  }
508
670
 
509
671
  // ../../packages/ycodium-acp-executor/src/util.ts
510
- function isRecord2(value) {
672
+ function isRecord3(value) {
511
673
  return typeof value === "object" && value !== null && !Array.isArray(value);
512
674
  }
513
675
  function asTrimmedString(value) {
@@ -528,7 +690,7 @@ var selectPromptTurnId = (input2, activeTurnId, freshTurnId) => {
528
690
  };
529
691
 
530
692
  // ../../packages/ycodium-executor-common/src/toolPresentation.ts
531
- function isRecord3(value) {
693
+ function isRecord4(value) {
532
694
  return typeof value === "object" && value !== null && !Array.isArray(value);
533
695
  }
534
696
  function asTrimmedString2(value) {
@@ -570,11 +732,11 @@ function extractCommandFromTitle(title) {
570
732
  return backtickMatch?.[1]?.trim() || void 0;
571
733
  }
572
734
  function extractToolCommand(data, title) {
573
- const item = isRecord3(data?.["item"]) ? data["item"] : void 0;
574
- const itemInput = item && isRecord3(item["input"]) ? item["input"] : void 0;
575
- const itemResult = item && isRecord3(item["result"]) ? item["result"] : void 0;
576
- const rawInput = isRecord3(data?.["rawInput"]) ? data["rawInput"] : void 0;
577
- const dataInput = isRecord3(data?.["input"]) ? data["input"] : void 0;
735
+ const item = isRecord4(data?.["item"]) ? data["item"] : void 0;
736
+ const itemInput = item && isRecord4(item["input"]) ? item["input"] : void 0;
737
+ const itemResult = item && isRecord4(item["result"]) ? item["result"] : void 0;
738
+ const rawInput = isRecord4(data?.["rawInput"]) ? data["rawInput"] : void 0;
739
+ const dataInput = isRecord4(data?.["input"]) ? data["input"] : void 0;
578
740
  const candidates = [
579
741
  normalizeCommandValue(item?.["command"]),
580
742
  normalizeCommandValue(itemInput?.["command"]),
@@ -619,7 +781,7 @@ function collectPaths(value, paths, seen, depth) {
619
781
  }
620
782
  return;
621
783
  }
622
- if (!isRecord3(value)) {
784
+ if (!isRecord4(value)) {
623
785
  return;
624
786
  }
625
787
  for (const key of ["path", "filePath", "relativePath", "filename", "newPath", "oldPath"]) {
@@ -682,7 +844,7 @@ function deriveToolActivityPresentation(input2) {
682
844
  const title = asTrimmedString2(input2.title);
683
845
  const detail = stripTrailingExitCode(asTrimmedString2(input2.detail));
684
846
  const fallbackSummary = asTrimmedString2(input2.fallbackSummary) ?? "Tool";
685
- const data = isRecord3(input2.data) ? input2.data : void 0;
847
+ const data = isRecord4(input2.data) ? input2.data : void 0;
686
848
  const command = extractToolCommand(data, title);
687
849
  const primaryPath = extractPrimaryPath(data);
688
850
  const action = classifyToolAction({
@@ -714,7 +876,7 @@ function deriveToolActivityPresentation(input2) {
714
876
  };
715
877
  }
716
878
  if (action === "search") {
717
- const rawInput = isRecord3(data?.["rawInput"]) ? data["rawInput"] : void 0;
879
+ const rawInput = isRecord4(data?.["rawInput"]) ? data["rawInput"] : void 0;
718
880
  const query = asTrimmedString2(rawInput?.["query"]) ?? asTrimmedString2(rawInput?.["pattern"]) ?? asTrimmedString2(rawInput?.["searchTerm"]);
719
881
  return {
720
882
  summary: "Searched files",
@@ -791,7 +953,7 @@ function extractCommandFromTitle2(title) {
791
953
  return match?.[1]?.trim() || void 0;
792
954
  }
793
955
  function extractToolCallCommand(rawInput, title) {
794
- if (isRecord2(rawInput)) {
956
+ if (isRecord3(rawInput)) {
795
957
  const directCommand = normalizeCommandValue2(rawInput["command"]);
796
958
  if (directCommand) {
797
959
  return directCommand;
@@ -819,7 +981,7 @@ function boundTailText(text2, limit = TOOL_CALL_CONTENT_MAX_CHARS) {
819
981
  var boundToolCallOutputText = (text2) => boundTailText(text2);
820
982
  var RAW_OUTPUT_TEXT_FIELDS = ["content", "stdout", "stderr", "output"];
821
983
  function boundToolCallRawOutput(rawOutput) {
822
- if (!isRecord2(rawOutput)) {
984
+ if (!isRecord3(rawOutput)) {
823
985
  return rawOutput;
824
986
  }
825
987
  let changed = false;
@@ -1035,11 +1197,11 @@ function collectSessionConfigOptionValues(configOption) {
1035
1197
  );
1036
1198
  }
1037
1199
  function collectSessionModelIds(models) {
1038
- if (!isRecord2(models) || !Array.isArray(models["availableModels"])) {
1200
+ if (!isRecord3(models) || !Array.isArray(models["availableModels"])) {
1039
1201
  return [];
1040
1202
  }
1041
1203
  return models["availableModels"].flatMap(
1042
- (model) => isRecord2(model) && typeof model["modelId"] === "string" ? [model["modelId"]] : []
1204
+ (model) => isRecord3(model) && typeof model["modelId"] === "string" ? [model["modelId"]] : []
1043
1205
  );
1044
1206
  }
1045
1207
  function parseSessionModeState(sessionResponse) {
@@ -1087,7 +1249,7 @@ function parseAvailableCommandsUpdate(params) {
1087
1249
  }
1088
1250
  const commands = [];
1089
1251
  for (const command of availableCommands) {
1090
- if (!isRecord2(command)) {
1252
+ if (!isRecord3(command)) {
1091
1253
  continue;
1092
1254
  }
1093
1255
  const name = typeof command["name"] === "string" ? command["name"].trim() : "";
@@ -1095,7 +1257,7 @@ function parseAvailableCommandsUpdate(params) {
1095
1257
  continue;
1096
1258
  }
1097
1259
  const description = typeof command["description"] === "string" ? command["description"].trim() || void 0 : void 0;
1098
- const input2 = isRecord2(command["input"]) ? command["input"] : void 0;
1260
+ const input2 = isRecord3(command["input"]) ? command["input"] : void 0;
1099
1261
  const inputHint = typeof input2?.["hint"] === "string" ? input2["hint"].trim() || void 0 : void 0;
1100
1262
  commands.push({
1101
1263
  name,
@@ -1125,7 +1287,7 @@ function parsePermissionRequest(params, known) {
1125
1287
  const kind = toolCall?.kind ?? "unknown";
1126
1288
  const content = toolCall?.data["content"];
1127
1289
  const firstText = Array.isArray(content) ? content.flatMap((entry) => {
1128
- if (!isRecord2(entry) || entry["type"] !== "content" || !isRecord2(entry["content"]))
1290
+ if (!isRecord3(entry) || entry["type"] !== "content" || !isRecord3(entry["content"]))
1129
1291
  return [];
1130
1292
  const block = entry["content"];
1131
1293
  return block["type"] === "text" && typeof block["text"] === "string" && block["text"].trim() ? [block["text"]] : [];
@@ -1157,7 +1319,7 @@ function boundToolCallRawPayload(params, update, toolCall) {
1157
1319
  }
1158
1320
  function textFromContentBlocks(blocks) {
1159
1321
  const parts = blocks.flatMap(
1160
- (block) => isRecord2(block) && block["type"] === "text" && typeof block["text"] === "string" ? [block["text"]] : []
1322
+ (block) => isRecord3(block) && block["type"] === "text" && typeof block["text"] === "string" ? [block["text"]] : []
1161
1323
  );
1162
1324
  const joined = parts.join("");
1163
1325
  return joined.trim().length > 0 ? joined : void 0;
@@ -1182,7 +1344,7 @@ function parseSessionUpdateEvent(params) {
1182
1344
  const entries = Array.isArray(upd["entries"]) ? upd["entries"] : [];
1183
1345
  const plan = entries.map((entry, index) => ({
1184
1346
  step: readAcpText(entry, "content") ?? `Step ${index + 1}`,
1185
- status: normalizePlanStepStatus(isRecord2(entry) ? entry["status"] : void 0)
1347
+ status: normalizePlanStepStatus(isRecord3(entry) ? entry["status"] : void 0)
1186
1348
  }));
1187
1349
  if (plan.length > 0) {
1188
1350
  events.push({
@@ -1222,7 +1384,7 @@ function parseSessionUpdateEvent(params) {
1222
1384
  }
1223
1385
  case "agent_message_chunk":
1224
1386
  case "agent_thought_chunk": {
1225
- const content = isRecord2(upd["content"]) ? upd["content"] : void 0;
1387
+ const content = isRecord3(upd["content"]) ? upd["content"] : void 0;
1226
1388
  const contentType = content?.["type"];
1227
1389
  const streamKind = kind === "agent_thought_chunk" ? "reasoning_text" : "assistant_text";
1228
1390
  if (contentType === "text") {
@@ -1246,6 +1408,14 @@ function parseSessionUpdateEvent(params) {
1246
1408
  }
1247
1409
  break;
1248
1410
  }
1411
+ case "usage_update": {
1412
+ const used = upd["used"];
1413
+ const size = upd["size"];
1414
+ if (typeof used === "number" && Number.isSafeInteger(used) && used >= 0 && typeof size === "number" && Number.isSafeInteger(size) && size > 0) {
1415
+ events.push({ _tag: "ContextWindowUpdated", usedTokens: used, maxTokens: size });
1416
+ }
1417
+ break;
1418
+ }
1249
1419
  case "compaction_update": {
1250
1420
  const compactionId = readAcpText(upd, "compactionId");
1251
1421
  const status = readAcpText(upd, "status");
@@ -1262,7 +1432,7 @@ function parseSessionUpdateEvent(params) {
1262
1432
  }
1263
1433
  case "compaction_summary_chunk": {
1264
1434
  const compactionId = readAcpText(upd, "compactionId");
1265
- const content = isRecord2(upd["content"]) ? upd["content"] : void 0;
1435
+ const content = isRecord3(upd["content"]) ? upd["content"] : void 0;
1266
1436
  const text2 = content?.["type"] === "text" ? content["text"] : void 0;
1267
1437
  if (compactionId === void 0 || typeof text2 !== "string" || text2.length === 0) break;
1268
1438
  events.push({ _tag: "CompactionSummaryChunk", compactionId, text: text2 });
@@ -22957,17 +23127,17 @@ function isResponseMessage(value) {
22957
23127
  function isNotificationMessage(value) {
22958
23128
  return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
22959
23129
  }
22960
- function isRecord4(value) {
23130
+ function isRecord5(value) {
22961
23131
  return typeof value === "object" && value !== null;
22962
23132
  }
22963
23133
  function isJsonRpcEnvelope(value) {
22964
- return isRecord4(value) && value["jsonrpc"] === "2.0";
23134
+ return isRecord5(value) && value["jsonrpc"] === "2.0";
22965
23135
  }
22966
23136
  function isJsonRpcId(value) {
22967
23137
  return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
22968
23138
  }
22969
23139
  function isResponseShapedMessage(value) {
22970
- return isRecord4(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
23140
+ return isRecord5(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
22971
23141
  }
22972
23142
  function isResponseBatch(batch) {
22973
23143
  let hasValidCall = false;
@@ -22977,7 +23147,7 @@ function isResponseBatch(batch) {
22977
23147
  for (const entry of batch) {
22978
23148
  hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
22979
23149
  hasValidResponse ||= isResponseMessage(entry);
22980
- if (!isRecord4(entry)) {
23150
+ if (!isRecord5(entry)) {
22981
23151
  continue;
22982
23152
  }
22983
23153
  hasCallShape ||= "method" in entry;
@@ -22992,13 +23162,13 @@ function isResponseBatch(batch) {
22992
23162
  return hasResponseShape && !hasCallShape;
22993
23163
  }
22994
23164
  function cancelRequestId(params) {
22995
- if (!isRecord4(params) || !isJsonRpcId(params["requestId"])) {
23165
+ if (!isRecord5(params) || !isJsonRpcId(params["requestId"])) {
22996
23166
  return void 0;
22997
23167
  }
22998
23168
  return params["requestId"];
22999
23169
  }
23000
23170
  function isErrorResponse(value) {
23001
- return isRecord4(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
23171
+ return isRecord5(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
23002
23172
  }
23003
23173
  var Handled = {
23004
23174
  /**
@@ -23543,7 +23713,7 @@ var Connection = class {
23543
23713
  if (this.abortController.signal.aborted) {
23544
23714
  return Promise.resolve();
23545
23715
  }
23546
- if (!isRecord4(message)) {
23716
+ if (!isRecord5(message)) {
23547
23717
  console.error("Invalid message", { message });
23548
23718
  return Promise.resolve();
23549
23719
  }
@@ -23946,7 +24116,7 @@ function ndJsonStream(output2, input2) {
23946
24116
  await writeJson(protocolErrorResponse(RequestError.parseError()));
23947
24117
  return;
23948
24118
  }
23949
- if (isRecord4(message) || Array.isArray(message)) {
24119
+ if (isRecord5(message) || Array.isArray(message)) {
23950
24120
  controller.enqueue(message);
23951
24121
  } else {
23952
24122
  await writeJson(protocolErrorResponse(RequestError.invalidRequest(message)));
@@ -24933,14 +25103,14 @@ var legacyClientNotificationMethods = /* @__PURE__ */ new Set([
24933
25103
  import * as NodeStream from "node:stream";
24934
25104
 
24935
25105
  // ../../packages/ycodium-acp-executor/src/jsonrpc.ts
24936
- function isRecord5(value) {
25106
+ function isRecord6(value) {
24937
25107
  return typeof value === "object" && value !== null;
24938
25108
  }
24939
25109
  function isJsonRpcId2(value) {
24940
25110
  return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
24941
25111
  }
24942
25112
  function isJsonRpcEnvelope2(value) {
24943
- return isRecord5(value) && value["jsonrpc"] === "2.0";
25113
+ return isRecord6(value) && value["jsonrpc"] === "2.0";
24944
25114
  }
24945
25115
  function isRequestMessage2(value) {
24946
25116
  return isJsonRpcEnvelope2(value) && "id" in value && typeof value["method"] === "string" && isJsonRpcId2(value["id"]);
@@ -24960,7 +25130,7 @@ function isNotificationMessage2(value) {
24960
25130
  return isJsonRpcEnvelope2(value) && !("id" in value) && typeof value["method"] === "string";
24961
25131
  }
24962
25132
  function readJsonRpcError(value) {
24963
- if (!isRecord5(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
25133
+ if (!isRecord6(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
24964
25134
  return void 0;
24965
25135
  }
24966
25136
  return {
@@ -25033,11 +25203,11 @@ var KNOWN_SESSION_UPDATES = /* @__PURE__ */ new Set([
25033
25203
  "compaction_summary_chunk"
25034
25204
  ]);
25035
25205
  function isSessionUpdateEnvelope(payload) {
25036
- if (!isRecord5(payload) || typeof payload["sessionId"] !== "string") {
25206
+ if (!isRecord6(payload) || typeof payload["sessionId"] !== "string") {
25037
25207
  return false;
25038
25208
  }
25039
25209
  const update = payload["update"];
25040
- return isRecord5(update) && typeof update["sessionUpdate"] === "string";
25210
+ return isRecord6(update) && typeof update["sessionUpdate"] === "string";
25041
25211
  }
25042
25212
  function hasKnownVariantShape(update) {
25043
25213
  const kind = update["sessionUpdate"];
@@ -25045,7 +25215,7 @@ function hasKnownVariantShape(update) {
25045
25215
  return false;
25046
25216
  }
25047
25217
  if (kind === "user_message_chunk" || kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
25048
- return isRecord5(update["content"]);
25218
+ return isRecord6(update["content"]);
25049
25219
  }
25050
25220
  return true;
25051
25221
  }
@@ -25455,7 +25625,7 @@ function forgetConfigOptionValue(state, configId) {
25455
25625
  const forgetsModel = configId === void 0 || configId === state.modelConfigId;
25456
25626
  const { currentModelReported: _forgottenReport, ...withoutReport } = state;
25457
25627
  const configOptions = configId !== void 0 && Array.isArray(state.configOptions) ? state.configOptions.map((option) => {
25458
- if (!isRecord2(option) || option["id"] !== configId) return option;
25628
+ if (!isRecord3(option) || option["id"] !== configId) return option;
25459
25629
  const { currentValue: _forgotten, ...rest } = option;
25460
25630
  return rest;
25461
25631
  }) : state.configOptions;
@@ -25466,7 +25636,7 @@ function forgetConfigOptionValue(state, configId) {
25466
25636
  };
25467
25637
  }
25468
25638
  function modelSelectionStateFromSetup(setup) {
25469
- const sessionModels = isRecord2(setup.models) ? setup.models : void 0;
25639
+ const sessionModels = isRecord3(setup.models) ? setup.models : void 0;
25470
25640
  const modelConfigId = extractModelConfigId(setup);
25471
25641
  const strategy = modelConfigId !== void 0 ? "config-option" : "session/set_model";
25472
25642
  const modelConfigOption = modelConfigId === void 0 ? void 0 : findSessionConfigOption(setup.configOptions, modelConfigId);
@@ -26661,7 +26831,7 @@ function createPromptResults({
26661
26831
  // ../../packages/ycodium-acp-executor/src/permission-statement.ts
26662
26832
  function defaultPermissionStatement(request) {
26663
26833
  const rawInput = request.toolCall?.data["rawInput"];
26664
- const input2 = isRecord2(rawInput) ? rawInput : {};
26834
+ const input2 = isRecord3(rawInput) ? rawInput : {};
26665
26835
  const coveredArgs = [];
26666
26836
  const text2 = (name) => {
26667
26837
  const value = input2[name];
@@ -26907,7 +27077,7 @@ function createExecutorRequests({
26907
27077
  pendingUserInputs.delete(requestId);
26908
27078
  pending.resolve({
26909
27079
  kind: "answered",
26910
- answers: isRecord2(answers) ? answers : {}
27080
+ answers: isRecord3(answers) ? answers : {}
26911
27081
  });
26912
27082
  };
26913
27083
  return {
@@ -27204,18 +27374,18 @@ function modelRefreshFailedError(requestedModelId, error62) {
27204
27374
  }
27205
27375
 
27206
27376
  // ../../packages/ycodium-acp-executor/src/runtime-mode.ts
27207
- function isRecord6(value) {
27377
+ function isRecord7(value) {
27208
27378
  return typeof value === "object" && value !== null && !Array.isArray(value);
27209
27379
  }
27210
27380
  function asString2(value) {
27211
27381
  return typeof value === "string" ? value : void 0;
27212
27382
  }
27213
27383
  function acpModeConfigId(setup) {
27214
- if (!isRecord6(setup)) return void 0;
27384
+ if (!isRecord7(setup)) return void 0;
27215
27385
  const configOptions = setup["configOptions"];
27216
27386
  if (!Array.isArray(configOptions)) return void 0;
27217
27387
  for (const option of configOptions) {
27218
- if (!isRecord6(option)) continue;
27388
+ if (!isRecord7(option)) continue;
27219
27389
  if (asString2(option["category"])?.trim().toLowerCase() !== "mode") continue;
27220
27390
  const id = asString2(option["id"])?.trim();
27221
27391
  if (id) return id;
@@ -27223,16 +27393,16 @@ function acpModeConfigId(setup) {
27223
27393
  return void 0;
27224
27394
  }
27225
27395
  function acpCurrentModeId(setup) {
27226
- if (!isRecord6(setup)) return void 0;
27396
+ if (!isRecord7(setup)) return void 0;
27227
27397
  const modes = setup["modes"];
27228
- if (isRecord6(modes)) {
27398
+ if (isRecord7(modes)) {
27229
27399
  const current = asString2(modes["currentModeId"])?.trim();
27230
27400
  if (current) return current;
27231
27401
  }
27232
27402
  const configOptions = setup["configOptions"];
27233
27403
  if (Array.isArray(configOptions)) {
27234
27404
  for (const option of configOptions) {
27235
- if (!isRecord6(option)) continue;
27405
+ if (!isRecord7(option)) continue;
27236
27406
  if (asString2(option["category"])?.trim().toLowerCase() !== "mode") continue;
27237
27407
  const current = asString2(option["currentValue"])?.trim();
27238
27408
  if (current) return current;
@@ -27681,14 +27851,14 @@ function createExecutorSettlement({
27681
27851
 
27682
27852
  // ../../packages/ycodium-acp-executor/src/executor/subagent-sessions.ts
27683
27853
  function parseState(raw) {
27684
- if (!isRecord2(raw)) return { status: void 0, error: void 0 };
27854
+ if (!isRecord3(raw)) return { status: void 0, error: void 0 };
27685
27855
  const state = raw["state"];
27686
27856
  if (state === "running") return { status: "running", error: void 0 };
27687
27857
  if (state === "requires_action") return { status: "waiting", error: void 0 };
27688
27858
  if (state !== "idle") return { status: void 0, error: void 0 };
27689
27859
  const stopReason = raw["stopReason"];
27690
- const error62 = isRecord2(raw["error"]) ? asTrimmedString(raw["error"]["message"]) : void 0;
27691
- if (stopReason === "error" || isRecord2(raw["error"])) return { status: "failed", error: error62 };
27860
+ const error62 = isRecord3(raw["error"]) ? asTrimmedString(raw["error"]["message"]) : void 0;
27861
+ if (stopReason === "error" || isRecord3(raw["error"])) return { status: "failed", error: error62 };
27692
27862
  if (stopReason === "cancelled") return { status: "cancelled", error: void 0 };
27693
27863
  return { status: "idle", error: void 0 };
27694
27864
  }
@@ -27704,7 +27874,7 @@ function childLinkage(childId, record3) {
27704
27874
  function createSubagentSessionTracker(registry2) {
27705
27875
  const observe = (notification, ctx) => {
27706
27876
  const update = notification.update;
27707
- if (!isRecord2(update) || update["sessionUpdate"] !== "subagent_update") return [];
27877
+ if (!isRecord3(update) || update["sessionUpdate"] !== "subagent_update") return [];
27708
27878
  const childId = asTrimmedString(update["sessionId"]);
27709
27879
  if (childId === void 0 || ctx.ownSessionIds.has(childId)) return [];
27710
27880
  const outerId = notification.sessionId;
@@ -28029,6 +28199,17 @@ function createExecutorUpdates({
28029
28199
  emitArtifacts(resourceLinkArtifacts(event2.content));
28030
28200
  continue;
28031
28201
  }
28202
+ if (event2._tag === "ContextWindowUpdated") {
28203
+ emit({
28204
+ type: "thread.token-usage.updated",
28205
+ ...stamp(),
28206
+ provider: options.provider,
28207
+ threadId: options.threadId,
28208
+ ...shared.activeTurnId === void 0 ? {} : { turnId: shared.activeTurnId },
28209
+ payload: { usage: { usedTokens: event2.usedTokens, maxTokens: event2.maxTokens } }
28210
+ });
28211
+ continue;
28212
+ }
28032
28213
  if (event2._tag === "CompactionUpdated") {
28033
28214
  applyCompactionUpdate(event2);
28034
28215
  continue;
@@ -28236,7 +28417,7 @@ function defaultNowIso() {
28236
28417
  return (/* @__PURE__ */ new Date()).toISOString();
28237
28418
  }
28238
28419
  function defaultRandomId() {
28239
- return NodeCrypto.randomUUID();
28420
+ return NodeCrypto2.randomUUID();
28240
28421
  }
28241
28422
  function createAcpExecutor(options) {
28242
28423
  const hooks = { ...defaultVendorHooks, ...options.hooks };
@@ -28752,7 +28933,7 @@ function createAcpThreadOperations(options) {
28752
28933
  }
28753
28934
 
28754
28935
  // ../../packages/ycodium-executor-common/src/modelSelection.ts
28755
- function modelSelectionStringOption(selection, optionId) {
28936
+ function modelSelectionStringOption2(selection, optionId) {
28756
28937
  if (typeof selection !== "object" || selection === null || Array.isArray(selection)) {
28757
28938
  return void 0;
28758
28939
  }
@@ -28999,7 +29180,7 @@ function acpLaunchFromHandle(input2) {
28999
29180
  const { readable, writable, stderrTail } = nodeStreamsFromHandle(input2.handle);
29000
29181
  const resume = acpResumeFrom(input2.start, input2.resumeSchemaVersion);
29001
29182
  const requestedModelId = input2.modelIdFromSelection(input2.modelSelection);
29002
- const requestedEffort = modelSelectionStringOption(input2.modelSelection, input2.effortOptionId);
29183
+ const requestedEffort = modelSelectionStringOption2(input2.modelSelection, input2.effortOptionId);
29003
29184
  return { readable, writable, stderrTail, resume, requestedModelId, requestedEffort };
29004
29185
  }
29005
29186
  async function stopExistingAcpThread(table, threadId, isDisposed, signal) {
@@ -29153,30 +29334,6 @@ function parseCliVersion(output2) {
29153
29334
  }
29154
29335
  var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
29155
29336
 
29156
- // ../../packages/ycodium-jsonl-stream/src/sessionTranscript.ts
29157
- var SESSION_IMPORT_ACTIVITY_TEXT_LIMIT = 32e3;
29158
- function bounded(value, tail = false) {
29159
- if (value.length <= SESSION_IMPORT_ACTIVITY_TEXT_LIMIT) return { text: value, truncated: false };
29160
- const offset = tail ? value.length - SESSION_IMPORT_ACTIVITY_TEXT_LIMIT : SESSION_IMPORT_ACTIVITY_TEXT_LIMIT;
29161
- const character = value.charCodeAt(offset);
29162
- const previous = value.charCodeAt(offset - 1);
29163
- const splitPair = character >= 56320 && character <= 57343 && previous >= 55296 && previous <= 56319;
29164
- return {
29165
- text: tail ? value.slice(offset + (splitPair ? 1 : 0)) : value.slice(0, offset - (splitPair ? 1 : 0)),
29166
- truncated: true
29167
- };
29168
- }
29169
- function inputPayload(input2) {
29170
- if (input2 === void 0) return {};
29171
- const result = bounded(input2);
29172
- return { input: result.text, ...result.truncated ? { inputTruncated: true } : {} };
29173
- }
29174
- function outputPayload(output2) {
29175
- if (output2 === void 0) return {};
29176
- const result = bounded(output2, true);
29177
- return { output: result.text, ...result.truncated ? { outputTruncated: true } : {} };
29178
- }
29179
-
29180
29337
  // ../../packages/ycodium-instance-config/src/launchArgs.ts
29181
29338
  function tokenizeShellWords(value) {
29182
29339
  const input2 = value.trim();
@@ -29230,66 +29387,8 @@ function tokenizeShellWords(value) {
29230
29387
  return tokens;
29231
29388
  }
29232
29389
 
29233
- // ../../packages/ycodium-instance-config/src/instanceConfig.ts
29234
- import { modelSelectionStringOption as modelSelectionStringOption2 } from "@ycodium-ai/plugin-api/executor";
29235
- function isRecord7(value) {
29236
- return typeof value === "object" && value !== null && !Array.isArray(value);
29237
- }
29238
- function readString(value) {
29239
- return typeof value === "string" ? value : "";
29240
- }
29241
- function readTrimmed(value) {
29242
- return readString(value).trim();
29243
- }
29244
- function modelIdFromSelection(selection) {
29245
- if (!isRecord7(selection)) return void 0;
29246
- const model = selection["model"];
29247
- return typeof model === "string" ? model.trim() || void 0 : void 0;
29248
- }
29249
- function readTurnSelection(selection, effortOptionId) {
29250
- const requestedModelId = modelIdFromSelection(selection);
29251
- const requestedEffort = modelSelectionStringOption2(selection, effortOptionId);
29252
- return {
29253
- ...requestedModelId === void 0 ? {} : { requestedModelId },
29254
- ...requestedEffort === void 0 ? {} : { requestedEffort }
29255
- };
29256
- }
29257
- function readEnvironment(value) {
29258
- if (!Array.isArray(value)) return {};
29259
- const env = {};
29260
- for (const entry of value) {
29261
- if (!isRecord7(entry)) continue;
29262
- const name = readTrimmed(entry["name"]);
29263
- if (name.length === 0) continue;
29264
- env[name] = readString(entry["value"]);
29265
- }
29266
- return env;
29267
- }
29268
- function instanceSettings(config2) {
29269
- if (!isRecord7(config2)) return {};
29270
- return isRecord7(config2["config"]) ? config2["config"] : config2;
29271
- }
29272
- function readInstanceEnvelope(config2) {
29273
- const envelope = isRecord7(config2) ? config2 : {};
29274
- const settings = instanceSettings(config2);
29275
- return {
29276
- settings,
29277
- settingOrEnvelope: (key) => readTrimmed(settings[key]) || readTrimmed(envelope[key]),
29278
- environment: readEnvironment(envelope["environment"]),
29279
- envelopeDriver: readTrimmed(envelope["driver"]) || void 0
29280
- };
29281
- }
29282
- function readLaunchInstanceRecipe(config2, defaultLaunchArgs = "") {
29283
- const envelope = readInstanceEnvelope(config2);
29284
- return {
29285
- binaryPath: readTrimmed(envelope.settings["binaryPath"]),
29286
- launchArgs: readString(envelope.settings["launchArgs"]) || defaultLaunchArgs,
29287
- homePath: envelope.settingOrEnvelope("homePath"),
29288
- homeEnvVar: envelope.settingOrEnvelope("homeEnvVar"),
29289
- environment: envelope.environment,
29290
- envelopeDriver: envelope.envelopeDriver
29291
- };
29292
- }
29390
+ // src/kimiInstance.ts
29391
+ import { createCliDeviceSignIn } from "@ycodium-ai/plugin-api/runtime-maintenance";
29293
29392
 
29294
29393
  // src/config.ts
29295
29394
  function parseKimiInstanceConfig(config2) {
@@ -29557,39 +29656,47 @@ import { parseRetryAfterMs } from "@ycodium-ai/plugin-api/usage";
29557
29656
  var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29558
29657
 
29559
29658
  // ../../packages/ycodium-credential-account/src/quotaRequest.ts
29560
- async function requestQuotaJson(input2) {
29659
+ async function requestQuotaJsonValue(input2) {
29561
29660
  let response;
29562
29661
  try {
29563
29662
  response = await input2.fetch(input2.url, {
29564
29663
  headers: input2.headers,
29664
+ ...input2.method === void 0 ? {} : { method: input2.method },
29665
+ ...input2.body === void 0 ? {} : { body: input2.body },
29666
+ ...input2.redirect === void 0 ? {} : { redirect: input2.redirect },
29565
29667
  signal: AbortSignal.any([
29566
29668
  ...input2.signal === void 0 ? [] : [input2.signal],
29567
29669
  AbortSignal.timeout(input2.timeoutMs)
29568
29670
  ])
29569
29671
  });
29570
- } catch {
29672
+ } catch (cause) {
29673
+ if (input2.propagateCallerAbort && input2.signal?.aborted) throw cause;
29571
29674
  return { status: "unavailable", reason: "unreachable" };
29572
29675
  }
29573
- if (response.status === 401 || response.status === 403) {
29574
- return { status: "unavailable", reason: "authRejected" };
29575
- }
29576
- if (response.status === 429) {
29577
- const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), input2.now());
29578
- return {
29579
- status: "unavailable",
29580
- reason: "rateLimited",
29581
- ...retryAfterMs === null ? {} : { retryAfterMs }
29582
- };
29676
+ if (!response.ok) {
29677
+ void response.body?.cancel().catch(() => void 0);
29678
+ if (response.status === 429) {
29679
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), input2.now());
29680
+ return {
29681
+ status: "unavailable",
29682
+ reason: "rateLimited",
29683
+ ...retryAfterMs === null ? {} : { retryAfterMs }
29684
+ };
29685
+ }
29686
+ const reason = input2.statusReasons?.[response.status] ?? (response.status === 401 || response.status === 403 ? "authRejected" : "unreachable");
29687
+ return { status: "unavailable", reason };
29583
29688
  }
29584
- if (!response.ok) return { status: "unavailable", reason: "unreachable" };
29585
- let body;
29586
29689
  try {
29587
- body = JSON.parse(await response.text());
29588
- } catch {
29690
+ return { body: JSON.parse(await response.text()) };
29691
+ } catch (cause) {
29692
+ if (input2.propagateCallerAbort && input2.signal?.aborted) throw cause;
29589
29693
  return { status: "unavailable", reason: "unreachable" };
29590
29694
  }
29591
- if (!isRecord9(body)) return { status: "unavailable", reason: "unreachable" };
29592
- return { body };
29695
+ }
29696
+ async function requestQuotaJson(input2) {
29697
+ const answer = await requestQuotaJsonValue(input2);
29698
+ if (!("body" in answer)) return answer;
29699
+ return isRecord9(answer.body) ? { body: answer.body } : { status: "unavailable", reason: "unreachable" };
29593
29700
  }
29594
29701
 
29595
29702
  // ../../packages/ycodium-credential-account/src/quotaJson.ts
@@ -29603,6 +29710,7 @@ var parseJson = (raw) => {
29603
29710
  return null;
29604
29711
  }
29605
29712
  };
29713
+ var clampPercent = (value) => Math.min(100, Math.max(0, value));
29606
29714
 
29607
29715
  // src/kimiAccount.ts
29608
29716
  import * as NodeFS4 from "node:fs";
@@ -29647,7 +29755,6 @@ var asCount = (value) => {
29647
29755
  const parsed = Number(text2);
29648
29756
  return Number.isFinite(parsed) ? parsed : null;
29649
29757
  };
29650
- var clampPercent = (value) => Math.min(100, Math.max(0, value));
29651
29758
  var expiryMs = (value) => {
29652
29759
  const raw = asNumber(value);
29653
29760
  if (raw === null || raw <= 0) return null;
@@ -29979,15 +30086,44 @@ var createKimiTokenReader = (input2) => {
29979
30086
  return { readTokenUsage };
29980
30087
  };
29981
30088
 
30089
+ // ../../packages/ycodium-instance-config/src/probeProcess.ts
30090
+ import {
30091
+ describeExecutorSpawnFailure,
30092
+ ExecutorSpawnAbortedError,
30093
+ ExecutorSpawnRefusedError
30094
+ } from "@ycodium-ai/plugin-api/executor";
30095
+ import {
30096
+ isOperationCleanupError,
30097
+ runProcessOperation
30098
+ } from "@ycodium-ai/plugin-api/process-operation";
30099
+ async function readCliVersionCommand(host, input2) {
30100
+ try {
30101
+ const run = await runProcessOperation(host, {
30102
+ program: input2.program,
30103
+ args: ["--version"],
30104
+ owner: { bindingId: host.bindingId },
30105
+ ...Object.keys(input2.env).length > 0 ? { env: input2.env } : {},
30106
+ signal: input2.signal,
30107
+ timeoutMs: input2.timeoutMs,
30108
+ maxOutputBytes: 64 * 1024
30109
+ });
30110
+ if (run.exitCode !== 0 && !input2.acceptNonzeroExit) return null;
30111
+ return input2.parse(run.stdout) ?? input2.parse(run.stderr);
30112
+ } catch (error62) {
30113
+ if (isOperationCleanupError(error62) || input2.signal?.aborted) throw error62;
30114
+ return null;
30115
+ }
30116
+ }
30117
+
29982
30118
  // src/kimiModels.ts
29983
30119
  import {
29984
- runProcessOperation,
29985
- OperationCleanupError
30120
+ runProcessOperation as runProcessOperation2,
30121
+ isOperationCleanupError as isOperationCleanupError2
29986
30122
  } from "@ycodium-ai/plugin-api/process-operation";
29987
30123
  import {
29988
- describeExecutorSpawnFailure,
29989
- ExecutorSpawnAbortedError,
29990
- ExecutorSpawnRefusedError,
30124
+ describeExecutorSpawnFailure as describeExecutorSpawnFailure2,
30125
+ ExecutorSpawnAbortedError as ExecutorSpawnAbortedError2,
30126
+ ExecutorSpawnRefusedError as ExecutorSpawnRefusedError2,
29991
30127
  REASONING_OPTION_LABEL,
29992
30128
  reasoningEffortShortLabel
29993
30129
  } from "@ycodium-ai/plugin-api/executor";
@@ -30060,7 +30196,7 @@ async function probeKimiModels(input2) {
30060
30196
  const { recipe, host, env } = input2;
30061
30197
  let spawned = false;
30062
30198
  try {
30063
- const run = await runProcessOperation(
30199
+ const run = await runProcessOperation2(
30064
30200
  {
30065
30201
  ...host,
30066
30202
  process: {
@@ -30095,30 +30231,21 @@ async function probeKimiModels(input2) {
30095
30231
  models: run.stdout === void 0 ? void 0 : kimiProbeModels(run.stdout)
30096
30232
  };
30097
30233
  } catch (error62) {
30098
- if (error62 instanceof ExecutorSpawnRefusedError || error62 instanceof ExecutorSpawnAbortedError || error62 instanceof OperationCleanupError || input2.signal?.aborted)
30234
+ if (error62 instanceof ExecutorSpawnRefusedError2 || error62 instanceof ExecutorSpawnAbortedError2 || isOperationCleanupError2(error62) || input2.signal?.aborted)
30099
30235
  throw error62;
30100
- if (!spawned) return { kind: "not-started", ...describeExecutorSpawnFailure(error62) };
30236
+ if (!spawned) return { kind: "not-started", ...describeExecutorSpawnFailure2(error62) };
30101
30237
  return { kind: "failed", detail: acpProbeFailureDetail(error62) };
30102
30238
  }
30103
30239
  }
30104
30240
  async function probeKimiVersion(input2) {
30105
30241
  const { recipe, host, env, signal } = input2;
30106
- try {
30107
- const run = await runProcessOperation(host, {
30108
- program: recipe.binaryPath,
30109
- args: ["--version"],
30110
- owner: { bindingId: host.bindingId },
30111
- ...Object.keys(env).length > 0 ? { env } : {},
30112
- signal,
30113
- timeoutMs: PROBE_TIMEOUT_MS,
30114
- maxOutputBytes: 64 * 1024
30115
- });
30116
- if (run.exitCode !== 0) return null;
30117
- return parseCliVersion(run.stdout) ?? parseCliVersion(run.stderr);
30118
- } catch (error62) {
30119
- if (error62 instanceof OperationCleanupError || signal?.aborted) throw error62;
30120
- return null;
30121
- }
30242
+ return readCliVersionCommand(host, {
30243
+ program: recipe.binaryPath,
30244
+ env,
30245
+ signal,
30246
+ timeoutMs: PROBE_TIMEOUT_MS,
30247
+ parse: parseCliVersion
30248
+ });
30122
30249
  }
30123
30250
  async function probeKimi(input2) {
30124
30251
  const [listed, version2] = await Promise.all([probeKimiModels(input2), probeKimiVersion(input2)]);
@@ -30368,10 +30495,37 @@ var kimiPermissionStatement = ({
30368
30495
  };
30369
30496
 
30370
30497
  // src/nativeSessions.ts
30371
- import * as NodeFS7 from "node:fs";
30498
+ import * as NodeFS8 from "node:fs";
30372
30499
  import * as NodeFSP from "node:fs/promises";
30373
- import * as NodePath8 from "node:path";
30500
+ import * as NodePath9 from "node:path";
30374
30501
  import * as NodeReadline from "node:readline";
30502
+
30503
+ // ../../packages/ycodium-jsonl-stream/src/sessionDirectory.ts
30504
+ import * as NodeFS7 from "node:fs";
30505
+ import * as NodePath8 from "node:path";
30506
+ function readableStoragePath(home) {
30507
+ try {
30508
+ return NodeFS7.realpathSync.native(home);
30509
+ } catch {
30510
+ return home;
30511
+ }
30512
+ }
30513
+ function isAbsoluteDirectory(path) {
30514
+ if (!NodePath8.isAbsolute(path)) return false;
30515
+ if (NodePath8.sep !== "\\") return true;
30516
+ const { root } = NodePath8.parse(path);
30517
+ return root.length > 1;
30518
+ }
30519
+ var directoryKey = (directory) => {
30520
+ const resolved = NodePath8.resolve(directory);
30521
+ return NodePath8.sep === "\\" ? resolved.toLowerCase() : resolved;
30522
+ };
30523
+ function matchesSessionDirectory(rootKey, cwd, mode) {
30524
+ const relative2 = NodePath8.relative(rootKey, directoryKey(cwd));
30525
+ return relative2 === "" || mode === "scan" && relative2 !== ".." && !relative2.startsWith(`..${NodePath8.sep}`) && !NodePath8.isAbsolute(relative2);
30526
+ }
30527
+
30528
+ // src/nativeSessions.ts
30375
30529
  var sessionIdPattern = /^[a-zA-Z0-9_-]+$/u;
30376
30530
  function record2(value) {
30377
30531
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
@@ -30395,47 +30549,33 @@ async function directories(path) {
30395
30549
  throw error62;
30396
30550
  }
30397
30551
  }
30398
- function readableStoragePath(home) {
30399
- try {
30400
- return NodeFS7.realpathSync.native(home);
30401
- } catch {
30402
- return home;
30403
- }
30404
- }
30405
- function isAbsoluteDirectory(path) {
30406
- if (!NodePath8.isAbsolute(path)) return false;
30407
- if (NodePath8.sep !== "\\") return true;
30408
- const { root } = NodePath8.parse(path);
30409
- return root.length > 1;
30410
- }
30411
- var directoryKey = (directory) => {
30412
- const resolved = NodePath8.resolve(directory);
30413
- return NodePath8.sep === "\\" ? resolved.toLowerCase() : resolved;
30414
- };
30415
30552
  async function findSessions(home, cwd, signal, nativeSessionId) {
30416
30553
  signal?.throwIfAborted();
30417
30554
  const expectedCwd = directoryKey(cwd);
30418
30555
  const result = [];
30419
- const root = NodePath8.join(home, "sessions");
30556
+ const root = NodePath9.join(home, "sessions");
30420
30557
  for (const workspace of await directories(root)) {
30421
30558
  if (workspace.startsWith(".")) continue;
30422
- const workspacePath = NodePath8.join(root, workspace);
30559
+ const workspacePath = NodePath9.join(root, workspace);
30423
30560
  for (const id of await directories(workspacePath)) {
30424
30561
  signal?.throwIfAborted();
30425
30562
  if (!sessionIdPattern.test(id) || nativeSessionId !== void 0 && nativeSessionId !== id)
30426
30563
  continue;
30427
- const sessionPath = NodePath8.join(workspacePath, id);
30428
- const statePath = NodePath8.join(sessionPath, "state.json");
30564
+ const sessionPath = NodePath9.join(workspacePath, id);
30565
+ const statePath = NodePath9.join(sessionPath, "state.json");
30429
30566
  try {
30430
30567
  if (!(await NodeFSP.lstat(statePath)).isFile()) continue;
30431
30568
  const state = parseRecord(await NodeFSP.readFile(statePath, { encoding: "utf8", signal }));
30432
30569
  if (state?.id !== id || typeof state.cwd !== "string" || !isAbsoluteDirectory(state.cwd))
30433
30570
  continue;
30434
- const relative2 = NodePath8.relative(expectedCwd, directoryKey(state.cwd));
30435
- if (relative2 !== "" && (nativeSessionId !== void 0 || relative2 === ".." || relative2.startsWith(`..${NodePath8.sep}`) || NodePath8.isAbsolute(relative2)))
30571
+ if (!matchesSessionDirectory(
30572
+ expectedCwd,
30573
+ state.cwd,
30574
+ nativeSessionId === void 0 ? "scan" : "read"
30575
+ ))
30436
30576
  continue;
30437
- const wire = NodePath8.join(sessionPath, "agents", "main", "wire.jsonl");
30438
- if (!(await NodeFSP.lstat(NodePath8.join(sessionPath, "agents"))).isDirectory() || !(await NodeFSP.lstat(NodePath8.dirname(wire))).isDirectory() || !(await NodeFSP.lstat(wire)).isFile())
30577
+ const wire = NodePath9.join(sessionPath, "agents", "main", "wire.jsonl");
30578
+ if (!(await NodeFSP.lstat(NodePath9.join(sessionPath, "agents"))).isDirectory() || !(await NodeFSP.lstat(NodePath9.dirname(wire))).isDirectory() || !(await NodeFSP.lstat(wire)).isFile())
30439
30579
  continue;
30440
30580
  result.push({
30441
30581
  id,
@@ -30454,7 +30594,7 @@ async function findSessions(home, cwd, signal, nativeSessionId) {
30454
30594
  return result;
30455
30595
  }
30456
30596
  async function readTranscript(session, signal, summaryOnly = false) {
30457
- const stream = NodeFS7.createReadStream(session.wire, { signal });
30597
+ const stream = NodeFS8.createReadStream(session.wire, { signal });
30458
30598
  const lines = NodeReadline.createInterface({ input: stream, crlfDelay: Infinity });
30459
30599
  const messages = [];
30460
30600
  const activities = [];
@@ -30671,8 +30811,15 @@ function kimiHooks(recipe) {
30671
30811
  readContextWindow: ({ sessionId }) => readKimiContextWindow({ homePath, acpSessionId: sessionId })
30672
30812
  };
30673
30813
  }
30674
- var createKimiInstance = (config2, host) => {
30675
- const recipe = parseKimiInstanceConfig(config2);
30814
+ var createKimiInstance = (config2, host, profileDataDir2) => {
30815
+ const { recipe, home } = applyPrivateAccountHome(
30816
+ parseKimiInstanceConfig(config2),
30817
+ readInstanceEnvelope(config2).settings,
30818
+ "KIMI_CODE_HOME",
30819
+ profileDataDir2,
30820
+ host.instanceId,
30821
+ ["KIMI_API_KEY", "KIMI_CODE_API_KEY", "MOONSHOT_API_KEY"]
30822
+ );
30676
30823
  let disposed = false;
30677
30824
  const { table, threads, requireThread, registerSession, stopSession, disposeOnce, threadOps } = bindAcpInstanceThreads({
30678
30825
  log: host.log,
@@ -30685,23 +30832,30 @@ var createKimiInstance = (config2, host) => {
30685
30832
  kimiAccountHome(sessionHome?.trim() ?? ""),
30686
30833
  RESUME_SCHEMA_VERSION
30687
30834
  );
30835
+ const login = createCliDeviceSignIn({
30836
+ name: "Kimi Code",
30837
+ host,
30838
+ program: recipe.binaryPath,
30839
+ args: KIMI_CARD.deviceCodeSignInArgs,
30840
+ env: homeLaunchEnv(recipe, recipe.homePath),
30841
+ stream: "stderr",
30842
+ parse: (text2) => {
30843
+ const verificationUrl = /^Opening browser for Kimi device login: (https?:\/\/\S+)\r?$/m.exec(
30844
+ text2
30845
+ )?.[1];
30846
+ const userCode = /enter code: (\S+)\r?\n/.exec(text2)?.[1];
30847
+ return verificationUrl && userCode ? { verificationUrl, userCode } : void 0;
30848
+ },
30849
+ probe: (signal) => instance.probe(signal),
30850
+ isDisposed: () => disposed
30851
+ });
30688
30852
  const instance = {
30853
+ signIn: login.signIn,
30854
+ ...home ? { signInCommandEnv: recipe.environment } : {},
30689
30855
  sessions: {
30690
30856
  ...sessions,
30691
30857
  scan: ({ projectId, directory, signal }) => sessions.scan({ directory: directory ?? host.workspacePath(projectId), signal }),
30692
- read: async (input2) => {
30693
- const imported = await sessions.readImport(input2);
30694
- return {
30695
- nativeSessionId: input2.nativeSessionId,
30696
- model: imported.model,
30697
- resumeCursor: imported.resumeCursor,
30698
- messages: imported.messages.map(({ role, text: text2, createdAt }) => ({
30699
- role,
30700
- text: text2,
30701
- createdAt: Date.parse(createdAt)
30702
- }))
30703
- };
30704
- }
30858
+ read: async (input2) => sessionReadFromImport(input2.nativeSessionId, await sessions.readImport(input2))
30705
30859
  },
30706
30860
  probe: async (signal) => {
30707
30861
  if (recipe.binaryPath.length === 0) {
@@ -30884,20 +31038,21 @@ var createKimiInstance = (config2, host) => {
30884
31038
  continuationKey: homeContinuationKey("kimiCode", recipe),
30885
31039
  dispose: () => {
30886
31040
  disposed = true;
30887
- return disposeOnce();
31041
+ return Promise.all([disposeOnce(), login.close()]).then(() => void 0);
30888
31042
  }
30889
31043
  };
30890
31044
  return instance;
30891
31045
  };
30892
31046
 
30893
31047
  // src/index.ts
31048
+ var profileDataDir;
30894
31049
  var executors = [
30895
31050
  {
30896
31051
  card: KIMI_CARD,
30897
31052
  lifecycle: [{ kind: "detect", reversible: true }],
30898
31053
  createInstance: async (config2, host) => {
30899
31054
  host.log.info("createInstance");
30900
- return createKimiInstance(config2, host);
31055
+ return createKimiInstance(config2, host, profileDataDir);
30901
31056
  }
30902
31057
  }
30903
31058
  ];
@@ -30906,23 +31061,13 @@ var index_default = definePlugin({
30906
31061
  apiVersion: PLUGIN_API_VERSION,
30907
31062
  executors,
30908
31063
  activate(ctx) {
30909
- ctx.command({
30910
- name: "effectiveConfig",
30911
- description: "Settings form: the account directory an empty path resolves to on this machine.",
30912
- scope: "read",
30913
- payloadSchema: EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
30914
- handle: async (payload) => {
30915
- const request = readExecutorEffectiveRequest(payload);
30916
- return {
30917
- homePath: executorHomeEffectiveValue(
30918
- "KIMI_CODE_HOME",
30919
- request,
30920
- process.env,
30921
- (value) => value === void 0 ? NodePath9.join(NodeOS7.homedir(), ".kimi-code") : NodePath9.resolve(expandHomePath(value))
30922
- )
30923
- };
30924
- }
30925
- });
31064
+ profileDataDir = ctx.paths?.dataDir;
31065
+ registerEffectiveHomeCommand(
31066
+ ctx,
31067
+ KIMI_CARD.homeEnvVar,
31068
+ (value) => value === void 0 ? NodePath10.join(NodeOS7.homedir(), ".kimi-code") : NodePath10.resolve(expandHomePath(value)),
31069
+ profileDataDir
31070
+ );
30926
31071
  ctx.log.info("Kimi Code executor ready");
30927
31072
  }
30928
31073
  });
package/locales/en.json CHANGED
@@ -11,13 +11,17 @@
11
11
  },
12
12
  "homePath": {
13
13
  "title": "Account directory",
14
- "description": "Sessions and the `kimi login` credentials live here, so providers sharing this directory can pick up each other's threads and providers with different directories cannot. Leave empty to use the CLI's default.",
14
+ "description": "Sessions and the `kimi login` credentials live here, so providers sharing this directory can pick up each other's threads and providers with different directories cannot.",
15
15
  "placeholder": "e.g. ~/.kimi-code-work"
16
16
  },
17
17
  "effective": {
18
18
  "provider": "{{name}} in this provider",
19
19
  "machine": "{{name}} on this machine",
20
20
  "default": "default"
21
+ },
22
+ "privateAccount": {
23
+ "title": "Use a private account directory",
24
+ "description": "When no account directory is configured, keep this instance’s account and sessions in their own directory."
21
25
  }
22
26
  },
23
27
  "usage": {
@@ -11,13 +11,17 @@
11
11
  },
12
12
  "homePath": {
13
13
  "title": "账号目录",
14
- "description": "会话和 `kimi login` 的凭据都保存在这里,因此共用同一目录的 provider 可以接手彼此的会话,目录不同的则不能。留空则使用该命令行工具的默认目录。",
14
+ "description": "会话和 `kimi login` 的凭据都保存在这里,因此共用同一目录的 provider 可以接手彼此的会话,目录不同的则不能。",
15
15
  "placeholder": "例如 ~/.kimi-code-work"
16
16
  },
17
17
  "effective": {
18
18
  "provider": "本 provider 的 {{name}}",
19
19
  "machine": "本机的 {{name}}",
20
20
  "default": "默认"
21
+ },
22
+ "privateAccount": {
23
+ "title": "使用私有账号目录",
24
+ "description": "未指定账号目录时,将此实例的账号和会话单独存放。"
21
25
  }
22
26
  },
23
27
  "usage": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-kimi",
3
- "version": "0.2.5557",
3
+ "version": "0.2.5634",
4
4
  "description": "Kimi Code executor: runs `kimi acp` over Agent Client Protocol stdio.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -21,11 +21,11 @@
21
21
  "@types/node": "24.12.4",
22
22
  "esbuild": "0.28.1",
23
23
  "vite-plus": "0.2.2",
24
- "@ycodium-ai/plugin-api": "0.2.5557",
25
- "ycodium-acp-executor": "0.2.0",
24
+ "@ycodium-ai/plugin-api": "0.2.0",
25
+ "ycodium-acp-executor": "0.2.5634",
26
26
  "ycodium-credential-account": "0.0.0",
27
- "ycodium-instance-config": "0.0.0",
28
27
  "ycodium-executor-testing": "0.0.0",
28
+ "ycodium-instance-config": "0.0.0",
29
29
  "ycodium-jsonl-stream": "0.0.0"
30
30
  },
31
31
  "ycodium": {