@liberseek/boft-cli-win32-arm64 0.7.7 → 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.
@@ -6,6 +6,7 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // ../../harness-broker/dist/client.js
9
+ import { execFile } from "node:child_process";
9
10
  import { randomUUID } from "node:crypto";
10
11
  import { lstat, readFile } from "node:fs/promises";
11
12
  import net, {} from "node:net";
@@ -776,10 +777,10 @@ function mergeDefs(...defs) {
776
777
  function cloneDef(schema) {
777
778
  return mergeDefs(schema._zod.def);
778
779
  }
779
- function getElementAtPath(obj, path9) {
780
- if (!path9)
780
+ function getElementAtPath(obj, path10) {
781
+ if (!path10)
781
782
  return obj;
782
- return path9.reduce((acc, key) => acc?.[key], obj);
783
+ return path10.reduce((acc, key) => acc?.[key], obj);
783
784
  }
784
785
  function promiseAllObject(promisesObj) {
785
786
  const keys = Object.keys(promisesObj);
@@ -1188,11 +1189,11 @@ function explicitlyAborted(x, startIndex = 0) {
1188
1189
  }
1189
1190
  return false;
1190
1191
  }
1191
- function prefixIssues(path9, issues) {
1192
+ function prefixIssues(path10, issues) {
1192
1193
  return issues.map((iss) => {
1193
1194
  var _a3;
1194
1195
  (_a3 = iss).path ?? (_a3.path = []);
1195
- iss.path.unshift(path9);
1196
+ iss.path.unshift(path10);
1196
1197
  return iss;
1197
1198
  });
1198
1199
  }
@@ -1339,16 +1340,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1339
1340
  }
1340
1341
  function formatError(error51, mapper = (issue2) => issue2.message) {
1341
1342
  const fieldErrors = { _errors: [] };
1342
- const processError = (error52, path9 = []) => {
1343
+ const processError = (error52, path10 = []) => {
1343
1344
  for (const issue2 of error52.issues) {
1344
1345
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1345
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1346
+ issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1346
1347
  } else if (issue2.code === "invalid_key") {
1347
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1348
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1348
1349
  } else if (issue2.code === "invalid_element") {
1349
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1350
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1350
1351
  } else {
1351
- const fullpath = [...path9, ...issue2.path];
1352
+ const fullpath = [...path10, ...issue2.path];
1352
1353
  if (fullpath.length === 0) {
1353
1354
  fieldErrors._errors.push(mapper(issue2));
1354
1355
  } else {
@@ -1375,17 +1376,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1375
1376
  }
1376
1377
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1377
1378
  const result = { errors: [] };
1378
- const processError = (error52, path9 = []) => {
1379
+ const processError = (error52, path10 = []) => {
1379
1380
  var _a3, _b;
1380
1381
  for (const issue2 of error52.issues) {
1381
1382
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1382
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1383
+ issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1383
1384
  } else if (issue2.code === "invalid_key") {
1384
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1385
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1385
1386
  } else if (issue2.code === "invalid_element") {
1386
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1387
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1387
1388
  } else {
1388
- const fullpath = [...path9, ...issue2.path];
1389
+ const fullpath = [...path10, ...issue2.path];
1389
1390
  if (fullpath.length === 0) {
1390
1391
  result.errors.push(mapper(issue2));
1391
1392
  continue;
@@ -1417,8 +1418,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1417
1418
  }
1418
1419
  function toDotPath(_path) {
1419
1420
  const segs = [];
1420
- const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1421
- for (const seg of path9) {
1421
+ const path10 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1422
+ for (const seg of path10) {
1422
1423
  if (typeof seg === "number")
1423
1424
  segs.push(`[${seg}]`);
1424
1425
  else if (typeof seg === "symbol")
@@ -14110,13 +14111,13 @@ function resolveRef(ref, ctx) {
14110
14111
  if (!ref.startsWith("#")) {
14111
14112
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14112
14113
  }
14113
- const path9 = ref.slice(1).split("/").filter(Boolean);
14114
- if (path9.length === 0) {
14114
+ const path10 = ref.slice(1).split("/").filter(Boolean);
14115
+ if (path10.length === 0) {
14115
14116
  return ctx.rootSchema;
14116
14117
  }
14117
14118
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14118
- if (path9[0] === defsKey) {
14119
- const key = path9[1];
14119
+ if (path10[0] === defsKey) {
14120
+ const key = path10[1];
14120
14121
  if (!key || !ctx.defs[key]) {
14121
14122
  throw new Error(`Reference not found: ${ref}`);
14122
14123
  }
@@ -14604,6 +14605,10 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
14604
14605
  var hostItemIdSchema = opaqueIdSchema.brand();
14605
14606
  var hostInteractionIdSchema = opaqueIdSchema.brand();
14606
14607
 
14608
+ // ../../shared-contracts/dist/thread-prewarm.js
14609
+ var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
14610
+ var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
14611
+
14607
14612
  // ../../shared-contracts/dist/harness-plugins.js
14608
14613
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
14609
14614
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -14671,6 +14676,9 @@ var consoleOpenResultSchema = external_exports.strictObject({
14671
14676
  url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
14672
14677
  });
14673
14678
  var CONSOLE_HOST_METHODS = Object.freeze([
14679
+ "codexhost/console/remote-connections",
14680
+ "codexhost/runtime/status",
14681
+ "codexhost/remote/ssh-setup",
14674
14682
  "codexhost/harness/plugins/list",
14675
14683
  "codexhost/harness/display-settings/get",
14676
14684
  "codexhost/harness/display-settings/set",
@@ -15299,7 +15307,10 @@ var harnessInstallationStateSchema = external_exports.object({
15299
15307
  latestVersion: external_exports.string().min(1).max(128),
15300
15308
  updateAvailable: external_exports.boolean(),
15301
15309
  canUpdate: external_exports.boolean(),
15302
- message: external_exports.string().max(2048).optional()
15310
+ // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
15311
+ message: external_exports.string().max(2048).optional(),
15312
+ messageCode: external_exports.string().min(1).max(128).optional(),
15313
+ latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
15303
15314
  }).strict();
15304
15315
 
15305
15316
  // ../../shared-contracts/dist/codex-accounts.js
@@ -15594,7 +15605,7 @@ var updateStatusSchema = external_exports.strictObject({
15594
15605
  }
15595
15606
  });
15596
15607
  var updateEmptyParamsSchema = external_exports.strictObject({});
15597
- var githubReleaseNotesUrlSchema = external_exports.string().max(300).regex(/^https:\/\/github\.com\/LiberSeek\/BOFT-CLI\/releases\/tag\/v[0-9A-Za-z.+-]+$/u, "release notes URL must identify a codexhost GitHub Release");
15608
+ var githubReleaseNotesUrlSchema = external_exports.string().max(300).regex(/^https:\/\/github\.com\/(LiberSeek|LIBERSEEK)\/BOFT-CLI\/releases\/tag\/v[0-9A-Za-z.+-]+$/u, "release notes URL must identify a codexhost GitHub Release");
15598
15609
  var updateCheckResultSchema = external_exports.strictObject({
15599
15610
  currentVersion: updateSemanticVersionSchema,
15600
15611
  installation: updateInstallationSchema.nullable(),
@@ -15613,6 +15624,80 @@ var updateStatusResultSchema = external_exports.strictObject({
15613
15624
  status: updateStatusSchema.nullable()
15614
15625
  });
15615
15626
 
15627
+ // ../../shared-contracts/dist/remote-runtime.js
15628
+ var remoteUpdatePhaseSchema = external_exports.enum([
15629
+ "idle",
15630
+ "installing",
15631
+ "restarting",
15632
+ "succeeded",
15633
+ "failed"
15634
+ ]);
15635
+ var runtimeStatusSchema = external_exports.object({
15636
+ runningVersion: external_exports.string().nullable(),
15637
+ installedVersion: external_exports.string().nullable(),
15638
+ restartRequired: external_exports.boolean(),
15639
+ remote: external_exports.boolean(),
15640
+ updateSupported: external_exports.boolean(),
15641
+ update: external_exports.object({
15642
+ phase: remoteUpdatePhaseSchema,
15643
+ targetVersion: external_exports.string().nullable(),
15644
+ error: external_exports.string().nullable()
15645
+ })
15646
+ });
15647
+ var remoteUpdateParamsSchema = external_exports.object({
15648
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)
15649
+ }).strict();
15650
+ var remoteSshSetupParamsSchema = external_exports.object({
15651
+ hostname: external_exports.string().min(1).max(1024).refine((value) => !value.startsWith("-") && !/\s/u.test(value)),
15652
+ port: external_exports.number().int().min(1).max(65535).nullable(),
15653
+ identity: external_exports.string().max(4096).nullable(),
15654
+ action: external_exports.enum(["inspect", "install", "update", "repair", "uninstall"]),
15655
+ uninstallPackage: external_exports.boolean().optional(),
15656
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+$/u).nullable()
15657
+ }).strict();
15658
+ var remoteSshSetupResultSchema = external_exports.object({ state: external_exports.enum(["installed", "not-installed"]) }).strict();
15659
+
15660
+ // ../../shared-contracts/dist/remote-connections.js
15661
+ var hostId = external_exports.string().min(1).max(1024);
15662
+ var codexSshConnectionSchema = external_exports.object({
15663
+ hostId,
15664
+ displayName: external_exports.string().min(1).max(1024),
15665
+ source: external_exports.enum(["codex-managed", "discovered"]),
15666
+ sshAlias: external_exports.string().max(1024).nullable(),
15667
+ sshHost: external_exports.string().min(1).max(1024),
15668
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
15669
+ identity: external_exports.string().max(4096).nullable(),
15670
+ autoConnect: external_exports.boolean(),
15671
+ connectionAnalyticsId: external_exports.string().max(1024).optional()
15672
+ });
15673
+ var codexSshDraftSchema = external_exports.strictObject({
15674
+ displayName: external_exports.string().min(1).max(1024),
15675
+ hostname: external_exports.string().min(1).max(1024),
15676
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
15677
+ identity: external_exports.string().max(4096).nullable()
15678
+ });
15679
+ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
15680
+ external_exports.strictObject({ action: external_exports.literal("list") }),
15681
+ external_exports.strictObject({
15682
+ action: external_exports.literal("save"),
15683
+ draft: codexSshDraftSchema,
15684
+ previous: codexSshConnectionSchema.nullable()
15685
+ }),
15686
+ external_exports.strictObject({ action: external_exports.literal("remove"), previous: codexSshConnectionSchema }),
15687
+ external_exports.strictObject({ action: external_exports.literal("connect"), hostId, enabled: external_exports.boolean() }),
15688
+ external_exports.strictObject({ action: external_exports.literal("state"), hostId }),
15689
+ external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
15690
+ external_exports.strictObject({
15691
+ action: external_exports.literal("update"),
15692
+ hostId: hostId.refine((id) => id !== "local"),
15693
+ version: remoteUpdateParamsSchema.shape.version
15694
+ })
15695
+ ]);
15696
+ var remoteConnectionsReplySchema = external_exports.union([
15697
+ external_exports.strictObject({ result: jsonValueSchema }),
15698
+ external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
15699
+ ]);
15700
+
15616
15701
  // ../../shared-contracts/dist/index.js
15617
15702
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
15618
15703
 
@@ -15913,9 +15998,12 @@ var HARNESS_BROKER_MAX_FRAME_BYTES = 8 * 1024 * 1024;
15913
15998
  var HARNESS_BROKER_MAX_PENDING_REQUESTS = 32;
15914
15999
  var HARNESS_BROKER_REQUEST_TIMEOUT_MS = 15e3;
15915
16000
  var HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE = 100;
16001
+ var HARNESS_BROKER_IDLE_TIMEOUT_MS = 60 * 60 * 1e3;
16002
+ var HARNESS_BROKER_RETIRING_ERROR_CODE = "brokerRetiring";
15916
16003
  var harnessBrokerMethodSchema = external_exports.enum([
15917
16004
  "adapter.inspect",
15918
16005
  "adapter.inspectAccount",
16006
+ "adapter.credits",
15919
16007
  "adapter.open",
15920
16008
  "adapter.sessionImport.list",
15921
16009
  "adapter.sessionImport.resolve",
@@ -16035,6 +16123,14 @@ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId
16035
16123
  return path.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
16036
16124
  return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
16037
16125
  }
16126
+ function harnessBrokerLaunchAgentLabel(harnessId = "claude-code") {
16127
+ harnessPluginIdSchema.parse(harnessId);
16128
+ return harnessId === "claude-code" ? "ai.bytepioneer.codexhost.native-harness-broker" : `ai.bytepioneer.codexhost.${harnessId}-broker`;
16129
+ }
16130
+ function harnessBrokerLaunchAgentPlistPath(environment = process.env, harnessId = "claude-code") {
16131
+ const home = environment.HOME || os.homedir();
16132
+ return path.join(home, "Library", "LaunchAgents", `${harnessBrokerLaunchAgentLabel(harnessId)}.plist`);
16133
+ }
16038
16134
 
16039
16135
  // ../../harness-broker/dist/validation.js
16040
16136
  var cwdSchema = external_exports.string().min(1).max(16384);
@@ -16361,10 +16457,55 @@ async function readDescriptor(descriptorPath) {
16361
16457
  try {
16362
16458
  process.kill(descriptor.ownerPid, 0);
16363
16459
  } catch {
16364
- throw new Error("Aqua Harness broker owner process is unavailable");
16460
+ throw new BrokerNotRunningError("its owner process has exited");
16365
16461
  }
16366
16462
  return descriptor;
16367
16463
  }
16464
+ var BrokerNotRunningError = class extends Error {
16465
+ };
16466
+ var BrokerRetiringError = class extends Error {
16467
+ };
16468
+ var BrokerRequestNotDeliveredError = class extends Error {
16469
+ };
16470
+ var HarnessNotInstalledError = class extends Error {
16471
+ };
16472
+ var BROKER_NOT_RUNNING_CODES = /* @__PURE__ */ new Set(["ENOENT", "ECONNREFUSED"]);
16473
+ var BROKER_START_TIMEOUT_MS = 15e3;
16474
+ var BROKER_START_POLL_MS = 250;
16475
+ function classifyConnectFailure(error51) {
16476
+ if (error51 instanceof BrokerNotRunningError)
16477
+ return error51;
16478
+ const code = error51?.code;
16479
+ if (code && BROKER_NOT_RUNNING_CODES.has(code)) {
16480
+ return new BrokerNotRunningError(code === "ENOENT" ? "its descriptor or socket is missing" : "its socket refused the connection");
16481
+ }
16482
+ return error51 instanceof Error ? error51 : new Error(String(error51));
16483
+ }
16484
+ function describeBrokerFailure(error51, harnessId) {
16485
+ if (error51 instanceof BrokerNotRunningError) {
16486
+ 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}`;
16487
+ }
16488
+ return error51 instanceof Error ? error51.message : String(error51);
16489
+ }
16490
+ function runLaunchctl(arguments_) {
16491
+ return new Promise((resolve) => {
16492
+ execFile("/bin/launchctl", arguments_, { timeout: 1e4 }, (error51) => resolve(!error51));
16493
+ });
16494
+ }
16495
+ async function startBrokerLaunchAgent(harnessId, environment) {
16496
+ const uid = process.getuid?.();
16497
+ if (uid === void 0)
16498
+ return;
16499
+ const target = `gui/${uid}/${harnessBrokerLaunchAgentLabel(harnessId)}`;
16500
+ if (await runLaunchctl(["kickstart", target]))
16501
+ return;
16502
+ await runLaunchctl([
16503
+ "bootstrap",
16504
+ `gui/${uid}`,
16505
+ harnessBrokerLaunchAgentPlistPath(environment, harnessId)
16506
+ ]);
16507
+ await runLaunchctl(["kickstart", target]);
16508
+ }
16368
16509
  var BrokerConnection = class _BrokerConnection {
16369
16510
  #onClose;
16370
16511
  onClose(callback) {
@@ -16388,21 +16529,31 @@ var BrokerConnection = class _BrokerConnection {
16388
16529
  socket.once("error", (error51) => this.#fail(error51));
16389
16530
  }
16390
16531
  static async connect(descriptorPath, harnessId) {
16391
- const descriptor = await readDescriptor(descriptorPath);
16392
- if (descriptor.harnessId !== harnessId)
16393
- throw new Error("Aqua broker belongs to another Harness");
16394
- const socket = net.createConnection(descriptor.socketPath);
16395
- await new Promise((resolve, reject) => {
16396
- const timeout = setTimeout(() => reject(new Error("Timed out connecting to Aqua Harness broker")), HARNESS_BROKER_REQUEST_TIMEOUT_MS);
16397
- socket.once("connect", () => {
16398
- clearTimeout(timeout);
16399
- resolve();
16400
- });
16401
- socket.once("error", (error51) => {
16402
- clearTimeout(timeout);
16403
- reject(error51);
16532
+ let descriptor;
16533
+ let socket;
16534
+ let connecting;
16535
+ try {
16536
+ descriptor = await readDescriptor(descriptorPath);
16537
+ if (descriptor.harnessId !== harnessId)
16538
+ throw new Error("Aqua broker belongs to another Harness");
16539
+ connecting = net.createConnection(descriptor.socketPath);
16540
+ const pending = connecting;
16541
+ await new Promise((resolve, reject) => {
16542
+ const timeout = setTimeout(() => reject(new Error("Timed out connecting to Aqua Harness broker")), HARNESS_BROKER_REQUEST_TIMEOUT_MS);
16543
+ pending.once("connect", () => {
16544
+ clearTimeout(timeout);
16545
+ resolve();
16546
+ });
16547
+ pending.once("error", (error51) => {
16548
+ clearTimeout(timeout);
16549
+ reject(error51);
16550
+ });
16404
16551
  });
16405
- });
16552
+ socket = pending;
16553
+ } catch (error51) {
16554
+ connecting?.destroy();
16555
+ throw classifyConnectFailure(error51);
16556
+ }
16406
16557
  const connection = new _BrokerConnection(descriptor, socket);
16407
16558
  const hello = connection.#waitForHello();
16408
16559
  await writeBrokerFrame(socket, {
@@ -16455,15 +16606,24 @@ var BrokerConnection = class _BrokerConnection {
16455
16606
  }, HARNESS_BROKER_REQUEST_TIMEOUT_MS);
16456
16607
  this.#pending.set(id, { resolve, reject, timeout });
16457
16608
  });
16458
- await writeBrokerFrame(this.#socket, {
16459
- version: HARNESS_BROKER_PROTOCOL_VERSION,
16460
- generation: this.#descriptor.generation,
16461
- sequence: this.#inputSequence,
16462
- kind: "request",
16463
- id,
16464
- method,
16465
- params
16466
- });
16609
+ try {
16610
+ await writeBrokerFrame(this.#socket, {
16611
+ version: HARNESS_BROKER_PROTOCOL_VERSION,
16612
+ generation: this.#descriptor.generation,
16613
+ sequence: this.#inputSequence,
16614
+ kind: "request",
16615
+ id,
16616
+ method,
16617
+ params
16618
+ });
16619
+ } catch (error51) {
16620
+ const pending = this.#pending.get(id);
16621
+ if (pending)
16622
+ clearTimeout(pending.timeout);
16623
+ this.#pending.delete(id);
16624
+ response.catch(() => void 0);
16625
+ throw new BrokerRequestNotDeliveredError(error51 instanceof Error ? error51.message : String(error51));
16626
+ }
16467
16627
  return response;
16468
16628
  }
16469
16629
  close() {
@@ -16507,6 +16667,8 @@ var BrokerConnection = class _BrokerConnection {
16507
16667
  this.#pending.delete(frame.id);
16508
16668
  if (frame.ok)
16509
16669
  pending.resolve(frame.value);
16670
+ else if (frame.error?.code === HARNESS_BROKER_RETIRING_ERROR_CODE)
16671
+ pending.reject(new BrokerRetiringError(frame.error.message));
16510
16672
  else
16511
16673
  pending.reject(new Error(frame.error?.message ?? "Broker request failed"));
16512
16674
  }
@@ -16732,18 +16894,20 @@ var BrokeredHarnessAdapter = class {
16732
16894
  harnessId;
16733
16895
  #descriptorPath;
16734
16896
  #forwardEnvironment;
16897
+ #isInstalled;
16898
+ #startBroker;
16899
+ #startTimeoutMs;
16735
16900
  #connection = null;
16736
16901
  #closed = false;
16737
16902
  #sessionImportListing = null;
16903
+ #credits = null;
16904
+ #creditsRefresh = null;
16738
16905
  subagents = {
16739
16906
  readSnapshot: async (input) => {
16740
16907
  try {
16741
- return parseHarnessResult(await (await this.#connect()).request("adapter.subagent.readSnapshot", input));
16908
+ return parseHarnessResult(await this.#request("adapter.subagent.readSnapshot", input));
16742
16909
  } catch (error51) {
16743
- return {
16744
- ok: false,
16745
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
16746
- };
16910
+ return { ok: false, error: this.#error(error51) };
16747
16911
  }
16748
16912
  }
16749
16913
  };
@@ -16833,12 +16997,39 @@ var BrokeredHarnessAdapter = class {
16833
16997
  if (input.liveCommandCatalog)
16834
16998
  this.liveCommandCatalog = true;
16835
16999
  this.#descriptorPath = input.descriptorPath ?? defaultHarnessBrokerDescriptorPath(input.environment, this.harnessId);
17000
+ this.#isInstalled = input.isInstalled;
17001
+ const environment = input.environment ?? process.env;
17002
+ this.#startBroker = input.startBroker === false ? void 0 : input.startBroker ?? (process.platform === "darwin" && !input.descriptorPath ? () => startBrokerLaunchAgent(this.harnessId, environment) : void 0);
17003
+ this.#startTimeoutMs = input.startTimeoutMs ?? BROKER_START_TIMEOUT_MS;
17004
+ }
17005
+ credits() {
17006
+ return this.#credits;
17007
+ }
17008
+ refreshCredits() {
17009
+ if (this.#closed)
17010
+ return Promise.resolve(null);
17011
+ if (this.#creditsRefresh)
17012
+ return this.#creditsRefresh;
17013
+ this.#creditsRefresh = this.#readCredits().finally(() => {
17014
+ this.#creditsRefresh = null;
17015
+ });
17016
+ return this.#creditsRefresh;
17017
+ }
17018
+ async #readCredits() {
17019
+ try {
17020
+ const value = await this.#request("adapter.credits", {}, true);
17021
+ const credits = accountCreditsSnapshotSchema.nullable().parse(value);
17022
+ if (!this.#closed)
17023
+ this.#credits = credits;
17024
+ } catch {
17025
+ }
17026
+ return this.#credits;
16836
17027
  }
16837
17028
  async inspectAccount() {
16838
17029
  if (this.#closed)
16839
17030
  return null;
16840
17031
  try {
16841
- const value = await (await this.#connect()).request("adapter.inspectAccount", {});
17032
+ const value = await this.#request("adapter.inspectAccount", {}, true);
16842
17033
  return harnessAccountSnapshotSchema.nullable().parse(value);
16843
17034
  } catch {
16844
17035
  return null;
@@ -16848,33 +17039,46 @@ var BrokeredHarnessAdapter = class {
16848
17039
  if (this.#closed)
16849
17040
  return failedInspection("Aqua Harness broker adapter is closed");
16850
17041
  try {
16851
- return harnessInspectionSchema.parse(await (await this.#connect()).request("adapter.inspect", input));
17042
+ return harnessInspectionSchema.parse(await this.#request("adapter.inspect", input, true));
16852
17043
  } catch (error51) {
16853
17044
  this.#connection = null;
16854
- return failedInspection(error51 instanceof Error ? error51.message : String(error51));
17045
+ if (error51 instanceof HarnessNotInstalledError)
17046
+ return { status: "notInstalled", error: this.#error(error51) };
17047
+ return failedInspection(describeBrokerFailure(error51, this.harnessId));
16855
17048
  }
16856
17049
  }
16857
17050
  async open(input) {
16858
17051
  if (this.#closed)
16859
17052
  return { ok: false, error: unavailable("Aqua Harness broker adapter is closed", false) };
17053
+ const safeInput = { ...input };
17054
+ delete safeInput.environment;
17055
+ if (this.#forwardEnvironment && input.environment) {
17056
+ const allowed = [
17057
+ "CODEXHOST_CLI_PATH",
17058
+ "CODEXHOST_CLI_NODE_PATH",
17059
+ "CODEXHOST_RUNTIME_ENDPOINT",
17060
+ "CODEXHOST_RUNTIME_TOKEN",
17061
+ "CODEXHOST_THREAD_ID"
17062
+ ];
17063
+ const environment = Object.fromEntries(Object.entries(input.environment).filter(([key, value]) => allowed.includes(key) && value !== void 0));
17064
+ if (Object.keys(environment).length)
17065
+ safeInput.environment = environment;
17066
+ }
16860
17067
  let connection;
16861
17068
  try {
16862
- const safeInput = { ...input };
16863
- delete safeInput.environment;
16864
- if (this.#forwardEnvironment && input.environment) {
16865
- const allowed = [
16866
- "CODEXHOST_CLI_PATH",
16867
- "CODEXHOST_CLI_NODE_PATH",
16868
- "CODEXHOST_RUNTIME_ENDPOINT",
16869
- "CODEXHOST_RUNTIME_TOKEN",
16870
- "CODEXHOST_THREAD_ID"
16871
- ];
16872
- const environment = Object.fromEntries(Object.entries(input.environment).filter(([key, value]) => allowed.includes(key) && value !== void 0));
16873
- if (Object.keys(environment).length)
16874
- safeInput.environment = environment;
16875
- }
16876
- connection = await this.#connect();
16877
- const result = parseHarnessResult(await connection.request("adapter.open", safeInput));
17069
+ let value;
17070
+ for (let attempt = 0; ; attempt += 1) {
17071
+ connection = await this.#connect();
17072
+ try {
17073
+ value = await connection.request("adapter.open", safeInput);
17074
+ break;
17075
+ } catch (error51) {
17076
+ if (attempt > 0 || !(error51 instanceof BrokerRetiringError || error51 instanceof BrokerRequestNotDeliveredError))
17077
+ throw error51;
17078
+ this.#connection = null;
17079
+ }
17080
+ }
17081
+ const result = parseHarnessResult(value);
16878
17082
  if (!result.ok)
16879
17083
  return result;
16880
17084
  const session = new BrokeredHarnessSession(connection, parseSessionMetadata(result.value), this.harnessId, safeInput, () => this.#connect(), () => {
@@ -16885,25 +17089,51 @@ var BrokeredHarnessAdapter = class {
16885
17089
  } catch (error51) {
16886
17090
  connection?.close();
16887
17091
  this.#connection = null;
16888
- return {
16889
- ok: false,
16890
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
16891
- };
17092
+ return { ok: false, error: this.#error(error51) };
16892
17093
  }
16893
17094
  }
16894
17095
  async close() {
16895
17096
  this.#closed = true;
17097
+ this.#credits = null;
16896
17098
  await Promise.allSettled([...this.#sessions].map((session) => session.close()));
16897
17099
  this.#sessions.clear();
16898
17100
  const connection = await this.#connection?.catch(() => null);
16899
17101
  await connection?.dispose();
16900
17102
  this.#connection = null;
16901
17103
  }
17104
+ #error(error51) {
17105
+ if (error51 instanceof HarnessNotInstalledError)
17106
+ return {
17107
+ code: "notInstalled",
17108
+ message: error51.message,
17109
+ retryable: false,
17110
+ stage: "harnessBroker"
17111
+ };
17112
+ return unavailable(describeBrokerFailure(error51, this.harnessId));
17113
+ }
17114
+ /**
17115
+ * Sends one adapter-level request. A broker that retired between requests refuses it
17116
+ * unprocessed, so it is retried once on a fresh broker. Idempotent reads also retry
17117
+ * once after a plain disconnect.
17118
+ */
17119
+ async #request(method, params, idempotent = false) {
17120
+ for (let attempt = 0; ; attempt += 1) {
17121
+ const connection = await this.#connect();
17122
+ try {
17123
+ return await connection.request(method, params);
17124
+ } catch (error51) {
17125
+ const retryable = error51 instanceof BrokerRetiringError || error51 instanceof BrokerRequestNotDeliveredError || idempotent && connection.closed;
17126
+ if (attempt > 0 || !retryable)
17127
+ throw error51;
17128
+ this.#connection = null;
17129
+ }
17130
+ }
17131
+ }
16902
17132
  #connect() {
16903
17133
  if (this.#closed)
16904
17134
  return Promise.reject(new Error("Aqua Harness broker adapter is closed"));
16905
17135
  if (!this.#connection) {
16906
- const pending = BrokerConnection.connect(this.#descriptorPath, this.harnessId).then((connection) => {
17136
+ const pending = this.#establish().then((connection) => {
16907
17137
  connection.onClose(() => {
16908
17138
  if (this.#connection === pending)
16909
17139
  this.#connection = null;
@@ -16918,13 +17148,35 @@ var BrokeredHarnessAdapter = class {
16918
17148
  }
16919
17149
  return this.#connection;
16920
17150
  }
17151
+ async #establish() {
17152
+ try {
17153
+ return await BrokerConnection.connect(this.#descriptorPath, this.harnessId);
17154
+ } catch (error51) {
17155
+ if (!(error51 instanceof BrokerNotRunningError) || !this.#startBroker)
17156
+ throw error51;
17157
+ }
17158
+ if (this.#isInstalled && !this.#isInstalled()) {
17159
+ throw new HarnessNotInstalledError(`${this.harnessId} is not installed on this Mac`);
17160
+ }
17161
+ const deadline = Date.now() + this.#startTimeoutMs;
17162
+ for (; ; ) {
17163
+ await this.#startBroker();
17164
+ try {
17165
+ return await BrokerConnection.connect(this.#descriptorPath, this.harnessId);
17166
+ } catch (error51) {
17167
+ if (!(error51 instanceof BrokerNotRunningError) || Date.now() >= deadline)
17168
+ throw error51;
17169
+ }
17170
+ await new Promise((resolve) => setTimeout(resolve, BROKER_START_POLL_MS));
17171
+ }
17172
+ }
16921
17173
  };
16922
17174
 
16923
17175
  // ../codebuddy/dist/codebuddy-adapter.js
16924
- import { stat as stat2 } from "node:fs/promises";
17176
+ import { stat as stat3 } from "node:fs/promises";
16925
17177
 
16926
17178
  // ../codebuddy/dist/acp-client.js
16927
- import { execFile, spawn } from "node:child_process";
17179
+ import { execFile as execFile2, spawn } from "node:child_process";
16928
17180
  import { Readable as Readable2, Writable } from "node:stream";
16929
17181
 
16930
17182
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -21644,7 +21896,7 @@ var CodeBuddyAcpClient = class {
21644
21896
  }
21645
21897
  const pid = this.#child.pid;
21646
21898
  if (pid && process.platform === "win32") {
21647
- await new Promise((resolve) => execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => resolve()));
21899
+ await new Promise((resolve) => execFile2("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => resolve()));
21648
21900
  } else if (pid) {
21649
21901
  try {
21650
21902
  process.kill(-pid, "SIGKILL");
@@ -21736,7 +21988,7 @@ function confirmedConfiguration(response, id, value, profile = CODEBUDDY_RUNTIME
21736
21988
 
21737
21989
  // ../codebuddy/dist/derivation.js
21738
21990
  import { randomUUID as randomUUID2 } from "node:crypto";
21739
- import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
21991
+ import { execFile as execFile3, spawn as spawn2 } from "node:child_process";
21740
21992
  import { lstat as lstat2, mkdir, readFile as readFile3, realpath as realpath4, unlink, writeFile } from "node:fs/promises";
21741
21993
  import path6 from "node:path";
21742
21994
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
@@ -21849,16 +22101,16 @@ var Diff = class {
21849
22101
  }
21850
22102
  }
21851
22103
  }
21852
- addToPath(path9, added, removed, oldPosInc, options) {
21853
- const last = path9.lastComponent;
22104
+ addToPath(path10, added, removed, oldPosInc, options) {
22105
+ const last = path10.lastComponent;
21854
22106
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21855
22107
  return {
21856
- oldPos: path9.oldPos + oldPosInc,
22108
+ oldPos: path10.oldPos + oldPosInc,
21857
22109
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21858
22110
  };
21859
22111
  } else {
21860
22112
  return {
21861
- oldPos: path9.oldPos + oldPosInc,
22113
+ oldPos: path10.oldPos + oldPosInc,
21862
22114
  lastComponent: { count: 1, added, removed, previousComponent: last }
21863
22115
  };
21864
22116
  }
@@ -23199,7 +23451,7 @@ async function copyCodeBuddySession(cwd, sourceId, targetId, environment, signal
23199
23451
  child.stderr.destroy();
23200
23452
  } else if (process.platform === "win32" && child.pid) {
23201
23453
  termination = new Promise((done) => {
23202
- execFile2("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => {
23454
+ execFile3("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => {
23203
23455
  child.kill();
23204
23456
  done();
23205
23457
  });
@@ -23741,6 +23993,345 @@ async function deriveCodeBuddySession(options) {
23741
23993
  }
23742
23994
  }
23743
23995
 
23996
+ // ../codebuddy/dist/session-import.js
23997
+ import { createReadStream } from "node:fs";
23998
+ import { opendir, readFile as readFile4, stat as stat2 } from "node:fs/promises";
23999
+ import path7 from "node:path";
24000
+ import { createInterface as createInterface2 } from "node:readline";
24001
+
24002
+ // ../../harness-adapter/dist/session-import.js
24003
+ import { lstat as lstat3 } from "node:fs/promises";
24004
+ var SessionImportChangedError = class extends Error {
24005
+ constructor(message = "Native Session changed during discovery; refresh and retry") {
24006
+ super(message);
24007
+ this.name = "SessionImportChangedError";
24008
+ }
24009
+ };
24010
+ function isMissingFileError(error51) {
24011
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
24012
+ }
24013
+ function sameFileFingerprint(left, right) {
24014
+ 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;
24015
+ }
24016
+ var STORAGE_ACCESS_ERRORS = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"]);
24017
+ function isStorageAccessError(error51) {
24018
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" && STORAGE_ACCESS_ERRORS.has(error51.code);
24019
+ }
24020
+ async function optionalLstat(file2) {
24021
+ try {
24022
+ return await lstat3(file2);
24023
+ } catch (error51) {
24024
+ if (isMissingFileError(error51))
24025
+ return null;
24026
+ throw error51;
24027
+ }
24028
+ }
24029
+ async function readStableFiles(files, read) {
24030
+ const before = await Promise.all(files.map(optionalLstat));
24031
+ const value = await read(before);
24032
+ const after = await Promise.all(files.map(optionalLstat));
24033
+ if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
24034
+ throw new SessionImportChangedError();
24035
+ return value;
24036
+ }
24037
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
24038
+ if (typeof value !== "string")
24039
+ return null;
24040
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
24041
+ if (!normalized)
24042
+ return null;
24043
+ if (normalized.length <= maxLength)
24044
+ return normalized;
24045
+ const characters = [...normalized];
24046
+ if (characters.length <= maxLength)
24047
+ return normalized;
24048
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
24049
+ }
24050
+ function sessionImportCandidate(input) {
24051
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
24052
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
24053
+ nativeSessionId: input.nativeSessionId,
24054
+ cwd: input.cwd,
24055
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
24056
+ updatedAt: Math.floor(time3),
24057
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
24058
+ running: typeof input.running === "boolean" ? input.running : null
24059
+ });
24060
+ return parsed.success ? parsed.data : null;
24061
+ }
24062
+ var SessionImportScope = class {
24063
+ #abort = new AbortController();
24064
+ #options;
24065
+ #pending = /* @__PURE__ */ new Set();
24066
+ constructor(options) {
24067
+ this.#options = options;
24068
+ }
24069
+ #closed() {
24070
+ return {
24071
+ ok: false,
24072
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
24073
+ };
24074
+ }
24075
+ read(operation) {
24076
+ const signal = this.#abort.signal;
24077
+ if (signal.aborted)
24078
+ return Promise.resolve(this.#closed());
24079
+ let started;
24080
+ try {
24081
+ started = operation(signal);
24082
+ } catch (error51) {
24083
+ started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
24084
+ }
24085
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
24086
+ ok: false,
24087
+ error: {
24088
+ code: "unavailable",
24089
+ message: this.#options.unavailableMessage,
24090
+ retryable: true
24091
+ }
24092
+ }).finally(() => this.#pending.delete(request));
24093
+ this.#pending.add(request);
24094
+ return request;
24095
+ }
24096
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
24097
+ async resolve(operation) {
24098
+ const result = await this.read(operation);
24099
+ if (!result.ok)
24100
+ return result;
24101
+ return result.value ? { ok: true, value: result.value } : {
24102
+ ok: false,
24103
+ error: {
24104
+ code: "sessionNotFound",
24105
+ message: this.#options.notFoundMessage,
24106
+ retryable: false
24107
+ }
24108
+ };
24109
+ }
24110
+ /** Idempotent. Resolves after every started read has settled. */
24111
+ async close() {
24112
+ this.#abort.abort();
24113
+ await Promise.allSettled(this.#pending);
24114
+ }
24115
+ };
24116
+
24117
+ // ../codebuddy/dist/session-import.js
24118
+ var SESSION_FILE = /^([A-Za-z0-9][A-Za-z0-9_-]{0,199})\.jsonl$/u;
24119
+ var MAX_HISTORY_BYTES = 64e6;
24120
+ var MAX_MARKER_BYTES = 64 * 1024;
24121
+ function processAlive(pid) {
24122
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
24123
+ return false;
24124
+ try {
24125
+ process.kill(pid, 0);
24126
+ return true;
24127
+ } catch (error51) {
24128
+ return record2(error51).code === "EPERM";
24129
+ }
24130
+ }
24131
+ function userText(row) {
24132
+ if (row.type !== "message" || row.role !== "user")
24133
+ return null;
24134
+ const { content } = row;
24135
+ if (typeof content === "string")
24136
+ return content;
24137
+ if (!Array.isArray(content))
24138
+ return "";
24139
+ return content.map((part) => record2(part)).filter((part) => typeof part.text === "string").map((part) => String(part.text)).join(" ");
24140
+ }
24141
+ async function readFacts(file2, signal) {
24142
+ const stream = createReadStream(file2, { encoding: "utf8", signal });
24143
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
24144
+ let cwd = null;
24145
+ let customTitle = null;
24146
+ let generatedTitle = null;
24147
+ let firstPrompt = null;
24148
+ let hasUser = false;
24149
+ let updatedAt = null;
24150
+ try {
24151
+ for await (const line of lines) {
24152
+ signal.throwIfAborted();
24153
+ if (!line.trim())
24154
+ continue;
24155
+ let parsed;
24156
+ try {
24157
+ parsed = JSON.parse(line);
24158
+ } catch {
24159
+ return null;
24160
+ }
24161
+ const row = record2(parsed);
24162
+ if (typeof row.cwd === "string" && path7.isAbsolute(row.cwd))
24163
+ cwd ??= row.cwd;
24164
+ if (typeof row.timestamp === "number" && Number.isFinite(row.timestamp))
24165
+ updatedAt = row.timestamp;
24166
+ if (row.type === "custom-title")
24167
+ customTitle = sessionImportTitle(row.customTitle);
24168
+ else if (row.type === "ai-title")
24169
+ generatedTitle = sessionImportTitle(row.aiTitle);
24170
+ else {
24171
+ const text2 = userText(row);
24172
+ if (text2 !== null) {
24173
+ hasUser = true;
24174
+ firstPrompt ??= sessionImportTitle(text2);
24175
+ }
24176
+ }
24177
+ }
24178
+ } finally {
24179
+ lines.close();
24180
+ stream.destroy();
24181
+ }
24182
+ if (!hasUser || !cwd)
24183
+ return null;
24184
+ return { cwd, title: customTitle ?? generatedTitle ?? firstPrompt, updatedAt };
24185
+ }
24186
+ var CodeBuddySessionImport = class {
24187
+ #environment;
24188
+ #profile;
24189
+ #scope;
24190
+ constructor(environment, profile = CODEBUDDY_RUNTIME_PROFILE) {
24191
+ this.#environment = { ...environment };
24192
+ this.#profile = profile;
24193
+ this.#scope = new SessionImportScope({
24194
+ closedMessage: `${profile.displayName} Session import is closed`,
24195
+ unavailableMessage: `${profile.displayName} sessions could not be read; close native clients, check storage access and retry`,
24196
+ notFoundMessage: `${profile.displayName} Session is no longer importable`
24197
+ });
24198
+ }
24199
+ listCandidates() {
24200
+ return this.#scope.read(async (signal) => {
24201
+ const active = await this.#activeSessions(signal);
24202
+ const candidates = [];
24203
+ for (const [nativeSessionId, files] of await this.#sessionFiles(signal)) {
24204
+ if (files.length !== 1 || !files[0])
24205
+ continue;
24206
+ try {
24207
+ const source = await this.#source(nativeSessionId, files[0], active, signal);
24208
+ if (source)
24209
+ candidates.push(source.candidate);
24210
+ } catch (error51) {
24211
+ if (!(error51 instanceof SessionImportChangedError))
24212
+ throw error51;
24213
+ }
24214
+ }
24215
+ return candidates;
24216
+ });
24217
+ }
24218
+ resolveCandidate(nativeSessionId) {
24219
+ return this.#scope.resolve(async (signal) => {
24220
+ const files = (await this.#sessionFiles(signal)).get(nativeSessionId);
24221
+ if (files?.length !== 1 || !files[0])
24222
+ return null;
24223
+ return this.#source(nativeSessionId, files[0], await this.#activeSessions(signal), signal);
24224
+ });
24225
+ }
24226
+ close() {
24227
+ return this.#scope.close();
24228
+ }
24229
+ #root() {
24230
+ return codeBuddyConfigRoot(this.#environment, this.#profile);
24231
+ }
24232
+ /** IDs a live native process registered in `<config>/sessions/<pid>.json`. */
24233
+ async #activeSessions(signal) {
24234
+ const active = /* @__PURE__ */ new Set();
24235
+ const directory = path7.join(this.#root(), "sessions");
24236
+ const markers = await opendir(directory).catch((error51) => {
24237
+ if (isMissingFileError(error51) || record2(error51).code === "ENOTDIR")
24238
+ return null;
24239
+ throw error51;
24240
+ });
24241
+ if (!markers)
24242
+ return active;
24243
+ for await (const marker of markers) {
24244
+ signal.throwIfAborted();
24245
+ if (!marker.isFile() || !marker.name.endsWith(".json"))
24246
+ continue;
24247
+ try {
24248
+ const file2 = path7.join(directory, marker.name);
24249
+ if ((await stat2(file2)).size > MAX_MARKER_BYTES)
24250
+ continue;
24251
+ const entry = record2(JSON.parse(await readFile4(file2, { encoding: "utf8", signal })));
24252
+ if (typeof entry.sessionId === "string" && processAlive(entry.pid))
24253
+ active.add(entry.sessionId);
24254
+ } catch (error51) {
24255
+ signal.throwIfAborted();
24256
+ if (isStorageAccessError(error51))
24257
+ throw error51;
24258
+ }
24259
+ }
24260
+ return active;
24261
+ }
24262
+ /** Session ID to every project file claiming it. Enumerated links are not followed. */
24263
+ async #sessionFiles(signal) {
24264
+ const root = path7.join(this.#root(), "projects");
24265
+ const found = /* @__PURE__ */ new Map();
24266
+ const info = await optionalLstat(root);
24267
+ if (!info)
24268
+ return found;
24269
+ if (!info.isDirectory())
24270
+ throw new Error(`${this.#profile.displayName} Session store is not a directory`);
24271
+ for await (const project of await opendir(root)) {
24272
+ signal.throwIfAborted();
24273
+ if (!project.isDirectory())
24274
+ continue;
24275
+ const projectDirectory = path7.join(root, project.name);
24276
+ const entries = await opendir(projectDirectory).catch((error51) => {
24277
+ if (isMissingFileError(error51))
24278
+ return null;
24279
+ throw error51;
24280
+ });
24281
+ if (!entries)
24282
+ continue;
24283
+ for await (const entry of entries) {
24284
+ signal.throwIfAborted();
24285
+ const nativeSessionId = entry.isFile() ? SESSION_FILE.exec(entry.name)?.[1] : void 0;
24286
+ if (!nativeSessionId)
24287
+ continue;
24288
+ const files = found.get(nativeSessionId) ?? [];
24289
+ files.push(path7.join(projectDirectory, entry.name));
24290
+ found.set(nativeSessionId, files);
24291
+ }
24292
+ }
24293
+ return found;
24294
+ }
24295
+ async #source(nativeSessionId, file2, active, signal) {
24296
+ signal.throwIfAborted();
24297
+ return readStableFiles([file2], async ([info]) => {
24298
+ if (!info?.isFile() || info.size === 0 || info.size > MAX_HISTORY_BYTES)
24299
+ return null;
24300
+ try {
24301
+ const facts = await readFacts(file2, signal);
24302
+ if (!facts)
24303
+ return null;
24304
+ const cwd = path7.resolve(facts.cwd);
24305
+ if (!(await stat2(cwd)).isDirectory())
24306
+ return null;
24307
+ const nativeRef = nativeSessionRefSchema.parse({
24308
+ harnessId: this.#profile.harnessId,
24309
+ nativeSessionId,
24310
+ formatVersion: 1
24311
+ });
24312
+ signal.throwIfAborted();
24313
+ const history = await codeBuddyNativeHistory(cwd, nativeRef, this.#environment, this.#profile);
24314
+ if (path7.resolve(history.file) !== path7.resolve(file2))
24315
+ return null;
24316
+ const candidate = sessionImportCandidate({
24317
+ nativeSessionId,
24318
+ cwd,
24319
+ title: facts.title,
24320
+ updatedAt: facts.updatedAt ?? info.mtimeMs,
24321
+ // A registered live process holds the Session. Absence is not proof of idleness.
24322
+ running: active.has(nativeSessionId) ? true : null
24323
+ });
24324
+ return candidate ? { candidate, nativeRef } : null;
24325
+ } catch (error51) {
24326
+ signal.throwIfAborted();
24327
+ if (isStorageAccessError(error51))
24328
+ throw error51;
24329
+ return null;
24330
+ }
24331
+ });
24332
+ }
24333
+ };
24334
+
23744
24335
  // ../codebuddy/dist/interactions.js
23745
24336
  var CodeBuddyInteractions = class {
23746
24337
  emit;
@@ -23884,7 +24475,7 @@ var CodeBuddyInteractions = class {
23884
24475
 
23885
24476
  // ../codebuddy/dist/subagent-history.js
23886
24477
  import { readdir as readdir2, realpath as realpath5 } from "node:fs/promises";
23887
- import path7 from "node:path";
24478
+ import path8 from "node:path";
23888
24479
  var equalPath2 = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
23889
24480
  var MAX_CACHED_CHILDREN = 16;
23890
24481
  var CodeBuddyChildObserver = class {
@@ -23948,8 +24539,8 @@ var CodeBuddyChildObserver = class {
23948
24539
  }
23949
24540
  async #directory() {
23950
24541
  const history = await this.#parentHistory();
23951
- const project = path7.dirname(await realpath5(history.file));
23952
- const expected = path7.join(project, this.parent.nativeSessionId, "subagents");
24542
+ const project = path8.dirname(await realpath5(history.file));
24543
+ const expected = path8.join(project, this.parent.nativeSessionId, "subagents");
23953
24544
  const actual = await realpath5(expected);
23954
24545
  this.#assertOpen();
23955
24546
  if (!equalPath2(actual, expected))
@@ -23959,7 +24550,7 @@ var CodeBuddyChildObserver = class {
23959
24550
  async #child(directory, childId) {
23960
24551
  if (!validCodeBuddyChildId(childId))
23961
24552
  throw new CodeBuddyError("invalidRequest", "Invalid native Subagent ID");
23962
- const file2 = path7.join(directory, `${childId}.jsonl`);
24553
+ const file2 = path8.join(directory, `${childId}.jsonl`);
23963
24554
  const before = await codeBuddyFileVersion(file2);
23964
24555
  if (!equalPath2(before.realFile, file2))
23965
24556
  throw new CodeBuddyError("invalidRequest", "Redirected Subagent transcript");
@@ -24672,6 +25263,7 @@ var CodeBuddyAdapter = class {
24672
25263
  harnessId;
24673
25264
  commandCatalog;
24674
25265
  liveCommandCatalog = true;
25266
+ sessionImport;
24675
25267
  subagents = {
24676
25268
  readSnapshot: async ({ parent, nativeSubagentId, cwd }) => {
24677
25269
  try {
@@ -24705,6 +25297,7 @@ var CodeBuddyAdapter = class {
24705
25297
  this.commandCatalog = commandCatalog2;
24706
25298
  }
24707
25299
  this.#environment = { ...options.environment ?? process.env };
25300
+ this.sessionImport = new CodeBuddySessionImport(this.#environment, this.#profile);
24708
25301
  this.#invocation = options.invocationFactory ?? codeBuddyInvocation;
24709
25302
  this.#factory = options.clientFactory ?? ((clientOptions) => new CodeBuddyAcpClient(clientOptions, void 0, this.#invocation));
24710
25303
  }
@@ -24724,7 +25317,7 @@ var CodeBuddyAdapter = class {
24724
25317
  try {
24725
25318
  if (this.#closed)
24726
25319
  throw new CodeBuddyError("invalidState", "Adapter is closed");
24727
- if (!(await stat2(cwd)).isDirectory())
25320
+ if (!(await stat3(cwd)).isDirectory())
24728
25321
  throw new CodeBuddyError("invalidRequest", "Working directory is not a directory");
24729
25322
  client2 = this.#factory({
24730
25323
  cwd,
@@ -24770,7 +25363,7 @@ var CodeBuddyAdapter = class {
24770
25363
  return failure("invalidRequest", "Unattended execution requires native fullAccess permissions", this.#profile);
24771
25364
  let session;
24772
25365
  try {
24773
- if (!(await stat2(input.cwd)).isDirectory())
25366
+ if (!(await stat3(input.cwd)).isDirectory())
24774
25367
  throw new CodeBuddyError("invalidRequest", "Working directory is not a directory");
24775
25368
  if (this.#closed)
24776
25369
  throw new CodeBuddyError("invalidState", "Adapter closed while opening Session");
@@ -24833,7 +25426,7 @@ var CodeBuddyAdapter = class {
24833
25426
  async close() {
24834
25427
  this.#closed = true;
24835
25428
  this.#abort.abort();
24836
- await Promise.allSettled([...this.#derivations]);
25429
+ await Promise.allSettled([this.sessionImport.close(), ...this.#derivations]);
24837
25430
  const results = await Promise.allSettled([...this.#sessions, ...this.#inspections].map((resource) => resource.close()));
24838
25431
  this.#sessions.clear();
24839
25432
  this.#inspections.clear();
@@ -25052,8 +25645,8 @@ var WORKBUDDY_RUNTIME_PROFILE = {
25052
25645
  };
25053
25646
 
25054
25647
  // dist/product-models.js
25055
- import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
25056
- import path8 from "node:path";
25648
+ import { readFile as readFile5, stat as stat4 } from "node:fs/promises";
25649
+ import path9 from "node:path";
25057
25650
  var MAX_PRODUCT_SNAPSHOT_BYTES = 8 * 1024 * 1024;
25058
25651
  var PRODUCT_CONFIG_PATH_ENV = "ACC_PRODUCT_CONFIG_PATH";
25059
25652
  var PRODUCT_CONFIG_INLINE_ENVS = [
@@ -25106,16 +25699,16 @@ function parseWorkBuddyProductModels(value) {
25106
25699
  return parsed;
25107
25700
  }
25108
25701
  async function readProductJson(file2) {
25109
- const metadata = await stat3(file2);
25702
+ const metadata = await stat4(file2);
25110
25703
  if (!metadata.isFile() || metadata.size <= 0 || metadata.size > MAX_PRODUCT_SNAPSHOT_BYTES)
25111
25704
  return;
25112
- return JSON.parse(await readFile4(file2, "utf8"));
25705
+ return JSON.parse(await readFile5(file2, "utf8"));
25113
25706
  }
25114
25707
  function bundledFallbackProductPath(invocation) {
25115
25708
  const cli = invocation.arguments[0];
25116
25709
  if (!cli || cli.startsWith("-"))
25117
25710
  return;
25118
- return path8.join(path8.dirname(path8.dirname(cli)), "product.json");
25711
+ return path9.join(path9.dirname(path9.dirname(cli)), "product.json");
25119
25712
  }
25120
25713
  async function loadWorkBuddyProductModels(environment) {
25121
25714
  const invocation = workBuddyInvocation(environment, true);
@@ -25218,14 +25811,27 @@ var WorkBuddyAdapter = class extends CodeBuddyAdapter {
25218
25811
 
25219
25812
  // dist/plugin.js
25220
25813
  function createHarnessAdapter(context) {
25221
- if (context.platform === "darwin" && context.managedRemoteHost)
25814
+ if (context.platform === "darwin" && context.managedRemoteHost) {
25815
+ const environment = {
25816
+ ...context.environment,
25817
+ ...context.launchCommand ? { CODEXHOST_WORKBUDDY_COMMAND: context.launchCommand } : {}
25818
+ };
25222
25819
  return new BrokeredHarnessAdapter({
25223
25820
  harnessId: "workbuddy",
25224
25821
  commandCatalog: WORKBUDDY_COMMAND_CATALOG,
25225
25822
  forwardDelegationEnvironment: true,
25226
25823
  environment: { ...context.environment },
25824
+ isInstalled: () => {
25825
+ try {
25826
+ workBuddyInvocation(environment, true);
25827
+ return true;
25828
+ } catch (error51) {
25829
+ return !(error51 instanceof CodeBuddyError && error51.code === "notInstalled");
25830
+ }
25831
+ },
25227
25832
  ...context.brokerDescriptorPath ? { descriptorPath: context.brokerDescriptorPath } : {}
25228
25833
  });
25834
+ }
25229
25835
  return new WorkBuddyAdapter({
25230
25836
  environment: {
25231
25837
  ...context.environment,