@liberseek/boft-cli-win32-arm64 0.7.8 → 0.7.9

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.
@@ -27655,6 +27655,10 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
27655
27655
  var hostItemIdSchema = opaqueIdSchema.brand();
27656
27656
  var hostInteractionIdSchema = opaqueIdSchema.brand();
27657
27657
 
27658
+ // ../../shared-contracts/dist/thread-prewarm.js
27659
+ var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
27660
+ var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
27661
+
27658
27662
  // ../../shared-contracts/dist/harness-plugins.js
27659
27663
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
27660
27664
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -27722,6 +27726,9 @@ var consoleOpenResultSchema = external_exports.strictObject({
27722
27726
  url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
27723
27727
  });
27724
27728
  var CONSOLE_HOST_METHODS = Object.freeze([
27729
+ "codexhost/console/remote-connections",
27730
+ "codexhost/runtime/status",
27731
+ "codexhost/remote/ssh-setup",
27725
27732
  "codexhost/harness/plugins/list",
27726
27733
  "codexhost/harness/display-settings/get",
27727
27734
  "codexhost/harness/display-settings/set",
@@ -28667,6 +28674,80 @@ var updateStatusResultSchema = external_exports.strictObject({
28667
28674
  status: updateStatusSchema.nullable()
28668
28675
  });
28669
28676
 
28677
+ // ../../shared-contracts/dist/remote-runtime.js
28678
+ var remoteUpdatePhaseSchema = external_exports.enum([
28679
+ "idle",
28680
+ "installing",
28681
+ "restarting",
28682
+ "succeeded",
28683
+ "failed"
28684
+ ]);
28685
+ var runtimeStatusSchema = external_exports.object({
28686
+ runningVersion: external_exports.string().nullable(),
28687
+ installedVersion: external_exports.string().nullable(),
28688
+ restartRequired: external_exports.boolean(),
28689
+ remote: external_exports.boolean(),
28690
+ updateSupported: external_exports.boolean(),
28691
+ update: external_exports.object({
28692
+ phase: remoteUpdatePhaseSchema,
28693
+ targetVersion: external_exports.string().nullable(),
28694
+ error: external_exports.string().nullable()
28695
+ })
28696
+ });
28697
+ var remoteUpdateParamsSchema = external_exports.object({
28698
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)
28699
+ }).strict();
28700
+ var remoteSshSetupParamsSchema = external_exports.object({
28701
+ hostname: external_exports.string().min(1).max(1024).refine((value) => !value.startsWith("-") && !/\s/u.test(value)),
28702
+ port: external_exports.number().int().min(1).max(65535).nullable(),
28703
+ identity: external_exports.string().max(4096).nullable(),
28704
+ action: external_exports.enum(["inspect", "install", "update", "repair", "uninstall"]),
28705
+ uninstallPackage: external_exports.boolean().optional(),
28706
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+$/u).nullable()
28707
+ }).strict();
28708
+ var remoteSshSetupResultSchema = external_exports.object({ state: external_exports.enum(["installed", "not-installed"]) }).strict();
28709
+
28710
+ // ../../shared-contracts/dist/remote-connections.js
28711
+ var hostId = external_exports.string().min(1).max(1024);
28712
+ var codexSshConnectionSchema = external_exports.object({
28713
+ hostId,
28714
+ displayName: external_exports.string().min(1).max(1024),
28715
+ source: external_exports.enum(["codex-managed", "discovered"]),
28716
+ sshAlias: external_exports.string().max(1024).nullable(),
28717
+ sshHost: external_exports.string().min(1).max(1024),
28718
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
28719
+ identity: external_exports.string().max(4096).nullable(),
28720
+ autoConnect: external_exports.boolean(),
28721
+ connectionAnalyticsId: external_exports.string().max(1024).optional()
28722
+ });
28723
+ var codexSshDraftSchema = external_exports.strictObject({
28724
+ displayName: external_exports.string().min(1).max(1024),
28725
+ hostname: external_exports.string().min(1).max(1024),
28726
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
28727
+ identity: external_exports.string().max(4096).nullable()
28728
+ });
28729
+ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
28730
+ external_exports.strictObject({ action: external_exports.literal("list") }),
28731
+ external_exports.strictObject({
28732
+ action: external_exports.literal("save"),
28733
+ draft: codexSshDraftSchema,
28734
+ previous: codexSshConnectionSchema.nullable()
28735
+ }),
28736
+ external_exports.strictObject({ action: external_exports.literal("remove"), previous: codexSshConnectionSchema }),
28737
+ external_exports.strictObject({ action: external_exports.literal("connect"), hostId, enabled: external_exports.boolean() }),
28738
+ external_exports.strictObject({ action: external_exports.literal("state"), hostId }),
28739
+ external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
28740
+ external_exports.strictObject({
28741
+ action: external_exports.literal("update"),
28742
+ hostId: hostId.refine((id) => id !== "local"),
28743
+ version: remoteUpdateParamsSchema.shape.version
28744
+ })
28745
+ ]);
28746
+ var remoteConnectionsReplySchema = external_exports.union([
28747
+ external_exports.strictObject({ result: jsonValueSchema }),
28748
+ external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
28749
+ ]);
28750
+
28670
28751
  // ../../shared-contracts/dist/index.js
