@liberseek/boft-cli-linux-x64 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.
@@ -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",
@@ -15616,6 +15624,80 @@ var updateStatusResultSchema = external_exports.strictObject({
15616
15624
  status: updateStatusSchema.nullable()
15617
15625
  });
15618
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
+
15619
15701
  // ../../shared-contracts/dist/index.js
15620
15702
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
15621
15703
 
@@ -15916,9 +15998,12 @@ var HARNESS_BROKER_MAX_FRAME_BYTES = 8 * 1024 * 1024;
15916
15998
  var HARNESS_BROKER_MAX_PENDING_REQUESTS = 32;
15917
15999
  var HARNESS_BROKER_REQUEST_TIMEOUT_MS = 15e3;
15918
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";
15919
16003
  var harnessBrokerMethodSchema = external_exports.enum([
15920
16004
  "adapter.inspect",
15921
16005
  "adapter.inspectAccount",
16006
+ "adapter.credits",
15922
16007
  "adapter.open",
15923
16008
  "adapter.sessionImport.list",
15924
16009
  "adapter.sessionImport.resolve",
@@ -16038,6 +16123,14 @@ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId
16038
16123
  return path.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
16039
16124
  return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
16040
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
+ }
16041
16134
 
16042
16135
  // ../../harness-broker/dist/validation.js
16043
16136
  var cwdSchema = external_exports.string().min(1).max(16384);
@@ -16364,10 +16457,55 @@ async function readDescriptor(descriptorPath) {
16364
16457
  try {
16365
16458
  process.kill(descriptor.ownerPid, 0);
16366
16459
  } catch {
16367
- throw new Error("Aqua Harness broker owner process is unavailable");
16460
+ throw new BrokerNotRunningError("its owner process has exited");
16368
16461
  }
16369
16462
  return descriptor;
16370
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
+ }
16371
16509
  var BrokerConnection = class _BrokerConnection {
16372
16510
  #onClose;
16373
16511
  onClose(callback) {
@@ -16391,21 +16529,31 @@ var BrokerConnection = class _BrokerConnection {
16391
16529
  socket.once("error", (error51) => this.#fail(error51));
16392
16530
  }
16393
16531
  static async connect(descriptorPath, harnessId) {
16394
- const descriptor = await readDescriptor(descriptorPath);
16395
- if (descriptor.harnessId !== harnessId)
16396
- throw new Error("Aqua broker belongs to another Harness");
16397
- const socket = net.createConnection(descriptor.socketPath);
16398
- await new Promise((resolve, reject) => {
16399
- const timeout = setTimeout(() => reject(new Error("Timed out connecting to Aqua Harness broker")), HARNESS_BROKER_REQUEST_TIMEOUT_MS);
16400
- socket.once("connect", () => {
16401
- clearTimeout(timeout);
16402
- resolve();
16403
- });
16404
- socket.once("error", (error51) => {
16405
- clearTimeout(timeout);
16406
- 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
+ });
16407
16551
  });
16408
- });
16552
+ socket = pending;
16553
+ } catch (error51) {
16554
+ connecting?.destroy();
16555
+ throw classifyConnectFailure(error51);
16556
+ }
16409
16557
  const connection = new _BrokerConnection(descriptor, socket);
16410
16558
  const hello = connection.#waitForHello();
16411
16559
  await writeBrokerFrame(socket, {
@@ -16458,15 +16606,24 @@ var BrokerConnection = class _BrokerConnection {
16458
16606
  }, HARNESS_BROKER_REQUEST_TIMEOUT_MS);
16459
16607
  this.#pending.set(id, { resolve, reject, timeout });
16460
16608
  });
16461
- await writeBrokerFrame(this.#socket, {
16462
- version: HARNESS_BROKER_PROTOCOL_VERSION,
16463
- generation: this.#descriptor.generation,
16464
- sequence: this.#inputSequence,
16465
- kind: "request",
16466
- id,
16467
- method,
16468
- params
16469
- });
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
+ }
16470
16627
  return response;
