@codexhost/cli-darwin-x64 0.10.2 → 0.11.0

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.
@@ -6,8 +6,8 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // dist/kimi-adapter.js
9
- import { readFile as readFile3 } from "node:fs/promises";
10
- import path6 from "node:path";
9
+ import { readFile as readFile5 } from "node:fs/promises";
10
+ import path8 from "node:path";
11
11
  import { isDeepStrictEqual } from "node:util";
12
12
 
13
13
  // ../../../node_modules/zod/v4/classic/external.js
@@ -776,10 +776,10 @@ function mergeDefs(...defs) {
776
776
  function cloneDef(schema) {
777
777
  return mergeDefs(schema._zod.def);
778
778
  }
779
- function getElementAtPath(obj, path7) {
780
- if (!path7)
779
+ function getElementAtPath(obj, path9) {
780
+ if (!path9)
781
781
  return obj;
782
- return path7.reduce((acc, key) => acc?.[key], obj);
782
+ return path9.reduce((acc, key) => acc?.[key], obj);
783
783
  }
784
784
  function promiseAllObject(promisesObj) {
785
785
  const keys = Object.keys(promisesObj);
@@ -1188,11 +1188,11 @@ function explicitlyAborted(x, startIndex = 0) {
1188
1188
  }
1189
1189
  return false;
1190
1190
  }
1191
- function prefixIssues(path7, issues) {
1191
+ function prefixIssues(path9, issues) {
1192
1192
  return issues.map((iss) => {
1193
1193
  var _a3;
1194
1194
  (_a3 = iss).path ?? (_a3.path = []);
1195
- iss.path.unshift(path7);
1195
+ iss.path.unshift(path9);
1196
1196
  return iss;
1197
1197
  });
1198
1198
  }
@@ -1339,16 +1339,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1339
1339
  }
1340
1340
  function formatError(error51, mapper = (issue2) => issue2.message) {
1341
1341
  const fieldErrors = { _errors: [] };
1342
- const processError = (error52, path7 = []) => {
1342
+ const processError = (error52, path9 = []) => {
1343
1343
  for (const issue2 of error52.issues) {
1344
1344
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1345
- issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1345
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1346
1346
  } else if (issue2.code === "invalid_key") {
1347
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1347
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1348
1348
  } else if (issue2.code === "invalid_element") {
1349
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1349
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1350
1350
  } else {
1351
- const fullpath = [...path7, ...issue2.path];
1351
+ const fullpath = [...path9, ...issue2.path];
1352
1352
  if (fullpath.length === 0) {
1353
1353
  fieldErrors._errors.push(mapper(issue2));
1354
1354
  } else {
@@ -1375,17 +1375,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1375
1375
  }
1376
1376
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1377
1377
  const result = { errors: [] };
1378
- const processError = (error52, path7 = []) => {
1378
+ const processError = (error52, path9 = []) => {
1379
1379
  var _a3, _b;
1380
1380
  for (const issue2 of error52.issues) {
1381
1381
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1382
- issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1382
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1383
1383
  } else if (issue2.code === "invalid_key") {
1384
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1384
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1385
1385
  } else if (issue2.code === "invalid_element") {
1386
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1386
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1387
1387
  } else {
1388
- const fullpath = [...path7, ...issue2.path];
1388
+ const fullpath = [...path9, ...issue2.path];
1389
1389
  if (fullpath.length === 0) {
1390
1390
  result.errors.push(mapper(issue2));
1391
1391
  continue;
@@ -1417,8 +1417,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1417
1417
  }
1418
1418
  function toDotPath(_path) {
1419
1419
  const segs = [];
1420
- const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1421
- for (const seg of path7) {
1420
+ const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1421
+ for (const seg of path9) {
1422
1422
  if (typeof seg === "number")
1423
1423
  segs.push(`[${seg}]`);
1424
1424
  else if (typeof seg === "symbol")
@@ -14110,13 +14110,13 @@ function resolveRef(ref, ctx) {
14110
14110
  if (!ref.startsWith("#")) {
14111
14111
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14112
14112
  }
14113
- const path7 = ref.slice(1).split("/").filter(Boolean);
14114
- if (path7.length === 0) {
14113
+ const path9 = ref.slice(1).split("/").filter(Boolean);
14114
+ if (path9.length === 0) {
14115
14115
  return ctx.rootSchema;
14116
14116
  }
14117
14117
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14118
- if (path7[0] === defsKey) {
14119
- const key = path7[1];
14118
+ if (path9[0] === defsKey) {
14119
+ const key = path9[1];
14120
14120
  if (!key || !ctx.defs[key]) {
14121
14121
  throw new Error(`Reference not found: ${ref}`);
14122
14122
  }
@@ -14579,6 +14579,55 @@ var credentialImportsParamsSchema = external_exports.object({
14579
14579
  request: credentialImportsRequestSchema
14580
14580
  }).strict();
14581
14581
 
14582
+ // ../../shared-contracts/dist/harness-display-settings.js
14583
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
14584
+ agent: external_exports.string().min(1).max(128),
14585
+ section: external_exports.enum(["main", "more", "auto"])
14586
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
14587
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
14588
+ entries: harnessDisplayEntriesSchema.nullable()
14589
+ });
14590
+ var harnessDisplayGetSchema = external_exports.strictObject({});
14591
+ var harnessDisplaySetSchema = external_exports.strictObject({
14592
+ entries: harnessDisplayEntriesSchema,
14593
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
14594
+ initializeOnly: external_exports.boolean().optional()
14595
+ });
14596
+
14597
+ // ../../shared-contracts/dist/console.js
14598
+ var consoleAnnouncementSchema = external_exports.strictObject({
14599
+ title: external_exports.string().trim().min(1).max(200),
14600
+ type: external_exports.enum(["info", "warning", "danger"]),
14601
+ body: external_exports.string().trim().min(1).max(16 * 1024)
14602
+ });
14603
+ var consoleOpenParamsSchema = external_exports.strictObject({});
14604
+ var consoleOpenResultSchema = external_exports.strictObject({
14605
+ /** The console address. */
14606
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
14607
+ });
14608
+ var CONSOLE_HOST_METHODS = Object.freeze([
14609
+ "codexhost/harness/plugins/list",
14610
+ "codexhost/harness/display-settings/get",
14611
+ "codexhost/harness/display-settings/set",
14612
+ "codexhost/harness/inspect",
14613
+ "codexhost/harness/launch-settings/get",
14614
+ "codexhost/harness/launch-settings/set",
14615
+ "codexhost/harness/web-ui/open",
14616
+ "codexhost/harness/accounts/sources",
14617
+ "codexhost/harness/accounts/list",
14618
+ "codexhost/harness/accounts/inspect",
14619
+ "codexhost/harness/credential-imports",
14620
+ "codexhost/harness/session-import/sources",
14621
+ "codexhost/harness/session-import/list",
14622
+ "codexhost/harness/session-import/import",
14623
+ "codexhost/account/list",
14624
+ "codexhost/account/refresh",
14625
+ "codexhost/account/usage/inspect",
14626
+ "codexhost/update/check",
14627
+ "codexhost/update/start",
14628
+ "codexhost/update/status"
14629
+ ]);
14630
+
14582
14631
  // ../../shared-contracts/dist/version.js
14583
14632
  var WORKSPACE_CONTRACT_VERSION = 1;
14584
14633
 
@@ -14632,6 +14681,12 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
14632
14681
  var hostItemIdSchema = opaqueIdSchema.brand();
14633
14682
  var hostInteractionIdSchema = opaqueIdSchema.brand();
14634
14683
 
14684
+ // ../../shared-contracts/dist/manual-compaction.js
14685
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
14686
+ threadId: hostThreadIdSchema,
14687
+ turnId: hostTurnIdSchema
14688
+ });
14689
+
14635
14690
  // ../../shared-contracts/dist/thread-usage.js
14636
14691
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
14637
14692
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -14692,6 +14747,10 @@ var threadUsageSnapshotSchema = external_exports.object({
14692
14747
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
14693
14748
  var accountCreditsProductUsageSchema = external_exports.object({
14694
14749
  product: external_exports.string().min(1),
14750
+ used: external_exports.number().finite().nonnegative().optional(),
14751
+ // Zero is a real empty cap, not an absent field.
14752
+ limit: external_exports.number().finite().nonnegative().optional(),
14753
+ unit: external_exports.string().min(1).max(32).optional(),
14695
14754
  usagePercent: usagePercentSchema,
14696
14755
  resetsAt: external_exports.string().min(1).optional()
14697
14756
  }).strict();
@@ -14701,6 +14760,10 @@ var accountResetCreditsSchema = external_exports.object({
14701
14760
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
14702
14761
  }).strict();
14703
14762
  var accountCreditsSnapshotSchema = external_exports.object({
14763
+ used: external_exports.number().finite().nonnegative().optional(),
14764
+ // Zero is a real empty cap, not an absent field.
14765
+ limit: external_exports.number().finite().nonnegative().optional(),
14766
+ unit: external_exports.string().min(1).max(32).optional(),
14704
14767
  /** Native label when the primary limit is scoped to a model or product group. */
14705
14768
  label: external_exports.string().min(1).optional(),
14706
14769
  usedPercent: usagePercentSchema,
@@ -14720,12 +14783,27 @@ var threadUsageInspectionSchema = external_exports.object({
14720
14783
  }).strict();
14721
14784
 
14722
14785
  // ../../shared-contracts/dist/harness-accounts.js
14723
- var harnessAccountSnapshotSchema = external_exports.object({
14786
+ var accountBalanceSnapshotSchema = external_exports.object({
14787
+ amount: external_exports.number().finite().nonnegative(),
14788
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
14789
+ currency: external_exports.string().trim().min(1).max(8),
14790
+ /** Native label when the Harness exposes several Billing Sources. */
14791
+ label: external_exports.string().trim().min(1).max(128).optional()
14792
+ }).strict();
14793
+ var harnessAccountSnapshotObject = external_exports.object({
14724
14794
  email: external_exports.string().trim().min(1).max(320).optional(),
14725
14795
  label: external_exports.string().trim().min(1).max(256).optional(),
14726
14796
  plan: external_exports.string().trim().min(1).max(128).optional(),
14727
- credits: accountCreditsSnapshotSchema
14797
+ credits: accountCreditsSnapshotSchema.optional(),
14798
+ balance: accountBalanceSnapshotSchema.optional()
14728
14799
  }).strict();
14800
+ function requireReportedQuota(schema) {
14801
+ return schema.refine((value) => {
14802
+ const reported = value;
14803
+ return reported.credits !== void 0 || reported.balance !== void 0;
14804
+ }, { message: "Account must report either credits or a balance" });
14805
+ }
14806
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
14729
14807
  var harnessAccountIdentityShape = {
14730
14808
  harnessId: harnessIdSchema,
14731
14809
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -14736,11 +14814,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
14736
14814
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
14737
14815
  var harnessAccountInspectResultSchema = external_exports.object({
14738
14816
  ...harnessAccountIdentityShape,
14739
- account: harnessAccountSnapshotSchema.nullable()
14817
+ account: harnessAccountSnapshotSchema.nullable(),
14818
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
14819
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
14740
14820
  }).strict();
14741
14821
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
14742
14822
  var harnessAccountListResultSchema = external_exports.object({
14743
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
14823
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
14744
14824
  }).strict();
14745
14825
 
14746
14826
  // ../../shared-contracts/dist/json-value.js
@@ -14878,6 +14958,8 @@ var harnessModelSchema = external_exports.object({
14878
14958
  ref: harnessModelRefSchema,
14879
14959
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
14880
14960
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
14961
+ /** Optional opaque selection for this same Model with priority processing enabled. */
14962
+ fastModel: harnessModelRefSchema.optional(),
14881
14963
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
14882
14964
  }).strict();
14883
14965
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -14910,6 +14992,16 @@ var harnessModelCatalogSchema = external_exports.object({
14910
14992
  });
14911
14993
  }
14912
14994
  refs.add(model.ref.id);
14995
+ if (model.fastModel) {
14996
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
14997
+ context.addIssue({
14998
+ code: "custom",
14999
+ message: "Fast Model refs must be distinct and unique",
15000
+ path: ["models", index, "fastModel"]
15001
+ });
15002
+ }
15003
+ refs.add(model.fastModel.id);
15004
+ }
14913
15005
  const supportedThinkingIds = /* @__PURE__ */ new Set();
14914
15006
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
14915
15007
  if (supportedThinkingIds.has(optionId)) {
@@ -15029,11 +15121,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
15029
15121
  thinkingOptionId: harnessThinkingOptionIdSchema
15030
15122
  }).strict();
15031
15123
  var threadInspectionParamsSchema = external_exports.object({
15032
- threadId: hostThreadIdSchema
15124
+ threadId: hostThreadIdSchema,
15125
+ includeReferenceCapability: external_exports.boolean().optional()
15033
15126
  }).strict();
15034
15127
  var codexThreadInspectionSchema = external_exports.object({
15035
15128
  owner: external_exports.literal("codex"),
15036
- locked: external_exports.literal(true)
15129
+ locked: external_exports.literal(true),
15130
+ supportsThreadReferences: external_exports.literal(true).optional()
15037
15131
  }).strict();
15038
15132
  var externalThreadInspectionSchema = external_exports.object({
15039
15133
  owner: external_exports.literal("external"),
@@ -15159,6 +15253,19 @@ var harnessLaunchSettingsSchema = external_exports.object({
15159
15253
  restartRequired: external_exports.boolean()
15160
15254
  }).strict();
15161
15255
 
15256
+ // ../../shared-contracts/dist/harness-installation.js
15257
+ var harnessInstallationParamsSchema = external_exports.object({
15258
+ harnessId: harnessIdSchema,
15259
+ action: external_exports.enum(["check", "update"])
15260
+ }).strict();
15261
+ var harnessInstallationStateSchema = external_exports.object({
15262
+ currentVersion: external_exports.string().min(1).max(128),
15263
+ latestVersion: external_exports.string().min(1).max(128),
15264
+ updateAvailable: external_exports.boolean(),
15265
+ canUpdate: external_exports.boolean(),
15266
+ message: external_exports.string().max(2048).optional()
15267
+ }).strict();
15268
+
15162
15269
  // ../../shared-contracts/dist/codex-accounts.js
15163
15270
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
15164
15271
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
@@ -19818,7 +19925,7 @@ var ClientSideConnection = class {
19818
19925
  };
19819
19926
 
19820
19927
  // dist/command.js
19821
- import path3 from "node:path";
19928
+ import path5 from "node:path";
19822
19929
 
19823
19930
  // ../../harness-discovery/dist/environment.js
19824
19931
  import fs from "node:fs";
@@ -19882,6 +19989,20 @@ function commandInvocation(command, arguments_, environment, platform = process.
19882
19989
  };
19883
19990
  }
19884
19991
 
19992
+ // ../../harness-discovery/dist/node-runtime.js
19993
+ import path3 from "node:path";
19994
+ function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
19995
+ const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
19996
+ const delimiter = platform === "win32" ? ";" : ":";
19997
+ const runtimeDirectory = path3.dirname(runtimeExecutable);
19998
+ const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
19999
+ const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
20000
+ if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
20001
+ directories.push(runtimeDirectory);
20002
+ }
20003
+ return { ...environment, [pathKey]: directories.join(delimiter) };
20004
+ }
20005
+
19885
20006
  // ../../harness-discovery/dist/resolve.js
19886
20007
  import os from "node:os";
19887
20008
 
@@ -20045,6 +20166,195 @@ function resolveHarnessExecutable(spec, input, dependencies = {}) {
20045
20166
  return void 0;
20046
20167
  }
20047
20168
 
20169
+ // ../../harness-discovery/dist/installation.js
20170
+ import { execFile } from "node:child_process";
20171
+ import { homedir } from "node:os";
20172
+ function runInstallationCommand(command, args, environment, timeout = 3e4) {
20173
+ const env = withNodeRuntimeOnPath(environment);
20174
+ const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
20175
+ return new Promise((resolve, reject) => {
20176
+ const child = execFile(invocation.command, invocation.arguments, {
20177
+ env,
20178
+ cwd: env.HOME ?? env.USERPROFILE ?? homedir(),
20179
+ encoding: "utf8",
20180
+ timeout,
20181
+ killSignal: "SIGKILL",
20182
+ maxBuffer: 1024 * 1024,
20183
+ windowsHide: true,
20184
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
20185
+ }, (error51, stdout, stderr) => {
20186
+ if (error51)
20187
+ reject(new Error(error51.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
20188
+ else
20189
+ resolve((stdout || stderr).trim());
20190
+ });
20191
+ child.stdin?.end();
20192
+ });
20193
+ }
20194
+ function installationVersion(value) {
20195
+ if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
20196
+ throw new Error("Harness returned an invalid version");
20197
+ return value.trim().replace(/^v/, "");
20198
+ }
20199
+ function versionFromOutput(output) {
20200
+ return installationVersion(output.match(/\b\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?\b/)?.[0]);
20201
+ }
20202
+ function newerInstallationVersion(current, latest) {
20203
+ const a = installationVersion(current).replace(/\+.*/, "");
20204
+ const b = installationVersion(latest).replace(/\+.*/, "");
20205
+ const coreA = a.replace(/-.*/, "").split(".").map(BigInt);
20206
+ const coreB = b.replace(/-.*/, "").split(".").map(BigInt);
20207
+ for (let i = 0; i < Math.max(coreA.length, coreB.length); i++) {
20208
+ if ((coreA[i] ?? 0n) !== (coreB[i] ?? 0n))
20209
+ return (coreB[i] ?? 0n) > (coreA[i] ?? 0n);
20210
+ }
20211
+ const preA = a.includes("-") ? a.slice(a.indexOf("-") + 1).split(".") : [];
20212
+ const preB = b.includes("-") ? b.slice(b.indexOf("-") + 1).split(".") : [];
20213
+ if (!preA.length || !preB.length)
20214
+ return !!preA.length && !preB.length;
20215
+ for (let i = 0; i < Math.max(preA.length, preB.length); i++) {
20216
+ const x = preA[i];
20217
+ const y = preB[i];
20218
+ if (x === y)
20219
+ continue;
20220
+ if (x === void 0 || y === void 0)
20221
+ return x === void 0;
20222
+ const numericX = /^\d+$/.test(x);
20223
+ const numericY = /^\d+$/.test(y);
20224
+ if (numericX && numericY) {
20225
+ if (BigInt(x) === BigInt(y))
20226
+ continue;
20227
+ return BigInt(y) > BigInt(x);
20228
+ }
20229
+ if (numericX !== numericY)
20230
+ return numericX;
20231
+ return y > x;
20232
+ }
20233
+ return false;
20234
+ }
20235
+ function createInstallationManager(options) {
20236
+ let checking;
20237
+ let updating;
20238
+ const check2 = () => checking ??= options.check().finally(() => {
20239
+ checking = void 0;
20240
+ });
20241
+ return (action) => {
20242
+ if (updating)
20243
+ return updating;
20244
+ if (action === "check")
20245
+ return check2();
20246
+ updating = (async () => {
20247
+ const before = await check2();
20248
+ if (!before.updateAvailable)
20249
+ return before;
20250
+ if (!before.canUpdate)
20251
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
20252
+ await options.update(before);
20253
+ const after = await check2();
20254
+ if (after.currentVersion === before.currentVersion)
20255
+ throw new Error("The Harness version did not change; check the native updater and retry");
20256
+ return after;
20257
+ })().finally(() => {
20258
+ updating = void 0;
20259
+ });
20260
+ return updating;
20261
+ };
20262
+ }
20263
+ async function fetchInstallationText(url2) {
20264
+ const request = async () => {
20265
+ const response = await fetch(url2, { signal: AbortSignal.timeout(15e3) });
20266
+ if (!response.ok)
20267
+ throw new Error("Could not check the latest Harness version");
20268
+ return response.text();
20269
+ };
20270
+ try {
20271
+ return await request();
20272
+ } catch (error51) {
20273
+ if (error51 instanceof DOMException && (error51.name === "AbortError" || error51.name === "TimeoutError"))
20274
+ throw error51;
20275
+ return request();
20276
+ }
20277
+ }
20278
+
20279
+ // ../../harness-discovery/dist/npm-installation.js
20280
+ import { readFile, realpath } from "node:fs/promises";
20281
+ import path4 from "node:path";
20282
+ function referencesNpmBin(shim, name, bin) {
20283
+ if (bin.includes(".."))
20284
+ return false;
20285
+ const target = `node_modules/${name}/${bin.replace(/^\.\//, "")}`.toLowerCase();
20286
+ const text = shim.replaceAll("\\", "/").toLowerCase();
20287
+ return text.includes(`%dp0%/${target}"`) || text.includes(`%~dp0/${target}"`);
20288
+ }
20289
+ async function npmInstallation(command, packages, environment) {
20290
+ let selected = await realpath(command);
20291
+ if (process.platform === "win32" && /\.(cmd|bat)$/i.test(selected)) {
20292
+ const shim = (await readFile(selected, "utf8")).replaceAll("\\", "/");
20293
+ const root = path4.dirname(selected);
20294
+ for (const name of packages) {
20295
+ const directory2 = path4.join(root, "node_modules", ...name.split("/"));
20296
+ const metadata = await readFile(path4.join(directory2, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
20297
+ const bins = typeof metadata?.bin === "string" ? [metadata.bin] : Object.values(metadata?.bin ?? {});
20298
+ const bin = bins.find((entry) => referencesNpmBin(shim, name, entry));
20299
+ if (bin) {
20300
+ selected = await realpath(path4.join(directory2, bin));
20301
+ break;
20302
+ }
20303
+ }
20304
+ }
20305
+ let directory = path4.dirname(selected);
20306
+ for (let depth = 0; depth < 8; depth++) {
20307
+ const metadata = await readFile(path4.join(directory, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
20308
+ if (metadata?.name && packages.includes(metadata.name)) {
20309
+ const name = metadata.name;
20310
+ const currentVersion = installationVersion(metadata.version);
20311
+ const segments = name.split("/");
20312
+ let modules = directory;
20313
+ for (let index = 0; index < segments.length; index++)
20314
+ modules = path4.dirname(modules);
20315
+ const prefix = process.platform === "win32" ? path4.dirname(modules) : path4.dirname(path4.dirname(modules));
20316
+ const globalRoot = process.platform === "win32" ? path4.join(prefix, "node_modules") : path4.join(prefix, "lib", "node_modules");
20317
+ const env = withNodeRuntimeOnPath(environment);
20318
+ const npm = resolveHarnessExecutable({ id: "npm", command: "npm", installRoots: { posix: [], windows: [] } }, { environment: env });
20319
+ let globalInstall = modules === globalRoot;
20320
+ if (process.platform === "win32") {
20321
+ const project = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile(path4.join(prefix, file2), "utf8").then(() => true, (error51) => error51.code !== "ENOENT")))).some(Boolean);
20322
+ const bins = typeof metadata.bin === "string" ? { [name.split("/").at(-1) ?? name]: metadata.bin } : metadata.bin ?? {};
20323
+ const launchers = await Promise.all(Object.entries(bins).map(async ([bin, entry]) => {
20324
+ if (path4.basename(bin) !== bin || entry.includes(".."))
20325
+ return false;
20326
+ const target = await realpath(path4.join(directory, entry)).catch(() => "");
20327
+ if (target.toLowerCase() !== selected.toLowerCase())
20328
+ return false;
20329
+ const shim = await readFile(path4.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
20330
+ return referencesNpmBin(shim, name, entry);
20331
+ }));
20332
+ globalInstall = globalInstall && !project && launchers.some(Boolean);
20333
+ }
20334
+ const canUpdate = globalInstall && !!npm;
20335
+ return {
20336
+ prefix,
20337
+ currentVersion,
20338
+ canUpdate,
20339
+ latest: async () => {
20340
+ const data = JSON.parse(await fetchInstallationText(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`));
20341
+ return installationVersion(data.version);
20342
+ },
20343
+ update: async (version2) => {
20344
+ if (!canUpdate || !npm)
20345
+ throw new Error("Use the original package manager to update this installation");
20346
+ await runInstallationCommand(npm.executable, ["install", "--global", "--prefix", prefix, `${name}@${installationVersion(version2)}`], env, 3e5);
20347
+ }
20348
+ };
20349
+ }
20350
+ const parent = path4.dirname(directory);
20351
+ if (parent === directory)
20352
+ break;
20353
+ directory = parent;
20354
+ }
20355
+ return null;
20356
+ }
20357
+
20048
20358
  // dist/command.js
20049
20359
  var KimiExecutableError = class extends Error {
20050
20360
  code = "KIMI_NOT_FOUND";
@@ -20069,7 +20379,7 @@ function resolveKimiExecutable(input = {}) {
20069
20379
  });
20070
20380
  if (!resolution)
20071
20381
  throw new KimiExecutableError("Kimi Code CLI is not installed");
20072
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path3.resolve(resolution.executable);
20382
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
20073
20383
  }
20074
20384
  function kimiInvocation(command, environment = process.env, platform = process.platform) {
20075
20385
  return commandInvocation(command, ["acp"], environment, platform);
@@ -20513,10 +20823,229 @@ var KimiAcpTransport = class {
20513
20823
  }
20514
20824
  };
20515
20825
 
20826
+ // dist/account-identity.js
20827
+ import { randomUUID } from "node:crypto";
20828
+ import { readFile as readFile2, rename, unlink, writeFile } from "node:fs/promises";
20829
+ import { homedir as homedir2 } from "node:os";
20830
+ import { join } from "node:path";
20831
+ var KIMI_USAGES_ENDPOINT = "https://api.kimi.com/coding/v1/usages";
20832
+ var KIMI_OAUTH_TOKEN_ENDPOINT = "https://auth.kimi.com/api/oauth/token";
20833
+ var KIMI_CODE_CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098";
20834
+ var REQUEST_TIMEOUT_MS = 8e3;
20835
+ var REFRESH_SKEW_MS = 6e4;
20836
+ var credentialSchema = external_exports.object({
20837
+ access_token: external_exports.string().min(1),
20838
+ refresh_token: external_exports.string().min(1).optional(),
20839
+ expires_at: external_exports.number().optional(),
20840
+ expires_in: external_exports.number().optional(),
20841
+ scope: external_exports.string().optional(),
20842
+ token_type: external_exports.string().optional()
20843
+ });
20844
+ var refreshResponseSchema = external_exports.object({
20845
+ access_token: external_exports.string().min(1),
20846
+ refresh_token: external_exports.string().min(1).optional(),
20847
+ expires_in: external_exports.number().positive().optional(),
20848
+ scope: external_exports.string().optional(),
20849
+ token_type: external_exports.string().optional()
20850
+ });
20851
+ function kimiHome(environment) {
20852
+ return environment.KIMI_CODE_HOME ?? join(environment.HOME ?? homedir2(), ".kimi-code");
20853
+ }
20854
+ function credentialPath(environment) {
20855
+ return join(kimiHome(environment), "credentials", "kimi-code.json");
20856
+ }
20857
+ function oauthTokenUrl(environment) {
20858
+ const host = environment.KIMI_CODE_OAUTH_HOST ?? environment.KIMI_OAUTH_HOST;
20859
+ return host ? `${host.replace(/\/$/u, "")}/api/oauth/token` : KIMI_OAUTH_TOKEN_ENDPOINT;
20860
+ }
20861
+ function isRecord3(value) {
20862
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20863
+ }
20864
+ function quantity(value) {
20865
+ if (typeof value === "number" && Number.isFinite(value))
20866
+ return value;
20867
+ if (typeof value === "string" && value.trim()) {
20868
+ const parsed = Number(value);
20869
+ if (Number.isFinite(parsed))
20870
+ return parsed;
20871
+ }
20872
+ return void 0;
20873
+ }
20874
+ function isFiveHourWindow(window) {
20875
+ if (!isRecord3(window))
20876
+ return false;
20877
+ const duration3 = quantity(window.duration);
20878
+ const unit = String(window.timeUnit ?? "").toLowerCase();
20879
+ return duration3 === 300 && unit.includes("minute");
20880
+ }
20881
+ function usageShare(detail) {
20882
+ if (!isRecord3(detail))
20883
+ return void 0;
20884
+ const limit = quantity(detail.limit);
20885
+ const remaining = quantity(detail.remaining);
20886
+ const used = quantity(detail.used) ?? (limit !== void 0 && remaining !== void 0 ? Math.max(0, limit - remaining) : void 0);
20887
+ if (limit === void 0 || limit <= 0 || used === void 0 || used < 0)
20888
+ return void 0;
20889
+ const resetsAt = typeof detail.resetTime === "string" && detail.resetTime ? detail.resetTime : void 0;
20890
+ return { usedPercent: Math.min(100, used / limit * 100), ...resetsAt ? { resetsAt } : {} };
20891
+ }
20892
+ function membershipPlan(user) {
20893
+ if (!isRecord3(user) || !isRecord3(user.membership) || typeof user.membership.level !== "string")
20894
+ return void 0;
20895
+ return user.membership.level.replace(/^LEVEL_/u, "").trim() || void 0;
20896
+ }
20897
+ function nickname(user) {
20898
+ if (!isRecord3(user) || typeof user.nickname !== "string")
20899
+ return void 0;
20900
+ return user.nickname.trim() || void 0;
20901
+ }
20902
+ function expiresAtMs(expiresAt) {
20903
+ if (expiresAt === void 0 || !Number.isFinite(expiresAt))
20904
+ return void 0;
20905
+ return expiresAt < 1e12 ? expiresAt * 1e3 : expiresAt;
20906
+ }
20907
+ function accessTokenFresh(credentials, now) {
20908
+ const expires = expiresAtMs(credentials.expires_at);
20909
+ return expires === void 0 || expires - REFRESH_SKEW_MS > now;
20910
+ }
20911
+ function projectKimiUsages(payload) {
20912
+ if (!isRecord3(payload))
20913
+ return null;
20914
+ const weekly = usageShare(payload.usage);
20915
+ if (!weekly)
20916
+ return null;
20917
+ const productUsage = (Array.isArray(payload.limits) ? payload.limits : []).flatMap((entry) => {
20918
+ if (!isRecord3(entry))
20919
+ return [];
20920
+ const share = usageShare(entry.detail);
20921
+ if (!share || !isFiveHourWindow(entry.window))
20922
+ return [];
20923
+ return [
20924
+ {
20925
+ product: "Kimi Code · 5-hour window",
20926
+ usagePercent: share.usedPercent,
20927
+ ...share.resetsAt ? { resetsAt: share.resetsAt } : {}
20928
+ }
20929
+ ];
20930
+ });
20931
+ const credits = {
20932
+ usedPercent: weekly.usedPercent,
20933
+ periodType: "weekly",
20934
+ ...weekly.resetsAt ? { resetsAt: weekly.resetsAt } : {},
20935
+ ...productUsage.length ? { productUsage } : {}
20936
+ };
20937
+ const plan = membershipPlan(payload.user);
20938
+ const label = nickname(payload.user);
20939
+ const parsed = harnessAccountSnapshotSchema.safeParse({
20940
+ label: label || "Kimi Code",
20941
+ ...plan ? { plan } : {},
20942
+ credits
20943
+ });
20944
+ return parsed.success ? parsed.data : null;
20945
+ }
20946
+ async function readNativeCredentials(filePath, readAuthFile) {
20947
+ try {
20948
+ const raw = JSON.parse(await readAuthFile(filePath));
20949
+ if (!isRecord3(raw))
20950
+ return void 0;
20951
+ const parsed = credentialSchema.safeParse(raw);
20952
+ return parsed.success ? { raw, credentials: parsed.data } : void 0;
20953
+ } catch {
20954
+ return void 0;
20955
+ }
20956
+ }
20957
+ async function defaultWriteAuthFile(filePath, contents) {
20958
+ const temporary = `${filePath}.${randomUUID()}.tmp`;
20959
+ try {
20960
+ await writeFile(temporary, contents, { encoding: "utf8", mode: 384, flag: "wx" });
20961
+ await rename(temporary, filePath);
20962
+ } finally {
20963
+ await unlink(temporary).catch(() => void 0);
20964
+ }
20965
+ }
20966
+ async function refreshNativeCredentials(environment, stored, filePath, fetchImpl, writeAuthFile, signal, now) {
20967
+ const refreshToken = stored.credentials.refresh_token;
20968
+ if (!refreshToken)
20969
+ return void 0;
20970
+ const response = await fetchImpl(oauthTokenUrl(environment), {
20971
+ method: "POST",
20972
+ headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
20973
+ body: new URLSearchParams({
20974
+ client_id: KIMI_CODE_CLIENT_ID,
20975
+ grant_type: "refresh_token",
20976
+ refresh_token: refreshToken
20977
+ }),
20978
+ signal
20979
+ });
20980
+ if (!response.ok)
20981
+ return void 0;
20982
+ const parsed = refreshResponseSchema.safeParse(await response.json());
20983
+ if (!parsed.success)
20984
+ return void 0;
20985
+ const expiresIn = parsed.data.expires_in ?? stored.credentials.expires_in ?? 900;
20986
+ const next = {
20987
+ ...stored.raw,
20988
+ access_token: parsed.data.access_token,
20989
+ refresh_token: parsed.data.refresh_token ?? refreshToken,
20990
+ expires_in: expiresIn,
20991
+ expires_at: now / 1e3 + expiresIn,
20992
+ ...parsed.data.scope ? { scope: parsed.data.scope } : {},
20993
+ ...parsed.data.token_type ? { token_type: parsed.data.token_type } : {}
20994
+ };
20995
+ await writeAuthFile(filePath, `${JSON.stringify(next, void 0, 2)}
20996
+ `).catch(() => void 0);
20997
+ stored.raw = next;
20998
+ stored.credentials = {
20999
+ ...stored.credentials,
21000
+ access_token: parsed.data.access_token,
21001
+ refresh_token: parsed.data.refresh_token ?? refreshToken,
21002
+ expires_in: expiresIn,
21003
+ expires_at: now / 1e3 + expiresIn
21004
+ };
21005
+ return parsed.data.access_token;
21006
+ }
21007
+ async function fetchKimiAccount(input = {}) {
21008
+ try {
21009
+ const environment = input.environment ?? process.env;
21010
+ const fromEnv = environment.KIMI_CODE_API_KEY?.trim() || environment.KIMI_API_KEY?.trim();
21011
+ const readAuthFile = input.readAuthFile ?? ((filePath2) => readFile2(filePath2, "utf8"));
21012
+ const writeAuthFile = input.writeAuthFile ?? defaultWriteAuthFile;
21013
+ const fetchImpl = input.fetch ?? fetch;
21014
+ const requestSignal = () => input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
21015
+ const now = input.now ?? Date.now();
21016
+ const filePath = credentialPath(environment);
21017
+ const stored = fromEnv ? void 0 : await readNativeCredentials(filePath, readAuthFile);
21018
+ let token = fromEnv ?? stored?.credentials.access_token;
21019
+ if (!token)
21020
+ return null;
21021
+ if (stored && !accessTokenFresh(stored.credentials, now)) {
21022
+ token = await refreshNativeCredentials(environment, stored, filePath, fetchImpl, writeAuthFile, requestSignal(), now) ?? token;
21023
+ }
21024
+ const requestUsages = (accessToken) => fetchImpl(KIMI_USAGES_ENDPOINT, {
21025
+ method: "GET",
21026
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
21027
+ signal: requestSignal()
21028
+ });
21029
+ let response = await requestUsages(token);
21030
+ if (response.status === 401 && stored?.credentials.refresh_token) {
21031
+ const refreshed = await refreshNativeCredentials(environment, stored, filePath, fetchImpl, writeAuthFile, requestSignal(), now);
21032
+ if (!refreshed)
21033
+ return null;
21034
+ token = refreshed;
21035
+ response = await requestUsages(token);
21036
+ }
21037
+ if (!response.ok)
21038
+ return null;
21039
+ return projectKimiUsages(await response.json());
21040
+ } catch {
21041
+ return null;
21042
+ }
21043
+ }
21044
+
20516
21045
  // dist/history.js
20517
- import { readFile } from "node:fs/promises";
21046
+ import { readFile as readFile3 } from "node:fs/promises";
20518
21047
  import os2 from "node:os";
20519
- import path4 from "node:path";
21048
+ import path6 from "node:path";
20520
21049
 
20521
21050
  // ../../../node_modules/diff/libesm/diff/base.js
20522
21051
  var Diff = class {
@@ -20618,16 +21147,16 @@ var Diff = class {
20618
21147
  }
20619
21148
  }
20620
21149
  }
20621
- addToPath(path7, added, removed, oldPosInc, options) {
20622
- const last = path7.lastComponent;
21150
+ addToPath(path9, added, removed, oldPosInc, options) {
21151
+ const last = path9.lastComponent;
20623
21152
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
20624
21153
  return {
20625
- oldPos: path7.oldPos + oldPosInc,
21154
+ oldPos: path9.oldPos + oldPosInc,
20626
21155
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
20627
21156
  };
20628
21157
  } else {
20629
21158
  return {
20630
- oldPos: path7.oldPos + oldPosInc,
21159
+ oldPos: path9.oldPos + oldPosInc,
20631
21160
  lastComponent: { count: 1, added, removed, previousComponent: last }
20632
21161
  };
20633
21162
  }
@@ -21759,9 +22288,9 @@ function readKimiThinkingOptions(configOptions) {
21759
22288
  }
21760
22289
 
21761
22290
  // dist/projection.js
21762
- import { randomUUID } from "node:crypto";
22291
+ import { randomUUID as randomUUID2 } from "node:crypto";
21763
22292
  function projectKimiApprovalRequest(turnId, request) {
21764
- const interactionId = hostInteractionIdSchema.parse(randomUUID());
22293
+ const interactionId = hostInteractionIdSchema.parse(randomUUID2());
21765
22294
  const optionIdByActionId = /* @__PURE__ */ new Map();
21766
22295
  const actions = [];
21767
22296
  const description = readAcpToolContentText(request.toolCall.content);
@@ -21805,7 +22334,7 @@ function projectKimiApprovalRequest(turnId, request) {
21805
22334
  return { interaction, optionIdByActionId };
21806
22335
  }
21807
22336
  function projectKimiElicitationRequest(turnId, request) {
21808
- const interactionId = hostInteractionIdSchema.parse(randomUUID());
22337
+ const interactionId = hostInteractionIdSchema.parse(randomUUID2());
21809
22338
  const questions = [];
21810
22339
  const schemaProperties = {};
21811
22340
  const req = request;
@@ -21875,18 +22404,18 @@ function formatElicitationResponse(response, schemaProperties) {
21875
22404
  }
21876
22405
  return { action: "accept", content };
21877
22406
  }
21878
- function isRecord3(value) {
22407
+ function isRecord4(value) {
21879
22408
  return typeof value === "object" && value !== null && !Array.isArray(value);
21880
22409
  }
21881
22410
  function canonicalizeKimiToolName(name, kind, rawInput) {
21882
22411
  const trimmed = name?.trim();
21883
22412
  const lower = trimmed?.toLowerCase() ?? "";
21884
22413
  if (lower.startsWith("write") || lower.startsWith("writ")) {
21885
- const isEdit = isRecord3(rawInput) && ("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
22414
+ const isEdit = isRecord4(rawInput) && ("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
21886
22415
  return isEdit ? "Edit" : "Write";
21887
22416
  }
21888
22417
  if (kind === "edit" || lower.startsWith("edit")) {
21889
- const isWrite = isRecord3(rawInput) && ("content" in rawInput || "text" in rawInput) && !("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
22418
+ const isWrite = isRecord4(rawInput) && ("content" in rawInput || "text" in rawInput) && !("old_string" in rawInput || "oldText" in rawInput || "old" in rawInput);
21890
22419
  return isWrite ? "Write" : "Edit";
21891
22420
  }
21892
22421
  if (kind === "execute" || lower.startsWith("bash") || lower.startsWith("shell") || lower.startsWith("run")) {
@@ -22095,14 +22624,14 @@ function createKimiNativeCheckpointRef(sessionId, turnId) {
22095
22624
  });
22096
22625
  }
22097
22626
  function getKimiCodeHome(homeDirectory, environment = process.env) {
22098
- return environment.KIMI_CODE_HOME || (homeDirectory ? path4.join(homeDirectory, ".kimi-code") : path4.join(os2.homedir(), ".kimi-code"));
22627
+ return environment.KIMI_CODE_HOME || (homeDirectory ? path6.join(homeDirectory, ".kimi-code") : path6.join(os2.homedir(), ".kimi-code"));
22099
22628
  }
22100
22629
  async function locateKimiSession(sessionId, options = {}) {
22101
- const kimiHome = options.kimiCodeHome || getKimiCodeHome(options.homeDirectory);
22102
- const indexFile = path4.join(kimiHome, "session_index.jsonl");
22630
+ const kimiHome2 = options.kimiCodeHome || getKimiCodeHome(options.homeDirectory);
22631
+ const indexFile = path6.join(kimiHome2, "session_index.jsonl");
22103
22632
  let content;
22104
22633
  try {
22105
- content = await readFile(indexFile, "utf8");
22634
+ content = await readFile3(indexFile, "utf8");
22106
22635
  } catch {
22107
22636
  return null;
22108
22637
  }
@@ -22123,15 +22652,15 @@ async function locateKimiSession(sessionId, options = {}) {
22123
22652
  if (!targetEntry || targetEntry.deleted || !targetEntry.sessionDir) {
22124
22653
  return null;
22125
22654
  }
22126
- const sessionDir = path4.resolve(targetEntry.sessionDir);
22127
- const normalizedKimiHome = path4.resolve(kimiHome);
22128
- const relativeToHome = path4.relative(normalizedKimiHome, sessionDir);
22129
- if (relativeToHome.startsWith("..") || path4.isAbsolute(relativeToHome)) {
22655
+ const sessionDir = path6.resolve(targetEntry.sessionDir);
22656
+ const normalizedKimiHome = path6.resolve(kimiHome2);
22657
+ const relativeToHome = path6.relative(normalizedKimiHome, sessionDir);
22658
+ if (relativeToHome.startsWith("..") || path6.isAbsolute(relativeToHome)) {
22130
22659
  throw new Error(`Session directory ${sessionDir} is outside KIMI_CODE_HOME`);
22131
22660
  }
22132
22661
  let state;
22133
22662
  try {
22134
- const stateContent = await readFile(path4.join(sessionDir, "state.json"), "utf8");
22663
+ const stateContent = await readFile3(path6.join(sessionDir, "state.json"), "utf8");
22135
22664
  state = JSON.parse(stateContent);
22136
22665
  } catch {
22137
22666
  return null;
@@ -22139,7 +22668,7 @@ async function locateKimiSession(sessionId, options = {}) {
22139
22668
  if (state.id !== sessionId) {
22140
22669
  throw new Error(`State JSON session ID mismatch: expected ${sessionId}, found ${state.id}`);
22141
22670
  }
22142
- const mainHomeDir = state.agents?.main?.homedir ? path4.resolve(state.agents.main.homedir) : path4.join(sessionDir, "agents", "main");
22671
+ const mainHomeDir = state.agents?.main?.homedir ? path6.resolve(state.agents.main.homedir) : path6.join(sessionDir, "agents", "main");
22143
22672
  return { sessionDir, mainHomeDir, state };
22144
22673
  }
22145
22674
  async function parseKimiWireLog(wireContent, sessionId, mainHomeDir) {
@@ -22432,14 +22961,14 @@ async function parseKimiWireLog(wireContent, sessionId, mainHomeDir) {
22432
22961
  let newContent = "";
22433
22962
  if (tracked?.key) {
22434
22963
  try {
22435
- oldContent = await readFile(path4.join(mainHomeDir, tracked.key), "utf8");
22964
+ oldContent = await readFile3(path6.join(mainHomeDir, tracked.key), "utf8");
22436
22965
  } catch {
22437
22966
  oldContent = "";
22438
22967
  }
22439
22968
  }
22440
22969
  if (checkpoint?.key) {
22441
22970
  try {
22442
- newContent = await readFile(path4.join(mainHomeDir, checkpoint.key), "utf8");
22971
+ newContent = await readFile3(path6.join(mainHomeDir, checkpoint.key), "utf8");
22443
22972
  } catch {
22444
22973
  newContent = "";
22445
22974
  }
@@ -22512,10 +23041,10 @@ async function readKimiSessionSnapshot(sessionId, options = {}) {
22512
23041
  if (!located) {
22513
23042
  throw new Error(`Kimi native session not found: ${sessionId}`);
22514
23043
  }
22515
- const wirePath = path4.join(located.mainHomeDir, "wire.jsonl");
23044
+ const wirePath = path6.join(located.mainHomeDir, "wire.jsonl");
22516
23045
  let wireContent = "";
22517
23046
  try {
22518
- wireContent = await readFile(wirePath, "utf8");
23047
+ wireContent = await readFile3(wirePath, "utf8");
22519
23048
  } catch (error51) {
22520
23049
  throw new Error(`Failed to read Kimi native history ${wirePath}: ${error51 instanceof Error ? error51.message : String(error51)}`, { cause: error51 });
22521
23050
  }
@@ -22572,9 +23101,9 @@ async function readKimiSessionUsage(sessionId, options = {}) {
22572
23101
  const located = await locateKimiSession(sessionId, options);
22573
23102
  if (!located)
22574
23103
  return null;
22575
- const wirePath = path4.join(located.mainHomeDir, "wire.jsonl");
23104
+ const wirePath = path6.join(located.mainHomeDir, "wire.jsonl");
22576
23105
  try {
22577
- const wireContent = await readFile(wirePath, "utf8");
23106
+ const wireContent = await readFile3(wirePath, "utf8");
22578
23107
  return extractKimiUsageFromWireLog(wireContent, options.contextWindowTokens);
22579
23108
  } catch {
22580
23109
  return null;
@@ -22585,15 +23114,15 @@ async function readKimiSessionUsage(sessionId, options = {}) {
22585
23114
  import { setTimeout as delay } from "node:timers/promises";
22586
23115
 
22587
23116
  // dist/command-history.js
22588
- import { appendFile, readFile as readFile2, writeFile } from "node:fs/promises";
22589
- import path5 from "node:path";
23117
+ import { appendFile, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
23118
+ import path7 from "node:path";
22590
23119
  async function readKimiCommandHistory(sessionId, options) {
22591
23120
  const located = await locateKimiSession(sessionId, options);
22592
23121
  if (!located)
22593
23122
  return [];
22594
23123
  let content;
22595
23124
  try {
22596
- content = await readFile2(path5.join(located.sessionDir, "codexhost-commands.jsonl"), "utf8");
23125
+ content = await readFile4(path7.join(located.sessionDir, "codexhost-commands.jsonl"), "utf8");
22597
23126
  } catch (error51) {
22598
23127
  if (error51.code === "ENOENT")
22599
23128
  return [];
@@ -22623,7 +23152,7 @@ async function appendKimiCommandHistory(turn, options) {
22623
23152
  const located = await locateKimiSession(turn.nativeTurnRef.nativeSessionId, options);
22624
23153
  if (!located)
22625
23154
  throw new Error("Cannot persist Kimi command: native session is missing");
22626
- await appendFile(path5.join(located.sessionDir, "codexhost-commands.jsonl"), `${JSON.stringify(turn)}
23155
+ await appendFile(path7.join(located.sessionDir, "codexhost-commands.jsonl"), `${JSON.stringify(turn)}
22627
23156
  `, "utf8");
22628
23157
  }
22629
23158
  async function copyKimiCommandHistory(turns, sessionId, options) {
@@ -22637,7 +23166,7 @@ async function copyKimiCommandHistory(turns, sessionId, options) {
22637
23166
  nativeTurnRef: { ...turn.nativeTurnRef, nativeSessionId: sessionId },
22638
23167
  ...turn.checkpoint ? { checkpoint: { ...turn.checkpoint, nativeSessionId: sessionId } } : {}
22639
23168
  }));
22640
- await writeFile(path5.join(located.sessionDir, "codexhost-commands.jsonl"), copied.map((turn) => `${JSON.stringify(turn)}
23169
+ await writeFile2(path7.join(located.sessionDir, "codexhost-commands.jsonl"), copied.map((turn) => `${JSON.stringify(turn)}
22641
23170
  `).join(""), "utf8");
22642
23171
  }
22643
23172
 
@@ -23819,6 +24348,11 @@ var KimiAdapter = class {
23819
24348
  this.#options = options;
23820
24349
  this.#deps = dependencies;
23821
24350
  }
24351
+ async inspectAccount() {
24352
+ if (this.#closed)
24353
+ return null;
24354
+ return fetchKimiAccount({ environment: { ...process.env, ...this.#options.environment } });
24355
+ }
23822
24356
  #createTransport(options) {
23823
24357
  return this.#deps.createTransport ? this.#deps.createTransport(options) : new KimiAcpTransport(options);
23824
24358
  }
@@ -23850,11 +24384,11 @@ var KimiAdapter = class {
23850
24384
  this.#inspectionCache = result;
23851
24385
  return result;
23852
24386
  }
23853
- const kimiHome = getKimiCodeHome(this.#options.homeDirectory, environment);
23854
- const configPath = path6.join(kimiHome, "config.toml");
24387
+ const kimiHome2 = getKimiCodeHome(this.#options.homeDirectory, environment);
24388
+ const configPath = path8.join(kimiHome2, "config.toml");
23855
24389
  let nativeConfig = null;
23856
24390
  try {
23857
- const configContent = await readFile3(configPath, "utf8");
24391
+ const configContent = await readFile5(configPath, "utf8");
23858
24392
  nativeConfig = parseKimiConfigToml(configContent);
23859
24393
  } catch {
23860
24394
  nativeConfig = null;
@@ -23964,11 +24498,11 @@ var KimiAdapter = class {
23964
24498
  ...this.#options.closeTimeoutMs ? { closeTimeoutMs: this.#options.closeTimeoutMs } : {},
23965
24499
  onFault: (error51) => session?.handleTransportFault(error51)
23966
24500
  });
23967
- const kimiHome = getKimiCodeHome(this.#options.homeDirectory, environment);
23968
- const configPath = path6.join(kimiHome, "config.toml");
24501
+ const kimiHome2 = getKimiCodeHome(this.#options.homeDirectory, environment);
24502
+ const configPath = path8.join(kimiHome2, "config.toml");
23969
24503
  let nativeConfig = null;
23970
24504
  try {
23971
- const configContent = await readFile3(configPath, "utf8");
24505
+ const configContent = await readFile5(configPath, "utf8");
23972
24506
  nativeConfig = parseKimiConfigToml(configContent);
23973
24507
  } catch {
23974
24508
  nativeConfig = null;
@@ -24025,7 +24559,7 @@ var KimiAdapter = class {
24025
24559
  await transport.close().catch(() => void 0);
24026
24560
  return err2("checkpointNotFound", "Kimi Checkpoint does not belong to the source Native Session");
24027
24561
  }
24028
- if (path6.resolve(cwd) !== path6.resolve(located.state.cwd)) {
24562
+ if (path8.resolve(cwd) !== path8.resolve(located.state.cwd)) {
24029
24563
  await transport.close().catch(() => void 0);
24030
24564
  return err2("unsupported", "Kimi Code cannot fork across different working directories");
24031
24565
  }
@@ -24148,7 +24682,7 @@ var KimiAdapter = class {
24148
24682
  const located = await locateKimiSession(sourceId, historyOptions);
24149
24683
  if (!located)
24150
24684
  return err2("sessionNotFound", "Kimi source session was not found");
24151
- if (path6.resolve(input.cwd) !== path6.resolve(located.state.cwd))
24685
+ if (path8.resolve(input.cwd) !== path8.resolve(located.state.cwd))
24152
24686
  return err2("unsupported", "Kimi cannot roll back into another working directory");
24153
24687
  const source = [...this.#sessions].find((candidate) => candidate.initialState.nativeRef?.nativeSessionId === sourceId);
24154
24688
  if (source) {
@@ -24213,13 +24747,64 @@ var KimiAdapter = class {
24213
24747
  }
24214
24748
  };
24215
24749
 
24750
+ // dist/installation.js
24751
+ import { open, readFile as readFile6 } from "node:fs/promises";
24752
+ import { homedir as homedir3 } from "node:os";
24753
+ import { join as join2 } from "node:path";
24754
+ function createKimiInstallation(environment) {
24755
+ const executable = () => resolveKimiExecutable({ environment });
24756
+ const run = (args, timeout) => runInstallationCommand(executable(), args, { ...environment, KIMI_CODE_NO_AUTO_UPDATE: "1" }, timeout);
24757
+ const nativeUpdaterAvailable = async () => {
24758
+ const file2 = await open(executable(), "r");
24759
+ try {
24760
+ const header = Buffer.alloc(4);
24761
+ await file2.read(header, 0, 4, 0);
24762
+ const magic = header.toString("hex");
24763
+ if (!["cffaedfe", "cefaedfe", "cafebabe", "7f454c46"].includes(magic) && !magic.startsWith("4d5a"))
24764
+ return false;
24765
+ } finally {
24766
+ await file2.close();
24767
+ }
24768
+ return /--manual/.test(await run(["__update_download", "--help"]));
24769
+ };
24770
+ return createInstallationManager({
24771
+ async check() {
24772
+ const currentVersion = versionFromOutput(await run(["--version"]));
24773
+ const home = environment.KIMI_CODE_HOME ?? join2(environment.HOME ?? homedir3(), ".kimi-code");
24774
+ const region = await readFile6(join2(home, "region"), "utf8").catch(() => "");
24775
+ const base = region.trim() === "global" ? "https://code.kimi.ai/kimi-code" : "https://code.kimi.com/kimi-code";
24776
+ const latestVersion = installationVersion(await fetchInstallationText(`${base}/latest`));
24777
+ const npm = await npmInstallation(executable(), ["@moonshot-ai/kimi-code"], environment);
24778
+ const canUpdate = npm ? npm.canUpdate : await nativeUpdaterAvailable();
24779
+ return {
24780
+ currentVersion,
24781
+ latestVersion,
24782
+ updateAvailable: newerInstallationVersion(currentVersion, latestVersion),
24783
+ canUpdate,
24784
+ ...!canUpdate ? { message: "Use the original installer to update this Kimi installation" } : {}
24785
+ };
24786
+ },
24787
+ async update(state) {
24788
+ const npm = await npmInstallation(executable(), ["@moonshot-ai/kimi-code"], environment);
24789
+ if (npm)
24790
+ await npm.update(state.latestVersion);
24791
+ else {
24792
+ if (!await nativeUpdaterAvailable())
24793
+ throw new Error("Kimi native updater is unavailable");
24794
+ await run(["__update_download", state.latestVersion, "--manual"], 3e5);
24795
+ await run(["--version"]);
24796
+ }
24797
+ }
24798
+ });
24799
+ }
24800
+
24216
24801
  // dist/plugin.js
24217
24802
  function createHarnessAdapter(context) {
24218
24803
  const environment = { ...context.environment };
24219
- return new KimiAdapter({
24804
+ return Object.assign(new KimiAdapter({
24220
24805
  ...environment[KIMI_COMMAND_ENV] ? { command: environment[KIMI_COMMAND_ENV] } : {},
24221
24806
  environment
24222
- });
24807
+ }), { installation: createKimiInstallation(environment) });
24223
24808
  }
24224
24809
  export {
24225
24810
  createHarnessAdapter