@liberseek/boft-cli-linux-x64 0.7.5 → 0.7.6

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.
@@ -3229,8 +3229,8 @@ var require_utils = __commonJS({
3229
3229
  }
3230
3230
  return ind;
3231
3231
  }
3232
- function removeDotSegments(path9) {
3233
- let input = path9;
3232
+ function removeDotSegments(path12) {
3233
+ let input = path12;
3234
3234
  const output = [];
3235
3235
  let nextSlash = -1;
3236
3236
  let len = 0;
@@ -3482,8 +3482,8 @@ var require_schemes = __commonJS({
3482
3482
  wsComponent.secure = void 0;
3483
3483
  }
3484
3484
  if (wsComponent.resourceName) {
3485
- const [path9, query] = wsComponent.resourceName.split("?");
3486
- wsComponent.path = path9 && path9 !== "/" ? path9 : void 0;
3485
+ const [path12, query] = wsComponent.resourceName.split("?");
3486
+ wsComponent.path = path12 && path12 !== "/" ? path12 : void 0;
3487
3487
  wsComponent.query = query;
3488
3488
  wsComponent.resourceName = void 0;
3489
3489
  }
@@ -13460,10 +13460,10 @@ function mergeDefs(...defs) {
13460
13460
  function cloneDef(schema) {
13461
13461
  return mergeDefs(schema._zod.def);
13462
13462
  }
13463
- function getElementAtPath(obj2, path9) {
13464
- if (!path9)
13463
+ function getElementAtPath(obj2, path12) {
13464
+ if (!path12)
13465
13465
  return obj2;
13466
- return path9.reduce((acc, key) => acc?.[key], obj2);
13466
+ return path12.reduce((acc, key) => acc?.[key], obj2);
13467
13467
  }
13468
13468
  function promiseAllObject(promisesObj) {
13469
13469
  const keys = Object.keys(promisesObj);
@@ -13872,11 +13872,11 @@ function explicitlyAborted(x, startIndex = 0) {
13872
13872
  }
13873
13873
  return false;
13874
13874
  }
13875
- function prefixIssues(path9, issues) {
13875
+ function prefixIssues(path12, issues) {
13876
13876
  return issues.map((iss) => {
13877
13877
  var _a3;
13878
13878
  (_a3 = iss).path ?? (_a3.path = []);
13879
- iss.path.unshift(path9);
13879
+ iss.path.unshift(path12);
13880
13880
  return iss;
13881
13881
  });
13882
13882
  }
@@ -14023,16 +14023,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
14023
14023
  }
14024
14024
  function formatError(error51, mapper = (issue2) => issue2.message) {
14025
14025
  const fieldErrors = { _errors: [] };
14026
- const processError = (error52, path9 = []) => {
14026
+ const processError = (error52, path12 = []) => {
14027
14027
  for (const issue2 of error52.issues) {
14028
14028
  if (issue2.code === "invalid_union" && issue2.errors.length) {
14029
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
14029
+ issue2.errors.map((issues) => processError({ issues }, [...path12, ...issue2.path]));
14030
14030
  } else if (issue2.code === "invalid_key") {
14031
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
14031
+ processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
14032
14032
  } else if (issue2.code === "invalid_element") {
14033
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
14033
+ processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
14034
14034
  } else {
14035
- const fullpath = [...path9, ...issue2.path];
14035
+ const fullpath = [...path12, ...issue2.path];
14036
14036
  if (fullpath.length === 0) {
14037
14037
  fieldErrors._errors.push(mapper(issue2));
14038
14038
  } else {
@@ -14059,17 +14059,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
14059
14059
  }
14060
14060
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
14061
14061
  const result = { errors: [] };
14062
- const processError = (error52, path9 = []) => {
14062
+ const processError = (error52, path12 = []) => {
14063
14063
  var _a3, _b;
14064
14064
  for (const issue2 of error52.issues) {
14065
14065
  if (issue2.code === "invalid_union" && issue2.errors.length) {
14066
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
14066
+ issue2.errors.map((issues) => processError({ issues }, [...path12, ...issue2.path]));
14067
14067
  } else if (issue2.code === "invalid_key") {
14068
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
14068
+ processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
14069
14069
  } else if (issue2.code === "invalid_element") {
14070
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
14070
+ processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
14071
14071
  } else {
14072
- const fullpath = [...path9, ...issue2.path];
14072
+ const fullpath = [...path12, ...issue2.path];
14073
14073
  if (fullpath.length === 0) {
14074
14074
  result.errors.push(mapper(issue2));
14075
14075
  continue;
@@ -14101,8 +14101,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
14101
14101
  }
14102
14102
  function toDotPath(_path) {
14103
14103
  const segs = [];
14104
- const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
14105
- for (const seg of path9) {
14104
+ const path12 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
14105
+ for (const seg of path12) {
14106
14106
  if (typeof seg === "number")
14107
14107
  segs.push(`[${seg}]`);
14108
14108
  else if (typeof seg === "symbol")
@@ -26794,13 +26794,13 @@ function resolveRef(ref, ctx) {
26794
26794
  if (!ref.startsWith("#")) {
26795
26795
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
26796
26796
  }
26797
- const path9 = ref.slice(1).split("/").filter(Boolean);
26798
- if (path9.length === 0) {
26797
+ const path12 = ref.slice(1).split("/").filter(Boolean);
26798
+ if (path12.length === 0) {
26799
26799
  return ctx.rootSchema;
26800
26800
  }
26801
26801
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
26802
- if (path9[0] === defsKey) {
26803
- const key = path9[1];
26802
+ if (path12[0] === defsKey) {
26803
+ const key = path12[1];
26804
26804
  if (!key || !ctx.defs[key]) {
26805
26805
  throw new Error(`Reference not found: ${ref}`);
26806
26806
  }
@@ -27263,6 +27263,55 @@ var credentialImportsParamsSchema = external_exports.object({
27263
27263
  request: credentialImportsRequestSchema
27264
27264
  }).strict();
27265
27265
 
27266
+ // ../../shared-contracts/dist/harness-display-settings.js
27267
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
27268
+ agent: external_exports.string().min(1).max(128),
27269
+ section: external_exports.enum(["main", "more", "auto"])
27270
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
27271
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
27272
+ entries: harnessDisplayEntriesSchema.nullable()
27273
+ });
27274
+ var harnessDisplayGetSchema = external_exports.strictObject({});
27275
+ var harnessDisplaySetSchema = external_exports.strictObject({
27276
+ entries: harnessDisplayEntriesSchema,
27277
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
27278
+ initializeOnly: external_exports.boolean().optional()
27279
+ });
27280
+
27281
+ // ../../shared-contracts/dist/console.js
27282
+ var consoleAnnouncementSchema = external_exports.strictObject({
27283
+ title: external_exports.string().trim().min(1).max(200),
27284
+ type: external_exports.enum(["info", "warning", "danger"]),
27285
+ body: external_exports.string().trim().min(1).max(16 * 1024)
27286
+ });
27287
+ var consoleOpenParamsSchema = external_exports.strictObject({});
27288
+ var consoleOpenResultSchema = external_exports.strictObject({
27289
+ /** The console address. */
27290
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
27291
+ });
27292
+ var CONSOLE_HOST_METHODS = Object.freeze([
27293
+ "codexhost/harness/plugins/list",
27294
+ "codexhost/harness/display-settings/get",
27295
+ "codexhost/harness/display-settings/set",
27296
+ "codexhost/harness/inspect",
27297
+ "codexhost/harness/launch-settings/get",
27298
+ "codexhost/harness/launch-settings/set",
27299
+ "codexhost/harness/web-ui/open",
27300
+ "codexhost/harness/accounts/sources",
27301
+ "codexhost/harness/accounts/list",
27302
+ "codexhost/harness/accounts/inspect",
27303
+ "codexhost/harness/credential-imports",
27304
+ "codexhost/harness/session-import/sources",
27305
+ "codexhost/harness/session-import/list",
27306
+ "codexhost/harness/session-import/import",
27307
+ "codexhost/account/list",
27308
+ "codexhost/account/refresh",
27309
+ "codexhost/account/usage/inspect",
27310
+ "codexhost/update/check",
27311
+ "codexhost/update/start",
27312
+ "codexhost/update/status"
27313
+ ]);
27314
+
27266
27315
  // ../../shared-contracts/dist/version.js
27267
27316
  var WORKSPACE_CONTRACT_VERSION = 1;
27268
27317
 
@@ -27316,6 +27365,12 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
27316
27365
  var hostItemIdSchema = opaqueIdSchema.brand();
27317
27366
  var hostInteractionIdSchema = opaqueIdSchema.brand();
27318
27367
 
27368
+ // ../../shared-contracts/dist/manual-compaction.js
27369
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
27370
+ threadId: hostThreadIdSchema,
27371
+ turnId: hostTurnIdSchema
27372
+ });
27373
+
27319
27374
  // ../../shared-contracts/dist/thread-usage.js
27320
27375
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
27321
27376
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -27376,6 +27431,10 @@ var threadUsageSnapshotSchema = external_exports.object({
27376
27431
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
27377
27432
  var accountCreditsProductUsageSchema = external_exports.object({
27378
27433
  product: external_exports.string().min(1),
27434
+ used: external_exports.number().finite().nonnegative().optional(),
27435
+ // Zero is a real empty cap, not an absent field.
27436
+ limit: external_exports.number().finite().nonnegative().optional(),
27437
+ unit: external_exports.string().min(1).max(32).optional(),
27379
27438
  usagePercent: usagePercentSchema,
27380
27439
  resetsAt: external_exports.string().min(1).optional()
27381
27440
  }).strict();
@@ -27385,11 +27444,14 @@ var accountResetCreditsSchema = external_exports.object({
27385
27444
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
27386
27445
  }).strict();
27387
27446
  var accountCreditsSnapshotSchema = external_exports.object({
27447
+ used: external_exports.number().finite().nonnegative().optional(),
27448
+ // Zero is a real empty cap, not an absent field.
27449
+ limit: external_exports.number().finite().nonnegative().optional(),
27450
+ unit: external_exports.string().trim().min(1).max(32).optional(),
27388
27451
  /** Native label when the primary limit is scoped to a model or product group. */
27389
27452
  label: external_exports.string().min(1).optional(),
27390
27453
  usedPercent: usagePercentSchema.optional(),
27391
27454
  remaining: external_exports.number().finite().optional(),
27392
- unit: external_exports.string().trim().min(1).max(32).optional(),
27393
27455
  resetsAt: external_exports.string().min(1).optional(),
27394
27456
  periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
27395
27457
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
@@ -27420,12 +27482,27 @@ var threadUsageInspectionSchema = external_exports.object({
27420
27482
  }).strict();
27421
27483
 
27422
27484
  // ../../shared-contracts/dist/harness-accounts.js
27423
- var harnessAccountSnapshotSchema = external_exports.object({
27485
+ var accountBalanceSnapshotSchema = external_exports.object({
27486
+ amount: external_exports.number().finite().nonnegative(),
27487
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
27488
+ currency: external_exports.string().trim().min(1).max(8),
27489
+ /** Native label when the Harness exposes several Billing Sources. */
27490
+ label: external_exports.string().trim().min(1).max(128).optional()
27491
+ }).strict();
27492
+ var harnessAccountSnapshotObject = external_exports.object({
27424
27493
  email: external_exports.string().trim().min(1).max(320).optional(),
27425
27494
  label: external_exports.string().trim().min(1).max(256).optional(),
27426
27495
  plan: external_exports.string().trim().min(1).max(128).optional(),
27427
- credits: accountCreditsSnapshotSchema
27496
+ credits: accountCreditsSnapshotSchema.optional(),
27497
+ balance: accountBalanceSnapshotSchema.optional()
27428
27498
  }).strict();
27499
+ function requireReportedQuota(schema) {
27500
+ return schema.refine((value) => {
27501
+ const reported = value;
27502
+ return reported.credits !== void 0 || reported.balance !== void 0;
27503
+ }, { message: "Account must report either credits or a balance" });
27504
+ }
27505
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
27429
27506
  var harnessAccountIdentityShape = {
27430
27507
  harnessId: harnessIdSchema,
27431
27508
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -27436,11 +27513,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
27436
27513
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
27437
27514
  var harnessAccountInspectResultSchema = external_exports.object({
27438
27515
  ...harnessAccountIdentityShape,
27439
- account: harnessAccountSnapshotSchema.nullable()
27516
+ account: harnessAccountSnapshotSchema.nullable(),
27517
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
27518
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
27440
27519
  }).strict();
27441
27520
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
27442
27521
  var harnessAccountListResultSchema = external_exports.object({
27443
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
27522
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
27444
27523
  }).strict();
27445
27524
 
27446
27525
  // ../../shared-contracts/dist/json-value.js
@@ -27578,6 +27657,8 @@ var harnessModelSchema = external_exports.object({
27578
27657
  ref: harnessModelRefSchema,
27579
27658
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
27580
27659
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
27660
+ /** Optional opaque selection for this same Model with priority processing enabled. */
27661
+ fastModel: harnessModelRefSchema.optional(),
27581
27662
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
27582
27663
  }).strict();
27583
27664
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -27610,6 +27691,16 @@ var harnessModelCatalogSchema = external_exports.object({
27610
27691
  });
27611
27692
  }
27612
27693
  refs.add(model.ref.id);
27694
+ if (model.fastModel) {
27695
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
27696
+ context.addIssue({
27697
+ code: "custom",
27698
+ message: "Fast Model refs must be distinct and unique",
27699
+ path: ["models", index, "fastModel"]
27700
+ });
27701
+ }
27702
+ refs.add(model.fastModel.id);
27703
+ }
27613
27704
  const supportedThinkingIds = /* @__PURE__ */ new Set();
27614
27705
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
27615
27706
  if (supportedThinkingIds.has(optionId)) {
@@ -27732,11 +27823,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
27732
27823
  thinkingOptionId: harnessThinkingOptionIdSchema
27733
27824
  }).strict();
27734
27825
  var threadInspectionParamsSchema = external_exports.object({
27735
- threadId: hostThreadIdSchema
27826
+ threadId: hostThreadIdSchema,
27827
+ includeReferenceCapability: external_exports.boolean().optional()
27736
27828
  }).strict();
27737
27829
  var codexThreadInspectionSchema = external_exports.object({
27738
27830
  owner: external_exports.literal("codex"),
27739
- locked: external_exports.literal(true)
27831
+ locked: external_exports.literal(true),
27832
+ supportsThreadReferences: external_exports.literal(true).optional()
27740
27833
  }).strict();
27741
27834
  var externalThreadInspectionSchema = external_exports.object({
27742
27835
  owner: external_exports.literal("external"),
@@ -27864,10 +27957,31 @@ var harnessLaunchSettingsSchema = external_exports.object({
27864
27957
  restartRequired: external_exports.boolean()
27865
27958
  }).strict();
27866
27959
 
27960
+ // ../../shared-contracts/dist/harness-installation.js
27961
+ var harnessInstallationParamsSchema = external_exports.object({
27962
+ harnessId: harnessIdSchema,
27963
+ action: external_exports.enum(["check", "update"])
27964
+ }).strict();
27965
+ var harnessInstallationStateSchema = external_exports.object({
27966
+ currentVersion: external_exports.string().min(1).max(128),
27967
+ latestVersion: external_exports.string().min(1).max(128),
27968
+ updateAvailable: external_exports.boolean(),
27969
+ canUpdate: external_exports.boolean(),
27970
+ message: external_exports.string().max(2048).optional()
27971
+ }).strict();
27972
+
27867
27973
  // ../../shared-contracts/dist/codex-accounts.js
27868
27974
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
27869
27975
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
27870
27976
  var codexAccountAuthKindSchema = external_exports.enum(["api", "chatgpt"]);
27977
+ var codexAccountSiteUrlPattern = /^https?:\/\/(?:\[[0-9a-fA-F:]+\]|[^/\s:@?#]+)(?::\d{1,5})?(?:[/?#][^\s]*)?$/u;
27978
+ function isCodexAccountSiteUrl(value) {
27979
+ return value.length > 0 && value.length <= 2048 && codexAccountSiteUrlPattern.test(value);
27980
+ }
27981
+ var externalUrlOpenParamsSchema = external_exports.object({
27982
+ url: external_exports.string().max(2048).refine(isCodexAccountSiteUrl, "External URL must be http(s)")
27983
+ }).strict();
27984
+ var externalUrlOpenResultSchema = external_exports.object({}).strict();
27871
27985
  var codexAccountPlanTypeSchema = external_exports.enum([
27872
27986
  "free",
27873
27987
  "go",
@@ -27893,7 +28007,8 @@ var codexAccountSchema = external_exports.object({
27893
28007
  email: external_exports.string().email().max(320).optional(),
27894
28008
  planType: codexAccountPlanTypeSchema.optional(),
27895
28009
  authKind: codexAccountAuthKindSchema.optional(),
27896
- authIdentity: nonBlankTextSchema3.max(256).optional()
28010
+ authIdentity: nonBlankTextSchema3.max(256).optional(),
28011
+ siteUrl: external_exports.string().refine(isCodexAccountSiteUrl, "Account site URL must be http(s)").optional()
27897
28012
  }).strict();
27898
28013
  var codexAccountPhaseSchema = external_exports.enum(["ready", "unavailable"]);
27899
28014
  var codexAccountListResultSchema = external_exports.object({
@@ -28510,9 +28625,778 @@ function cursorCommandPrompt(command, catalog) {
28510
28625
  return { ok: true, value: `${descriptor.invocation}${text2 ? ` ${text2}` : ""}` };
28511
28626
  }
28512
28627
 
28628
+ // ../../harness-discovery/dist/environment.js
28629
+ import fs from "node:fs";
28630
+ import path from "node:path";
28631
+ function targetPath(platform) {
28632
+ return platform === "win32" ? path.win32 : path.posix;
28633
+ }
28634
+ function environmentValue(environment, name) {
28635
+ const lowered = name.toLowerCase();
28636
+ for (const [key, value] of Object.entries(environment)) {
28637
+ if (key.toLowerCase() === lowered)
28638
+ return value;
28639
+ }
28640
+ return void 0;
28641
+ }
28642
+ function pathDelimiter(platform) {
28643
+ return platform === "win32" ? ";" : ":";
28644
+ }
28645
+ function pathDirectories(environment, platform) {
28646
+ return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
28647
+ }
28648
+ function executableExtensions(command, platform, environment) {
28649
+ if (platform !== "win32")
28650
+ return [""];
28651
+ if (targetPath(platform).extname(command) !== "")
28652
+ return [""];
28653
+ return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
28654
+ }
28655
+ function isExecutableFile(filePath, platform) {
28656
+ try {
28657
+ fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
28658
+ return fs.statSync(filePath).isFile();
28659
+ } catch {
28660
+ return false;
28661
+ }
28662
+ }
28663
+ function subdirectoryNames(directory) {
28664
+ try {
28665
+ return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
28666
+ } catch {
28667
+ return [];
28668
+ }
28669
+ }
28670
+ function newestFirst(names) {
28671
+ return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
28672
+ }
28673
+
28674
+ // ../../harness-discovery/dist/invocation.js
28675
+ import path2 from "node:path";
28676
+ function commandInvocation(command, arguments_, environment, platform = process.platform) {
28677
+ const extension = path2.win32.extname(command).toLowerCase();
28678
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
28679
+ return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
28680
+ }
28681
+ const quote2 = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
28682
+ const commandLine = [command, ...arguments_].map(quote2).join(" ");
28683
+ return {
28684
+ command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
28685
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
28686
+ windowsVerbatimArguments: true
28687
+ };
28688
+ }
28689
+
28690
+ // ../../harness-discovery/dist/node-runtime.js
28691
+ import path3 from "node:path";
28692
+ function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
28693
+ const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
28694
+ const delimiter = platform === "win32" ? ";" : ":";
28695
+ const runtimeDirectory = path3.dirname(runtimeExecutable);
28696
+ const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
28697
+ const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
28698
+ if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
28699
+ directories.push(runtimeDirectory);
28700
+ }
28701
+ return { ...environment, [pathKey]: directories.join(delimiter) };
28702
+ }
28703
+
28704
+ // ../../harness-discovery/dist/resolve.js
28705
+ import os from "node:os";
28706
+
28707
+ // ../../harness-discovery/dist/version-managers.js
28708
+ function versionManagerBinaryDirectories(context) {
28709
+ const { platform, environment, home } = context;
28710
+ const list = context.subdirectories ?? subdirectoryNames;
28711
+ const pathFlavor = targetPath(platform);
28712
+ const value = (name) => environmentValue(environment, name);
28713
+ const directories = [];
28714
+ const versioned = (root, ...tail) => {
28715
+ for (const version2 of newestFirst(list(root))) {
28716
+ directories.push(pathFlavor.join(root, version2, ...tail));
28717
+ }
28718
+ };
28719
+ if (platform === "win32") {
28720
+ const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
28721
+ const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
28722
+ versioned(pathFlavor.join(appData, "nvm"));
28723
+ versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
28724
+ directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
28725
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
28726
+ const pnpmHome2 = value("PNPM_HOME");
28727
+ if (pnpmHome2)
28728
+ directories.push(pnpmHome2);
28729
+ directories.push(pathFlavor.join(localAppData, "pnpm"));
28730
+ return directories;
28731
+ }
28732
+ versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
28733
+ const fnmRoots = [
28734
+ value("FNM_DIR"),
28735
+ pathFlavor.join(home, ".local", "share", "fnm"),
28736
+ pathFlavor.join(home, "Library", "Application Support", "fnm")
28737
+ ].filter((root) => root !== void 0);
28738
+ for (const root of fnmRoots) {
28739
+ versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
28740
+ }
28741
+ const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
28742
+ versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
28743
+ directories.push(pathFlavor.join(voltaHome, "bin"));
28744
+ const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
28745
+ versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
28746
+ directories.push(pathFlavor.join(asdfHome, "shims"));
28747
+ const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
28748
+ versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
28749
+ directories.push(pathFlavor.join(nodenvHome, "shims"));
28750
+ versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
28751
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
28752
+ const pnpmHome = value("PNPM_HOME");
28753
+ if (pnpmHome)
28754
+ directories.push(pnpmHome);
28755
+ directories.push(pathFlavor.join(home, "Library", "pnpm"));
28756
+ directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
28757
+ for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
28758
+ for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
28759
+ directories.push(pathFlavor.join(prefix, formula, "bin"));
28760
+ }
28761
+ }
28762
+ return directories;
28763
+ }
28764
+
28765
+ // ../../harness-discovery/dist/resolve.js
28766
+ var VERSION_MANAGER_ROOTS = "<version-managers>";
28767
+ function installRootExtensions(platform) {
28768
+ return platform === "win32" ? [".exe", ".cmd"] : [""];
28769
+ }
28770
+ function resolveHomeDirectory(input) {
28771
+ return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
28772
+ }
28773
+ function templateVariables(environment, platform, home) {
28774
+ const pathFlavor = targetPath(platform);
28775
+ return {
28776
+ HOME: home,
28777
+ USERPROFILE: home,
28778
+ APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
28779
+ LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
28780
+ };
28781
+ }
28782
+ function joinTemplate(platform, value) {
28783
+ const pathFlavor = targetPath(platform);
28784
+ const segments = value.split("/");
28785
+ const head = segments[0] ?? "";
28786
+ const tail = segments.slice(1);
28787
+ if (head === "")
28788
+ return pathFlavor.join(pathFlavor.sep, ...tail);
28789
+ return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
28790
+ }
28791
+ function expandInstallRoot(template, environment, platform, home) {
28792
+ const variables = templateVariables(environment, platform, home);
28793
+ let unresolved = false;
28794
+ const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
28795
+ const value = variables[name] ?? environmentValue(environment, name);
28796
+ if (value === void 0 || value === "") {
28797
+ unresolved = true;
28798
+ return "";
28799
+ }
28800
+ return value;
28801
+ });
28802
+ return unresolved ? void 0 : joinTemplate(platform, substituted);
28803
+ }
28804
+ function installRootDirectories(spec, input, dependencies, platform, home) {
28805
+ const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
28806
+ const directories = [];
28807
+ for (const template of templates) {
28808
+ if (template === VERSION_MANAGER_ROOTS) {
28809
+ directories.push(...versionManagerBinaryDirectories({
28810
+ platform,
28811
+ environment: input.environment,
28812
+ home,
28813
+ ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
28814
+ }));
28815
+ continue;
28816
+ }
28817
+ const directory = expandInstallRoot(template, input.environment, platform, home);
28818
+ if (directory !== void 0)
28819
+ directories.push(directory);
28820
+ }
28821
+ return directories;
28822
+ }
28823
+ function harnessCandidates(spec, input, dependencies = {}) {
28824
+ const platform = input.platform ?? process.platform;
28825
+ const pathFlavor = targetPath(platform);
28826
+ const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
28827
+ const command = configured ?? spec.command;
28828
+ if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
28829
+ return [{ candidate: command, source: "configured" }];
28830
+ }
28831
+ const candidates = [];
28832
+ const extensions = executableExtensions(command, platform, input.environment);
28833
+ for (const directory of pathDirectories(input.environment, platform)) {
28834
+ for (const extension of extensions) {
28835
+ candidates.push({
28836
+ candidate: pathFlavor.join(directory, command + extension),
28837
+ source: "path"
28838
+ });
28839
+ }
28840
+ }
28841
+ if (configured !== void 0)
28842
+ return candidates;
28843
+ const home = resolveHomeDirectory(input);
28844
+ for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
28845
+ for (const extension of installRootExtensions(platform)) {
28846
+ candidates.push({
28847
+ candidate: pathFlavor.join(directory, spec.command + extension),
28848
+ source: "install-root"
28849
+ });
28850
+ }
28851
+ }
28852
+ return candidates;
28853
+ }
28854
+ function resolveHarnessExecutable(spec, input, dependencies = {}) {
28855
+ const platform = input.platform ?? process.platform;
28856
+ const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
28857
+ const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
28858
+ const context = { platform, isExecutable };
28859
+ for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
28860
+ const executable = runnable(candidate, context);
28861
+ if (executable !== void 0 && isExecutable(executable))
28862
+ return { executable, source };
28863
+ }
28864
+ return void 0;
28865
+ }
28866
+
28867
+ // ../../harness-discovery/dist/installation.js
28868
+ import { execFile } from "node:child_process";
28869
+ import { homedir } from "node:os";
28870
+ function runInstallationCommand(command, args, environment, timeout = 3e4) {
28871
+ const env = withNodeRuntimeOnPath(environment);
28872
+ const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
28873
+ return new Promise((resolve, reject) => {
28874
+ const child = execFile(invocation.command, invocation.arguments, {
28875
+ env,
28876
+ cwd: env.HOME ?? env.USERPROFILE ?? homedir(),
28877
+ encoding: "utf8",
28878
+ timeout,
28879
+ killSignal: "SIGKILL",
28880
+ maxBuffer: 1024 * 1024,
28881
+ windowsHide: true,
28882
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
28883
+ }, (error51, stdout, stderr) => {
28884
+ if (error51)
28885
+ reject(new Error(error51.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
28886
+ else
28887
+ resolve((stdout || stderr).trim());
28888
+ });
28889
+ child.stdin?.end();
28890
+ });
28891
+ }
28892
+ function installationVersion(value) {
28893
+ if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
28894
+ throw new Error("Harness returned an invalid version");
28895
+ return value.trim().replace(/^v/, "");
28896
+ }
28897
+ function createInstallationManager(options) {
28898
+ let checking;
28899
+ let updating;
28900
+ const check2 = () => checking ??= options.check().finally(() => {
28901
+ checking = void 0;
28902
+ });
28903
+ return (action) => {
28904
+ if (updating)
28905
+ return updating;
28906
+ if (action === "check")
28907
+ return check2();
28908
+ updating = (async () => {
28909
+ const before = await check2();
28910
+ if (!before.updateAvailable)
28911
+ return before;
28912
+ if (!before.canUpdate)
28913
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
28914
+ await options.update(before);
28915
+ const after = await check2();
28916
+ if (after.currentVersion === before.currentVersion)
28917
+ throw new Error("The Harness version did not change; check the native updater and retry");
28918
+ return after;
28919
+ })().finally(() => {
28920
+ updating = void 0;
28921
+ });
28922
+ return updating;
28923
+ };
28924
+ }
28925
+
28926
+ // dist/command.js
28927
+ import { existsSync, readdirSync } from "node:fs";
28928
+ import path4 from "node:path";
28929
+ var PINNED_VERSION_AGENT = /[/\\]cursor-agent[/\\]versions[/\\][^/\\]+[/\\]cursor-agent(?:\.exe)?$/iu;
28930
+ function cursorDiscoverySpec(skipPinnedVersions) {
28931
+ return {
28932
+ id: "cursor-cli",
28933
+ command: "cursor-agent",
28934
+ commandEnvironmentVariable: "CODEXHOST_CURSOR_COMMAND",
28935
+ installRoots: {
28936
+ posix: ["~/.local/bin", "/usr/local/bin", "/opt/homebrew/bin"],
28937
+ windows: ["${LOCALAPPDATA}/cursor-agent"]
28938
+ },
28939
+ ...skipPinnedVersions ? {
28940
+ runnableCandidate: (candidate) => PINNED_VERSION_AGENT.test(candidate) ? void 0 : candidate
28941
+ } : {}
28942
+ };
28943
+ }
28944
+ function resolveCursorExecutable(environment, command) {
28945
+ const input = { environment, ...command ? { command } : {} };
28946
+ const pinned = resolveHarnessExecutable(cursorDiscoverySpec(false), input);
28947
+ if (!pinned)
28948
+ throw new Error("Cursor CLI is not installed; install cursor-agent or set CODEXHOST_CURSOR_COMMAND");
28949
+ const explicit = command?.trim() || environment.CODEXHOST_CURSOR_COMMAND?.trim();
28950
+ if (explicit || !PINNED_VERSION_AGENT.test(pinned.executable))
28951
+ return pinned;
28952
+ return resolveHarnessExecutable(cursorDiscoverySpec(true), input) ?? pinned;
28953
+ }
28954
+ function cursorInvocation(environment, command, args) {
28955
+ const resolution = resolveCursorExecutable(environment, command);
28956
+ if (process.platform === "win32" && /\.(cmd|ps1)$/iu.test(resolution.executable)) {
28957
+ const root = path4.dirname(resolution.executable);
28958
+ const versions = path4.join(root, "versions");
28959
+ if (existsSync(versions)) {
28960
+ const version2 = readdirSync(versions).filter((name) => /^\d{4}\.\d{2}\.\d{2}-(?:\d{2}-\d{2}-\d{2}-)?[a-f0-9]+$/u.test(name)).sort().reverse().find((name) => existsSync(path4.join(versions, name, "node.exe")) && existsSync(path4.join(versions, name, "index.js")));
28961
+ if (version2)
28962
+ return {
28963
+ command: path4.join(versions, version2, "node.exe"),
28964
+ arguments: [path4.join(versions, version2, "index.js"), ...args],
28965
+ windowsVerbatimArguments: false
28966
+ };
28967
+ }
28968
+ throw new Error("Cursor Windows launcher has no supported native bundle; configure a native executable");
28969
+ }
28970
+ return commandInvocation(resolution.executable, args, environment);
28971
+ }
28972
+
28973
+ // dist/installation.js
28974
+ function createCursorInstallation(environment) {
28975
+ const run = (args, timeout) => {
28976
+ const invocation = cursorInvocation(environment, void 0, args);
28977
+ return runInstallationCommand(invocation.command, invocation.arguments, environment, timeout);
28978
+ };
28979
+ return createInstallationManager({
28980
+ async check() {
28981
+ const state = JSON.parse(await run(["about", "--format", "json"]));
28982
+ if (state.latestStatus !== "up_to_date" && state.latestStatus !== "update_available")
28983
+ throw new Error("Cursor update checks are disabled or unavailable");
28984
+ return {
28985
+ currentVersion: installationVersion(state.cliVersion),
28986
+ latestVersion: installationVersion(state.latestVersion),
28987
+ updateAvailable: state.latestStatus === "update_available",
28988
+ canUpdate: true
28989
+ };
28990
+ },
28991
+ async update() {
28992
+ await run(["update"], 3e5);
28993
+ }
28994
+ });
28995
+ }
28996
+
28513
28997
  // dist/adapter.js
28998
+ import path10 from "node:path";
28999
+
29000
+ // dist/account-usage.js
29001
+ import { execFile as execFile2 } from "node:child_process";
29002
+ import { readFile } from "node:fs/promises";
29003
+ import { homedir as homedir2 } from "node:os";
29004
+ import path5 from "node:path";
29005
+ import { promisify } from "node:util";
29006
+ var execute = promisify(execFile2);
29007
+ var ENDPOINT = "https://api2.cursor.sh/aiserver.v1.DashboardService/";
29008
+ var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
29009
+ var percent = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.min(100, value) : void 0;
29010
+ function projectCursorAccountUsage(usage, identity, plan) {
29011
+ const data = record2(usage);
29012
+ const buckets = record2(data.planUsage);
29013
+ const usedPercent = percent(buckets.autoPercentUsed);
29014
+ if (usedPercent === void 0)
29015
+ return null;
29016
+ const end = typeof data.billingCycleEnd === "string" || typeof data.billingCycleEnd === "number" ? Number(data.billingCycleEnd) : NaN;
29017
+ const date5 = new Date(end);
29018
+ const resetsAt = Number.isFinite(date5.getTime()) && end > 0 ? date5.toISOString() : void 0;
29019
+ const apiPercent = percent(buckets.apiPercentUsed);
29020
+ const email3 = record2(identity).email;
29021
+ const planName = record2(record2(plan).planInfo).planName;
29022
+ const result = harnessAccountSnapshotSchema.safeParse({
29023
+ ...typeof email3 === "string" && email3.trim() ? { email: email3 } : {},
29024
+ ...typeof planName === "string" && planName.trim() ? { plan: planName } : {},
29025
+ credits: {
29026
+ usedPercent,
29027
+ label: "Auto · monthly",
29028
+ periodType: "monthly",
29029
+ ...resetsAt ? { resetsAt } : {},
29030
+ ...apiPercent === void 0 ? {} : {
29031
+ productUsage: [
29032
+ {
29033
+ product: "API · monthly",
29034
+ usagePercent: apiPercent,
29035
+ ...resetsAt ? { resetsAt } : {}
29036
+ }
29037
+ ]
29038
+ }
29039
+ }
29040
+ });
29041
+ return result.success ? result.data : null;
29042
+ }
29043
+ async function accessToken(environment) {
29044
+ if (environment.CURSOR_API_KEY?.trim() || environment.AGENT_CLI_CREDENTIAL_STORE === "memory")
29045
+ return void 0;
29046
+ if (process.platform === "darwin" && environment.AGENT_CLI_CREDENTIAL_STORE !== "file") {
29047
+ const result = await execute("/usr/bin/security", ["find-generic-password", "-s", "cursor-access-token", "-a", "cursor-user", "-w"], { timeout: 5e3, maxBuffer: 64 * 1024 });
29048
+ return result.stdout.trim() || void 0;
29049
+ }
29050
+ const home = environment.HOME ?? environment.USERPROFILE ?? homedir2();
29051
+ const authPath = process.platform === "darwin" ? path5.join(home, ".cursor", "auth.json") : process.platform === "win32" ? path5.join(environment.APPDATA ?? path5.join(home, "AppData", "Roaming"), "Cursor", "auth.json") : path5.join(environment.XDG_CONFIG_HOME ?? path5.join(home, ".config"), "cursor", "auth.json");
29052
+ const auth = record2(JSON.parse(await readFile(authPath, "utf8")));
29053
+ return typeof auth.accessToken === "string" && auth.accessToken.trim() ? auth.accessToken : void 0;
29054
+ }
29055
+ async function fetchCursorAccount(input = {}) {
29056
+ try {
29057
+ const environment = input.environment ?? process.env;
29058
+ if (environment.CURSOR_API_KEY?.trim() || environment.AGENT_CLI_CREDENTIAL_STORE === "memory")
29059
+ return null;
29060
+ const token = await (input.readAccessToken ? input.readAccessToken() : accessToken(environment));
29061
+ if (!token)
29062
+ return null;
29063
+ const signal = input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
29064
+ const request = async (method) => {
29065
+ const response = await (input.fetch ?? fetch)(ENDPOINT + method, {
29066
+ method: "POST",
29067
+ headers: {
29068
+ Authorization: `Bearer ${token}`,
29069
+ "Content-Type": "application/json",
29070
+ "Connect-Protocol-Version": "1"
29071
+ },
29072
+ body: "{}",
29073
+ signal
29074
+ });
29075
+ return response.ok ? response.json() : null;
29076
+ };
29077
+ const [usage, identity, plan] = await Promise.all([
29078
+ request("GetCurrentPeriodUsage"),
29079
+ request("GetMe").catch(() => null),
29080
+ request("GetPlanInfo").catch(() => null)
29081
+ ]);
29082
+ return projectCursorAccountUsage(usage, identity, plan);
29083
+ } catch {
29084
+ return null;
29085
+ }
29086
+ }
29087
+
29088
+ // dist/session-import.js
29089
+ import { lstat, opendir, readFile as readFile2, realpath, stat } from "node:fs/promises";
28514
29090
  import path7 from "node:path";
28515
29091
 
29092
+ // dist/native-history.js
29093
+ import { existsSync as existsSync2, readFileSync, realpathSync } from "node:fs";
29094
+ import os2 from "node:os";
29095
+ import path6 from "node:path";
29096
+ import { DatabaseSync } from "node:sqlite";
29097
+ function cursorConfigDirectory(environment) {
29098
+ const home = environment.HOME ?? environment.USERPROFILE ?? os2.homedir();
29099
+ return environment.CURSOR_CONFIG_DIR?.trim() ? path6.resolve(environment.CURSOR_CONFIG_DIR) : environment.XDG_CONFIG_HOME?.trim() ? path6.resolve(environment.XDG_CONFIG_HOME, "cursor") : path6.join(home, ".cursor");
29100
+ }
29101
+ function cursorSessionDirectory(sessionId, environment) {
29102
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(sessionId))
29103
+ throw new Error("Unsupported Cursor native session ID");
29104
+ return path6.join(cursorConfigDirectory(environment), "acp-sessions", sessionId);
29105
+ }
29106
+ function cursorSameWorkspace(left, right) {
29107
+ return path6.resolve(left) === path6.resolve(right) || existsSync2(left) && existsSync2(right) && realpathSync(left) === realpathSync(right);
29108
+ }
29109
+ function protobufBytes(data) {
29110
+ if (data.length > 32 * 1024 * 1024)
29111
+ throw new Error("Cursor native record is too large");
29112
+ let offset = 0;
29113
+ const varint = () => {
29114
+ let result = 0;
29115
+ for (let shift = 0; shift < 70; shift += 7) {
29116
+ const value = data[offset++];
29117
+ if (value === void 0)
29118
+ throw new Error("Truncated Cursor native record");
29119
+ result += (value & 127) * 2 ** shift;
29120
+ if (!(value & 128))
29121
+ return result;
29122
+ }
29123
+ throw new Error("Invalid Cursor native varint");
29124
+ };
29125
+ const fields = /* @__PURE__ */ new Map();
29126
+ while (offset < data.length) {
29127
+ const tag = varint();
29128
+ const field = Math.floor(tag / 8), wire = tag % 8;
29129
+ if (!Number.isSafeInteger(tag) || field === 0)
29130
+ throw new Error("Invalid Cursor native field");
29131
+ if (wire === 0) {
29132
+ varint();
29133
+ continue;
29134
+ }
29135
+ const length = wire === 2 ? varint() : wire === 1 ? 8 : wire === 5 ? 4 : -1;
29136
+ if (!Number.isSafeInteger(length) || length < 0 || offset + length > data.length)
29137
+ throw new Error("Unsupported Cursor native record");
29138
+ if (wire === 2) {
29139
+ const values = fields.get(field) ?? [];
29140
+ values.push(Buffer.from(data.subarray(offset, offset + length)));
29141
+ fields.set(field, values);
29142
+ }
29143
+ offset += length;
29144
+ }
29145
+ return fields;
29146
+ }
29147
+ function one(fields, field) {
29148
+ const values = fields.get(field);
29149
+ if (values?.length !== 1 || !values[0])
29150
+ throw new Error("Cursor native history identity is missing or ambiguous");
29151
+ return values[0];
29152
+ }
29153
+ function readCursorNativeHistory(sessionId, cwd, environment, allowMissing = false) {
29154
+ const directory = cursorSessionDirectory(sessionId, environment);
29155
+ const filename = path6.join(directory, "store.db");
29156
+ if (allowMissing && !existsSync2(filename))
29157
+ return { revision: void 0, turns: [] };
29158
+ const info = JSON.parse(readFileSync(path6.join(directory, "meta.json"), "utf8"));
29159
+ if (!info || typeof info !== "object" || !("cwd" in info) || typeof info.cwd !== "string" || !cursorSameWorkspace(info.cwd, cwd))
29160
+ throw new Error("Cursor session workspace does not match");
29161
+ const db = new DatabaseSync(filename, { readOnly: true });
29162
+ try {
29163
+ db.exec("BEGIN");
29164
+ const row = db.prepare("SELECT value FROM meta WHERE key = ?").get("0");
29165
+ if (!row && allowMissing)
29166
+ return { revision: void 0, turns: [] };
29167
+ if (typeof row?.value !== "string" || row.value.length > 1e6)
29168
+ throw new Error("Unsupported Cursor native metadata");
29169
+ const metadata = JSON.parse(Buffer.from(row.value, "hex").toString("utf8"));
29170
+ if (metadata.agentId !== sessionId || typeof metadata.latestRootBlobId !== "string")
29171
+ throw new Error("Cursor native session identity mismatch");
29172
+ const get = (id) => {
29173
+ if (!/^[0-9a-f]{64}$/u.test(id))
29174
+ throw new Error("Invalid Cursor native blob reference");
29175
+ const blob = db.prepare("SELECT data FROM blobs WHERE id = ?").get(id)?.data;
29176
+ if (!(blob instanceof Uint8Array))
29177
+ throw new Error("Cursor native history blob is missing");
29178
+ return protobufBytes(blob);
29179
+ };
29180
+ const root = get(metadata.latestRootBlobId);
29181
+ const result = [];
29182
+ for (const ref of root.get(8) ?? []) {
29183
+ if (ref.length !== 32)
29184
+ throw new Error("Unsupported Cursor turn reference");
29185
+ const container = get(ref.toString("hex"));
29186
+ for (const record3 of container.get(1) ?? []) {
29187
+ const turn = protobufBytes(record3);
29188
+ const user = get(one(turn, 1).toString("hex"));
29189
+ const id = one(user, 2).toString("utf8");
29190
+ if (!/^[0-9a-f-]{36}$/iu.test(id) || result.some((existing) => existing.id === id))
29191
+ throw new Error("Cursor native turn ID is invalid or duplicated");
29192
+ const anchor = user.get(10)?.[0];
29193
+ const rewindRoot = anchor?.length === 32 && db.prepare("SELECT 1 FROM blobs WHERE id = ?").get(anchor.toString("hex")) ? anchor.toString("hex") : void 0;
29194
+ result.push({
29195
+ id,
29196
+ text: one(user, 1).toString("utf8"),
29197
+ ...rewindRoot ? { rewindRoot } : {}
29198
+ });
29199
+ }
29200
+ }
29201
+ return { revision: metadata.latestRootBlobId, turns: result };
29202
+ } finally {
29203
+ db.close();
29204
+ }
29205
+ }
29206
+ function readCursorNativeTurns(sessionId, cwd, environment, allowMissing = false) {
29207
+ return readCursorNativeHistory(sessionId, cwd, environment, allowMissing).turns;
29208
+ }
29209
+
29210
+ // dist/session-ref.js
29211
+ var cursorHarnessId = harnessIdSchema.parse("cursor-cli");
29212
+ var cursorSessionLocatorSchema = external_exports.strictObject({
29213
+ executionPolicy: external_exports.enum(["default", "unattended-full-access"])
29214
+ });
29215
+ function cursorNativeSessionRef(nativeSessionId, executionPolicy) {
29216
+ return nativeSessionRefSchema.parse({
29217
+ harnessId: cursorHarnessId,
29218
+ nativeSessionId,
29219
+ locator: { executionPolicy },
29220
+ formatVersion: 1
29221
+ });
29222
+ }
29223
+ function cursorExecutionPolicy(ref) {
29224
+ if (ref.harnessId !== cursorHarnessId || ref.formatVersion !== 1)
29225
+ throw new Error("Invalid Cursor Native Session Ref");
29226
+ if (ref.locator === void 0)
29227
+ return "default";
29228
+ const locator = cursorSessionLocatorSchema.safeParse(ref.locator);
29229
+ if (!locator.success)
29230
+ throw new Error("Invalid Cursor Native Session locator");
29231
+ return locator.data.executionPolicy;
29232
+ }
29233
+
29234
+ // dist/session-import.js
29235
+ var SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
29236
+ var MAX_METADATA_BYTES = 1024 * 1024;
29237
+ var CursorSessionChangedError = class extends Error {
29238
+ };
29239
+ function errorCode(error51) {
29240
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" ? error51.code : void 0;
29241
+ }
29242
+ async function optionalStat(file2) {
29243
+ try {
29244
+ return await lstat(file2);
29245
+ } catch (error51) {
29246
+ if (errorCode(error51) === "ENOENT")
29247
+ return null;
29248
+ throw error51;
29249
+ }
29250
+ }
29251
+ function sameFile(left, right) {
29252
+ return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
29253
+ }
29254
+ var CursorSessionImport = class {
29255
+ #environment;
29256
+ #abort = new AbortController();
29257
+ #pending = /* @__PURE__ */ new Set();
29258
+ constructor(environment) {
29259
+ this.#environment = { ...environment };
29260
+ }
29261
+ listCandidates() {
29262
+ return this.#read(async (signal) => {
29263
+ const root = path7.join(cursorConfigDirectory(this.#environment), "acp-sessions");
29264
+ const info = await optionalStat(root);
29265
+ if (!info)
29266
+ return [];
29267
+ if (!info.isDirectory())
29268
+ throw new Error("Cursor ACP store is not a directory");
29269
+ const candidates = [];
29270
+ const entries = await opendir(root);
29271
+ for await (const entry of entries) {
29272
+ signal.throwIfAborted();
29273
+ if (!entry.isDirectory() || !SESSION_ID.test(entry.name))
29274
+ continue;
29275
+ try {
29276
+ const candidate = await this.#candidate(entry.name, signal);
29277
+ if (candidate)
29278
+ candidates.push(candidate);
29279
+ } catch (error51) {
29280
+ if (!(error51 instanceof CursorSessionChangedError))
29281
+ throw error51;
29282
+ }
29283
+ }
29284
+ return candidates;
29285
+ });
29286
+ }
29287
+ async resolveCandidate(nativeSessionId) {
29288
+ if (!SESSION_ID.test(nativeSessionId))
29289
+ return {
29290
+ ok: false,
29291
+ error: {
29292
+ code: "invalidRequest",
29293
+ message: "Invalid Cursor ACP Session ID",
29294
+ retryable: false
29295
+ }
29296
+ };
29297
+ const result = await this.#read((signal) => this.#candidate(nativeSessionId, signal));
29298
+ if (!result.ok)
29299
+ return result;
29300
+ if (!result.value)
29301
+ return {
29302
+ ok: false,
29303
+ error: {
29304
+ code: "sessionNotFound",
29305
+ message: "Cursor ACP Session is no longer importable",
29306
+ retryable: false
29307
+ }
29308
+ };
29309
+ return {
29310
+ ok: true,
29311
+ value: {
29312
+ candidate: result.value,
29313
+ // Native ACP stores do not attest to --force. Imported sessions must not
29314
+ // acquire unattended privileges from UI defaults or a guessed locator.
29315
+ nativeRef: cursorNativeSessionRef(nativeSessionId, "default")
29316
+ }
29317
+ };
29318
+ }
29319
+ async #candidate(id, signal) {
29320
+ signal.throwIfAborted();
29321
+ const root = path7.join(cursorConfigDirectory(this.#environment), "acp-sessions");
29322
+ if (!(await optionalStat(root))?.isDirectory())
29323
+ return null;
29324
+ const directory = cursorSessionDirectory(id, this.#environment);
29325
+ const files = [
29326
+ directory,
29327
+ path7.join(directory, "meta.json"),
29328
+ path7.join(directory, "store.db"),
29329
+ path7.join(directory, "store.db-wal")
29330
+ ];
29331
+ const before = await Promise.all(files.map(optionalStat));
29332
+ const [folder, metadata, database, wal] = before;
29333
+ if (!folder?.isDirectory() || !metadata?.isFile() || !database?.isFile() || wal && !wal.isFile() || metadata.size > MAX_METADATA_BYTES)
29334
+ return null;
29335
+ let cwd;
29336
+ let title;
29337
+ try {
29338
+ const raw = JSON.parse(await readFile2(files[1], { encoding: "utf8", signal }));
29339
+ if (!raw || typeof raw !== "object" || !("cwd" in raw) || typeof raw.cwd !== "string" || !path7.isAbsolute(raw.cwd) || raw.cwd.includes("\0"))
29340
+ return null;
29341
+ cwd = await realpath(raw.cwd);
29342
+ if (!(await stat(cwd)).isDirectory())
29343
+ return null;
29344
+ signal.throwIfAborted();
29345
+ const turns = readCursorNativeTurns(id, cwd, this.#environment);
29346
+ if (!turns.length)
29347
+ return null;
29348
+ title = turns[0]?.text.replaceAll("\0", "").replace(/\s+/gu, " ").trim().slice(0, HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) || null;
29349
+ } catch (error51) {
29350
+ signal.throwIfAborted();
29351
+ if (["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"].includes(errorCode(error51) ?? ""))
29352
+ throw error51;
29353
+ return null;
29354
+ }
29355
+ signal.throwIfAborted();
29356
+ const after = await Promise.all(files.map(optionalStat));
29357
+ if (before.some((info, index) => !sameFile(info, after[index] ?? null)))
29358
+ throw new CursorSessionChangedError("Cursor Session changed during discovery");
29359
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
29360
+ nativeSessionId: id,
29361
+ cwd,
29362
+ title,
29363
+ updatedAt: Math.floor(Math.max(database.mtimeMs, wal?.mtimeMs ?? 0)),
29364
+ // A stable read does not establish that another Cursor process is idle.
29365
+ running: null
29366
+ });
29367
+ return parsed.success ? parsed.data : null;
29368
+ }
29369
+ #read(operation) {
29370
+ const signal = this.#abort.signal;
29371
+ if (signal.aborted)
29372
+ return Promise.resolve({
29373
+ ok: false,
29374
+ error: {
29375
+ code: "invalidState",
29376
+ message: "Cursor Session import is closed",
29377
+ retryable: false
29378
+ }
29379
+ });
29380
+ const request = operation(signal).then((value) => {
29381
+ signal.throwIfAborted();
29382
+ return { ok: true, value };
29383
+ }).catch(() => ({
29384
+ ok: false,
29385
+ error: {
29386
+ code: signal.aborted ? "invalidState" : "unavailable",
29387
+ message: signal.aborted ? "Cursor Session import is closed" : "Cursor ACP sessions could not be read; close native clients, check storage access and retry",
29388
+ retryable: !signal.aborted
29389
+ }
29390
+ })).finally(() => this.#pending.delete(request));
29391
+ this.#pending.add(request);
29392
+ return request;
29393
+ }
29394
+ async close() {
29395
+ this.#abort.abort();
29396
+ await Promise.allSettled(this.#pending);
29397
+ }
29398
+ };
29399
+
28516
29400
  // dist/thinking.js
28517
29401
  var choices = (option) => option.type === "select" ? option.options.flatMap((entry) => "value" in entry ? [entry] : entry.options) : [];
28518
29402
  function cursorThinking(options) {
@@ -28553,9 +29437,9 @@ function cursorThinkingState(info) {
28553
29437
  }
28554
29438
 
28555
29439
  // dist/fork-support.js
28556
- import { existsSync } from "node:fs";
29440
+ import { existsSync as existsSync3 } from "node:fs";
28557
29441
  function cursorForkAvailable() {
28558
- return (process.platform === "darwin" || process.platform === "linux") && existsSync("/usr/bin/script");
29442
+ return (process.platform === "darwin" || process.platform === "linux") && existsSync3("/usr/bin/script");
28559
29443
  }
28560
29444
  function cursorCheckpoint(sessionId, turnId) {
28561
29445
  return nativeCheckpointRefSchema.parse({
@@ -32856,10 +33740,10 @@ var ClientSideConnection = class {
32856
33740
  };
32857
33741
 
32858
33742
  // dist/delegation-bridge.js
32859
- import { execFile } from "node:child_process";
33743
+ import { execFile as execFile3 } from "node:child_process";
32860
33744
  import { randomBytes } from "node:crypto";
32861
33745
  import { createServer } from "node:http";
32862
- import path from "node:path";
33746
+ import path8 from "node:path";
32863
33747
 
32864
33748
  // ../../../node_modules/zod/v3/helpers/util.js
32865
33749
  var util;
@@ -33220,8 +34104,8 @@ function getErrorMap2() {
33220
34104
 
33221
34105
  // ../../../node_modules/zod/v3/helpers/parseUtil.js
33222
34106
  var makeIssue = (params) => {
33223
- const { data, path: path9, errorMaps, issueData } = params;
33224
- const fullPath = [...path9, ...issueData.path || []];
34107
+ const { data, path: path12, errorMaps, issueData } = params;
34108
+ const fullPath = [...path12, ...issueData.path || []];
33225
34109
  const fullIssue = {
33226
34110
  ...issueData,
33227
34111
  path: fullPath
@@ -33336,11 +34220,11 @@ var errorUtil;
33336
34220
 
33337
34221
  // ../../../node_modules/zod/v3/types.js
33338
34222
  var ParseInputLazyPath = class {
33339
- constructor(parent, value, path9, key) {
34223
+ constructor(parent, value, path12, key) {
33340
34224
  this._cachedPath = [];
33341
34225
  this.parent = parent;
33342
34226
  this.data = value;
33343
- this._path = path9;
34227
+ this._path = path12;
33344
34228
  this._key = key;
33345
34229
  }
33346
34230
  get path() {
@@ -36867,11 +37751,11 @@ function normalizeObjectSchema(schema) {
36867
37751
  }
36868
37752
  return void 0;
36869
37753
  }
36870
- function getDotPath(path9) {
36871
- if (path9.length === 0) {
37754
+ function getDotPath(path12) {
37755
+ if (path12.length === 0) {
36872
37756
  return "object root";
36873
37757
  }
36874
- return path9.reduce((acc, seg, index) => {
37758
+ return path12.reduce((acc, seg, index) => {
36875
37759
  if (index === 0) {
36876
37760
  return String(seg);
36877
37761
  }
@@ -44240,7 +45124,7 @@ async function createCursorDelegationBridge(cwd, environment, commandTimeoutMs =
44240
45124
  const runtimeToken = environment.CODEXHOST_RUNTIME_TOKEN;
44241
45125
  if (!cli || !environment.CODEXHOST_RUNTIME_ENDPOINT || !runtimeToken || !environment.CODEXHOST_THREAD_ID)
44242
45126
  return void 0;
44243
- if (!path.isAbsolute(cli))
45127
+ if (!path8.isAbsolute(cli))
44244
45128
  throw new Error("Cursor delegation requires an absolute Host CLI path");
44245
45129
  const token = randomBytes(32).toString("base64url");
44246
45130
  const children = /* @__PURE__ */ new Set();
@@ -44255,7 +45139,7 @@ async function createCursorDelegationBridge(cwd, environment, commandTimeoutMs =
44255
45139
  });
44256
45140
  return;
44257
45141
  }
44258
- const child = execFile(cli, [...args, "--format", "compact"], {
45142
+ const child = execFile3(cli, [...args, "--format", "compact"], {
44259
45143
  cwd,
44260
45144
  env: environment,
44261
45145
  windowsHide: true,
@@ -44395,265 +45279,6 @@ async function createCursorDelegationBridge(cwd, environment, commandTimeoutMs =
44395
45279
  };
44396
45280
  }
44397
45281
 
44398
- // dist/command.js
44399
- import { existsSync as existsSync2, readdirSync } from "node:fs";
44400
- import path4 from "node:path";
44401
-
44402
- // ../../harness-discovery/dist/environment.js
44403
- import fs from "node:fs";
44404
- import path2 from "node:path";
44405
- function targetPath(platform) {
44406
- return platform === "win32" ? path2.win32 : path2.posix;
44407
- }
44408
- function environmentValue(environment, name) {
44409
- const lowered = name.toLowerCase();
44410
- for (const [key, value] of Object.entries(environment)) {
44411
- if (key.toLowerCase() === lowered)
44412
- return value;
44413
- }
44414
- return void 0;
44415
- }
44416
- function pathDelimiter(platform) {
44417
- return platform === "win32" ? ";" : ":";
44418
- }
44419
- function pathDirectories(environment, platform) {
44420
- return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
44421
- }
44422
- function executableExtensions(command, platform, environment) {
44423
- if (platform !== "win32")
44424
- return [""];
44425
- if (targetPath(platform).extname(command) !== "")
44426
- return [""];
44427
- return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
44428
- }
44429
- function isExecutableFile(filePath, platform) {
44430
- try {
44431
- fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
44432
- return fs.statSync(filePath).isFile();
44433
- } catch {
44434
- return false;
44435
- }
44436
- }
44437
- function subdirectoryNames(directory) {
44438
- try {
44439
- return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
44440
- } catch {
44441
- return [];
44442
- }
44443
- }
44444
- function newestFirst(names) {
44445
- return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
44446
- }
44447
-
44448
- // ../../harness-discovery/dist/invocation.js
44449
- import path3 from "node:path";
44450
- function commandInvocation(command, arguments_, environment, platform = process.platform) {
44451
- const extension = path3.win32.extname(command).toLowerCase();
44452
- if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
44453
- return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
44454
- }
44455
- const quote2 = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
44456
- const commandLine = [command, ...arguments_].map(quote2).join(" ");
44457
- return {
44458
- command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
44459
- arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
44460
- windowsVerbatimArguments: true
44461
- };
44462
- }
44463
-
44464
- // ../../harness-discovery/dist/resolve.js
44465
- import os from "node:os";
44466
-
44467
- // ../../harness-discovery/dist/version-managers.js
44468
- function versionManagerBinaryDirectories(context) {
44469
- const { platform, environment, home } = context;
44470
- const list = context.subdirectories ?? subdirectoryNames;
44471
- const pathFlavor = targetPath(platform);
44472
- const value = (name) => environmentValue(environment, name);
44473
- const directories = [];
44474
- const versioned = (root, ...tail) => {
44475
- for (const version2 of newestFirst(list(root))) {
44476
- directories.push(pathFlavor.join(root, version2, ...tail));
44477
- }
44478
- };
44479
- if (platform === "win32") {
44480
- const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
44481
- const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
44482
- versioned(pathFlavor.join(appData, "nvm"));
44483
- versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
44484
- directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
44485
- directories.push(pathFlavor.join(home, ".bun", "bin"));
44486
- const pnpmHome2 = value("PNPM_HOME");
44487
- if (pnpmHome2)
44488
- directories.push(pnpmHome2);
44489
- directories.push(pathFlavor.join(localAppData, "pnpm"));
44490
- return directories;
44491
- }
44492
- versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
44493
- const fnmRoots = [
44494
- value("FNM_DIR"),
44495
- pathFlavor.join(home, ".local", "share", "fnm"),
44496
- pathFlavor.join(home, "Library", "Application Support", "fnm")
44497
- ].filter((root) => root !== void 0);
44498
- for (const root of fnmRoots) {
44499
- versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
44500
- }
44501
- const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
44502
- versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
44503
- directories.push(pathFlavor.join(voltaHome, "bin"));
44504
- const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
44505
- versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
44506
- directories.push(pathFlavor.join(asdfHome, "shims"));
44507
- const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
44508
- versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
44509
- directories.push(pathFlavor.join(nodenvHome, "shims"));
44510
- versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
44511
- directories.push(pathFlavor.join(home, ".bun", "bin"));
44512
- const pnpmHome = value("PNPM_HOME");
44513
- if (pnpmHome)
44514
- directories.push(pnpmHome);
44515
- directories.push(pathFlavor.join(home, "Library", "pnpm"));
44516
- directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
44517
- for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
44518
- for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
44519
- directories.push(pathFlavor.join(prefix, formula, "bin"));
44520
- }
44521
- }
44522
- return directories;
44523
- }
44524
-
44525
- // ../../harness-discovery/dist/resolve.js
44526
- var VERSION_MANAGER_ROOTS = "<version-managers>";
44527
- function installRootExtensions(platform) {
44528
- return platform === "win32" ? [".exe", ".cmd"] : [""];
44529
- }
44530
- function resolveHomeDirectory(input) {
44531
- return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
44532
- }
44533
- function templateVariables(environment, platform, home) {
44534
- const pathFlavor = targetPath(platform);
44535
- return {
44536
- HOME: home,
44537
- USERPROFILE: home,
44538
- APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
44539
- LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
44540
- };
44541
- }
44542
- function joinTemplate(platform, value) {
44543
- const pathFlavor = targetPath(platform);
44544
- const segments = value.split("/");
44545
- const head = segments[0] ?? "";
44546
- const tail = segments.slice(1);
44547
- if (head === "")
44548
- return pathFlavor.join(pathFlavor.sep, ...tail);
44549
- return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
44550
- }
44551
- function expandInstallRoot(template, environment, platform, home) {
44552
- const variables = templateVariables(environment, platform, home);
44553
- let unresolved = false;
44554
- const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
44555
- const value = variables[name] ?? environmentValue(environment, name);
44556
- if (value === void 0 || value === "") {
44557
- unresolved = true;
44558
- return "";
44559
- }
44560
- return value;
44561
- });
44562
- return unresolved ? void 0 : joinTemplate(platform, substituted);
44563
- }
44564
- function installRootDirectories(spec, input, dependencies, platform, home) {
44565
- const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
44566
- const directories = [];
44567
- for (const template of templates) {
44568
- if (template === VERSION_MANAGER_ROOTS) {
44569
- directories.push(...versionManagerBinaryDirectories({
44570
- platform,
44571
- environment: input.environment,
44572
- home,
44573
- ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
44574
- }));
44575
- continue;
44576
- }
44577
- const directory = expandInstallRoot(template, input.environment, platform, home);
44578
- if (directory !== void 0)
44579
- directories.push(directory);
44580
- }
44581
- return directories;
44582
- }
44583
- function harnessCandidates(spec, input, dependencies = {}) {
44584
- const platform = input.platform ?? process.platform;
44585
- const pathFlavor = targetPath(platform);
44586
- const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
44587
- const command = configured ?? spec.command;
44588
- if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
44589
- return [{ candidate: command, source: "configured" }];
44590
- }
44591
- const candidates = [];
44592
- const extensions = executableExtensions(command, platform, input.environment);
44593
- for (const directory of pathDirectories(input.environment, platform)) {
44594
- for (const extension of extensions) {
44595
- candidates.push({
44596
- candidate: pathFlavor.join(directory, command + extension),
44597
- source: "path"
44598
- });
44599
- }
44600
- }
44601
- if (configured !== void 0)
44602
- return candidates;
44603
- const home = resolveHomeDirectory(input);
44604
- for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
44605
- for (const extension of installRootExtensions(platform)) {
44606
- candidates.push({
44607
- candidate: pathFlavor.join(directory, spec.command + extension),
44608
- source: "install-root"
44609
- });
44610
- }
44611
- }
44612
- return candidates;
44613
- }
44614
- function resolveHarnessExecutable(spec, input, dependencies = {}) {
44615
- const platform = input.platform ?? process.platform;
44616
- const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
44617
- const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
44618
- const context = { platform, isExecutable };
44619
- for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
44620
- const executable = runnable(candidate, context);
44621
- if (executable !== void 0 && isExecutable(executable))
44622
- return { executable, source };
44623
- }
44624
- return void 0;
44625
- }
44626
-
44627
- // dist/command.js
44628
- function cursorInvocation(environment, command, args) {
44629
- const resolution = resolveHarnessExecutable({
44630
- id: "cursor-cli",
44631
- command: "cursor-agent",
44632
- commandEnvironmentVariable: "CODEXHOST_CURSOR_COMMAND",
44633
- installRoots: {
44634
- posix: ["~/.local/bin", "/usr/local/bin", "/opt/homebrew/bin"],
44635
- windows: ["${LOCALAPPDATA}/cursor-agent"]
44636
- }
44637
- }, { environment, ...command ? { command } : {} });
44638
- if (!resolution)
44639
- throw new Error("Cursor CLI is not installed; install cursor-agent or set CODEXHOST_CURSOR_COMMAND");
44640
- if (process.platform === "win32" && /\.(cmd|ps1)$/iu.test(resolution.executable)) {
44641
- const root = path4.dirname(resolution.executable);
44642
- const versions = path4.join(root, "versions");
44643
- if (existsSync2(versions)) {
44644
- const version2 = readdirSync(versions).filter((name) => /^\d{4}\.\d{2}\.\d{2}-(?:\d{2}-\d{2}-\d{2}-)?[a-f0-9]+$/u.test(name)).sort().reverse().find((name) => existsSync2(path4.join(versions, name, "node.exe")) && existsSync2(path4.join(versions, name, "index.js")));
44645
- if (version2)
44646
- return {
44647
- command: path4.join(versions, version2, "node.exe"),
44648
- arguments: [path4.join(versions, version2, "index.js"), ...args],
44649
- windowsVerbatimArguments: false
44650
- };
44651
- }
44652
- throw new Error("Cursor Windows launcher has no supported native bundle; configure a native executable");
44653
- }
44654
- return commandInvocation(resolution.executable, args, environment);
44655
- }
44656
-
44657
45282
  // dist/transport.js
44658
45283
  var CursorTransport = class {
44659
45284
  options;
@@ -44887,124 +45512,6 @@ var CursorTransport = class {
44887
45512
  }
44888
45513
  };
44889
45514
 
44890
- // dist/native-history.js
44891
- import { existsSync as existsSync3, readFileSync, realpathSync } from "node:fs";
44892
- import os2 from "node:os";
44893
- import path5 from "node:path";
44894
- import { DatabaseSync } from "node:sqlite";
44895
- function cursorConfigDirectory(environment) {
44896
- const home = environment.HOME ?? environment.USERPROFILE ?? os2.homedir();
44897
- return environment.CURSOR_CONFIG_DIR?.trim() ? path5.resolve(environment.CURSOR_CONFIG_DIR) : environment.XDG_CONFIG_HOME?.trim() ? path5.resolve(environment.XDG_CONFIG_HOME, "cursor") : path5.join(home, ".cursor");
44898
- }
44899
- function cursorSessionDirectory(sessionId, environment) {
44900
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(sessionId))
44901
- throw new Error("Unsupported Cursor native session ID");
44902
- return path5.join(cursorConfigDirectory(environment), "acp-sessions", sessionId);
44903
- }
44904
- function cursorSameWorkspace(left, right) {
44905
- return path5.resolve(left) === path5.resolve(right) || existsSync3(left) && existsSync3(right) && realpathSync(left) === realpathSync(right);
44906
- }
44907
- function protobufBytes(data) {
44908
- if (data.length > 32 * 1024 * 1024)
44909
- throw new Error("Cursor native record is too large");
44910
- let offset = 0;
44911
- const varint = () => {
44912
- let result = 0;
44913
- for (let shift = 0; shift < 70; shift += 7) {
44914
- const value = data[offset++];
44915
- if (value === void 0)
44916
- throw new Error("Truncated Cursor native record");
44917
- result += (value & 127) * 2 ** shift;
44918
- if (!(value & 128))
44919
- return result;
44920
- }
44921
- throw new Error("Invalid Cursor native varint");
44922
- };
44923
- const fields = /* @__PURE__ */ new Map();
44924
- while (offset < data.length) {
44925
- const tag = varint();
44926
- const field = Math.floor(tag / 8), wire = tag % 8;
44927
- if (!Number.isSafeInteger(tag) || field === 0)
44928
- throw new Error("Invalid Cursor native field");
44929
- if (wire === 0) {
44930
- varint();
44931
- continue;
44932
- }
44933
- const length = wire === 2 ? varint() : wire === 1 ? 8 : wire === 5 ? 4 : -1;
44934
- if (!Number.isSafeInteger(length) || length < 0 || offset + length > data.length)
44935
- throw new Error("Unsupported Cursor native record");
44936
- if (wire === 2) {
44937
- const values = fields.get(field) ?? [];
44938
- values.push(Buffer.from(data.subarray(offset, offset + length)));
44939
- fields.set(field, values);
44940
- }
44941
- offset += length;
44942
- }
44943
- return fields;
44944
- }
44945
- function one(fields, field) {
44946
- const values = fields.get(field);
44947
- if (values?.length !== 1 || !values[0])
44948
- throw new Error("Cursor native history identity is missing or ambiguous");
44949
- return values[0];
44950
- }
44951
- function readCursorNativeHistory(sessionId, cwd, environment, allowMissing = false) {
44952
- const directory = cursorSessionDirectory(sessionId, environment);
44953
- const filename = path5.join(directory, "store.db");
44954
- if (allowMissing && !existsSync3(filename))
44955
- return { revision: void 0, turns: [] };
44956
- const info = JSON.parse(readFileSync(path5.join(directory, "meta.json"), "utf8"));
44957
- if (!info || typeof info !== "object" || !("cwd" in info) || typeof info.cwd !== "string" || !cursorSameWorkspace(info.cwd, cwd))
44958
- throw new Error("Cursor session workspace does not match");
44959
- const db = new DatabaseSync(filename, { readOnly: true });
44960
- try {
44961
- db.exec("BEGIN");
44962
- const row = db.prepare("SELECT value FROM meta WHERE key = ?").get("0");
44963
- if (!row && allowMissing)
44964
- return { revision: void 0, turns: [] };
44965
- if (typeof row?.value !== "string" || row.value.length > 1e6)
44966
- throw new Error("Unsupported Cursor native metadata");
44967
- const metadata = JSON.parse(Buffer.from(row.value, "hex").toString("utf8"));
44968
- if (metadata.agentId !== sessionId || typeof metadata.latestRootBlobId !== "string")
44969
- throw new Error("Cursor native session identity mismatch");
44970
- const get = (id) => {
44971
- if (!/^[0-9a-f]{64}$/u.test(id))
44972
- throw new Error("Invalid Cursor native blob reference");
44973
- const blob = db.prepare("SELECT data FROM blobs WHERE id = ?").get(id)?.data;
44974
- if (!(blob instanceof Uint8Array))
44975
- throw new Error("Cursor native history blob is missing");
44976
- return protobufBytes(blob);
44977
- };
44978
- const root = get(metadata.latestRootBlobId);
44979
- const result = [];
44980
- for (const ref of root.get(8) ?? []) {
44981
- if (ref.length !== 32)
44982
- throw new Error("Unsupported Cursor turn reference");
44983
- const container = get(ref.toString("hex"));
44984
- for (const record2 of container.get(1) ?? []) {
44985
- const turn = protobufBytes(record2);
44986
- const user = get(one(turn, 1).toString("hex"));
44987
- const id = one(user, 2).toString("utf8");
44988
- if (!/^[0-9a-f-]{36}$/iu.test(id) || result.some((existing) => existing.id === id))
44989
- throw new Error("Cursor native turn ID is invalid or duplicated");
44990
- const anchor = user.get(10)?.[0];
44991
- const rewindRoot = anchor?.length === 32 && db.prepare("SELECT 1 FROM blobs WHERE id = ?").get(anchor.toString("hex")) ? anchor.toString("hex") : void 0;
44992
- result.push({
44993
- id,
44994
- text: one(user, 1).toString("utf8"),
44995
- ...rewindRoot ? { rewindRoot } : {}
44996
- });
44997
- }
44998
- }
44999
- return { revision: metadata.latestRootBlobId, turns: result };
45000
- } finally {
45001
- db.close();
45002
- }
45003
- }
45004
- function readCursorNativeTurns(sessionId, cwd, environment, allowMissing = false) {
45005
- return readCursorNativeHistory(sessionId, cwd, environment, allowMissing).turns;
45006
- }
45007
-
45008
45515
  // ../../../node_modules/diff/libesm/diff/base.js
45009
45516
  var Diff = class {
45010
45517
  diff(oldStr, newStr, options = {}) {
@@ -45105,16 +45612,16 @@ var Diff = class {
45105
45612
  }
45106
45613
  }
45107
45614
  }
45108
- addToPath(path9, added, removed, oldPosInc, options) {
45109
- const last = path9.lastComponent;
45615
+ addToPath(path12, added, removed, oldPosInc, options) {
45616
+ const last = path12.lastComponent;
45110
45617
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
45111
45618
  return {
45112
- oldPos: path9.oldPos + oldPosInc,
45619
+ oldPos: path12.oldPos + oldPosInc,
45113
45620
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
45114
45621
  };
45115
45622
  } else {
45116
45623
  return {
45117
- oldPos: path9.oldPos + oldPosInc,
45624
+ oldPos: path12.oldPos + oldPosInc,
45118
45625
  lastComponent: { count: 1, added, removed, previousComponent: last }
45119
45626
  };
45120
45627
  }
@@ -45632,6 +46139,42 @@ function cursorChildSnapshot(parentId, item, terminal, output) {
45632
46139
  };
45633
46140
  }
45634
46141
 
46142
+ // dist/stream-error.js
46143
+ var CLOSED_ERROR = /(?:^|\n\n)Error:\s*(?:(?:RetriableError|T):)?\s*WritableIterable is closed\s*$/u;
46144
+ var CLOSED_PREFIXES = [
46145
+ "\n\nError: RetriableError: WritableIterable is closed",
46146
+ "\n\nError: T: WritableIterable is closed",
46147
+ "\n\nError: WritableIterable is closed",
46148
+ "Error: RetriableError: WritableIterable is closed",
46149
+ "Error: T: WritableIterable is closed",
46150
+ "Error: WritableIterable is closed"
46151
+ ];
46152
+ var LONGEST_PREFIX = Math.max(...CLOSED_PREFIXES.map((prefix) => prefix.length));
46153
+ function isCursorWritableIterableClosed(message) {
46154
+ return /WritableIterable is closed/iu.test(message);
46155
+ }
46156
+ function takeCursorWritableIterableClosed(text2, atMessageStart = true) {
46157
+ const match = text2.match(CLOSED_ERROR);
46158
+ if (!match || match.index === void 0 || match.index === 0 && !text2.startsWith("\n\n") && !atMessageStart)
46159
+ return { visible: text2, closed: false };
46160
+ return { visible: text2.slice(0, match.index), closed: true };
46161
+ }
46162
+ function holdCursorWritableIterablePrefix(text2, atMessageStart = true) {
46163
+ const taken = takeCursorWritableIterableClosed(text2, atMessageStart);
46164
+ if (taken.closed)
46165
+ return { emit: taken.visible, hold: text2.slice(taken.visible.length) };
46166
+ for (let size = Math.min(text2.length, LONGEST_PREFIX); size > 0; size -= 1) {
46167
+ const suffix = text2.slice(-size);
46168
+ const start = text2.length - size;
46169
+ if (!suffix.startsWith("\n") && !(start === 0 && atMessageStart) && text2.slice(Math.max(0, start - 2), start) !== "\n\n")
46170
+ continue;
46171
+ if (CLOSED_PREFIXES.some((candidate) => candidate.startsWith(suffix))) {
46172
+ return { emit: text2.slice(0, -size), hold: suffix };
46173
+ }
46174
+ }
46175
+ return { emit: text2, hold: "" };
46176
+ }
46177
+
45635
46178
  // dist/projection.js
45636
46179
  var TOOL_OUTPUT_LIMIT = 1e5;
45637
46180
  function cursorFileChanges(content) {
@@ -45661,11 +46204,52 @@ var CursorTurnOutput = class {
45661
46204
  #text;
45662
46205
  #tools = /* @__PURE__ */ new Map();
45663
46206
  #finishedTools = /* @__PURE__ */ new Set();
46207
+ #hold = "";
46208
+ #writableIterableClosed = false;
46209
+ #visibleAssistantText = false;
45664
46210
  constructor(turnId, emit, nativeTurnIndex = 0) {
45665
46211
  this.turnId = turnId;
45666
46212
  this.emit = emit;
45667
46213
  this.subagents = new CursorSubagents(turnId, emit, nativeTurnIndex);
45668
46214
  }
46215
+ sawWritableIterableClosed() {
46216
+ return this.#writableIterableClosed || takeCursorWritableIterableClosed(this.#hold).closed;
46217
+ }
46218
+ hasVisibleAssistantText() {
46219
+ return this.#visibleAssistantText || takeCursorWritableIterableClosed(this.#hold).visible.trim().length > 0;
46220
+ }
46221
+ #flushHold() {
46222
+ if (!this.#hold)
46223
+ return;
46224
+ const held = this.#hold;
46225
+ this.#hold = "";
46226
+ this.#appendText("agentMessage", held);
46227
+ }
46228
+ #appendText(type, text2) {
46229
+ if (!text2)
46230
+ return;
46231
+ if (type === "agentMessage" && text2.trim())
46232
+ this.#visibleAssistantText = true;
46233
+ if (this.#text?.type !== type) {
46234
+ this.#finishText();
46235
+ const item = {
46236
+ type,
46237
+ itemId: hostItemIdSchema.parse(`cursor-${this.turnId}-${++this.#index}`),
46238
+ text: ""
46239
+ };
46240
+ this.#text = item;
46241
+ this.emit({ type: "item.started", turnId: this.turnId, item: { ...item } });
46242
+ }
46243
+ if (!this.#text)
46244
+ return;
46245
+ this.#text.text += text2;
46246
+ this.emit({
46247
+ type: "item.updated",
46248
+ turnId: this.turnId,
46249
+ itemId: this.#text.itemId,
46250
+ update: { type: "text.append", text: text2 }
46251
+ });
46252
+ }
45669
46253
  #finishText(outcome = { status: "succeeded" }) {
45670
46254
  if (this.#text)
45671
46255
  this.emit({
@@ -45677,6 +46261,7 @@ var CursorTurnOutput = class {
45677
46261
  }
45678
46262
  update(notification) {
45679
46263
  if (this.subagents.update(notification)) {
46264
+ this.#flushHold();
45680
46265
  this.#finishText();
45681
46266
  return;
45682
46267
  }
@@ -45685,26 +46270,17 @@ var CursorTurnOutput = class {
45685
46270
  if (update.content.type !== "text")
45686
46271
  return;
45687
46272
  const type = update.sessionUpdate === "agent_message_chunk" ? "agentMessage" : "reasoning";
45688
- if (this.#text?.type !== type) {
45689
- this.#finishText();
45690
- const item = {
45691
- type,
45692
- itemId: hostItemIdSchema.parse(`cursor-${this.turnId}-${++this.#index}`),
45693
- text: ""
45694
- };
45695
- this.#text = item;
45696
- this.emit({ type: "item.started", turnId: this.turnId, item: { ...item } });
45697
- }
45698
- if (!this.#text)
46273
+ if (type === "reasoning") {
46274
+ this.#flushHold();
46275
+ this.#appendText(type, update.content.text);
45699
46276
  return;
45700
- this.#text.text += update.content.text;
45701
- this.emit({
45702
- type: "item.updated",
45703
- turnId: this.turnId,
45704
- itemId: this.#text.itemId,
45705
- update: { type: "text.append", text: update.content.text }
45706
- });
46277
+ }
46278
+ const combined = `${this.#hold}${update.content.text}`;
46279
+ const { emit, hold } = holdCursorWritableIterablePrefix(combined, this.#text?.type !== "agentMessage" || this.#text.text.length === 0);
46280
+ this.#hold = hold;
46281
+ this.#appendText(type, emit);
45707
46282
  } else if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
46283
+ this.#flushHold();
45708
46284
  this.#finishText();
45709
46285
  if (this.#finishedTools.has(update.toolCallId))
45710
46286
  return;
@@ -45773,6 +46349,11 @@ ${content.newText}`] : []).join("\n");
45773
46349
  }
45774
46350
  finish(outcome) {
45775
46351
  this.subagents.finish(outcome);
46352
+ if (takeCursorWritableIterableClosed(this.#hold).closed) {
46353
+ this.#writableIterableClosed = true;
46354
+ this.#hold = "";
46355
+ }
46356
+ this.#flushHold();
45776
46357
  this.#finishText(outcome);
45777
46358
  for (const { item } of this.#tools.values())
45778
46359
  this.emit({
@@ -45993,36 +46574,12 @@ var CursorInteractions = class {
45993
46574
  }
45994
46575
  };
45995
46576
 
45996
- // dist/session-ref.js
45997
- var cursorHarnessId = harnessIdSchema.parse("cursor-cli");
45998
- var cursorSessionLocatorSchema = external_exports.strictObject({
45999
- executionPolicy: external_exports.enum(["default", "unattended-full-access"])
46000
- });
46001
- function cursorNativeSessionRef(nativeSessionId, executionPolicy) {
46002
- return nativeSessionRefSchema.parse({
46003
- harnessId: cursorHarnessId,
46004
- nativeSessionId,
46005
- locator: { executionPolicy },
46006
- formatVersion: 1
46007
- });
46008
- }
46009
- function cursorExecutionPolicy(ref) {
46010
- if (ref.harnessId !== cursorHarnessId || ref.formatVersion !== 1)
46011
- throw new Error("Invalid Cursor Native Session Ref");
46012
- if (ref.locator === void 0)
46013
- return "default";
46014
- const locator = cursorSessionLocatorSchema.safeParse(ref.locator);
46015
- if (!locator.success)
46016
- throw new Error("Invalid Cursor Native Session locator");
46017
- return locator.data.executionPolicy;
46018
- }
46019
-
46020
46577
  // dist/fork.js
46021
46578
  import { createHash as createHash2 } from "node:crypto";
46022
- import { copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
46579
+ import { copyFile, mkdir, mkdtemp, readdir, readFile as readFile3, realpath as realpath2, rm, writeFile } from "node:fs/promises";
46023
46580
  import { readdirSync as readdirSync2 } from "node:fs";
46024
46581
  import os3 from "node:os";
46025
- import path6 from "node:path";
46582
+ import path9 from "node:path";
46026
46583
  import { backup, DatabaseSync as DatabaseSync2 } from "node:sqlite";
46027
46584
 
46028
46585
  // dist/fork-terminal.js
@@ -46140,16 +46697,16 @@ async function runCursorForkTerminal(options, sessionId, signal, rewind) {
46140
46697
 
46141
46698
  // dist/fork.js
46142
46699
  async function copySnapshot(source, target) {
46143
- const db = new DatabaseSync2(path6.join(source, "store.db"), { readOnly: true });
46700
+ const db = new DatabaseSync2(path9.join(source, "store.db"), { readOnly: true });
46144
46701
  try {
46145
- await backup(db, path6.join(target, "store.db"));
46702
+ await backup(db, path9.join(target, "store.db"));
46146
46703
  } finally {
46147
46704
  db.close();
46148
46705
  }
46149
- await copyFile(path6.join(source, "meta.json"), path6.join(target, "meta.json"));
46706
+ await copyFile(path9.join(source, "meta.json"), path9.join(target, "meta.json"));
46150
46707
  }
46151
46708
  function storeIdentity(directory, hashBlobs = true) {
46152
- const db = new DatabaseSync2(path6.join(directory, "store.db"), { readOnly: true });
46709
+ const db = new DatabaseSync2(path9.join(directory, "store.db"), { readOnly: true });
46153
46710
  try {
46154
46711
  db.exec("BEGIN");
46155
46712
  const value = db.prepare("SELECT value FROM meta WHERE key = '0'").get()?.value;
@@ -46190,7 +46747,7 @@ async function forkCursorSession(source, checkpoint, options, signal) {
46190
46747
  if (rewindTurn && !rewindTurn.rewindRoot)
46191
46748
  throw new Error("Cursor target has no native rewind checkpoint");
46192
46749
  const original = storeIdentity(sourceDirectory);
46193
- const temporary = await mkdtemp(path6.join(os3.tmpdir(), "codexhost-cursor-fork-"));
46750
+ const temporary = await mkdtemp(path9.join(os3.tmpdir(), "codexhost-cursor-fork-"));
46194
46751
  let target;
46195
46752
  let committed = false;
46196
46753
  const discard = async () => {
@@ -46199,12 +46756,12 @@ async function forkCursorSession(source, checkpoint, options, signal) {
46199
46756
  };
46200
46757
  try {
46201
46758
  signal.throwIfAborted();
46202
- const config2 = path6.join(temporary, "config");
46759
+ const config2 = path9.join(temporary, "config");
46203
46760
  await mkdir(config2, { mode: 448 });
46204
- const nativeConfig = path6.join(cursorConfigDirectory(options.environment), "cli-config.json");
46761
+ const nativeConfig = path9.join(cursorConfigDirectory(options.environment), "cli-config.json");
46205
46762
  let settings = {};
46206
46763
  try {
46207
- const data = JSON.parse(await readFile(nativeConfig, "utf8"));
46764
+ const data = JSON.parse(await readFile3(nativeConfig, "utf8"));
46208
46765
  if (!data || typeof data !== "object" || Array.isArray(data))
46209
46766
  throw new Error("Invalid Cursor CLI configuration");
46210
46767
  settings = data;
@@ -46212,9 +46769,9 @@ async function forkCursorSession(source, checkpoint, options, signal) {
46212
46769
  if (!(error51 instanceof Error && "code" in error51 && error51.code === "ENOENT"))
46213
46770
  throw error51;
46214
46771
  }
46215
- await writeFile(path6.join(config2, "cli-config.json"), JSON.stringify({ ...settings, rewind: true }), { mode: 384 });
46216
- const chats = path6.join(config2, "chats", createHash2("md5").update(await realpath(options.cwd)).digest("hex"));
46217
- const copy = path6.join(chats, source.nativeSessionId);
46772
+ await writeFile(path9.join(config2, "cli-config.json"), JSON.stringify({ ...settings, rewind: true }), { mode: 384 });
46773
+ const chats = path9.join(config2, "chats", createHash2("md5").update(await realpath2(options.cwd)).digest("hex"));
46774
+ const copy = path9.join(chats, source.nativeSessionId);
46218
46775
  await mkdir(copy, { recursive: true });
46219
46776
  await copySnapshot(sourceDirectory, copy);
46220
46777
  if (JSON.stringify(storeIdentity(copy)) !== JSON.stringify(original))
@@ -46224,14 +46781,14 @@ async function forkCursorSession(source, checkpoint, options, signal) {
46224
46781
  environment: {
46225
46782
  ...options.environment,
46226
46783
  CURSOR_CONFIG_DIR: config2,
46227
- CURSOR_DATA_DIR: path6.join(temporary, "data")
46784
+ CURSOR_DATA_DIR: path9.join(temporary, "data")
46228
46785
  }
46229
46786
  }, source.nativeSessionId, signal, rewindTurn ? {
46230
46787
  steps: sourceTurns.slice(retained).filter((turn) => turn.rewindRoot).length,
46231
46788
  complete: () => {
46232
46789
  const targets = readdirSync2(chats).filter((id) => id !== source.nativeSessionId);
46233
46790
  const targetId = targets[0];
46234
- return targets.length === 1 && !!targetId && storeIdentity(path6.join(chats, targetId), false).root === rewindTurn.rewindRoot;
46791
+ return targets.length === 1 && !!targetId && storeIdentity(path9.join(chats, targetId), false).root === rewindTurn.rewindRoot;
46235
46792
  }
46236
46793
  } : void 0);
46237
46794
  signal.throwIfAborted();
@@ -46240,7 +46797,7 @@ async function forkCursorSession(source, checkpoint, options, signal) {
46240
46797
  throw new Error("Cursor fork did not create one independent session");
46241
46798
  const sessionId = children[0].name;
46242
46799
  const destination = cursorSessionDirectory(sessionId, options.environment);
46243
- const nativeFork = path6.join(chats, sessionId);
46800
+ const nativeFork = path9.join(chats, sessionId);
46244
46801
  const forked = storeIdentity(nativeFork);
46245
46802
  if (forked.agentId !== sessionId || forked.root !== (rewindTurn?.rewindRoot ?? original.root) || forked.blobs !== original.blobs)
46246
46803
  throw new Error("Cursor native fork changed conversation contents or identity");
@@ -46277,6 +46834,13 @@ async function forkCursorSession(source, checkpoint, options, signal) {
46277
46834
  // dist/adapter.js
46278
46835
  function cursorError(error51) {
46279
46836
  const message = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : "Cursor operation failed");
46837
+ if (isCursorWritableIterableClosed(message)) {
46838
+ return {
46839
+ code: "nativeFailure",
46840
+ message: "Cursor stream closed (WritableIterable)",
46841
+ retryable: true
46842
+ };
46843
+ }
46280
46844
  const code = /not installed/iu.test(message) ? "notInstalled" : /auth|not logged in|login/iu.test(message) ? "authenticationRequired" : /exited|closed/iu.test(message) ? "processExited" : "protocolError";
46281
46845
  return { code, message, retryable: false };
46282
46846
  }
@@ -46295,7 +46859,7 @@ var CursorAdapter = class {
46295
46859
  try {
46296
46860
  cursorTaskAddress(nativeSubagentId);
46297
46861
  const session = [...this.#sessions].find((s) => s.transport.sessionId === parent.nativeSessionId);
46298
- if (session && path7.resolve(session.transport.options.cwd) !== path7.resolve(cwd))
46862
+ if (session && path10.resolve(session.transport.options.cwd) !== path10.resolve(cwd))
46299
46863
  return rejected("invalidRequest", "Cursor parent workspace does not match");
46300
46864
  const active = session?.subagentSnapshot(nativeSubagentId);
46301
46865
  if (active)
@@ -46328,12 +46892,19 @@ var CursorAdapter = class {
46328
46892
  #forks = /* @__PURE__ */ new Map();
46329
46893
  #inspections = /* @__PURE__ */ new Map();
46330
46894
  #closed = false;
46895
+ sessionImport;
46331
46896
  constructor(options = {}) {
46332
46897
  this.options = options;
46898
+ this.sessionImport = new CursorSessionImport(options.environment ?? process.env);
46899
+ }
46900
+ async inspectAccount() {
46901
+ if (this.#closed)
46902
+ return null;
46903
+ return fetchCursorAccount({ environment: this.options.environment ?? process.env });
46333
46904
  }
46334
46905
  transportOptions(cwd, environment) {
46335
46906
  return {
46336
- cwd: path7.resolve(cwd),
46907
+ cwd: path10.resolve(cwd),
46337
46908
  environment: { ...this.options.environment ?? process.env, ...environment },
46338
46909
  ...this.options.command ? { command: this.options.command } : {},
46339
46910
  ...this.options.timeoutMs ? { timeoutMs: this.options.timeoutMs } : {}
@@ -46345,7 +46916,7 @@ var CursorAdapter = class {
46345
46916
  status: "unavailable",
46346
46917
  error: { code: "unavailable", message: "Cursor adapter is closed", retryable: false }
46347
46918
  };
46348
- const cwd = path7.resolve(input.cwd ?? process.cwd());
46919
+ const cwd = path10.resolve(input.cwd ?? process.cwd());
46349
46920
  const cached2 = this.#inspections.get(cwd);
46350
46921
  if (cached2 && (cached2.pending || !input.refresh))
46351
46922
  return cached2.result;
@@ -46547,9 +47118,10 @@ var CursorAdapter = class {
46547
47118
  }
46548
47119
  async close() {
46549
47120
  this.#closed = true;
47121
+ const importing = this.sessionImport.close();
46550
47122
  for (const controller of this.#forks.keys())
46551
47123
  controller.abort();
46552
- await Promise.allSettled(this.#forks.values());
47124
+ await Promise.allSettled([importing, ...this.#forks.values()]);
46553
47125
  await Promise.allSettled([...this.#sessions].map((session) => session.close()));
46554
47126
  await Promise.allSettled([...this.#inspections.values()].map((inspection) => inspection.result));
46555
47127
  }
@@ -46778,7 +47350,15 @@ var CursorSession = class {
46778
47350
  output.subagents.extension(method, params);
46779
47351
  }
46780
47352
  });
46781
- outcome = this.#active?.cancelled || result.stopReason === "cancelled" ? { status: "cancelled" } : result.stopReason === "end_turn" ? { status: "succeeded" } : {
47353
+ const streamClosed = output.sawWritableIterableClosed() && !output.hasVisibleAssistantText();
47354
+ outcome = this.#active?.cancelled || result.stopReason === "cancelled" ? { status: "cancelled" } : streamClosed ? {
47355
+ status: "failed",
47356
+ error: {
47357
+ code: "nativeFailure",
47358
+ message: "Cursor stream closed (WritableIterable)",
47359
+ retryable: true
47360
+ }
47361
+ } : result.stopReason === "end_turn" ? { status: "succeeded" } : {
46782
47362
  status: "failed",
46783
47363
  error: {
46784
47364
  code: "nativeFailure",
@@ -46863,7 +47443,7 @@ var CursorSession = class {
46863
47443
 
46864
47444
  // ../../harness-broker/dist/client.js
46865
47445
  import { randomUUID as randomUUID2 } from "node:crypto";
46866
- import { lstat, readFile as readFile2 } from "node:fs/promises";
47446
+ import { lstat as lstat2, readFile as readFile4 } from "node:fs/promises";
46867
47447
  import net, {} from "node:net";
46868
47448
 
46869
47449
  // ../../harness-broker/dist/protocol.js
@@ -46981,24 +47561,25 @@ function consumeBrokerFrames(socket, onFrame, onError) {
46981
47561
 
46982
47562
  // ../../harness-broker/dist/paths.js
46983
47563
  import os4 from "node:os";
46984
- import path8 from "node:path";
47564
+ import path11 from "node:path";
46985
47565
  var HARNESS_BROKER_DESCRIPTOR_ENV = "CODEXHOST_CLAUDE_BROKER_DESCRIPTOR";
46986
47566
  var HARNESS_BROKER_DESCRIPTOR_FILE = "claude-code-broker-v1.json";
46987
47567
  function defaultHarnessBrokerDirectory(environment = process.env) {
46988
47568
  const home = environment.HOME || os4.homedir();
46989
- return path8.join(home, ".codexhost", "harness-broker");
47569
+ return path11.join(home, ".codexhost", "harness-broker");
46990
47570
  }
46991
47571
  function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId = "claude-code") {
46992
47572
  harnessPluginIdSchema.parse(harnessId);
46993
47573
  if (harnessId !== "claude-code")
46994
- return path8.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
46995
- return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path8.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
47574
+ return path11.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
47575
+ return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path11.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
46996
47576
  }
46997
47577
 
46998
47578
  // ../../harness-broker/dist/validation.js
46999
47579
  var cwdSchema = external_exports.string().min(1).max(16384);
47000
47580
  var brokerEnvironmentSchema = external_exports.object({
47001
47581
  CODEXHOST_CLI_PATH: external_exports.string().max(16384).optional(),
47582
+ CODEXHOST_CLI_NODE_PATH: external_exports.string().max(16384).optional(),
47002
47583
  CODEXHOST_RUNTIME_ENDPOINT: external_exports.string().max(16384).optional(),
47003
47584
  CODEXHOST_RUNTIME_TOKEN: external_exports.string().max(16384).optional(),
47004
47585
  CODEXHOST_THREAD_ID: external_exports.string().max(256).optional()
@@ -47146,7 +47727,7 @@ var harnessErrorSchema = external_exports.object({
47146
47727
  var harnessSessionStateSchema = external_exports.custom((value) => {
47147
47728
  if (!value || typeof value !== "object" || Array.isArray(value))
47148
47729
  return false;
47149
- const record2 = value;
47730
+ const record3 = value;
47150
47731
  const allowed = /* @__PURE__ */ new Set([
47151
47732
  "nativeRef",
47152
47733
  "effectiveModel",
@@ -47155,12 +47736,12 @@ var harnessSessionStateSchema = external_exports.custom((value) => {
47155
47736
  "availableThinkingOptions",
47156
47737
  "effectivePermissionModeId"
47157
47738
  ]);
47158
- if (Object.keys(record2).some((key) => !allowed.has(key)))
47739
+ if (Object.keys(record3).some((key) => !allowed.has(key)))
47159
47740
  return false;
47160
- if (record2.nativeRef !== void 0 && !nativeSessionRefSchema.safeParse(record2.nativeRef).success) {
47741
+ if (record3.nativeRef !== void 0 && !nativeSessionRefSchema.safeParse(record3.nativeRef).success) {
47161
47742
  return false;
47162
47743
  }
47163
- const { nativeRef: _nativeRef, ...configuration } = record2;
47744
+ const { nativeRef: _nativeRef, ...configuration } = record3;
47164
47745
  void _nativeRef;
47165
47746
  return harnessConfigurationStateSchema.safeParse(configuration).success;
47166
47747
  });
@@ -47174,6 +47755,7 @@ var eventKeys = /* @__PURE__ */ new Map([
47174
47755
  ["item.started", /* @__PURE__ */ new Set(["type", "turnId", "item"])],
47175
47756
  ["item.updated", /* @__PURE__ */ new Set(["type", "turnId", "itemId", "update"])],
47176
47757
  ["item.completed", /* @__PURE__ */ new Set(["type", "turnId", "snapshot"])],
47758
+ ["item.detached", /* @__PURE__ */ new Set(["type", "turnId", "itemId"])],
47177
47759
  ["interaction.closed", /* @__PURE__ */ new Set(["type", "interactionId", "turnId", "reason"])],
47178
47760
  ["turn.completed", /* @__PURE__ */ new Set(["type", "turnId", "nativeTurnRef", "outcome", "completedAtMs"])],
47179
47761
  ["session.faulted", /* @__PURE__ */ new Set(["type", "error"])]
@@ -47290,7 +47872,7 @@ function parseSessionMetadata(value) {
47290
47872
  };
47291
47873
  }
47292
47874
  async function readDescriptor(descriptorPath) {
47293
- const metadata = await lstat(descriptorPath);
47875
+ const metadata = await lstat2(descriptorPath);
47294
47876
  if (metadata.isSymbolicLink())
47295
47877
  throw new Error("Aqua Harness broker descriptor must not be a symlink");
47296
47878
  if (!metadata.isFile())
@@ -47302,12 +47884,12 @@ async function readDescriptor(descriptorPath) {
47302
47884
  throw new Error("Aqua Harness broker descriptor belongs to another user");
47303
47885
  }
47304
47886
  }
47305
- const descriptor = harnessBrokerDescriptorSchema.parse(JSON.parse(await readFile2(descriptorPath, "utf8")));
47887
+ const descriptor = harnessBrokerDescriptorSchema.parse(JSON.parse(await readFile4(descriptorPath, "utf8")));
47306
47888
  if (process.platform === "darwin" && Buffer.byteLength(descriptor.socketPath) > 103) {
47307
47889
  throw new Error("Aqua Harness broker socket path is too long for macOS");
47308
47890
  }
47309
47891
  if (process.platform !== "win32") {
47310
- const socket = await lstat(descriptor.socketPath);
47892
+ const socket = await lstat2(descriptor.socketPath);
47311
47893
  if (socket.isSymbolicLink() || !socket.isSocket()) {
47312
47894
  throw new Error("Aqua Harness broker endpoint is not a Unix socket");
47313
47895
  }
@@ -47821,6 +48403,7 @@ var BrokeredHarnessAdapter = class {
47821
48403
  if (this.#forwardEnvironment && input.environment) {
47822
48404
  const allowed = [
47823
48405
  "CODEXHOST_CLI_PATH",
48406
+ "CODEXHOST_CLI_NODE_PATH",
47824
48407
  "CODEXHOST_RUNTIME_ENDPOINT",
47825
48408
  "CODEXHOST_RUNTIME_TOKEN",
47826
48409
  "CODEXHOST_THREAD_ID"
@@ -47886,7 +48469,10 @@ function createHarnessAdapter(context) {
47886
48469
  liveCommandCatalog: true,
47887
48470
  environment: { ...context.environment }
47888
48471
  });
47889
- return new CursorAdapter({ environment: { ...context.environment } });
48472
+ const environment = { ...context.environment };
48473
+ return Object.assign(new CursorAdapter({ environment }), {
48474
+ installation: createCursorInstallation(environment)
48475
+ });
47890
48476
  }
47891
48477
  export {
47892
48478
  createHarnessAdapter