16471
16628
  }
16472
16629
  close() {
@@ -16510,6 +16667,8 @@ var BrokerConnection = class _BrokerConnection {
16510
16667
  this.#pending.delete(frame.id);
16511
16668
  if (frame.ok)
16512
16669
  pending.resolve(frame.value);
16670
+ else if (frame.error?.code === HARNESS_BROKER_RETIRING_ERROR_CODE)
16671
+ pending.reject(new BrokerRetiringError(frame.error.message));
16513
16672
  else
16514
16673
  pending.reject(new Error(frame.error?.message ?? "Broker request failed"));
16515
16674
  }
@@ -16735,18 +16894,20 @@ var BrokeredHarnessAdapter = class {
16735
16894
  harnessId;
16736
16895
  #descriptorPath;
16737
16896
  #forwardEnvironment;
16897
+ #isInstalled;
16898
+ #startBroker;
16899
+ #startTimeoutMs;
16738
16900
  #connection = null;
16739
16901
  #closed = false;
16740
16902
  #sessionImportListing = null;
16903
+ #credits = null;
16904
+ #creditsRefresh = null;
16741
16905
  subagents = {
16742
16906
  readSnapshot: async (input) => {
16743
16907
  try {
16744
- return parseHarnessResult(await (await this.#connect()).request("adapter.subagent.readSnapshot", input));
16908
+ return parseHarnessResult(await this.#request("adapter.subagent.readSnapshot", input));
16745
16909
  } catch (error51) {
16746
- return {
16747
- ok: false,
16748
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
16749
- };
16910
+ return { ok: false, error: this.#error(error51) };
16750
16911
  }
16751
16912
  }
16752
16913
  };
@@ -16836,12 +16997,39 @@ var BrokeredHarnessAdapter = class {
16836
16997
  if (input.liveCommandCatalog)
16837
16998
  this.liveCommandCatalog = true;
16838
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;
16839
17027
  }
16840
17028
  async inspectAccount() {
16841
17029
  if (this.#closed)
16842
17030
  return null;
16843
17031
  try {
16844
- const value = await (await this.#connect()).request("adapter.inspectAccount", {});
17032
+ const value = await this.#request("adapter.inspectAccount", {}, true);
16845
17033
  return harnessAccountSnapshotSchema.nullable().parse(value);
16846
17034
  } catch {
16847
17035
  return null;
@@ -16851,33 +17039,46 @@ var BrokeredHarnessAdapter = class {
16851
17039
  if (this.#closed)
16852
17040
  return failedInspection("Aqua Harness broker adapter is closed");
16853
17041
  try {
16854
- return harnessInspectionSchema.parse(await (await this.#connect()).request("adapter.inspect", input));
17042
+ return harnessInspectionSchema.parse(await this.#request("adapter.inspect", input, true));
16855
17043
  } catch (error51) {
16856
17044
  this.#connection = null;
16857
- 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));
16858
17048
  }
16859
17049
  }
16860
17050
  async open(input) {
16861
17051
  if (this.#closed)
16862
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
+ }
16863
17067
  let connection;
16864
17068
  try {
16865
- const safeInput = { ...input };
16866
- delete safeInput.environment;
16867
- if (this.#forwardEnvironment && input.environment) {
16868
- const allowed = [
16869
- "CODEXHOST_CLI_PATH",
16870
- "CODEXHOST_CLI_NODE_PATH",
16871
- "CODEXHOST_RUNTIME_ENDPOINT",
16872
- "CODEXHOST_RUNTIME_TOKEN",
16873
- "CODEXHOST_THREAD_ID"
16874
- ];
16875
- const environment = Object.fromEntries(Object.entries(input.environment).filter(([key, value]) => allowed.includes(key) && value !== void 0));
16876
- if (Object.keys(environment).length)
16877
- safeInput.environment = environment;
16878
- }
16879
- connection = await this.#connect();
16880
- 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);
16881
17082
  if (!result.ok)
16882
17083
  return result;
16883
17084
  const session = new BrokeredHarnessSession(connection, parseSessionMetadata(result.value), this.harnessId, safeInput, () => this.#connect(), () => {
@@ -16888,25 +17089,51 @@ var BrokeredHarnessAdapter = class {
16888
17089
  } catch (error51) {
16889
17090
  connection?.close();
16890
17091
  this.#connection = null;
16891
- return {
16892
- ok: false,
16893
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
16894
- };
17092
+ return { ok: false, error: this.#error(error51) };
16895
17093
  }
16896
17094
  }
16897
17095
  async close() {
16898
17096
  this.#closed = true;
17097
+ this.#credits = null;
16899
17098
  await Promise.allSettled([...this.#sessions].map((session) => session.close()));
16900
17099
  this.#sessions.clear();
16901
17100
  const connection = await this.#connection?.catch(() => null);
16902
17101
  await connection?.dispose();
16903
17102
  this.#connection = null;
16904
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
+ }
16905
17132
  #connect() {
16906
17133
  if (this.#closed)
16907
17134
  return Promise.reject(new Error("Aqua Harness broker adapter is closed"));
16908
17135
  if (!this.#connection) {
16909
- const pending = BrokerConnection.connect(this.#descriptorPath, this.harnessId).then((connection) => {
17136
+ const pending = this.#establish().then((connection) => {
16910
17137
  connection.onClose(() => {
16911
17138
  if (this.#connection === pending)
16912
17139
  this.#connection = null;
@@ -16921,13 +17148,35 @@ var BrokeredHarnessAdapter = class {
16921
17148
  }
16922
17149
  return this.#connection;
16923
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
+ }
16924
17173
  };
16925
17174
 
16926
17175
  // ../codebuddy/dist/codebuddy-adapter.js
16927
- import { stat as stat2 } from "node:fs/promises";
17176
+ import { stat as stat3 } from "node:fs/promises";
16928
17177
 
16929
17178
  // ../codebuddy/dist/acp-client.js
16930
- import { execFile, spawn } from "node:child_process";
17179
+ import { execFile as execFile2, spawn } from "node:child_process";
16931
17180
  import { Readable as Readable2, Writable } from "node:stream";
16932
17181
 
16933
17182
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -21647,7 +21896,7 @@ var CodeBuddyAcpClient = class {
21647
21896
  }
21648
21897
  const pid = this.#child.pid;
21649
21898
  if (pid && process.platform === "win32") {
21650
- 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()));
21651
21900
  } else if (pid) {
21652
21901
  try {
21653
21902
  process.kill(-pid, "SIGKILL");
@@ -21739,7 +21988,7 @@ function confirmedConfiguration(response, id, value, profile = CODEBUDDY_RUNTIME
21739
21988
 
21740
21989
  // ../codebuddy/dist/derivation.js
21741
21990
  import { randomUUID as randomUUID2 } from "node:crypto";
21742
- import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
21991
+ import { execFile as execFile3, spawn as spawn2 } from "node:child_process";
21743
21992
  import { lstat as lstat2, mkdir, readFile as readFile3, realpath as realpath4, unlink, writeFile } from "node:fs/promises";
21744
21993
  import path6 from "node:path";
21745
21994
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
@@ -21852,16 +22101,16 @@ var Diff = class {
21852
22101
  }
21853
22102
  }
21854
22103
  }
21855
- addToPath(path9, added, removed, oldPosInc, options) {
21856
- const last = path9.lastComponent;
22104
+ addToPath(path10, added, removed, oldPosInc, options) {
22105
+ const last = path10.lastComponent;
21857
22106
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21858
22107
  return {
21859
- oldPos: path9.oldPos + oldPosInc,
22108
+ oldPos: path10.oldPos + oldPosInc,
21860
22109
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21861
22110
  };
21862
22111
  } else {
21863
22112
  return {
21864
- oldPos: path9.oldPos + oldPosInc,
22113
+ oldPos: path10.oldPos + oldPosInc,
21865
22114
  lastComponent: { count: 1, added, removed, previousComponent: last }
21866
22115
  };
21867
22116
  }
@@ -23202,7 +23451,7 @@ async function copyCodeBuddySession(cwd, sourceId, targetId, environment, signal
23202
23451
  child.stderr.destroy();
23203
23452
  } else if (process.platform === "win32" && child.pid) {
23204
23453
  termination = new Promise((done) => {
23205
- 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 }, () => {
23206
23455
  child.kill();
23207
23456
  done();
23208
23457
  });
@@ -23744,6 +23993,345 @@ async function deriveCodeBuddySession(options) {
23744
23993
  }
23745
23994
  }
23746
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
+
23747
24335
  // ../codebuddy/dist/interactions.js
23748
24336
  var CodeBuddyInteractions = class {
23749
24337
  emit;
@@ -23887,7 +24475,7 @@ var CodeBuddyInteractions = class {
23887
24475
 
23888
24476
  // ../codebuddy/dist/subagent-history.js
23889
24477
  import { readdir as readdir2, realpath as realpath5 } from "node:fs/promises";
23890
- import path7 from "node:path";
24478
+ import path8 from "node:path";
23891
24479
  var equalPath2 = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
23892
24480
  var MAX_CACHED_CHILDREN = 16;
23893
24481
  var CodeBuddyChildObserver = class {
@@ -23951,8 +24539,8 @@ var CodeBuddyChildObserver = class {
23951
24539
  }
23952
24540
  async #directory() {
23953
24541
  const history = await this.#parentHistory();
23954
- const project = path7.dirname(await realpath5(history.file));
23955
- 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");
23956
24544
  const actual = await realpath5(expected);
23957
24545
  this.#assertOpen();
23958
24546
  if (!equalPath2(actual, expected))
@@ -23962,7 +24550,7 @@ var CodeBuddyChildObserver = class {
23962
24550
  async #child(directory, childId) {
23963
24551
  if (!validCodeBuddyChildId(childId))
23964
24552
  throw new CodeBuddyError("invalidRequest", "Invalid native Subagent ID");
23965
- const file2 = path7.join(directory, `${childId}.jsonl`);
24553
+ const file2 = path8.join(directory, `${childId}.jsonl`);
23966
24554
  const before = await codeBuddyFileVersion(file2);
23967
24555
  if (!equalPath2(before.realFile, file2))
23968
24556
  throw new CodeBuddyError("invalidRequest", "Redirected Subagent transcript");
@@ -24675,6 +25263,7 @@ var CodeBuddyAdapter = class {
24675
25263
  harnessId;
24676
25264
  commandCatalog;
24677
25265
  liveCommandCatalog = true;
25266
+ sessionImport;
24678
25267
  subagents = {
24679
25268
  readSnapshot: async ({ parent, nativeSubagentId, cwd }) => {
24680
25269
  try {
@@ -24708,6 +25297,7 @@ var CodeBuddyAdapter = class {
24708
25297
  this.commandCatalog = commandCatalog2;
24709
25298
  }
24710
25299
  this.#environment = { ...options.environment ?? process.env };
25300
+ this.sessionImport = new CodeBuddySessionImport(this.#environment, this.#profile);
24711
25301
  this.#invocation = options.invocationFactory ?? codeBuddyInvocation;
24712
25302
  this.#factory = options.clientFactory ?? ((clientOptions) => new CodeBuddyAcpClient(clientOptions, void 0, this.#invocation));
24713
25303
  }
@@ -24727,7 +25317,7 @@ var CodeBuddyAdapter = class {
24727
25317
  try {
24728
25318
  if (this.#closed)
24729
25319
  throw new CodeBuddyError("invalidState", "Adapter is closed");
24730
- if (!(await stat2(cwd)).isDirectory())
25320
+ if (!(await stat3(cwd)).isDirectory())
24731
25321
  throw new CodeBuddyError("invalidRequest", "Working directory is not a directory");
24732
25322
  client2 = this.#factory({
24733
25323
  cwd,
@@ -24773,7 +25363,7 @@ var CodeBuddyAdapter = class {
24773
25363
  return failure("invalidRequest", "Unattended execution requires native fullAccess permissions", this.#profile);
24774
25364
  let session;
24775
25365
  try {
24776
- if (!(await stat2(input.cwd)).isDirectory())
25366
+ if (!(await stat3(input.cwd)).isDirectory())
24777
25367
  throw new CodeBuddyError("invalidRequest", "Working directory is not a directory");
24778
25368
  if (this.#closed)
24779
25369
  throw new CodeBuddyError("invalidState", "Adapter closed while opening Session");
@@ -24836,7 +25426,7 @@ var CodeBuddyAdapter = class {
24836
25426
  async close() {
24837
25427
  this.#closed = true;
24838
25428
  this.#abort.abort();
24839
- await Promise.allSettled([...this.#derivations]);
25429
+ await Promise.allSettled([this.sessionImport.close(), ...this.#derivations]);
24840
25430
  const results = await Promise.allSettled([...this.#sessions, ...this.#inspections].map((resource) => resource.close()));
24841
25431
  this.#sessions.clear();
24842
25432
  this.#inspections.clear();
@@ -25055,8 +25645,8 @@ var WORKBUDDY_RUNTIME_PROFILE = {
25055
25645
  };
25056
25646
 
25057
25647
  // dist/product-models.js
25058
- import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
25059
- import path8 from "node:path";
25648
+ import { readFile as readFile5, stat as stat4 } from "node:fs/promises";
25649
+ import path9 from "node:path";
25060
25650
  var MAX_PRODUCT_SNAPSHOT_BYTES = 8 * 1024 * 1024;
25061
25651
  var PRODUCT_CONFIG_PATH_ENV = "ACC_PRODUCT_CONFIG_PATH";
25062
25652
  var PRODUCT_CONFIG_INLINE_ENVS = [
@@ -25109,16 +25699,16 @@ function parseWorkBuddyProductModels(value) {
25109
25699
  return parsed;
25110
25700
  }
25111
25701
  async function readProductJson(file2) {
25112
- const metadata = await stat3(file2);
25702
+ const metadata = await stat4(file2);
25113
25703
  if (!metadata.isFile() || metadata.size <= 0 || metadata.size > MAX_PRODUCT_SNAPSHOT_BYTES)
25114
25704
  return;
25115
- return JSON.parse(await readFile4(file2, "utf8"));
25705
+ return JSON.parse(await readFile5(file2, "utf8"));
25116
25706
  }
25117
25707
  function bundledFallbackProductPath(invocation) {
25118
25708
  const cli = invocation.arguments[0];
25119
25709
  if (!cli || cli.startsWith("-"))
25120
25710
  return;
25121
- return path8.join(path8.dirname(path8.dirname(cli)), "product.json");
25711
+ return path9.join(path9.dirname(path9.dirname(cli)), "product.json");
25122
25712
  }
25123
25713
  async function loadWorkBuddyProductModels(environment) {
25124
25714
  const invocation = workBuddyInvocation(environment, true);
@@ -25221,14 +25811,27 @@ var WorkBuddyAdapter = class extends CodeBuddyAdapter {
25221
25811
 
25222
25812
  // dist/plugin.js
25223
25813
  function createHarnessAdapter(context) {
25224
- 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
+ };
25225
25819
  return new BrokeredHarnessAdapter({
25226
25820
  harnessId: "workbuddy",
25227
25821
  commandCatalog: WORKBUDDY_COMMAND_CATALOG,
25228
25822
  forwardDelegationEnvironment: true,
25229
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
+ },
25230
25832
  ...context.brokerDescriptorPath ? { descriptorPath: context.brokerDescriptorPath } : {}
25231
25833
  });
25834
+ }
25232
25835
  return new WorkBuddyAdapter({
25233
25836
  environment: {
25234
25837
  ...context.environment,