@ycodium-ai/agent-kimi 0.2.5557 → 0.2.5751

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,74 +8,18 @@ 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 = 180;
12
12
 
13
13
  // src/index.ts
14
- import * as NodeOS7 from "node:os";
15
- import * as NodePath9 from "node:path";
14
+ import * as NodeOS6 from "node:os";
15
+ import * as NodePath8 from "node:path";
16
16
  import {
17
- EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
18
- executorHomeEffectiveValue,
19
- readExecutorEffectiveRequest
20
- } from "@ycodium-ai/plugin-api/executor";
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
- }
17
+ expandHomePath as expandHomePath2,
18
+ registerEffectiveHomeCommand
19
+ } from "@ycodium-ai/plugin-api/instance-config";
77
20
 
78
21
  // src/card.ts
22
+ import { programAndHomeConfigSchema } from "@ycodium-ai/plugin-api/instance-config";
79
23
  var KIMI_DRIVER_KIND = "kimiCode";
80
24
  var KIMI_CARD = {
81
25
  driverKind: KIMI_DRIVER_KIND,
@@ -130,7 +74,10 @@ var KIMI_CARD = {
130
74
  },
131
75
  credentialSources: [],
132
76
  diagnostics: [],
133
- configSchema: programAndHomeConfigSchema({ control: "executable-path" }),
77
+ configSchema: programAndHomeConfigSchema({
78
+ control: "executable-path",
79
+ privateAccountOption: true
80
+ }),
134
81
  modelConnectivity: {
135
82
  dialects: [],
136
83
  acceptsExternalEndpoints: false
@@ -138,7 +85,20 @@ var KIMI_CARD = {
138
85
  };
139
86
 
140
87
  // src/kimiInstance.ts
141
- import { raceAbort as raceAbort2 } from "@ycodium-ai/plugin-api/executor";
88
+ import {
89
+ applyPrivateAccountHome,
90
+ readInstanceEnvelope,
91
+ tokenizeShellWords,
92
+ expandHomePath,
93
+ homeContinuationKey,
94
+ homeLaunchEnv,
95
+ modelIdFromSelection,
96
+ readTurnSelection
97
+ } from "@ycodium-ai/plugin-api/instance-config";
98
+ import { sessionReadFromImport } from "@ycodium-ai/plugin-api/session-history";
99
+ import {
100
+ raceAbort as raceAbort2
101
+ } from "@ycodium-ai/plugin-api/executor";
142
102
 
143
103
  // ../../packages/ycodium-acp-executor/src/executor.ts
144
104
  import * as NodeCrypto from "node:crypto";
@@ -255,8 +215,8 @@ var UnboundedEventStream = class {
255
215
  iterators.subscribers.delete(subscriber);
256
216
  return { value: void 0, done: true };
257
217
  }
258
- await new Promise((resolve5) => {
259
- subscriber.wake = resolve5;
218
+ await new Promise((resolve3) => {
219
+ subscriber.wake = resolve3;
260
220
  });
261
221
  }
262
222
  },
@@ -482,8 +442,8 @@ var settledExitCode = async (exited) => {
482
442
  try {
483
443
  return await Promise.race([
484
444
  exited.catch(() => void 0),
485
- new Promise((resolve5) => {
486
- timer = setTimeout(() => resolve5(void 0), AGENT_EXIT_SETTLE_MS);
445
+ new Promise((resolve3) => {
446
+ timer = setTimeout(() => resolve3(void 0), AGENT_EXIT_SETTLE_MS);
487
447
  })
488
448
  ]);
489
449
  } finally {
@@ -823,15 +783,15 @@ function boundToolCallRawOutput(rawOutput) {
823
783
  return rawOutput;
824
784
  }
825
785
  let changed = false;
826
- const bounded2 = { ...rawOutput };
786
+ const bounded = { ...rawOutput };
827
787
  for (const field of RAW_OUTPUT_TEXT_FIELDS) {
828
788
  const value = rawOutput[field];
829
789
  if (typeof value === "string" && value.length > TOOL_CALL_CONTENT_MAX_CHARS) {
830
- bounded2[field] = boundToolCallOutputText(value);
790
+ bounded[field] = boundToolCallOutputText(value);
831
791
  changed = true;
832
792
  }
833
793
  }
834
- return changed ? bounded2 : rawOutput;
794
+ return changed ? bounded : rawOutput;
835
795
  }
836
796
  function toolCallContentText(entry) {
837
797
  if (entry.type !== "content" || entry.content?.type !== "text") {
@@ -858,7 +818,7 @@ function extractTextContentFromToolCallContent(content) {
858
818
  if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
859
819
  return { text: joined, content: typed };
860
820
  }
861
- const bounded2 = boundToolCallOutputText(joined);
821
+ const bounded = boundToolCallOutputText(joined);
862
822
  const lastContributingTextIndex = typed.reduce(
863
823
  (lastIndex, entry, index) => toolCallContentText(entry)?.trim() ? index : lastIndex,
864
824
  -1
@@ -870,9 +830,9 @@ function extractTextContentFromToolCallContent(content) {
870
830
  if (index !== lastContributingTextIndex) {
871
831
  return [];
872
832
  }
873
- return [{ type: "content", content: { type: "text", text: bounded2 } }];
833
+ return [{ type: "content", content: { type: "text", text: bounded } }];
874
834
  });
875
- return { text: bounded2, content: boundedContent };
835
+ return { text: bounded, content: boundedContent };
876
836
  }
877
837
  function normalizeToolKind(kind) {
878
838
  return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : void 0;
@@ -1246,6 +1206,14 @@ function parseSessionUpdateEvent(params) {
1246
1206
  }
1247
1207
  break;
1248
1208
  }
1209
+ case "usage_update": {
1210
+ const used = upd["used"];
1211
+ const size = upd["size"];
1212
+ if (typeof used === "number" && Number.isSafeInteger(used) && used >= 0 && typeof size === "number" && Number.isSafeInteger(size) && size > 0) {
1213
+ events.push({ _tag: "ContextWindowUpdated", usedTokens: used, maxTokens: size });
1214
+ }
1215
+ break;
1216
+ }
1249
1217
  case "compaction_update": {
1250
1218
  const compactionId = readAcpText(upd, "compactionId");
1251
1219
  const status = readAcpText(upd, "status");
@@ -3441,18 +3409,18 @@ var validateAsync = async (schema, value, _ctx) => {
3441
3409
  return result.issues.length === 0;
3442
3410
  };
3443
3411
  var _encode = (_Err) => {
3444
- const parse4 = _parse(_Err);
3412
+ const parse3 = _parse(_Err);
3445
3413
  const fn = (schema, value, _ctx, _params) => {
3446
3414
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
3447
- return parse4(schema, value, ctx, finalizeParams(fn, _params));
3415
+ return parse3(schema, value, ctx, finalizeParams(fn, _params));
3448
3416
  };
3449
3417
  return fn;
3450
3418
  };
3451
3419
  var encode = /* @__PURE__ */ _encode($ZodRealError);
3452
3420
  var _decode = (_Err) => {
3453
- const parse4 = _parse(_Err);
3421
+ const parse3 = _parse(_Err);
3454
3422
  const fn = (schema, value, _ctx, _params) => {
3455
- return parse4(schema, value, _ctx, finalizeParams(fn, _params));
3423
+ return parse3(schema, value, _ctx, finalizeParams(fn, _params));
3456
3424
  };
3457
3425
  return fn;
3458
3426
  };
@@ -6622,7 +6590,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6622
6590
  var NONE = 0;
6623
6591
  var ASSUMED = 1;
6624
6592
  var PROVEN = 2;
6625
- function isRecursive(inst, stack, resolve5) {
6593
+ function isRecursive(inst, stack, resolve3) {
6626
6594
  const cached2 = recursive.get(inst);
6627
6595
  if (cached2 !== void 0)
6628
6596
  return cached2 ? PROVEN : NONE;
@@ -6632,7 +6600,7 @@ function isRecursive(inst, stack, resolve5) {
6632
6600
  let result = NONE;
6633
6601
  const check2 = (child) => {
6634
6602
  if (result !== PROVEN && child?._zod) {
6635
- const answer = isRecursive(child, stack, resolve5);
6603
+ const answer = isRecursive(child, stack, resolve3);
6636
6604
  if (answer > result)
6637
6605
  result = answer;
6638
6606
  }
@@ -6643,7 +6611,7 @@ function isRecursive(inst, stack, resolve5) {
6643
6611
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6644
6612
  if (spread && !desc.enumerable)
6645
6613
  continue;
6646
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve5) : NONE;
6614
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6647
6615
  if (child > answer)
6648
6616
  answer = child;
6649
6617
  }
@@ -6707,7 +6675,7 @@ function isRecursive(inst, stack, resolve5) {
6707
6675
  break;
6708
6676
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6709
6677
  case "lazy": {
6710
- const inner = def._cachedInner ?? (resolve5 ? inst._zod.innerType : void 0);
6678
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6711
6679
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6712
6680
  break;
6713
6681
  }
@@ -23371,11 +23339,11 @@ var Connection = class {
23371
23339
  const id = this.nextRequestId++;
23372
23340
  let cancel = () => {
23373
23341
  };
23374
- const response = new Promise((resolve5, reject) => {
23342
+ const response = new Promise((resolve3, reject) => {
23375
23343
  const pendingResponse = {
23376
23344
  resolve: (value) => {
23377
23345
  try {
23378
- resolve5(mapResponse ? mapResponse(value) : value);
23346
+ resolve3(mapResponse ? mapResponse(value) : value);
23379
23347
  } catch (error62) {
23380
23348
  reject(error62);
23381
23349
  }
@@ -23432,8 +23400,8 @@ var Connection = class {
23432
23400
  this.stream = stream;
23433
23401
  this.staticHandlers = handlers;
23434
23402
  this.allowBatches = options?.allowBatches ?? true;
23435
- this.closedPromise = new Promise((resolve5) => {
23436
- this.abortController.signal.addEventListener("abort", () => resolve5());
23403
+ this.closedPromise = new Promise((resolve3) => {
23404
+ this.abortController.signal.addEventListener("abort", () => resolve3());
23437
23405
  });
23438
23406
  void this.receive();
23439
23407
  }
@@ -23724,13 +23692,13 @@ var ConnectionBuilder = class {
23724
23692
  /**
23725
23693
  * Adds a typed request handler for one method.
23726
23694
  */
23727
- onReceiveRequest(method, parse4, handler) {
23695
+ onReceiveRequest(method, parse3, handler) {
23728
23696
  return this.withHandler({
23729
23697
  handleMessage: async (message, cx) => {
23730
23698
  if (message.kind !== "request" || message.method !== method) {
23731
23699
  return Handled.no(message);
23732
23700
  }
23733
- const request = parse4(message.params);
23701
+ const request = parse3(message.params);
23734
23702
  return await handler(request, message.responder, cx) ?? Handled.yes();
23735
23703
  },
23736
23704
  describe: () => `${this.connectionName ?? "request"}:${method}`
@@ -23739,13 +23707,13 @@ var ConnectionBuilder = class {
23739
23707
  /**
23740
23708
  * Adds a typed notification handler for one method.
23741
23709
  */
23742
- onReceiveNotification(method, parse4, handler) {
23710
+ onReceiveNotification(method, parse3, handler) {
23743
23711
  return this.withHandler({
23744
23712
  handleMessage: async (message, cx) => {
23745
23713
  if (message.kind !== "notification" || message.method !== method) {
23746
23714
  return Handled.no(message);
23747
23715
  }
23748
- const notification = parse4(message.params);
23716
+ const notification = parse3(message.params);
23749
23717
  return await handler(notification, cx) ?? Handled.yes();
23750
23718
  },
23751
23719
  describe: () => `${this.connectionName ?? "notification"}:${method}`
@@ -24327,8 +24295,8 @@ var AsyncQueue = class {
24327
24295
  if (this.failed) {
24328
24296
  return Promise.reject(this.failure);
24329
24297
  }
24330
- return new Promise((resolve5, reject) => {
24331
- this.waiters.push({ resolve: resolve5, reject });
24298
+ return new Promise((resolve3, reject) => {
24299
+ this.waiters.push({ resolve: resolve3, reject });
24332
24300
  });
24333
24301
  }
24334
24302
  };
@@ -25375,12 +25343,12 @@ function createAcpConnection(options) {
25375
25343
  failIfClosed();
25376
25344
  const id = nextRequestId;
25377
25345
  nextRequestId += 1;
25378
- const { promise: promise2, resolve: resolve5, reject } = Promise.withResolvers();
25346
+ const { promise: promise2, resolve: resolve3, reject } = Promise.withResolvers();
25379
25347
  pending.set(String(id), {
25380
25348
  method,
25381
25349
  ...promptId === void 0 ? {} : { promptId },
25382
25350
  ...onArrival === void 0 ? {} : { onArrival },
25383
- resolve: resolve5,
25351
+ resolve: resolve3,
25384
25352
  reject
25385
25353
  });
25386
25354
  const message = params === void 0 ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
@@ -25409,8 +25377,8 @@ function createAcpConnection(options) {
25409
25377
  if (inboundBatches === 0) {
25410
25378
  return;
25411
25379
  }
25412
- await new Promise((resolve5) => {
25413
- idleWaiters.push(resolve5);
25380
+ await new Promise((resolve3) => {
25381
+ idleWaiters.push(resolve3);
25414
25382
  if (inboundBatches === 0) {
25415
25383
  releaseIdleWaiters();
25416
25384
  }
@@ -25496,8 +25464,8 @@ var Mutex = class {
25496
25464
  this.locked = true;
25497
25465
  return Promise.resolve();
25498
25466
  }
25499
- return new Promise((resolve5) => {
25500
- this.waiters.push(resolve5);
25467
+ return new Promise((resolve3) => {
25468
+ this.waiters.push(resolve3);
25501
25469
  });
25502
25470
  }
25503
25471
  tryAcquire() {
@@ -25698,9 +25666,9 @@ function createExecutorLifecycle({
25698
25666
  let timer;
25699
25667
  await Promise.race([
25700
25668
  connection.closed.catch(() => void 0),
25701
- new Promise((resolve5) => {
25669
+ new Promise((resolve3) => {
25702
25670
  timer = setTimeout(
25703
- resolve5,
25671
+ resolve3,
25704
25672
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
25705
25673
  );
25706
25674
  })
@@ -25873,7 +25841,7 @@ function toolSubagentSettlementOfTurn(state, failureCategory) {
25873
25841
  if (state === "cancelled") return "turn-interrupted";
25874
25842
  return state === "failed" && failureCategory === "process-exit" ? "session-ended" : "turn-ended";
25875
25843
  }
25876
- var sameFacts = (a, b) => a.title === b.title && a.description === b.description && a.summary === b.summary && a.role === b.role && a.model === b.model && a.effort === b.effort && a.rosterKind === b.rosterKind;
25844
+ var sameFacts = (a, b) => a.title === b.title && a.description === b.description && a.summary === b.summary && a.role === b.role && a.model === b.model && a.effort === b.effort && a.nativeSessionId === b.nativeSessionId && a.rosterKind === b.rosterKind;
25877
25845
  function linkage(taskId, toolCallId, facts) {
25878
25846
  return {
25879
25847
  taskId,
@@ -25883,6 +25851,7 @@ function linkage(taskId, toolCallId, facts) {
25883
25851
  ...facts.role === void 0 ? {} : { role: facts.role },
25884
25852
  ...facts.model === void 0 ? {} : { model: facts.model },
25885
25853
  ...facts.effort === void 0 ? {} : { effort: facts.effort },
25854
+ ...facts.nativeSessionId === void 0 ? {} : { nativeSessionId: facts.nativeSessionId },
25886
25855
  ...facts.rosterKind === void 0 ? {} : { rosterKind: facts.rosterKind }
25887
25856
  };
25888
25857
  }
@@ -26577,12 +26546,12 @@ function createPromptResults({
26577
26546
  }) {
26578
26547
  const prompts = /* @__PURE__ */ new Map();
26579
26548
  const add = (identity, finish) => {
26580
- const { promise: done, resolve: resolve5 } = Promise.withResolvers();
26549
+ const { promise: done, resolve: resolve3 } = Promise.withResolvers();
26581
26550
  const record3 = {
26582
26551
  ...identity,
26583
26552
  finish,
26584
26553
  done,
26585
- resolve: resolve5,
26554
+ resolve: resolve3,
26586
26555
  rejected: false,
26587
26556
  interrupted: false,
26588
26557
  finished: false
@@ -26630,9 +26599,9 @@ function createPromptResults({
26630
26599
  try {
26631
26600
  const drained = await Promise.race([
26632
26601
  Promise.all(claimed.map((record3) => record3.done)).then(() => true),
26633
- new Promise((resolve5) => {
26602
+ new Promise((resolve3) => {
26634
26603
  timer = setTimeout(
26635
- () => resolve5(false),
26604
+ () => resolve3(false),
26636
26605
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
26637
26606
  );
26638
26607
  })
@@ -26831,14 +26800,14 @@ function createExecutorRequests({
26831
26800
  const statement = hooks.permissionStatement?.(permissionContext) ?? defaultPermissionStatement(permissionRequest);
26832
26801
  const fileChanges = hooks.permissionFileChanges?.(permissionContext) ?? fileChangesFromAcpPermission(permissionRequest);
26833
26802
  const requestId = randomId();
26834
- const outcome = await new Promise((resolve5) => {
26803
+ const outcome = await new Promise((resolve3) => {
26835
26804
  const pending = {
26836
26805
  requestId,
26837
26806
  request: params,
26838
26807
  permissionRequest,
26839
26808
  turnId: shared.activeTurnId,
26840
26809
  settled: false,
26841
- resolve: resolve5
26810
+ resolve: resolve3
26842
26811
  };
26843
26812
  approvals.add(pending);
26844
26813
  emit(
@@ -26921,7 +26890,7 @@ function createExecutorRequests({
26921
26890
  }
26922
26891
 
26923
26892
  // ../../packages/ycodium-acp-executor/src/artifacts.ts
26924
- import * as NodePath2 from "node:path";
26893
+ import * as NodePath from "node:path";
26925
26894
  import * as NodeURL from "node:url";
26926
26895
  function resourceLinkArtifacts(content) {
26927
26896
  if (content["type"] !== "resource_link" || typeof content["uri"] !== "string") return [];
@@ -26932,7 +26901,7 @@ function resourceLinkArtifacts(content) {
26932
26901
  } catch {
26933
26902
  return [];
26934
26903
  }
26935
- if (!NodePath2.isAbsolute(path)) return [];
26904
+ if (!NodePath.isAbsolute(path)) return [];
26936
26905
  const name = typeof content["name"] === "string" ? content["name"].trim() : "";
26937
26906
  const mimeType = typeof content["mimeType"] === "string" ? content["mimeType"].trim() : "";
26938
26907
  return [
@@ -27055,14 +27024,14 @@ function createExecutorRuntime({
27055
27024
  if (!promptMutex.isLocked) {
27056
27025
  return true;
27057
27026
  }
27058
- return await new Promise((resolve5) => {
27027
+ return await new Promise((resolve3) => {
27059
27028
  const timer = setTimeout(() => {
27060
27029
  shared.promptWaiters = shared.promptWaiters.filter((waiter) => waiter !== onSettle);
27061
- resolve5(false);
27030
+ resolve3(false);
27062
27031
  }, timeoutMs);
27063
27032
  const onSettle = () => {
27064
27033
  clearTimeout(timer);
27065
- resolve5(true);
27034
+ resolve3(true);
27066
27035
  };
27067
27036
  shared.promptWaiters.push(onSettle);
27068
27037
  });
@@ -27431,10 +27400,27 @@ function createExecutorSession({
27431
27400
  throw new AcpExecutorDisposedError();
27432
27401
  }
27433
27402
  }
27403
+ const mcpCapabilities = initialized.agentCapabilities?.mcpCapabilities ?? hooks.mcpCapabilities;
27404
+ const requestedMcpServers = options.mcpServers ?? [];
27434
27405
  const mcpServers = filterMcpServersByAgentCapabilities(
27435
- options.mcpServers ?? [],
27436
- initialized.agentCapabilities
27406
+ requestedMcpServers,
27407
+ mcpCapabilities === void 0 ? initialized.agentCapabilities : { mcpCapabilities }
27437
27408
  );
27409
+ if (mcpServers.length < requestedMcpServers.length) {
27410
+ const kept = new Set(mcpServers);
27411
+ const dropped = requestedMcpServers.filter((server) => !kept.has(server)).map((server) => ({
27412
+ ...typeof server["name"] === "string" ? { name: server["name"] } : {},
27413
+ ...typeof server.type === "string" ? { type: server.type } : {}
27414
+ }));
27415
+ options.log?.warn?.(
27416
+ "acp session dropped MCP servers whose transport was not advertised in initialize.agentCapabilities.mcpCapabilities; set hooks.mcpCapabilities if the agent supports the transport without reporting it",
27417
+ {
27418
+ threadId: options.threadId,
27419
+ dropped,
27420
+ advertisedMcpCapabilities: initialized.agentCapabilities?.mcpCapabilities ?? null
27421
+ }
27422
+ );
27423
+ }
27438
27424
  const additionalDirectories = options.additionalDirectories !== void 0 && options.additionalDirectories.length > 0 ? { additionalDirectories: options.additionalDirectories } : {};
27439
27425
  let setup;
27440
27426
  let nextSessionId;
@@ -28029,6 +28015,17 @@ function createExecutorUpdates({
28029
28015
  emitArtifacts(resourceLinkArtifacts(event2.content));
28030
28016
  continue;
28031
28017
  }
28018
+ if (event2._tag === "ContextWindowUpdated") {
28019
+ emit({
28020
+ type: "thread.token-usage.updated",
28021
+ ...stamp(),
28022
+ provider: options.provider,
28023
+ threadId: options.threadId,
28024
+ ...shared.activeTurnId === void 0 ? {} : { turnId: shared.activeTurnId },
28025
+ payload: { usage: { usedTokens: event2.usedTokens, maxTokens: event2.maxTokens } }
28026
+ });
28027
+ continue;
28028
+ }
28032
28029
  if (event2._tag === "CompactionUpdated") {
28033
28030
  applyCompactionUpdate(event2);
28034
28031
  continue;
@@ -28146,8 +28143,8 @@ function readOpenToolCalls(toolCalls, turnId) {
28146
28143
 
28147
28144
  // ../../packages/ycodium-acp-executor/src/protocol-log.ts
28148
28145
  import * as NodeFS from "node:fs";
28149
- import * as NodeOS2 from "node:os";
28150
- import * as NodePath3 from "node:path";
28146
+ import * as NodeOS from "node:os";
28147
+ import * as NodePath2 from "node:path";
28151
28148
  var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
28152
28149
  var UNSAFE_FILE_CHARS = /[^A-Za-z0-9._-]+/gu;
28153
28150
  function safeFileName(value) {
@@ -28156,7 +28153,7 @@ function safeFileName(value) {
28156
28153
  function createAcpProtocolLogFile(input2) {
28157
28154
  const maxBytes = input2.maxBytes ?? DEFAULT_MAX_BYTES;
28158
28155
  NodeFS.mkdirSync(input2.directory, { recursive: true });
28159
- const filePath = NodePath3.join(
28156
+ const filePath = NodePath2.join(
28160
28157
  input2.directory,
28161
28158
  `${safeFileName(input2.provider)}-${safeFileName(input2.threadId)}-${Date.now().toString(36)}.ndjson`
28162
28159
  );
@@ -28212,7 +28209,7 @@ function createAcpProtocolLogFromEnv(input2) {
28212
28209
  const flag = process.env.YCODIUM_ACP_PROTOCOL_LOG;
28213
28210
  if (flag !== "1" && flag?.toLowerCase() !== "true") return void 0;
28214
28211
  const configured = process.env.YCODIUM_ACP_PROTOCOL_LOG_DIR?.trim();
28215
- const directory = configured && configured.length > 0 ? configured : NodePath3.join(NodeOS2.tmpdir(), "ycodium-acp-protocol");
28212
+ const directory = configured && configured.length > 0 ? configured : NodePath2.join(NodeOS.tmpdir(), "ycodium-acp-protocol");
28216
28213
  try {
28217
28214
  const sink = createAcpProtocolLogFile({
28218
28215
  directory,
@@ -28654,13 +28651,13 @@ function acpNativeSessionProcessMatcher(program, args) {
28654
28651
 
28655
28652
  // ../../packages/ycodium-acp-executor/src/prompt-dispatch.ts
28656
28653
  var dispatchAcpPrompt = (executor, input2) => {
28657
- const { promise: dispatched, resolve: resolve5 } = Promise.withResolvers();
28654
+ const { promise: dispatched, resolve: resolve3 } = Promise.withResolvers();
28658
28655
  let written = false;
28659
28656
  const finished = executor.prompt({
28660
28657
  ...input2,
28661
28658
  onDispatched: (turnId) => {
28662
28659
  written = true;
28663
- resolve5(turnId);
28660
+ resolve3(turnId);
28664
28661
  }
28665
28662
  });
28666
28663
  return Promise.race([
@@ -28675,8 +28672,8 @@ var dispatchAcpPrompt = (executor, input2) => {
28675
28672
  };
28676
28673
 
28677
28674
  // ../../packages/ycodium-acp-executor/src/thread-operations.ts
28678
- var yieldTick = () => new Promise((resolve5) => {
28679
- setImmediate(resolve5);
28675
+ var yieldTick = () => new Promise((resolve3) => {
28676
+ setImmediate(resolve3);
28680
28677
  });
28681
28678
  var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
28682
28679
  function createAcpThreadOperations(options) {
@@ -28769,7 +28766,7 @@ function modelSelectionStringOption(selection, optionId) {
28769
28766
  }
28770
28767
 
28771
28768
  // ../../packages/ycodium-executor-common/src/nodeStreams.ts
28772
- import * as NodeOS3 from "node:os";
28769
+ import * as NodeOS2 from "node:os";
28773
28770
  import * as NodeStream2 from "node:stream";
28774
28771
  var PEER_CLOSED_STDIN_CODES = /* @__PURE__ */ new Set([
28775
28772
  "EPIPE",
@@ -28837,7 +28834,7 @@ var API_KEY_HEADER_PATTERN = /\bx-api-key:\s*\S+/gi;
28837
28834
  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;
28838
28835
  function redactStderrExcerpt(text2, environment = process.env) {
28839
28836
  let result = text2.replaceAll("\0", "");
28840
- const homes = [environment["HOME"], environment["USERPROFILE"], NodeOS3.homedir()].filter(
28837
+ const homes = [environment["HOME"], environment["USERPROFILE"], NodeOS2.homedir()].filter(
28841
28838
  (value) => typeof value === "string" && value.length > 1
28842
28839
  );
28843
28840
  for (const home of new Set(homes)) {
@@ -28858,8 +28855,8 @@ function drainStderrTail(stderr) {
28858
28855
  let timer;
28859
28856
  await Promise.race([
28860
28857
  drained,
28861
- new Promise((resolve5) => {
28862
- timer = setTimeout(resolve5, STDERR_SETTLE_MS);
28858
+ new Promise((resolve3) => {
28859
+ timer = setTimeout(resolve3, STDERR_SETTLE_MS);
28863
28860
  })
28864
28861
  ]);
28865
28862
  clearTimeout(timer);
@@ -28873,11 +28870,11 @@ function nodeStreamsFromHandle(handle, errors = ownErrors) {
28873
28870
  for await (const chunk of handle.stdout) {
28874
28871
  if (!readable.writable) return;
28875
28872
  if (!readable.write(chunk)) {
28876
- await new Promise((resolve5) => {
28873
+ await new Promise((resolve3) => {
28877
28874
  const onDone = () => {
28878
28875
  readable.off("drain", onDone);
28879
28876
  readable.off("close", onDone);
28880
- resolve5();
28877
+ resolve3();
28881
28878
  };
28882
28879
  readable.once("drain", onDone);
28883
28880
  readable.once("close", onDone);
@@ -28934,8 +28931,8 @@ async function raceStartAbort(promise2, signal) {
28934
28931
  }
28935
28932
 
28936
28933
  // ../../packages/ycodium-acp-executor/src/instance-kit.ts
28937
- var yieldTick2 = () => new Promise((resolve5) => {
28938
- setImmediate(resolve5);
28934
+ var yieldTick2 = () => new Promise((resolve3) => {
28935
+ setImmediate(resolve3);
28939
28936
  });
28940
28937
  var nowIso2 = () => (/* @__PURE__ */ new Date()).toISOString();
28941
28938
  function createAcpThreadTable(log, beforeStopAll) {
@@ -29153,145 +29150,13 @@ function parseCliVersion(output2) {
29153
29150
  }
29154
29151
  var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
29155
29152
 
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
- // ../../packages/ycodium-instance-config/src/launchArgs.ts
29181
- function tokenizeShellWords(value) {
29182
- const input2 = value.trim();
29183
- if (!input2) return [];
29184
- const tokens = [];
29185
- let current = "";
29186
- let quote;
29187
- let quoted = false;
29188
- for (let index = 0; index < input2.length; index++) {
29189
- const char = input2[index];
29190
- if (char === void 0) continue;
29191
- if (quote) {
29192
- if (char === quote) {
29193
- quote = void 0;
29194
- quoted = true;
29195
- } else if (char === "\\" && quote === '"') {
29196
- const next = input2[index + 1];
29197
- if (next !== void 0 && ['"', "\\", "$", "`"].includes(next)) {
29198
- current += next;
29199
- index++;
29200
- } else {
29201
- current += char;
29202
- }
29203
- } else {
29204
- current += char;
29205
- }
29206
- continue;
29207
- }
29208
- if (char === "'" || char === '"') {
29209
- quote = char;
29210
- quoted = true;
29211
- } else if (/\s/.test(char)) {
29212
- if (current || quoted) {
29213
- tokens.push(current);
29214
- current = "";
29215
- quoted = false;
29216
- }
29217
- } else if (char === "\\") {
29218
- const next = input2[index + 1];
29219
- if (next !== void 0 && /\s/.test(next)) {
29220
- current += next;
29221
- index++;
29222
- } else {
29223
- current += char;
29224
- }
29225
- } else {
29226
- current += char;
29227
- }
29228
- }
29229
- if (current || quoted) tokens.push(current);
29230
- return tokens;
29231
- }
29232
-
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
- }
29153
+ // src/kimiInstance.ts
29154
+ import { createCliDeviceSignIn } from "@ycodium-ai/plugin-api/runtime-maintenance";
29293
29155
 
29294
29156
  // src/config.ts
29157
+ import {
29158
+ readLaunchInstanceRecipe
29159
+ } from "@ycodium-ai/plugin-api/instance-config";
29295
29160
  function parseKimiInstanceConfig(config2) {
29296
29161
  return {
29297
29162
  ...readLaunchInstanceRecipe(config2, KIMI_CARD.launchArgs),
@@ -29304,21 +29169,21 @@ import * as NodeFS3 from "node:fs";
29304
29169
 
29305
29170
  // src/kimi.ts
29306
29171
  import * as NodeFS2 from "node:fs";
29307
- import * as NodePath4 from "node:path";
29172
+ import * as NodePath3 from "node:path";
29308
29173
  var KIMI_USER_INPUT_TITLES = /* @__PURE__ */ new Set(["AskUserQuestion", "ExitPlanMode"]);
29309
29174
  var KIMI_PLAN_ACTIONS = {
29310
29175
  plan_approve: "approve",
29311
29176
  plan_revise: "revise",
29312
29177
  plan_reject_and_exit: "stop"
29313
29178
  };
29314
- var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29179
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29315
29180
  function questionTextFromContent(content) {
29316
29181
  if (!Array.isArray(content)) return "";
29317
29182
  const parts = [];
29318
29183
  for (const entry of content) {
29319
- if (!isRecord8(entry) || entry["type"] !== "content") continue;
29184
+ if (!isRecord7(entry) || entry["type"] !== "content") continue;
29320
29185
  const inner = entry["content"];
29321
- if (!isRecord8(inner) || inner["type"] !== "text") continue;
29186
+ if (!isRecord7(inner) || inner["type"] !== "text") continue;
29322
29187
  const text2 = inner["text"];
29323
29188
  if (typeof text2 === "string") parts.push(text2);
29324
29189
  }
@@ -29370,7 +29235,7 @@ function parseKimiContextWindow(contents) {
29370
29235
  } catch {
29371
29236
  continue;
29372
29237
  }
29373
- if (!isRecord8(record3)) continue;
29238
+ if (!isRecord7(record3)) continue;
29374
29239
  const type = record3["type"];
29375
29240
  if (type === "token_counting.turn_recorded" || type === "token_counting.measured") {
29376
29241
  usedTokens = positiveInt(record3["tokens"]) ?? usedTokens;
@@ -29407,7 +29272,7 @@ function readTail(filePath) {
29407
29272
  function findKimiSessionWireLog(input2) {
29408
29273
  if (!input2.acpSessionId || /[\\/:]/u.test(input2.acpSessionId) || [".", ".."].includes(input2.acpSessionId))
29409
29274
  return void 0;
29410
- const sessionsRoot = NodePath4.join(input2.homePath, SESSIONS_DIR);
29275
+ const sessionsRoot = NodePath3.join(input2.homePath, SESSIONS_DIR);
29411
29276
  let workspaces;
29412
29277
  try {
29413
29278
  workspaces = NodeFS2.readdirSync(sessionsRoot);
@@ -29415,7 +29280,7 @@ function findKimiSessionWireLog(input2) {
29415
29280
  return void 0;
29416
29281
  }
29417
29282
  for (const workspace of workspaces) {
29418
- const candidate = NodePath4.join(
29283
+ const candidate = NodePath3.join(
29419
29284
  sessionsRoot,
29420
29285
  workspace,
29421
29286
  input2.acpSessionId,
@@ -29508,13 +29373,13 @@ function observeKimiPromptFailure(homePath, acpSessionId) {
29508
29373
  if (first !== "pending") return first;
29509
29374
  const path = original ?? find();
29510
29375
  if (!path) return void 0;
29511
- return new Promise((resolve5) => {
29376
+ return new Promise((resolve3) => {
29512
29377
  let watcher;
29513
29378
  const finish = (failure2) => {
29514
29379
  clearTimeout(deadline);
29515
29380
  signal.removeEventListener("abort", abort);
29516
29381
  watcher?.close();
29517
- resolve5(failure2);
29382
+ resolve3(failure2);
29518
29383
  };
29519
29384
  const abort = () => finish();
29520
29385
  const check2 = () => {
@@ -29536,83 +29401,28 @@ function observeKimiPromptFailure(homePath, acpSessionId) {
29536
29401
 
29537
29402
  // src/kimiQuota.ts
29538
29403
  import * as NodeFS5 from "node:fs";
29539
- import * as NodeOS5 from "node:os";
29540
- import * as NodePath6 from "node:path";
29541
-
29542
- // ../../packages/ycodium-instance-config/src/tomlScalar.ts
29543
- function readTomlScalar(raw) {
29544
- const quoted = /^(["'])(.*?)\1/.exec(raw.trim());
29545
- if (quoted?.[2] !== void 0) return quoted[2];
29546
- const [beforeComment = ""] = raw.split("#");
29547
- return beforeComment.trim();
29548
- }
29549
-
29550
- // src/kimiQuota.ts
29404
+ import * as NodeOS4 from "node:os";
29405
+ import * as NodePath5 from "node:path";
29406
+ import { readTomlScalar } from "@ycodium-ai/plugin-api/instance-config";
29551
29407
  import "@ycodium-ai/plugin-api/usage";
29552
-
29553
- // ../../packages/ycodium-credential-account/src/quotaRequest.ts
29554
- import { parseRetryAfterMs } from "@ycodium-ai/plugin-api/usage";
29555
-
29556
- // ../../packages/ycodium-credential-account/src/credentialAccount.ts
29557
- var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29558
-
29559
- // ../../packages/ycodium-credential-account/src/quotaRequest.ts
29560
- async function requestQuotaJson(input2) {
29561
- let response;
29562
- try {
29563
- response = await input2.fetch(input2.url, {
29564
- headers: input2.headers,
29565
- signal: AbortSignal.any([
29566
- ...input2.signal === void 0 ? [] : [input2.signal],
29567
- AbortSignal.timeout(input2.timeoutMs)
29568
- ])
29569
- });
29570
- } catch {
29571
- return { status: "unavailable", reason: "unreachable" };
29572
- }
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
- };
29583
- }
29584
- if (!response.ok) return { status: "unavailable", reason: "unreachable" };
29585
- let body;
29586
- try {
29587
- body = JSON.parse(await response.text());
29588
- } catch {
29589
- return { status: "unavailable", reason: "unreachable" };
29590
- }
29591
- if (!isRecord9(body)) return { status: "unavailable", reason: "unreachable" };
29592
- return { body };
29593
- }
29594
-
29595
- // ../../packages/ycodium-credential-account/src/quotaJson.ts
29596
- var asObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
29597
- var asString3 = (value) => typeof value === "string" && value.length > 0 ? value : null;
29598
- var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
29599
- var parseJson = (raw) => {
29600
- try {
29601
- return JSON.parse(raw);
29602
- } catch {
29603
- return null;
29604
- }
29605
- };
29408
+ import {
29409
+ requestQuotaJson,
29410
+ clampPercent,
29411
+ asNumber,
29412
+ asObject,
29413
+ asString as asString3,
29414
+ parseJson
29415
+ } from "@ycodium-ai/plugin-api/credential-account";
29606
29416
 
29607
29417
  // src/kimiAccount.ts
29608
29418
  import * as NodeFS4 from "node:fs";
29609
- import * as NodeOS4 from "node:os";
29610
- import * as NodePath5 from "node:path";
29419
+ import * as NodeOS3 from "node:os";
29420
+ import * as NodePath4 from "node:path";
29611
29421
  function kimiAccountHome(resolvedHomePath) {
29612
- return resolvedHomePath.trim().length > 0 ? resolvedHomePath : NodePath5.join(NodeOS4.homedir(), ".kimi-code");
29422
+ return resolvedHomePath.trim().length > 0 ? resolvedHomePath : NodePath4.join(NodeOS3.homedir(), ".kimi-code");
29613
29423
  }
29614
29424
  function kimiCredentialsPath(resolvedHomePath) {
29615
- return NodePath5.join(kimiAccountHome(resolvedHomePath), "credentials", "kimi-code.json");
29425
+ return NodePath4.join(kimiAccountHome(resolvedHomePath), "credentials", "kimi-code.json");
29616
29426
  }
29617
29427
  var nonEmptyString = (value) => typeof value === "string" && value.length > 0;
29618
29428
  function readKimiAuthState(resolvedHomePath) {
@@ -29647,7 +29457,6 @@ var asCount = (value) => {
29647
29457
  const parsed = Number(text2);
29648
29458
  return Number.isFinite(parsed) ? parsed : null;
29649
29459
  };
29650
- var clampPercent = (value) => Math.min(100, Math.max(0, value));
29651
29460
  var expiryMs = (value) => {
29652
29461
  const raw = asNumber(value);
29653
29462
  if (raw === null || raw <= 0) return null;
@@ -29767,12 +29576,12 @@ var kimiEffectiveHome = (resolvedHomePath, processEnvHome) => {
29767
29576
  var createKimiUsage = (input2) => {
29768
29577
  const now = input2.now ?? Date.now;
29769
29578
  const processEnv = input2.processEnv ?? process.env;
29770
- const home = input2.homePath.trim().length > 0 ? input2.homePath : NodePath6.join(NodeOS5.homedir(), ".kimi-code");
29579
+ const home = input2.homePath.trim().length > 0 ? input2.homePath : NodePath5.join(NodeOS4.homedir(), ".kimi-code");
29771
29580
  const credentialsPath = kimiCredentialsPath(input2.homePath);
29772
29581
  const readQuota = async (request) => {
29773
29582
  let configToml = null;
29774
29583
  try {
29775
- configToml = NodeFS5.readFileSync(NodePath6.join(home, "config.toml"), "utf8");
29584
+ configToml = NodeFS5.readFileSync(NodePath5.join(home, "config.toml"), "utf8");
29776
29585
  } catch (error62) {
29777
29586
  if (error62.code !== "ENOENT") {
29778
29587
  return { status: "unavailable", reason: "unreachable" };
@@ -29814,11 +29623,11 @@ var createKimiUsage = (input2) => {
29814
29623
 
29815
29624
  // src/kimiTokens.ts
29816
29625
  import * as NodeFS6 from "node:fs";
29817
- import * as NodeOS6 from "node:os";
29818
- import * as NodePath7 from "node:path";
29626
+ import * as NodeOS5 from "node:os";
29627
+ import * as NodePath6 from "node:path";
29819
29628
  var MTIME_SLACK_MS = 36 * 60 * 60 * 1e3;
29820
29629
  var GUARD_LENGTH = 64;
29821
- var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29630
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29822
29631
  var count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
29823
29632
  var parseKimiUsageLine = (line) => {
29824
29633
  if (!line.includes('"usage.record"')) return void 0;
@@ -29828,11 +29637,11 @@ var parseKimiUsageLine = (line) => {
29828
29637
  } catch {
29829
29638
  return "malformed";
29830
29639
  }
29831
- if (!isRecord10(parsed) || parsed["type"] !== "usage.record") return void 0;
29640
+ if (!isRecord8(parsed) || parsed["type"] !== "usage.record") return void 0;
29832
29641
  const usage = parsed["usage"];
29833
29642
  const model = typeof parsed["model"] === "string" ? parsed["model"].trim() : "";
29834
29643
  const timeMs = parsed["time"];
29835
- if (!isRecord10(usage) || model.length === 0 || typeof timeMs !== "number" || !Number.isFinite(timeMs)) {
29644
+ if (!isRecord8(usage) || model.length === 0 || typeof timeMs !== "number" || !Number.isFinite(timeMs)) {
29836
29645
  return "malformed";
29837
29646
  }
29838
29647
  const totals = {
@@ -29860,10 +29669,10 @@ var readDirs = (dir) => {
29860
29669
  var listWireLogs = (sessionsRoot) => {
29861
29670
  const found = [];
29862
29671
  for (const workspace of readDirs(sessionsRoot)) {
29863
- for (const session of readDirs(NodePath7.join(sessionsRoot, workspace))) {
29864
- const agentsDir = NodePath7.join(sessionsRoot, workspace, session, "agents");
29672
+ for (const session of readDirs(NodePath6.join(sessionsRoot, workspace))) {
29673
+ const agentsDir = NodePath6.join(sessionsRoot, workspace, session, "agents");
29865
29674
  for (const agent of readDirs(agentsDir)) {
29866
- found.push({ file: NodePath7.join(agentsDir, agent, "wire.jsonl"), sessionId: session });
29675
+ found.push({ file: NodePath6.join(agentsDir, agent, "wire.jsonl"), sessionId: session });
29867
29676
  }
29868
29677
  }
29869
29678
  }
@@ -29887,8 +29696,8 @@ var readRange = (file2, from, to) => {
29887
29696
  };
29888
29697
  var guardOf = (file2, size) => readRange(file2, 0, Math.min(size, GUARD_LENGTH)).toString("base64");
29889
29698
  var createKimiTokenReader = (input2) => {
29890
- const home = input2.homePath.trim().length > 0 ? NodePath7.resolve(input2.homePath) : NodePath7.join(NodeOS6.homedir(), ".kimi-code");
29891
- const sessionsRoot = NodePath7.join(home, "sessions");
29699
+ const home = input2.homePath.trim().length > 0 ? NodePath6.resolve(input2.homePath) : NodePath6.join(NodeOS5.homedir(), ".kimi-code");
29700
+ const sessionsRoot = NodePath6.join(home, "sessions");
29892
29701
  const memos = /* @__PURE__ */ new Map();
29893
29702
  const refresh = (file2, size) => {
29894
29703
  const guard = guardOf(file2, size);
@@ -29980,9 +29789,10 @@ var createKimiTokenReader = (input2) => {
29980
29789
  };
29981
29790
 
29982
29791
  // src/kimiModels.ts
29792
+ import { readCliVersionCommand } from "@ycodium-ai/plugin-api/instance-config";
29983
29793
  import {
29984
29794
  runProcessOperation,
29985
- OperationCleanupError
29795
+ isOperationCleanupError
29986
29796
  } from "@ycodium-ai/plugin-api/process-operation";
29987
29797
  import {
29988
29798
  describeExecutorSpawnFailure,
@@ -29999,7 +29809,7 @@ var ACP_EFFORT_OPTION_ID = "reasoning";
29999
29809
  var PROBE_TIMEOUT_MS = 15e3;
30000
29810
  var MAX_OUTPUT_BYTES = 1024 * 1024;
30001
29811
  var KIMI_MODEL_LIST_ARGS = ["provider", "list", "--json"];
30002
- function isRecord11(value) {
29812
+ function isRecord9(value) {
30003
29813
  return typeof value === "object" && value !== null && !Array.isArray(value);
30004
29814
  }
30005
29815
  function asString4(value) {
@@ -30037,13 +29847,13 @@ function kimiProbeModels(stdout) {
30037
29847
  } catch {
30038
29848
  return void 0;
30039
29849
  }
30040
- if (!isRecord11(parsed)) return void 0;
29850
+ if (!isRecord9(parsed)) return void 0;
30041
29851
  const models = parsed["models"];
30042
- if (!isRecord11(models)) return void 0;
29852
+ if (!isRecord9(models)) return void 0;
30043
29853
  const out = [];
30044
29854
  for (const [slug, entry] of Object.entries(models)) {
30045
29855
  const trimmed2 = slug.trim();
30046
- if (trimmed2.length === 0 || !isRecord11(entry)) continue;
29856
+ if (trimmed2.length === 0 || !isRecord9(entry)) continue;
30047
29857
  const name = asString4(entry["displayName"]);
30048
29858
  const contextWindow = positiveInt2(entry["maxContextSize"]);
30049
29859
  const effort = kimiEffortDescriptor(entry);
@@ -30095,7 +29905,7 @@ async function probeKimiModels(input2) {
30095
29905
  models: run.stdout === void 0 ? void 0 : kimiProbeModels(run.stdout)
30096
29906
  };
30097
29907
  } catch (error62) {
30098
- if (error62 instanceof ExecutorSpawnRefusedError || error62 instanceof ExecutorSpawnAbortedError || error62 instanceof OperationCleanupError || input2.signal?.aborted)
29908
+ if (error62 instanceof ExecutorSpawnRefusedError || error62 instanceof ExecutorSpawnAbortedError || isOperationCleanupError(error62) || input2.signal?.aborted)
30099
29909
  throw error62;
30100
29910
  if (!spawned) return { kind: "not-started", ...describeExecutorSpawnFailure(error62) };
30101
29911
  return { kind: "failed", detail: acpProbeFailureDetail(error62) };
@@ -30103,22 +29913,13 @@ async function probeKimiModels(input2) {
30103
29913
  }
30104
29914
  async function probeKimiVersion(input2) {
30105
29915
  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
- }
29916
+ return readCliVersionCommand(host, {
29917
+ program: recipe.binaryPath,
29918
+ env,
29919
+ signal,
29920
+ timeoutMs: PROBE_TIMEOUT_MS,
29921
+ parse: parseCliVersion
29922
+ });
30122
29923
  }
30123
29924
  async function probeKimi(input2) {
30124
29925
  const [listed, version2] = await Promise.all([probeKimiModels(input2), probeKimiVersion(input2)]);
@@ -30221,7 +30022,7 @@ var FOREGROUND_ENDED_DESCRIPTION = "Turn ended before Kimi reported this agent's
30221
30022
  var BACKGROUND_ENDED_DESCRIPTION = "Running in the background. Kimi does not report when it finishes.";
30222
30023
  var SINGLE_TITLE = /^Launching (background )?(\S+) agent: ([\s\S]*)$/u;
30223
30024
  var SWARM_TITLE_PREFIX = "Launching agent swarm: ";
30224
- var isRecord12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30025
+ var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30225
30026
  var trimmed = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
30226
30027
  function classify(input2) {
30227
30028
  if (input2.kind !== void 0 && input2.kind !== "other") return void 0;
@@ -30235,7 +30036,7 @@ function requestedModel(value) {
30235
30036
  return model === "primary" ? void 0 : model;
30236
30037
  }
30237
30038
  function describe3(kind, input2, previous) {
30238
- const raw = isRecord12(input2.rawInput) ? input2.rawInput : {};
30039
+ const raw = isRecord10(input2.rawInput) ? input2.rawInput : {};
30239
30040
  if (kind === "swarm") {
30240
30041
  const fromTitle = input2.title?.startsWith(SWARM_TITLE_PREFIX) ? trimmed(input2.title.slice(SWARM_TITLE_PREFIX.length)) : void 0;
30241
30042
  return {
@@ -30336,7 +30137,7 @@ var kimiToolSubagents = {
30336
30137
  announce: "started",
30337
30138
  resolve: (call, kind) => resolveOutcome(call, asKind(kind)),
30338
30139
  resumes: (call, kind) => {
30339
- if (asKind(kind) !== "subagent" || !isRecord12(call.rawInput)) return void 0;
30140
+ if (asKind(kind) !== "subagent" || !isRecord10(call.rawInput)) return void 0;
30340
30141
  return trimmed(call.rawInput["resume"]);
30341
30142
  },
30342
30143
  endNote: ({ background }) => background ? { description: BACKGROUND_ENDED_DESCRIPTION, timelineBypass: true } : { description: FOREGROUND_ENDED_DESCRIPTION }
@@ -30370,8 +30171,16 @@ var kimiPermissionStatement = ({
30370
30171
  // src/nativeSessions.ts
30371
30172
  import * as NodeFS7 from "node:fs";
30372
30173
  import * as NodeFSP from "node:fs/promises";
30373
- import * as NodePath8 from "node:path";
30174
+ import * as NodePath7 from "node:path";
30374
30175
  import * as NodeReadline from "node:readline";
30176
+ import {
30177
+ directoryKey,
30178
+ isAbsoluteDirectory,
30179
+ matchesSessionDirectory,
30180
+ readableStoragePath,
30181
+ inputPayload as inputPayload2,
30182
+ outputPayload as outputPayload2
30183
+ } from "@ycodium-ai/plugin-api/session-history";
30375
30184
  var sessionIdPattern = /^[a-zA-Z0-9_-]+$/u;
30376
30185
  function record2(value) {
30377
30186
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
@@ -30395,47 +30204,33 @@ async function directories(path) {
30395
30204
  throw error62;
30396
30205
  }
30397
30206
  }
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
30207
  async function findSessions(home, cwd, signal, nativeSessionId) {
30416
30208
  signal?.throwIfAborted();
30417
30209
  const expectedCwd = directoryKey(cwd);
30418
30210
  const result = [];
30419
- const root = NodePath8.join(home, "sessions");
30211
+ const root = NodePath7.join(home, "sessions");
30420
30212
  for (const workspace of await directories(root)) {
30421
30213
  if (workspace.startsWith(".")) continue;
30422
- const workspacePath = NodePath8.join(root, workspace);
30214
+ const workspacePath = NodePath7.join(root, workspace);
30423
30215
  for (const id of await directories(workspacePath)) {
30424
30216
  signal?.throwIfAborted();
30425
30217
  if (!sessionIdPattern.test(id) || nativeSessionId !== void 0 && nativeSessionId !== id)
30426
30218
  continue;
30427
- const sessionPath = NodePath8.join(workspacePath, id);
30428
- const statePath = NodePath8.join(sessionPath, "state.json");
30219
+ const sessionPath = NodePath7.join(workspacePath, id);
30220
+ const statePath = NodePath7.join(sessionPath, "state.json");
30429
30221
  try {
30430
30222
  if (!(await NodeFSP.lstat(statePath)).isFile()) continue;
30431
30223
  const state = parseRecord(await NodeFSP.readFile(statePath, { encoding: "utf8", signal }));
30432
30224
  if (state?.id !== id || typeof state.cwd !== "string" || !isAbsoluteDirectory(state.cwd))
30433
30225
  continue;
30434
- const relative2 = NodePath8.relative(expectedCwd, directoryKey(state.cwd));
30435
- if (relative2 !== "" && (nativeSessionId !== void 0 || relative2 === ".." || relative2.startsWith(`..${NodePath8.sep}`) || NodePath8.isAbsolute(relative2)))
30226
+ if (!matchesSessionDirectory(
30227
+ expectedCwd,
30228
+ state.cwd,
30229
+ nativeSessionId === void 0 ? "scan" : "read"
30230
+ ))
30436
30231
  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())
30232
+ const wire = NodePath7.join(sessionPath, "agents", "main", "wire.jsonl");
30233
+ if (!(await NodeFSP.lstat(NodePath7.join(sessionPath, "agents"))).isDirectory() || !(await NodeFSP.lstat(NodePath7.dirname(wire))).isDirectory() || !(await NodeFSP.lstat(wire)).isFile())
30439
30234
  continue;
30440
30235
  result.push({
30441
30236
  id,
@@ -30528,7 +30323,7 @@ async function readTranscript(session, signal, summaryOnly = false) {
30528
30323
  toolName: name,
30529
30324
  itemType: record2(event2.display)?.kind === "command" ? "command_execution" : "dynamic_tool_call",
30530
30325
  startedAt: createdAt,
30531
- ...inputPayload(input2)
30326
+ ...inputPayload2(input2)
30532
30327
  }
30533
30328
  };
30534
30329
  activities.push(activity);
@@ -30549,7 +30344,7 @@ async function readTranscript(session, signal, summaryOnly = false) {
30549
30344
  payload: {
30550
30345
  ...start.payload,
30551
30346
  status,
30552
- ...outputPayload(output2)
30347
+ ...outputPayload2(output2)
30553
30348
  }
30554
30349
  });
30555
30350
  }
@@ -30671,8 +30466,15 @@ function kimiHooks(recipe) {
30671
30466
  readContextWindow: ({ sessionId }) => readKimiContextWindow({ homePath, acpSessionId: sessionId })
30672
30467
  };
30673
30468
  }
30674
- var createKimiInstance = (config2, host) => {
30675
- const recipe = parseKimiInstanceConfig(config2);
30469
+ var createKimiInstance = (config2, host, profileDataDir2) => {
30470
+ const { recipe, home } = applyPrivateAccountHome(
30471
+ parseKimiInstanceConfig(config2),
30472
+ readInstanceEnvelope(config2).settings,
30473
+ "KIMI_CODE_HOME",
30474
+ profileDataDir2,
30475
+ host.instanceId,
30476
+ ["KIMI_API_KEY", "KIMI_CODE_API_KEY", "MOONSHOT_API_KEY"]
30477
+ );
30676
30478
  let disposed = false;
30677
30479
  const { table, threads, requireThread, registerSession, stopSession, disposeOnce, threadOps } = bindAcpInstanceThreads({
30678
30480
  log: host.log,
@@ -30685,23 +30487,30 @@ var createKimiInstance = (config2, host) => {
30685
30487
  kimiAccountHome(sessionHome?.trim() ?? ""),
30686
30488
  RESUME_SCHEMA_VERSION
30687
30489
  );
30490
+ const login = createCliDeviceSignIn({
30491
+ name: "Kimi Code",
30492
+ host,
30493
+ program: recipe.binaryPath,
30494
+ args: KIMI_CARD.deviceCodeSignInArgs,
30495
+ env: homeLaunchEnv(recipe, recipe.homePath),
30496
+ stream: "stderr",
30497
+ parse: (text2) => {
30498
+ const verificationUrl = /^Opening browser for Kimi device login: (https?:\/\/\S+)\r?$/m.exec(
30499
+ text2
30500
+ )?.[1];
30501
+ const userCode = /enter code: (\S+)\r?\n/.exec(text2)?.[1];
30502
+ return verificationUrl && userCode ? { verificationUrl, userCode } : void 0;
30503
+ },
30504
+ probe: (signal) => instance.probe(signal),
30505
+ isDisposed: () => disposed
30506
+ });
30688
30507
  const instance = {
30508
+ signIn: login.signIn,
30509
+ ...home ? { signInCommandEnv: recipe.environment } : {},
30689
30510
  sessions: {
30690
30511
  ...sessions,
30691
30512
  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
- }
30513
+ read: async (input2) => sessionReadFromImport(input2.nativeSessionId, await sessions.readImport(input2))
30705
30514
  },
30706
30515
  probe: async (signal) => {
30707
30516
  if (recipe.binaryPath.length === 0) {
@@ -30884,20 +30693,21 @@ var createKimiInstance = (config2, host) => {
30884
30693
  continuationKey: homeContinuationKey("kimiCode", recipe),
30885
30694
  dispose: () => {
30886
30695
  disposed = true;
30887
- return disposeOnce();
30696
+ return Promise.all([disposeOnce(), login.close()]).then(() => void 0);
30888
30697
  }
30889
30698
  };
30890
30699
  return instance;
30891
30700
  };
30892
30701
 
30893
30702
  // src/index.ts
30703
+ var profileDataDir;
30894
30704
  var executors = [
30895
30705
  {
30896
30706
  card: KIMI_CARD,
30897
30707
  lifecycle: [{ kind: "detect", reversible: true }],
30898
30708
  createInstance: async (config2, host) => {
30899
30709
  host.log.info("createInstance");
30900
- return createKimiInstance(config2, host);
30710
+ return createKimiInstance(config2, host, profileDataDir);
30901
30711
  }
30902
30712
  }
30903
30713
  ];
@@ -30906,23 +30716,13 @@ var index_default = definePlugin({
30906
30716
  apiVersion: PLUGIN_API_VERSION,
30907
30717
  executors,
30908
30718
  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
- });
30719
+ profileDataDir = ctx.paths?.dataDir;
30720
+ registerEffectiveHomeCommand(
30721
+ ctx,
30722
+ KIMI_CARD.homeEnvVar,
30723
+ (value) => value === void 0 ? NodePath8.join(NodeOS6.homedir(), ".kimi-code") : NodePath8.resolve(expandHomePath2(value)),
30724
+ profileDataDir
30725
+ );
30926
30726
  ctx.log.info("Kimi Code executor ready");
30927
30727
  }
30928
30728
  });