28671
28752
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
28672
28753
 
@@ -29029,11 +29110,13 @@ function cursorDiscoverySpec(skipPinnedVersions) {
29029
29110
  } : {}
29030
29111
  };
29031
29112
  }
29113
+ var CursorNotInstalledError = class extends Error {
29114
+ };
29032
29115
  function resolveCursorExecutable(environment, command) {
29033
29116
  const input = { environment, ...command ? { command } : {} };
29034
29117
  const pinned = resolveHarnessExecutable(cursorDiscoverySpec(false), input);
29035
29118
  if (!pinned)
29036
- throw new Error("Cursor CLI is not installed; install cursor-agent or set CODEXHOST_CURSOR_COMMAND");
29119
+ throw new CursorNotInstalledError("Cursor CLI is not installed; install cursor-agent or set CODEXHOST_CURSOR_COMMAND");
29037
29120
  const explicit = command?.trim() || environment.CODEXHOST_CURSOR_COMMAND?.trim();
29038
29121
  if (explicit || !PINNED_VERSION_AGENT.test(pinned.executable))
29039
29122
  return pinned;
@@ -29177,6 +29260,99 @@ async function fetchCursorAccount(input = {}) {
29177
29260
  import { lstat, opendir, readFile as readFile2, realpath, stat } from "node:fs/promises";
29178
29261
  import path7 from "node:path";
29179
29262
 
29263
+ // ../../harness-adapter/dist/session-import.js
29264
+ var SessionImportChangedError = class extends Error {
29265
+ constructor(message = "Native Session changed during discovery; refresh and retry") {
29266
+ super(message);
29267
+ this.name = "SessionImportChangedError";
29268
+ }
29269
+ };
29270
+ function isMissingFileError(error51) {
29271
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
29272
+ }
29273
+ function sameFileFingerprint(left, right) {
29274
+ 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;
29275
+ }
29276
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
29277
+ if (typeof value !== "string")
29278
+ return null;
29279
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
29280
+ if (!normalized)
29281
+ return null;
29282
+ if (normalized.length <= maxLength)
29283
+ return normalized;
29284
+ const characters = [...normalized];
29285
+ if (characters.length <= maxLength)
29286
+ return normalized;
29287
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
29288
+ }
29289
+ function sessionImportCandidate(input) {
29290
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
29291
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
29292
+ nativeSessionId: input.nativeSessionId,
29293
+ cwd: input.cwd,
29294
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
29295
+ updatedAt: Math.floor(time3),
29296
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
29297
+ running: typeof input.running === "boolean" ? input.running : null
29298
+ });
29299
+ return parsed.success ? parsed.data : null;
29300
+ }
29301
+ var SessionImportScope = class {
29302
+ #abort = new AbortController();
29303
+ #options;
29304
+ #pending = /* @__PURE__ */ new Set();
29305
+ constructor(options) {
29306
+ this.#options = options;
29307
+ }
29308
+ #closed() {
29309
+ return {
29310
+ ok: false,
29311
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
29312
+ };
29313
+ }
29314
+ read(operation) {
29315
+ const signal = this.#abort.signal;
29316
+ if (signal.aborted)
29317
+ return Promise.resolve(this.#closed());
29318
+ let started;
29319
+ try {
29320
+ started = operation(signal);
29321
+ } catch (error51) {
29322
+ started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
29323
+ }
29324
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
29325
+ ok: false,
29326
+ error: {
29327
+ code: "unavailable",
29328
+ message: this.#options.unavailableMessage,
29329
+ retryable: true
29330
+ }
29331
+ }).finally(() => this.#pending.delete(request));
29332
+ this.#pending.add(request);
29333
+ return request;
29334
+ }
29335
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
29336
+ async resolve(operation) {
29337
+ const result = await this.read(operation);
29338
+ if (!result.ok)
29339
+ return result;
29340
+ return result.value ? { ok: true, value: result.value } : {
29341
+ ok: false,
29342
+ error: {
29343
+ code: "sessionNotFound",
29344
+ message: this.#options.notFoundMessage,
29345
+ retryable: false
29346
+ }
29347
+ };
29348
+ }
29349
+ /** Idempotent. Resolves after every started read has settled. */
29350
+ async close() {
29351
+ this.#abort.abort();
29352
+ await Promise.allSettled(this.#pending);
29353
+ }
29354
+ };
29355
+
29180
29356
  // dist/native-history.js
29181
29357
  import { existsSync as existsSync2, readFileSync, realpathSync } from "node:fs";
29182
29358
  import os2 from "node:os";
@@ -29322,8 +29498,6 @@ function cursorExecutionPolicy(ref) {
29322
29498
  // dist/session-import.js
29323
29499
  var SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
29324
29500
  var MAX_METADATA_BYTES = 1024 * 1024;
29325
- var CursorSessionChangedError = class extends Error {
29326
- };
29327
29501
  function errorCode(error51) {
29328
29502
  return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" ? error51.code : void 0;
29329
29503
  }
@@ -29331,23 +29505,23 @@ async function optionalStat(file2) {
29331
29505
  try {
29332
29506
  return await lstat(file2);
29333
29507
  } catch (error51) {
29334
- if (errorCode(error51) === "ENOENT")
29508
+ if (isMissingFileError(error51))
29335
29509
  return null;
29336
29510
  throw error51;
29337
29511
  }
29338
29512
  }
29339
- function sameFile(left, right) {
29340
- 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;
29341
- }
29342
29513
  var CursorSessionImport = class {
29343
29514
  #environment;
29344
- #abort = new AbortController();
29345
- #pending = /* @__PURE__ */ new Set();
29515
+ #scope = new SessionImportScope({
29516
+ closedMessage: "Cursor Session import is closed",
29517
+ unavailableMessage: "Cursor ACP sessions could not be read; close native clients, check storage access and retry",
29518
+ notFoundMessage: "Cursor ACP Session is no longer importable"
29519
+ });
29346
29520
  constructor(environment) {
29347
29521
  this.#environment = { ...environment };
29348
29522
  }
29349
29523
  listCandidates() {
29350
- return this.#read(async (signal) => {
29524
+ return this.#scope.read(async (signal) => {
29351
29525
  const root = path7.join(cursorConfigDirectory(this.#environment), "acp-sessions");
29352
29526
  const info = await optionalStat(root);
29353
29527
  if (!info)
@@ -29365,7 +29539,7 @@ var CursorSessionImport = class {
29365
29539
  if (candidate)
29366
29540
  candidates.push(candidate);
29367
29541
  } catch (error51) {
29368
- if (!(error51 instanceof CursorSessionChangedError))
29542
+ if (!(error51 instanceof SessionImportChangedError))
29369
29543
  throw error51;
29370
29544
  }
29371
29545
  }
@@ -29382,27 +29556,15 @@ var CursorSessionImport = class {
29382
29556
  retryable: false
29383
29557
  }
29384
29558
  };
29385
- const result = await this.#read((signal) => this.#candidate(nativeSessionId, signal));
29386
- if (!result.ok)
29387
- return result;
29388
- if (!result.value)
29389
- return {
29390
- ok: false,
29391
- error: {
29392
- code: "sessionNotFound",
29393
- message: "Cursor ACP Session is no longer importable",
29394
- retryable: false
29395
- }
29396
- };
29397
- return {
29398
- ok: true,
29399
- value: {
29400
- candidate: result.value,
29559
+ return this.#scope.resolve(async (signal) => {
29560
+ const candidate = await this.#candidate(nativeSessionId, signal);
29561
+ return candidate ? {
29562
+ candidate,
29401
29563
  // Native ACP stores do not attest to --force. Imported sessions must not
29402
29564
  // acquire unattended privileges from UI defaults or a guessed locator.
29403
29565
  nativeRef: cursorNativeSessionRef(nativeSessionId, "default")
29404
- }
29405
- };
29566
+ } : null;
29567
+ });
29406
29568
  }
29407
29569
  async #candidate(id, signal) {
29408
29570
  signal.throwIfAborted();
@@ -29433,7 +29595,7 @@ var CursorSessionImport = class {
29433
29595
  const turns = readCursorNativeTurns(id, cwd, this.#environment);
29434
29596
  if (!turns.length)
29435
29597
  return null;
29436
- title = turns[0]?.text.replaceAll("\0", "").replace(/\s+/gu, " ").trim().slice(0, HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) || null;
29598
+ title = sessionImportTitle(turns[0]?.text);
29437
29599
  } catch (error51) {
29438
29600
  signal.throwIfAborted();
29439
29601
  if (["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"].includes(errorCode(error51) ?? ""))
@@ -29442,46 +29604,17 @@ var CursorSessionImport = class {
29442
29604
  }
29443
29605
  signal.throwIfAborted();
29444
29606
  const after = await Promise.all(files.map(optionalStat));
29445
- if (before.some((info, index) => !sameFile(info, after[index] ?? null)))
29446
- throw new CursorSessionChangedError("Cursor Session changed during discovery");
29447
- const parsed = harnessSessionImportCandidateSchema.safeParse({
29607
+ if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
29608
+ throw new SessionImportChangedError("Cursor Session changed during discovery");
29609
+ return sessionImportCandidate({
29448
29610
  nativeSessionId: id,
29449
29611
  cwd,
29450
29612
  title,
29451
- updatedAt: Math.floor(Math.max(database.mtimeMs, wal?.mtimeMs ?? 0)),
29452
- // A stable read does not establish that another Cursor process is idle.
29453
- running: null
29613
+ updatedAt: Math.max(database.mtimeMs, wal?.mtimeMs ?? 0)
29454
29614
  });
29455
- return parsed.success ? parsed.data : null;
29456
29615
  }
29457
- #read(operation) {
29458
- const signal = this.#abort.signal;
29459
- if (signal.aborted)
29460
- return Promise.resolve({
29461
- ok: false,
29462
- error: {
29463
- code: "invalidState",
29464
- message: "Cursor Session import is closed",
29465
- retryable: false
29466
- }
29467
- });
29468
- const request = operation(signal).then((value) => {
29469
- signal.throwIfAborted();
29470
- return { ok: true, value };
29471
- }).catch(() => ({
29472
- ok: false,
29473
- error: {
29474
- code: signal.aborted ? "invalidState" : "unavailable",
29475
- message: signal.aborted ? "Cursor Session import is closed" : "Cursor ACP sessions could not be read; close native clients, check storage access and retry",
29476
- retryable: !signal.aborted
29477
- }
29478
- })).finally(() => this.#pending.delete(request));
29479
- this.#pending.add(request);
29480
- return request;
29481
- }
29482
- async close() {
29483
- this.#abort.abort();
29484
- await Promise.allSettled(this.#pending);
29616
+ close() {
29617
+ return this.#scope.close();
29485
29618
  }
29486
29619
  };
29487
29620
 
@@ -47530,6 +47663,7 @@ var CursorSession = class {
47530
47663
  };
47531
47664
 
47532
47665
  // ../../harness-broker/dist/client.js
47666
+ import { execFile as execFile4 } from "node:child_process";
47533
47667
  import { randomUUID as randomUUID2 } from "node:crypto";
47534
47668
  import { lstat as lstat2, readFile as readFile4 } from "node:fs/promises";
47535
47669
  import net, {} from "node:net";
@@ -47540,9 +47674,12 @@ var HARNESS_BROKER_MAX_FRAME_BYTES = 8 * 1024 * 1024;
47540
47674
  var HARNESS_BROKER_MAX_PENDING_REQUESTS = 32;
47541
47675
  var HARNESS_BROKER_REQUEST_TIMEOUT_MS = 15e3;
47542
47676
  var HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE = 100;
47677
+ var HARNESS_BROKER_IDLE_TIMEOUT_MS = 60 * 60 * 1e3;
47678
+ var HARNESS_BROKER_RETIRING_ERROR_CODE = "brokerRetiring";
47543
47679
  var harnessBrokerMethodSchema = external_exports.enum([
47544
47680
  "adapter.inspect",
47545
47681
  "adapter.inspectAccount",
47682
+ "adapter.credits",
47546
47683
  "adapter.open",
47547
47684
  "adapter.sessionImport.list",
47548
47685
  "adapter.sessionImport.resolve",
@@ -47662,6 +47799,14 @@ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId
47662
47799
  return path11.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
47663
47800
  return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path11.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
47664
47801
  }
47802
+ function harnessBrokerLaunchAgentLabel(harnessId = "claude-code") {
47803
+ harnessPluginIdSchema.parse(harnessId);
47804
+ return harnessId === "claude-code" ? "ai.bytepioneer.codexhost.native-harness-broker" : `ai.bytepioneer.codexhost.${harnessId}-broker`;
47805
+ }
47806
+ function harnessBrokerLaunchAgentPlistPath(environment = process.env, harnessId = "claude-code") {
47807
+ const home = environment.HOME || os4.homedir();
47808
+ return path11.join(home, "Library", "LaunchAgents", `${harnessBrokerLaunchAgentLabel(harnessId)}.plist`);
47809
+ }
47665
47810
 
47666
47811
  // ../../harness-broker/dist/validation.js
47667
47812
  var cwdSchema = external_exports.string().min(1).max(16384);
@@ -47988,10 +48133,55 @@ async function readDescriptor(descriptorPath) {
47988
48133
  try {
47989
48134
  process.kill(descriptor.ownerPid, 0);
47990
48135
  } catch {
47991
- throw new Error("Aqua Harness broker owner process is unavailable");
48136
+ throw new BrokerNotRunningError("its owner process has exited");
47992
48137
  }
47993
48138
  return descriptor;
47994
48139
  }
48140
+ var BrokerNotRunningError = class extends Error {
48141
+ };
48142
+ var BrokerRetiringError = class extends Error {
48143
+ };
48144
+ var BrokerRequestNotDeliveredError = class extends Error {
48145
+ };
48146
+ var HarnessNotInstalledError = class extends Error {
48147
+ };
48148
+ var BROKER_NOT_RUNNING_CODES = /* @__PURE__ */ new Set(["ENOENT", "ECONNREFUSED"]);
48149
+ var BROKER_START_TIMEOUT_MS = 15e3;
48150
+ var BROKER_START_POLL_MS = 250;
48151
+ function classifyConnectFailure(error51) {
48152
+ if (error51 instanceof BrokerNotRunningError)
48153
+ return error51;
48154
+ const code = error51?.code;
48155
+ if (code && BROKER_NOT_RUNNING_CODES.has(code)) {
48156
+ return new BrokerNotRunningError(code === "ENOENT" ? "its descriptor or socket is missing" : "its socket refused the connection");
48157
+ }
48158
+ return error51 instanceof Error ? error51 : new Error(String(error51));
48159
+ }
48160
+ function describeBrokerFailure(error51, harnessId) {
48161
+ if (error51 instanceof BrokerNotRunningError) {
48162
+ return `The ${harnessId} Aqua Harness broker on this Mac could not be started (${error51.message}). Keep the desktop user logged in, then repair the remote service or run on this Mac: codexhost broker install --harness ${harnessId}`;
48163
+ }
48164
+ return error51 instanceof Error ? error51.message : String(error51);
48165
+ }
48166
+ function runLaunchctl(arguments_) {
48167
+ return new Promise((resolve) => {
48168
+ execFile4("/bin/launchctl", arguments_, { timeout: 1e4 }, (error51) => resolve(!error51));
48169
+ });
48170
+ }
48171
+ async function startBrokerLaunchAgent(harnessId, environment) {
48172
+ const uid = process.getuid?.();
48173
+ if (uid === void 0)
48174
+ return;
48175
+ const target = `gui/${uid}/${harnessBrokerLaunchAgentLabel(harnessId)}`;
48176
+ if (await runLaunchctl(["kickstart", target]))
48177
+ return;
48178
+ await runLaunchctl([
48179
+ "bootstrap",
48180
+ `gui/${uid}`,
48181
+ harnessBrokerLaunchAgentPlistPath(environment, harnessId)
48182
+ ]);
48183
+ await runLaunchctl(["kickstart", target]);
48184
+ }
47995
48185
  var BrokerConnection = class _BrokerConnection {
47996
48186
  #onClose;
47997
48187
  onClose(callback) {
@@ -48015,21 +48205,31 @@ var BrokerConnection = class _BrokerConnection {
48015
48205
  socket.once("error", (error51) => this.#fail(error51));
48016
48206
  }
48017
48207
  static async connect(descriptorPath, harnessId) {
48018
- const descriptor = await readDescriptor(descriptorPath);
48019
- if (descriptor.harnessId !== harnessId)
48020
- throw new Error("Aqua broker belongs to another Harness");
48021
- const socket = net.createConnection(descriptor.socketPath);
48022
- await new Promise((resolve, reject) => {
48023
- const timeout = setTimeout(() => reject(new Error("Timed out connecting to Aqua Harness broker")), HARNESS_BROKER_REQUEST_TIMEOUT_MS);
48024
- socket.once("connect", () => {
48025
- clearTimeout(timeout);
48026
- resolve();
48027
- });
48028
- socket.once("error", (error51) => {
48029
- clearTimeout(timeout);
48030
- reject(error51);
48208
+ let descriptor;
48209
+ let socket;
48210
+ let connecting;
48211
+ try {
48212
+ descriptor = await readDescriptor(descriptorPath);
48213
+ if (descriptor.harnessId !== harnessId)
48214
+ throw new Error("Aqua broker belongs to another Harness");
48215
+ connecting = net.createConnection(descriptor.socketPath);
48216
+ const pending = connecting;
48217
+ await new Promise((resolve, reject) => {
48218
+ const timeout = setTimeout(() => reject(new Error("Timed out connecting to Aqua Harness broker")), HARNESS_BROKER_REQUEST_TIMEOUT_MS);
48219
+ pending.once("connect", () => {
48220
+ clearTimeout(timeout);
48221
+ resolve();
48222
+ });
48223
+ pending.once("error", (error51) => {
48224
+ clearTimeout(timeout);
48225
+ reject(error51);
48226
+ });
48031
48227
  });
48032
- });
48228
+ socket = pending;
48229
+ } catch (error51) {
48230
+ connecting?.destroy();
48231
+ throw classifyConnectFailure(error51);
48232
+ }
48033
48233
  const connection = new _BrokerConnection(descriptor, socket);
48034
48234
  const hello = connection.#waitForHello();
48035
48235
  await writeBrokerFrame(socket, {
@@ -48082,15 +48282,24 @@ var BrokerConnection = class _BrokerConnection {
48082
48282
  }, HARNESS_BROKER_REQUEST_TIMEOUT_MS);
48083
48283
  this.#pending.set(id, { resolve, reject, timeout });
48084
48284
  });
48085
- await writeBrokerFrame(this.#socket, {
48086
- version: HARNESS_BROKER_PROTOCOL_VERSION,
48087
- generation: this.#descriptor.generation,
48088
- sequence: this.#inputSequence,
48089
- kind: "request",
48090
- id,
48091
- method,
48092
- params
48093
- });
48285
+ try {
48286
+ await writeBrokerFrame(this.#socket, {
48287
+ version: HARNESS_BROKER_PROTOCOL_VERSION,
48288
+ generation: this.#descriptor.generation,
48289
+ sequence: this.#inputSequence,
48290
+ kind: "request",
48291
+ id,
48292
+ method,
48293
+ params
48294
+ });
48295
+ } catch (error51) {
48296
+ const pending = this.#pending.get(id);
48297
+ if (pending)
48298
+ clearTimeout(pending.timeout);
48299
+ this.#pending.delete(id);
48300
+ response.catch(() => void 0);
48301
+ throw new BrokerRequestNotDeliveredError(error51 instanceof Error ? error51.message : String(error51));
48302
+ }
48094
48303
  return response;
48095
48304
  }
48096
48305
  close() {
@@ -48134,6 +48343,8 @@ var BrokerConnection = class _BrokerConnection {
48134
48343
  this.#pending.delete(frame.id);
48135
48344
  if (frame.ok)
48136
48345
  pending.resolve(frame.value);
48346
+ else if (frame.error?.code === HARNESS_BROKER_RETIRING_ERROR_CODE)
48347
+ pending.reject(new BrokerRetiringError(frame.error.message));
48137
48348
  else
48138
48349
  pending.reject(new Error(frame.error?.message ?? "Broker request failed"));
48139
48350
  }
@@ -48359,18 +48570,20 @@ var BrokeredHarnessAdapter = class {
48359
48570
  harnessId;
48360
48571
  #descriptorPath;
48361
48572
  #forwardEnvironment;
48573
+ #isInstalled;
48574
+ #startBroker;
48575
+ #startTimeoutMs;
48362
48576
  #connection = null;
48363
48577
  #closed = false;
48364
48578
  #sessionImportListing = null;
48579
+ #credits = null;
48580
+ #creditsRefresh = null;
48365
48581
  subagents = {
48366
48582
  readSnapshot: async (input) => {
48367
48583
  try {
48368
- return parseHarnessResult(await (await this.#connect()).request("adapter.subagent.readSnapshot", input));
48584
+ return parseHarnessResult(await this.#request("adapter.subagent.readSnapshot", input));
48369
48585
  } catch (error51) {
48370
- return {
48371
- ok: false,
48372
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
48373
- };
48586
+ return { ok: false, error: this.#error(error51) };
48374
48587
  }
48375
48588
  }
48376
48589
  };
@@ -48460,12 +48673,39 @@ var BrokeredHarnessAdapter = class {
48460
48673
  if (input.liveCommandCatalog)
48461
48674
  this.liveCommandCatalog = true;
48462
48675
  this.#descriptorPath = input.descriptorPath ?? defaultHarnessBrokerDescriptorPath(input.environment, this.harnessId);
48676
+ this.#isInstalled = input.isInstalled;
48677
+ const environment = input.environment ?? process.env;
48678
+ this.#startBroker = input.startBroker === false ? void 0 : input.startBroker ?? (process.platform === "darwin" && !input.descriptorPath ? () => startBrokerLaunchAgent(this.harnessId, environment) : void 0);
48679
+ this.#startTimeoutMs = input.startTimeoutMs ?? BROKER_START_TIMEOUT_MS;
48680
+ }
48681
+ credits() {
48682
+ return this.#credits;
48683
+ }
48684
+ refreshCredits() {
48685
+ if (this.#closed)
48686
+ return Promise.resolve(null);
48687
+ if (this.#creditsRefresh)
48688
+ return this.#creditsRefresh;
48689
+ this.#creditsRefresh = this.#readCredits().finally(() => {
48690
+ this.#creditsRefresh = null;
48691
+ });
48692
+ return this.#creditsRefresh;
48693
+ }
48694
+ async #readCredits() {
48695
+ try {
48696
+ const value = await this.#request("adapter.credits", {}, true);
48697
+ const credits = accountCreditsSnapshotSchema.nullable().parse(value);
48698
+ if (!this.#closed)
48699
+ this.#credits = credits;
48700
+ } catch {
48701
+ }
48702
+ return this.#credits;
48463
48703
  }
48464
48704
  async inspectAccount() {
48465
48705
  if (this.#closed)
48466
48706
  return null;
48467
48707
  try {
48468
- const value = await (await this.#connect()).request("adapter.inspectAccount", {});
48708
+ const value = await this.#request("adapter.inspectAccount", {}, true);
48469
48709
  return harnessAccountSnapshotSchema.nullable().parse(value);
48470
48710
  } catch {
48471
48711
  return null;
@@ -48475,33 +48715,46 @@ var BrokeredHarnessAdapter = class {
48475
48715
  if (this.#closed)
48476
48716
  return failedInspection("Aqua Harness broker adapter is closed");
48477
48717
  try {
48478
- return harnessInspectionSchema.parse(await (await this.#connect()).request("adapter.inspect", input));
48718
+ return harnessInspectionSchema.parse(await this.#request("adapter.inspect", input, true));
48479
48719
  } catch (error51) {
48480
48720
  this.#connection = null;
48481
- return failedInspection(error51 instanceof Error ? error51.message : String(error51));
48721
+ if (error51 instanceof HarnessNotInstalledError)
48722
+ return { status: "notInstalled", error: this.#error(error51) };
48723
+ return failedInspection(describeBrokerFailure(error51, this.harnessId));
48482
48724
  }
48483
48725
  }
48484
48726
  async open(input) {
48485
48727
  if (this.#closed)
48486
48728
  return { ok: false, error: unavailable("Aqua Harness broker adapter is closed", false) };
48729
+ const safeInput = { ...input };
48730
+ delete safeInput.environment;
48731
+ if (this.#forwardEnvironment && input.environment) {
48732
+ const allowed = [
48733
+ "CODEXHOST_CLI_PATH",
48734
+ "CODEXHOST_CLI_NODE_PATH",
48735
+ "CODEXHOST_RUNTIME_ENDPOINT",
48736
+ "CODEXHOST_RUNTIME_TOKEN",
48737
+ "CODEXHOST_THREAD_ID"
48738
+ ];
48739
+ const environment = Object.fromEntries(Object.entries(input.environment).filter(([key, value]) => allowed.includes(key) && value !== void 0));
48740
+ if (Object.keys(environment).length)
48741
+ safeInput.environment = environment;
48742
+ }
48487
48743
  let connection;
48488
48744
  try {
48489
- const safeInput = { ...input };
48490
- delete safeInput.environment;
48491
- if (this.#forwardEnvironment && input.environment) {
48492
- const allowed = [
48493
- "CODEXHOST_CLI_PATH",
48494
- "CODEXHOST_CLI_NODE_PATH",
48495
- "CODEXHOST_RUNTIME_ENDPOINT",
48496
- "CODEXHOST_RUNTIME_TOKEN",
48497
- "CODEXHOST_THREAD_ID"
48498
- ];
48499
- const environment = Object.fromEntries(Object.entries(input.environment).filter(([key, value]) => allowed.includes(key) && value !== void 0));
48500
- if (Object.keys(environment).length)
48501
- safeInput.environment = environment;
48502
- }
48503
- connection = await this.#connect();
48504
- const result = parseHarnessResult(await connection.request("adapter.open", safeInput));
48745
+ let value;
48746
+ for (let attempt = 0; ; attempt += 1) {
48747
+ connection = await this.#connect();
48748
+ try {
48749
+ value = await connection.request("adapter.open", safeInput);
48750
+ break;
48751
+ } catch (error51) {
48752
+ if (attempt > 0 || !(error51 instanceof BrokerRetiringError || error51 instanceof BrokerRequestNotDeliveredError))
48753
+ throw error51;
48754
+ this.#connection = null;
48755
+ }
48756
+ }
48757
+ const result = parseHarnessResult(value);
48505
48758
  if (!result.ok)
48506
48759
  return result;
48507
48760
  const session = new BrokeredHarnessSession(connection, parseSessionMetadata(result.value), this.harnessId, safeInput, () => this.#connect(), () => {
@@ -48512,25 +48765,51 @@ var BrokeredHarnessAdapter = class {
48512
48765
  } catch (error51) {
48513
48766
  connection?.close();
48514
48767
  this.#connection = null;
48515
- return {
48516
- ok: false,
48517
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
48518
- };
48768
+ return { ok: false, error: this.#error(error51) };
48519
48769
  }
48520
48770
  }
48521
48771
  async close() {
48522
48772
  this.#closed = true;
48773
+ this.#credits = null;
48523
48774
  await Promise.allSettled([...this.#sessions].map((session) => session.close()));
48524
48775
  this.#sessions.clear();
48525
48776
  const connection = await this.#connection?.catch(() => null);
48526
48777
  await connection?.dispose();
48527
48778
  this.#connection = null;
48528
48779
  }
48780
+ #error(error51) {
48781
+ if (error51 instanceof HarnessNotInstalledError)
48782
+ return {
48783
+ code: "notInstalled",
48784
+ message: error51.message,
48785
+ retryable: false,
48786
+ stage: "harnessBroker"
48787
+ };
48788
+ return unavailable(describeBrokerFailure(error51, this.harnessId));
48789
+ }
48790
+ /**
48791
+ * Sends one adapter-level request. A broker that retired between requests refuses it
48792
+ * unprocessed, so it is retried once on a fresh broker. Idempotent reads also retry
48793
+ * once after a plain disconnect.
48794
+ */
48795
+ async #request(method, params, idempotent = false) {
48796
+ for (let attempt = 0; ; attempt += 1) {
48797
+ const connection = await this.#connect();
48798
+ try {
48799
+ return await connection.request(method, params);
48800
+ } catch (error51) {
48801
+ const retryable = error51 instanceof BrokerRetiringError || error51 instanceof BrokerRequestNotDeliveredError || idempotent && connection.closed;
48802
+ if (attempt > 0 || !retryable)
48803
+ throw error51;
48804
+ this.#connection = null;
48805
+ }
48806
+ }
48807
+ }
48529
48808
  #connect() {
48530
48809
  if (this.#closed)
48531
48810
  return Promise.reject(new Error("Aqua Harness broker adapter is closed"));
48532
48811
  if (!this.#connection) {
48533
- const pending = BrokerConnection.connect(this.#descriptorPath, this.harnessId).then((connection) => {
48812
+ const pending = this.#establish().then((connection) => {
48534
48813
  connection.onClose(() => {
48535
48814
  if (this.#connection === pending)
48536
48815
  this.#connection = null;
@@ -48545,18 +48824,50 @@ var BrokeredHarnessAdapter = class {
48545
48824
  }
48546
48825
  return this.#connection;
48547
48826
  }
48827
+ async #establish() {
48828
+ try {
48829
+ return await BrokerConnection.connect(this.#descriptorPath, this.harnessId);
48830
+ } catch (error51) {
48831
+ if (!(error51 instanceof BrokerNotRunningError) || !this.#startBroker)
48832
+ throw error51;
48833
+ }
48834
+ if (this.#isInstalled && !this.#isInstalled()) {
48835
+ throw new HarnessNotInstalledError(`${this.harnessId} is not installed on this Mac`);
48836
+ }
48837
+ const deadline = Date.now() + this.#startTimeoutMs;
48838
+ for (; ; ) {
48839
+ await this.#startBroker();
48840
+ try {
48841
+ return await BrokerConnection.connect(this.#descriptorPath, this.harnessId);
48842
+ } catch (error51) {
48843
+ if (!(error51 instanceof BrokerNotRunningError) || Date.now() >= deadline)
48844
+ throw error51;
48845
+ }
48846
+ await new Promise((resolve) => setTimeout(resolve, BROKER_START_POLL_MS));
48847
+ }
48848
+ }
48548
48849
  };
48549
48850
 
48550
48851
  // dist/plugin.js
48551
48852
  function createHarnessAdapter(context) {
48552
- if (context.platform === "darwin" && context.managedRemoteHost)
48853
+ if (context.platform === "darwin" && context.managedRemoteHost) {
48854
+ const environment2 = { ...context.environment };
48553
48855
  return new BrokeredHarnessAdapter({
48554
48856
  harnessId: "cursor-cli",
48555
48857
  forwardDelegationEnvironment: true,
48556
48858
  commandCatalog: CURSOR_COMMAND_CATALOG,
48557
48859
  liveCommandCatalog: true,
48558
- environment: { ...context.environment }
48860
+ environment: environment2,
48861
+ isInstalled: () => {
48862
+ try {
48863
+ resolveCursorExecutable(environment2);
48864
+ return true;
48865
+ } catch (error51) {
48866
+ return !(error51 instanceof CursorNotInstalledError);
48867
+ }
48868
+ }
48559
48869
  });
48870
+ }
48560
48871
  const environment = { ...context.environment };
48561
48872
  return Object.assign(new CursorAdapter({ environment }), {
48562
48873
  installation: createCursorInstallation(environment),