@codexhost/cli-darwin-x64 0.3.4 → 0.3.5

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.
@@ -3710,7 +3710,7 @@ var require_websocket_server = __commonJS({
3710
3710
  });
3711
3711
 
3712
3712
  // packages/host-runtime/src/run-host-runtime.ts
3713
- import path28 from "node:path";
3713
+ import path29 from "node:path";
3714
3714
  import { fileURLToPath } from "node:url";
3715
3715
 
3716
3716
  // packages/update-manager/dist/distribution.js
@@ -3790,7 +3790,14 @@ function parseDistributionMetadata(value) {
3790
3790
  if (Object.keys(metadata).some((key) => !allowed2.includes(key))) {
3791
3791
  throw new Error("distribution metadata contains unknown fields");
3792
3792
  }
3793
- if (metadata.schemaVersion !== 1 || metadata.distribution !== "npm" && metadata.distribution !== "installer" || !["macos-arm64", "macos-x64", "windows-x64", "windows-arm64", "linux-x64"].includes(String(metadata.target)) || typeof metadata.version !== "string") {
3793
+ if (metadata.schemaVersion !== 1 || metadata.distribution !== "npm" && metadata.distribution !== "installer" || ![
3794
+ "macos-arm64",
3795
+ "macos-x64",
3796
+ "windows-x64",
3797
+ "windows-arm64",
3798
+ "linux-x64",
3799
+ "linux-arm64"
3800
+ ].includes(String(metadata.target)) || typeof metadata.version !== "string") {
3794
3801
  throw new Error("distribution metadata is invalid");
3795
3802
  }
3796
3803
  return {
@@ -3823,6 +3830,8 @@ function expectedTarget(platform, architecture) {
3823
3830
  return "windows-x64";
3824
3831
  if (platform === "linux" && architecture === "x64")
3825
3832
  return "linux-x64";
3833
+ if (platform === "linux" && architecture === "arm64")
3834
+ return "linux-arm64";
3826
3835
  throw new Error(`unsupported update host ${platform}/${architecture}`);
3827
3836
  }
3828
3837
  function defaultUpdateStateDirectory(platform = process.platform, environment = process.env) {
@@ -4078,7 +4087,7 @@ async function discoverLatestUpdateStatus(stateDirectory) {
4078
4087
  return null;
4079
4088
  throw error54;
4080
4089
  }
4081
- const candidates2 = [];
4090
+ const candidates = [];
4082
4091
  for (const entry of entries) {
4083
4092
  if (!entry.isDirectory() || entry.isSymbolicLink() || !entry.name.startsWith("update-"))
4084
4093
  continue;
@@ -4086,15 +4095,15 @@ async function discoverLatestUpdateStatus(stateDirectory) {
4086
4095
  if (!await regularFile(statusPath))
4087
4096
  continue;
4088
4097
  try {
4089
- candidates2.push({
4098
+ candidates.push({
4090
4099
  statusPath,
4091
4100
  status: parseUpdateStatus(JSON.parse(await readFile2(statusPath, "utf8")))
4092
4101
  });
4093
4102
  } catch {
4094
4103
  }
4095
4104
  }
4096
- candidates2.sort((left, right) => right.status.updatedAt - left.status.updatedAt);
4097
- return candidates2[0] ?? null;
4105
+ candidates.sort((left, right) => right.status.updatedAt - left.status.updatedAt);
4106
+ return candidates[0] ?? null;
4098
4107
  }
4099
4108
  async function cleanupTerminalUpdateState(stateDirectory, options = {}) {
4100
4109
  const now = Math.floor((options.now ?? Date.now()) / 1e3);
@@ -5319,10 +5328,10 @@ function mergeDefs(...defs) {
5319
5328
  function cloneDef(schema) {
5320
5329
  return mergeDefs(schema._zod.def);
5321
5330
  }
5322
- function getElementAtPath(obj, path31) {
5323
- if (!path31)
5331
+ function getElementAtPath(obj, path32) {
5332
+ if (!path32)
5324
5333
  return obj;
5325
- return path31.reduce((acc, key) => acc?.[key], obj);
5334
+ return path32.reduce((acc, key) => acc?.[key], obj);
5326
5335
  }
5327
5336
  function promiseAllObject(promisesObj) {
5328
5337
  const keys = Object.keys(promisesObj);
@@ -5731,11 +5740,11 @@ function explicitlyAborted(x2, startIndex = 0) {
5731
5740
  }
5732
5741
  return false;
5733
5742
  }
5734
- function prefixIssues(path31, issues) {
5743
+ function prefixIssues(path32, issues) {
5735
5744
  return issues.map((iss) => {
5736
5745
  var _a4;
5737
5746
  (_a4 = iss).path ?? (_a4.path = []);
5738
- iss.path.unshift(path31);
5747
+ iss.path.unshift(path32);
5739
5748
  return iss;
5740
5749
  });
5741
5750
  }
@@ -5882,16 +5891,16 @@ function flattenError(error54, mapper = (issue2) => issue2.message) {
5882
5891
  }
5883
5892
  function formatError(error54, mapper = (issue2) => issue2.message) {
5884
5893
  const fieldErrors = { _errors: [] };
5885
- const processError = (error55, path31 = []) => {
5894
+ const processError = (error55, path32 = []) => {
5886
5895
  for (const issue2 of error55.issues) {
5887
5896
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5888
- issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
5897
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
5889
5898
  } else if (issue2.code === "invalid_key") {
5890
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5899
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5891
5900
  } else if (issue2.code === "invalid_element") {
5892
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5901
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5893
5902
  } else {
5894
- const fullpath = [...path31, ...issue2.path];
5903
+ const fullpath = [...path32, ...issue2.path];
5895
5904
  if (fullpath.length === 0) {
5896
5905
  fieldErrors._errors.push(mapper(issue2));
5897
5906
  } else {
@@ -5918,17 +5927,17 @@ function formatError(error54, mapper = (issue2) => issue2.message) {
5918
5927
  }
5919
5928
  function treeifyError(error54, mapper = (issue2) => issue2.message) {
5920
5929
  const result = { errors: [] };
5921
- const processError = (error55, path31 = []) => {
5930
+ const processError = (error55, path32 = []) => {
5922
5931
  var _a4, _b2;
5923
5932
  for (const issue2 of error55.issues) {
5924
5933
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5925
- issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
5934
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
5926
5935
  } else if (issue2.code === "invalid_key") {
5927
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5936
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5928
5937
  } else if (issue2.code === "invalid_element") {
5929
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5938
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5930
5939
  } else {
5931
- const fullpath = [...path31, ...issue2.path];
5940
+ const fullpath = [...path32, ...issue2.path];
5932
5941
  if (fullpath.length === 0) {
5933
5942
  result.errors.push(mapper(issue2));
5934
5943
  continue;
@@ -5960,8 +5969,8 @@ function treeifyError(error54, mapper = (issue2) => issue2.message) {
5960
5969
  }
5961
5970
  function toDotPath(_path) {
5962
5971
  const segs = [];
5963
- const path31 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5964
- for (const seg of path31) {
5972
+ const path32 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5973
+ for (const seg of path32) {
5965
5974
  if (typeof seg === "number")
5966
5975
  segs.push(`[${seg}]`);
5967
5976
  else if (typeof seg === "symbol")
@@ -18653,13 +18662,13 @@ function resolveRef(ref, ctx) {
18653
18662
  if (!ref.startsWith("#")) {
18654
18663
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
18655
18664
  }
18656
- const path31 = ref.slice(1).split("/").filter(Boolean);
18657
- if (path31.length === 0) {
18665
+ const path32 = ref.slice(1).split("/").filter(Boolean);
18666
+ if (path32.length === 0) {
18658
18667
  return ctx.rootSchema;
18659
18668
  }
18660
18669
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
18661
- if (path31[0] === defsKey) {
18662
- const key = path31[1];
18670
+ if (path32[0] === defsKey) {
18671
+ const key = path32[1];
18663
18672
  if (!key || !ctx.defs[key]) {
18664
18673
  throw new Error(`Reference not found: ${ref}`);
18665
18674
  }
@@ -19270,7 +19279,8 @@ var accountCreditsSnapshotSchema = external_exports.object({
19270
19279
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional()
19271
19280
  }).strict();
19272
19281
  var threadUsageInspectionParamsSchema = external_exports.object({
19273
- threadId: hostThreadIdSchema
19282
+ threadId: hostThreadIdSchema,
19283
+ refresh: external_exports.literal("exact").optional()
19274
19284
  }).strict();
19275
19285
  var threadUsageInspectionSchema = external_exports.object({
19276
19286
  threadId: hostThreadIdSchema,
@@ -19874,7 +19884,7 @@ var packageMetadata = {
19874
19884
 
19875
19885
  // packages/adapters/claude-code/dist/claude-code-adapter.js
19876
19886
  import { randomUUID as randomUUID2 } from "node:crypto";
19877
- import path8 from "node:path";
19887
+ import path11 from "node:path";
19878
19888
 
19879
19889
  // node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs
19880
19890
  import { createRequire as DW } from "node:module";
@@ -23779,8 +23789,8 @@ var qU = v(function(BU) {
23779
23789
  BU._globalThis = void 0;
23780
23790
  BU._globalThis = typeof globalThis === "object" ? globalThis : global;
23781
23791
  });
23782
- var GU = v(function(os9) {
23783
- var Axe = os9 && os9.__createBinding || (Object.create ? function(e, t, r, n) {
23792
+ var GU = v(function(os6) {
23793
+ var Axe = os6 && os6.__createBinding || (Object.create ? function(e, t, r, n) {
23784
23794
  if (n === void 0) n = r;
23785
23795
  Object.defineProperty(e, n, { enumerable: true, get: function() {
23786
23796
  return t[r];
@@ -23788,11 +23798,11 @@ var GU = v(function(os9) {
23788
23798
  } : function(e, t, r, n) {
23789
23799
  if (n === void 0) n = r;
23790
23800
  e[n] = t[r];
23791
- }), kxe = os9 && os9.__exportStar || function(e, t) {
23801
+ }), kxe = os6 && os6.__exportStar || function(e, t) {
23792
23802
  for (var r in e) if (r !== "default" && !Object.prototype.hasOwnProperty.call(t, r)) Axe(t, e, r);
23793
23803
  };
23794
- Object.defineProperty(os9, "__esModule", { value: true });
23795
- kxe(qU(), os9);
23804
+ Object.defineProperty(os6, "__esModule", { value: true });
23805
+ kxe(qU(), os6);
23796
23806
  });
23797
23807
  var WU = v(function(is) {
23798
23808
  var Oxe = is && is.__createBinding || (Object.create ? function(e, t, r, n) {
@@ -25735,7 +25745,7 @@ var sd = v(function(iB) {
25735
25745
  if (o.$async) r.throw(Ae._`new ${e.ValidationError}(${t})`);
25736
25746
  else r.assign(Ae._`${n}.errors`, t), r.return(false);
25737
25747
  }
25738
- var fs3 = { keyword: new Ae.Name("keyword"), schemaPath: new Ae.Name("schemaPath"), params: new Ae.Name("params"), propertyName: new Ae.Name("propertyName"), message: new Ae.Name("message"), schema: new Ae.Name("schema"), parentSchema: new Ae.Name("parentSchema") };
25748
+ var fs2 = { keyword: new Ae.Name("keyword"), schemaPath: new Ae.Name("schemaPath"), params: new Ae.Name("params"), propertyName: new Ae.Name("propertyName"), message: new Ae.Name("message"), schema: new Ae.Name("schema"), parentSchema: new Ae.Name("parentSchema") };
25739
25749
  function oB(e, t, r) {
25740
25750
  let { createErrors: n } = e.it;
25741
25751
  if (n === false) return Ae._`{}`;
@@ -25752,13 +25762,13 @@ var sd = v(function(iB) {
25752
25762
  function XAe({ keyword: e, it: { errSchemaPath: t } }, { schemaPath: r, parentSchema: n }) {
25753
25763
  let o = n ? t : Ae.str`${t}/${e}`;
25754
25764
  if (r) o = Ae.str`${o}${(0, H_.getErrorPath)(r, H_.Type.Str)}`;
25755
- return [fs3.schemaPath, o];
25765
+ return [fs2.schemaPath, o];
25756
25766
  }
25757
25767
  function QAe(e, { params: t, message: r }, n) {
25758
25768
  let { keyword: o, data: i, schemaValue: s, it: a } = e, { opts: c, propertyName: u, topSchemaRef: d, schemaPath: f } = a;
25759
- if (n.push([fs3.keyword, o], [fs3.params, typeof t == "function" ? t(e) : t || Ae._`{}`]), c.messages) n.push([fs3.message, typeof r == "function" ? r(e) : r]);
25760
- if (c.verbose) n.push([fs3.schema, s], [fs3.parentSchema, Ae._`${d}${f}`], [rr.default.data, i]);
25761
- if (u) n.push([fs3.propertyName, u]);
25769
+ if (n.push([fs2.keyword, o], [fs2.params, typeof t == "function" ? t(e) : t || Ae._`{}`]), c.messages) n.push([fs2.message, typeof r == "function" ? r(e) : r]);
25770
+ if (c.verbose) n.push([fs2.schema, s], [fs2.parentSchema, Ae._`${d}${f}`], [rr.default.data, i]);
25771
+ if (u) n.push([fs2.propertyName, u]);
25762
25772
  }
25763
25773
  });
25764
25774
  var uB = v(function(cB) {
@@ -45566,88 +45576,76 @@ var ClaudeBackgroundOccupancy = class {
45566
45576
  };
45567
45577
 
45568
45578
  // packages/adapters/claude-code/dist/command.js
45579
+ import path7 from "node:path";
45580
+
45581
+ // packages/harness-discovery/dist/environment.js
45569
45582
  import fs from "node:fs";
45570
- import os from "node:os";
45571
45583
  import path4 from "node:path";
45572
- var ClaudeCodeExecutableError = class extends Error {
45573
- code = "CLAUDE_NOT_FOUND";
45574
- };
45575
- function pathValue(environment) {
45576
- const key = Object.keys(environment).find((name) => name.toLowerCase() === "path");
45577
- return key ? environment[key] ?? "" : "";
45584
+ function targetPath(platform) {
45585
+ return platform === "win32" ? path4.win32 : path4.posix;
45578
45586
  }
45579
- function candidates(command, platform, environment) {
45580
- if (path4.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
45581
- return [command];
45587
+ function environmentValue(environment, name) {
45588
+ const lowered = name.toLowerCase();
45589
+ for (const [key, value] of Object.entries(environment)) {
45590
+ if (key.toLowerCase() === lowered)
45591
+ return value;
45582
45592
  }
45583
- const delimiter = platform === "win32" ? ";" : ":";
45584
- const extensions = platform === "win32" && path4.extname(command) === "" ? (environment.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";") : [""];
45585
- return pathValue(environment).split(delimiter).filter(Boolean).flatMap((directory) => extensions.map((extension2) => path4.join(directory, command + extension2)));
45593
+ return void 0;
45594
+ }
45595
+ function pathDelimiter(platform) {
45596
+ return platform === "win32" ? ";" : ":";
45586
45597
  }
45587
- function isExecutable(candidate, platform) {
45598
+ function pathDirectories(environment, platform) {
45599
+ return (environmentValue(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
45600
+ }
45601
+ function executableExtensions(command, platform, environment) {
45602
+ if (platform !== "win32")
45603
+ return [""];
45604
+ if (targetPath(platform).extname(command) !== "")
45605
+ return [""];
45606
+ return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean);
45607
+ }
45608
+ function isExecutableFile(filePath, platform) {
45588
45609
  try {
45589
- fs.accessSync(candidate, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
45590
- return fs.statSync(candidate).isFile();
45610
+ fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
45611
+ return fs.statSync(filePath).isFile();
45591
45612
  } catch {
45592
45613
  return false;
45593
45614
  }
45594
45615
  }
45595
- function claudeNpmNativeExecutable(npmDirectory) {
45596
- return path4.join(npmDirectory, "node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe");
45597
- }
45598
- function runnableCandidate(candidate, platform) {
45599
- if (platform === "win32" && path4.basename(candidate).toLowerCase() === "claude.cmd") {
45600
- const nativeExecutable = claudeNpmNativeExecutable(path4.dirname(candidate));
45601
- return isExecutable(nativeExecutable, platform) ? nativeExecutable : void 0;
45602
- }
45603
- return candidate;
45604
- }
45605
- function nvmCandidates(homeDirectory) {
45606
- const versionsDirectory = path4.join(homeDirectory, ".nvm", "versions", "node");
45616
+ function subdirectoryNames(directory) {
45607
45617
  try {
45608
- return fs.readdirSync(versionsDirectory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((left, right) => right.localeCompare(left, void 0, { numeric: true })).map((version2) => path4.join(versionsDirectory, version2, "bin", "claude"));
45618
+ return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
45609
45619
  } catch {
45610
45620
  return [];
45611
45621
  }
45612
45622
  }
45613
- function userInstallCandidates(platform, environment, homeDirectory) {
45614
- if (platform === "win32") {
45615
- const appData = environment.APPDATA ?? path4.join(homeDirectory, "AppData", "Roaming");
45616
- return [
45617
- claudeNpmNativeExecutable(path4.join(appData, "npm")),
45618
- path4.join(appData, "npm", "claude.cmd"),
45619
- path4.join(homeDirectory, ".local", "bin", "claude.exe"),
45620
- path4.join(homeDirectory, ".local", "bin", "claude.cmd")
45621
- ];
45622
- }
45623
- return [
45624
- path4.join(homeDirectory, ".npm-global", "bin", "claude"),
45625
- path4.join(homeDirectory, ".local", "bin", "claude"),
45626
- path4.join(homeDirectory, ".claude", "local", "claude"),
45627
- ...nvmCandidates(homeDirectory),
45628
- "/opt/homebrew/bin/claude",
45629
- "/usr/local/bin/claude"
45630
- ];
45623
+ function newestFirst(names) {
45624
+ return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
45631
45625
  }
45632
- function resolveClaudeCodeExecutable(input = {}) {
45633
- const environment = input.environment ?? process.env;
45634
- const platform = input.platform ?? process.platform;
45635
- const configuredCommand = input.command ?? environment.CODEXHOST_CLAUDE_COMMAND;
45636
- const command = configuredCommand ?? "claude";
45637
- const homeDirectory = input.homeDirectory ?? environment.HOME ?? environment.USERPROFILE ?? os.homedir();
45638
- const resolutionCandidates = [
45639
- ...candidates(command, platform, environment),
45640
- ...configuredCommand ? [] : userInstallCandidates(platform, environment, homeDirectory)
45641
- ];
45642
- const executable2 = resolutionCandidates.map((candidate) => runnableCandidate(candidate, platform)).find((candidate) => candidate !== void 0 && isExecutable(candidate, platform));
45643
- if (!executable2)
45644
- throw new ClaudeCodeExecutableError("Claude Code is not installed");
45645
- return path4.resolve(executable2);
45626
+
45627
+ // packages/harness-discovery/dist/invocation.js
45628
+ import path5 from "node:path";
45629
+ function commandInvocation(command, arguments_2, environment, platform = process.platform) {
45630
+ const extension2 = path5.win32.extname(command).toLowerCase();
45631
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
45632
+ return { command, arguments: [...arguments_2], windowsVerbatimArguments: false };
45633
+ }
45634
+ const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
45635
+ const commandLine = [command, ...arguments_2].map(quote).join(" ");
45636
+ return {
45637
+ command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
45638
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
45639
+ windowsVerbatimArguments: true
45640
+ };
45646
45641
  }
45642
+
45643
+ // packages/harness-discovery/dist/node-runtime.js
45644
+ import path6 from "node:path";
45647
45645
  function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
45648
45646
  const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
45649
45647
  const delimiter = platform === "win32" ? ";" : ":";
45650
- const runtimeDirectory = path4.dirname(runtimeExecutable);
45648
+ const runtimeDirectory = path6.dirname(runtimeExecutable);
45651
45649
  const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
45652
45650
  const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
45653
45651
  if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
@@ -45656,8 +45654,220 @@ function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath
45656
45654
  return { ...environment, [pathKey]: directories.join(delimiter) };
45657
45655
  }
45658
45656
 
45657
+ // packages/harness-discovery/dist/resolve.js
45658
+ import os from "node:os";
45659
+
45660
+ // packages/harness-discovery/dist/version-managers.js
45661
+ function versionManagerBinaryDirectories(context) {
45662
+ const { platform, environment, home } = context;
45663
+ const list = context.subdirectories ?? subdirectoryNames;
45664
+ const pathFlavor = targetPath(platform);
45665
+ const value = (name) => environmentValue(environment, name);
45666
+ const directories = [];
45667
+ const versioned = (root, ...tail) => {
45668
+ for (const version2 of newestFirst(list(root))) {
45669
+ directories.push(pathFlavor.join(root, version2, ...tail));
45670
+ }
45671
+ };
45672
+ if (platform === "win32") {
45673
+ const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
45674
+ const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
45675
+ versioned(pathFlavor.join(appData, "nvm"));
45676
+ versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
45677
+ directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
45678
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
45679
+ const pnpmHome2 = value("PNPM_HOME");
45680
+ if (pnpmHome2)
45681
+ directories.push(pnpmHome2);
45682
+ directories.push(pathFlavor.join(localAppData, "pnpm"));
45683
+ return directories;
45684
+ }
45685
+ versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
45686
+ const fnmRoots = [
45687
+ value("FNM_DIR"),
45688
+ pathFlavor.join(home, ".local", "share", "fnm"),
45689
+ pathFlavor.join(home, "Library", "Application Support", "fnm")
45690
+ ].filter((root) => root !== void 0);
45691
+ for (const root of fnmRoots) {
45692
+ versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
45693
+ }
45694
+ const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
45695
+ versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
45696
+ directories.push(pathFlavor.join(voltaHome, "bin"));
45697
+ const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
45698
+ versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
45699
+ directories.push(pathFlavor.join(asdfHome, "shims"));
45700
+ const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
45701
+ versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
45702
+ directories.push(pathFlavor.join(nodenvHome, "shims"));
45703
+ versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
45704
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
45705
+ const pnpmHome = value("PNPM_HOME");
45706
+ if (pnpmHome)
45707
+ directories.push(pnpmHome);
45708
+ directories.push(pathFlavor.join(home, "Library", "pnpm"));
45709
+ directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
45710
+ for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
45711
+ for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
45712
+ directories.push(pathFlavor.join(prefix, formula, "bin"));
45713
+ }
45714
+ }
45715
+ return directories;
45716
+ }
45717
+
45718
+ // packages/harness-discovery/dist/resolve.js
45719
+ var VERSION_MANAGER_ROOTS = "<version-managers>";
45720
+ function installRootExtensions(platform) {
45721
+ return platform === "win32" ? [".exe", ".cmd"] : [""];
45722
+ }
45723
+ function resolveHomeDirectory(input) {
45724
+ return input.homeDirectory ?? environmentValue(input.environment, "HOME") ?? environmentValue(input.environment, "USERPROFILE") ?? os.homedir();
45725
+ }
45726
+ function templateVariables(environment, platform, home) {
45727
+ const pathFlavor = targetPath(platform);
45728
+ return {
45729
+ HOME: home,
45730
+ USERPROFILE: home,
45731
+ APPDATA: environmentValue(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
45732
+ LOCALAPPDATA: environmentValue(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
45733
+ };
45734
+ }
45735
+ function joinTemplate(platform, value) {
45736
+ const pathFlavor = targetPath(platform);
45737
+ const segments = value.split("/");
45738
+ const head = segments[0] ?? "";
45739
+ const tail = segments.slice(1);
45740
+ if (head === "")
45741
+ return pathFlavor.join(pathFlavor.sep, ...tail);
45742
+ return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
45743
+ }
45744
+ function expandInstallRoot(template, environment, platform, home) {
45745
+ const variables = templateVariables(environment, platform, home);
45746
+ let unresolved = false;
45747
+ const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
45748
+ const value = variables[name] ?? environmentValue(environment, name);
45749
+ if (value === void 0 || value === "") {
45750
+ unresolved = true;
45751
+ return "";
45752
+ }
45753
+ return value;
45754
+ });
45755
+ return unresolved ? void 0 : joinTemplate(platform, substituted);
45756
+ }
45757
+ function installRootDirectories(spec, input, dependencies2, platform, home) {
45758
+ const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
45759
+ const directories = [];
45760
+ for (const template of templates) {
45761
+ if (template === VERSION_MANAGER_ROOTS) {
45762
+ directories.push(...versionManagerBinaryDirectories({
45763
+ platform,
45764
+ environment: input.environment,
45765
+ home,
45766
+ ...dependencies2.subdirectories ? { subdirectories: dependencies2.subdirectories } : {}
45767
+ }));
45768
+ continue;
45769
+ }
45770
+ const directory = expandInstallRoot(template, input.environment, platform, home);
45771
+ if (directory !== void 0)
45772
+ directories.push(directory);
45773
+ }
45774
+ return directories;
45775
+ }
45776
+ function harnessCandidates(spec, input, dependencies2 = {}) {
45777
+ const platform = input.platform ?? process.platform;
45778
+ const pathFlavor = targetPath(platform);
45779
+ const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue(input.environment, spec.commandEnvironmentVariable) : void 0);
45780
+ const command = configured ?? spec.command;
45781
+ if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
45782
+ return [{ candidate: command, source: "configured" }];
45783
+ }
45784
+ const candidates = [];
45785
+ const extensions = executableExtensions(command, platform, input.environment);
45786
+ for (const directory of pathDirectories(input.environment, platform)) {
45787
+ for (const extension2 of extensions) {
45788
+ candidates.push({
45789
+ candidate: pathFlavor.join(directory, command + extension2),
45790
+ source: "path"
45791
+ });
45792
+ }
45793
+ }
45794
+ if (configured !== void 0)
45795
+ return candidates;
45796
+ const home = resolveHomeDirectory(input);
45797
+ for (const directory of installRootDirectories(spec, input, dependencies2, platform, home)) {
45798
+ for (const extension2 of installRootExtensions(platform)) {
45799
+ candidates.push({
45800
+ candidate: pathFlavor.join(directory, spec.command + extension2),
45801
+ source: "install-root"
45802
+ });
45803
+ }
45804
+ }
45805
+ return candidates;
45806
+ }
45807
+ function resolveHarnessExecutable(spec, input, dependencies2 = {}) {
45808
+ const platform = input.platform ?? process.platform;
45809
+ const isExecutable = dependencies2.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
45810
+ const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
45811
+ const context = { platform, isExecutable };
45812
+ for (const { candidate, source } of harnessCandidates(spec, input, dependencies2)) {
45813
+ const executable2 = runnable(candidate, context);
45814
+ if (executable2 !== void 0 && isExecutable(executable2))
45815
+ return { executable: executable2, source };
45816
+ }
45817
+ return void 0;
45818
+ }
45819
+
45820
+ // packages/adapters/claude-code/dist/command.js
45821
+ var ClaudeCodeExecutableError = class extends Error {
45822
+ code = "CLAUDE_NOT_FOUND";
45823
+ };
45824
+ var CLAUDE_NPM_PACKAGE_BIN = "node_modules/@anthropic-ai/claude-code/bin";
45825
+ var claudeCodeDiscoverySpec = {
45826
+ id: "claude-code",
45827
+ command: "claude",
45828
+ commandEnvironmentVariable: "CODEXHOST_CLAUDE_COMMAND",
45829
+ installRoots: {
45830
+ posix: [
45831
+ "~/.npm-global/bin",
45832
+ "~/.local/bin",
45833
+ "~/.claude/local",
45834
+ VERSION_MANAGER_ROOTS,
45835
+ "/opt/homebrew/bin",
45836
+ "/usr/local/bin"
45837
+ ],
45838
+ windows: [
45839
+ `\${APPDATA}/npm/${CLAUDE_NPM_PACKAGE_BIN}`,
45840
+ "${APPDATA}/npm",
45841
+ "~/.local/bin",
45842
+ VERSION_MANAGER_ROOTS
45843
+ ]
45844
+ },
45845
+ // Prefer Claude Code's native binary over the npm CMD shim beside it: the
45846
+ // shim spawns an extra cmd.exe and loses signal handling.
45847
+ runnableCandidate: (candidate, { platform, isExecutable }) => {
45848
+ const pathFlavor = targetPath(platform);
45849
+ if (platform !== "win32" || pathFlavor.basename(candidate).toLowerCase() !== "claude.cmd") {
45850
+ return candidate;
45851
+ }
45852
+ const native = pathFlavor.join(pathFlavor.dirname(candidate), ...CLAUDE_NPM_PACKAGE_BIN.split("/"), "claude.exe");
45853
+ return isExecutable(native) ? native : void 0;
45854
+ }
45855
+ };
45856
+ function resolveClaudeCodeExecutable(input = {}, dependencies2 = {}) {
45857
+ const platform = input.platform ?? process.platform;
45858
+ const resolution = resolveHarnessExecutable(claudeCodeDiscoverySpec, {
45859
+ ...input.command ? { command: input.command } : {},
45860
+ environment: input.environment ?? process.env,
45861
+ ...input.homeDirectory ? { homeDirectory: input.homeDirectory } : {},
45862
+ platform
45863
+ }, dependencies2);
45864
+ if (!resolution)
45865
+ throw new ClaudeCodeExecutableError("Claude Code is not installed");
45866
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
45867
+ }
45868
+
45659
45869
  // packages/adapters/claude-code/dist/claude-fork.js
45660
- import path5 from "node:path";
45870
+ import path8 from "node:path";
45661
45871
  import { isDeepStrictEqual } from "node:util";
45662
45872
 
45663
45873
  // packages/adapters/claude-code/dist/item-identity.js
@@ -46177,7 +46387,7 @@ async function forkClaudeSession(input) {
46177
46387
  error: error51("protocolError", "Claude Code Session working directory is unavailable", false)
46178
46388
  };
46179
46389
  }
46180
- if (path5.resolve(sourceInfo.cwd) !== input.cwd) {
46390
+ if (path8.resolve(sourceInfo.cwd) !== input.cwd) {
46181
46391
  return {
46182
46392
  ok: false,
46183
46393
  error: error51("unsupported", "Claude Code cannot Fork across working directories", false)
@@ -46247,13 +46457,13 @@ async function forkClaudeSession(input) {
46247
46457
 
46248
46458
  // packages/adapters/claude-code/dist/claude-transcript.js
46249
46459
  import os2 from "node:os";
46250
- import path6 from "node:path";
46460
+ import path9 from "node:path";
46251
46461
  import { readFile as readFile4, readdir as readdir2, stat } from "node:fs/promises";
46252
46462
  function projectDirectoryName(cwd) {
46253
46463
  return cwd.replace(/[^A-Za-z0-9]/gu, "-");
46254
46464
  }
46255
46465
  function configDirectory(environment) {
46256
- return environment.CLAUDE_CONFIG_DIR ? path6.resolve(environment.CLAUDE_CONFIG_DIR) : path6.join(os2.homedir(), ".claude");
46466
+ return environment.CLAUDE_CONFIG_DIR ? path9.resolve(environment.CLAUDE_CONFIG_DIR) : path9.join(os2.homedir(), ".claude");
46257
46467
  }
46258
46468
  async function existingFile(file2) {
46259
46469
  try {
@@ -46263,9 +46473,9 @@ async function existingFile(file2) {
46263
46473
  }
46264
46474
  }
46265
46475
  async function findTranscript(input) {
46266
- const projectsDirectory = path6.join(configDirectory(input.environment), "projects");
46476
+ const projectsDirectory = path9.join(configDirectory(input.environment), "projects");
46267
46477
  const name = `${input.sessionId}.jsonl`;
46268
- const expected = path6.join(projectsDirectory, projectDirectoryName(input.cwd), name);
46478
+ const expected = path9.join(projectsDirectory, projectDirectoryName(input.cwd), name);
46269
46479
  if (await existingFile(expected))
46270
46480
  return expected;
46271
46481
  let projects;
@@ -46275,7 +46485,7 @@ async function findTranscript(input) {
46275
46485
  return null;
46276
46486
  }
46277
46487
  for (const project of projects) {
46278
- const candidate = path6.join(projectsDirectory, project, name);
46488
+ const candidate = path9.join(projectsDirectory, project, name);
46279
46489
  if (await existingFile(candidate))
46280
46490
  return candidate;
46281
46491
  }
@@ -46520,7 +46730,7 @@ function isClaudePermissionMode(value) {
46520
46730
  import { spawn as spawn2 } from "node:child_process";
46521
46731
 
46522
46732
  // packages/adapters/claude-code/dist/file-change.js
46523
- import path7 from "node:path";
46733
+ import path10 from "node:path";
46524
46734
  var hunkSchema = external_exports.object({
46525
46735
  oldStart: external_exports.number().int().nonnegative(),
46526
46736
  oldLines: external_exports.number().int().nonnegative(),
@@ -46568,10 +46778,10 @@ function parseClaudeNativeFileChange(toolName, value) {
46568
46778
  };
46569
46779
  }
46570
46780
  function displayPath(nativePath, cwd) {
46571
- const resolvedCwd = path7.resolve(cwd);
46572
- const resolvedPath = path7.isAbsolute(nativePath) ? path7.resolve(nativePath) : path7.resolve(cwd, nativePath);
46573
- const relative = path7.relative(resolvedCwd, resolvedPath);
46574
- const selected = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path7.sep}`) ? relative : resolvedPath;
46781
+ const resolvedCwd = path10.resolve(cwd);
46782
+ const resolvedPath = path10.isAbsolute(nativePath) ? path10.resolve(nativePath) : path10.resolve(cwd, nativePath);
46783
+ const relative = path10.relative(resolvedCwd, resolvedPath);
46784
+ const selected = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`) ? relative : resolvedPath;
46575
46785
  const normalized = selected.replaceAll("\\", "/");
46576
46786
  return validNativePath(normalized) && normalized !== "." ? normalized : null;
46577
46787
  }
@@ -46583,7 +46793,7 @@ function projectClaudeFileChange(value, cwd) {
46583
46793
  `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
46584
46794
  ...hunk.lines
46585
46795
  ]);
46586
- const absoluteDisplayPath = path7.posix.isAbsolute(normalizedPath);
46796
+ const absoluteDisplayPath = path10.posix.isAbsolute(normalizedPath);
46587
46797
  const oldHeader = value.kind === "add" ? "/dev/null" : absoluteDisplayPath ? normalizedPath : `a/${normalizedPath}`;
46588
46798
  const newHeader = absoluteDisplayPath ? normalizedPath : `b/${normalizedPath}`;
46589
46799
  const unifiedDiff = [`--- ${oldHeader}`, `+++ ${newHeader}`, ...body, ""].join("\n");
@@ -46682,16 +46892,37 @@ function parseResultModelUsage(value) {
46682
46892
  }
46683
46893
  return usage;
46684
46894
  }
46685
- function parseLastRequestUsage(value) {
46895
+ function parseLastRequestUsage(value, attribution = {}) {
46686
46896
  if (!isRecord5(value))
46687
46897
  return void 0;
46688
46898
  const inputTokens = value.input_tokens;
46899
+ const outputTokens = value.output_tokens;
46689
46900
  const cacheCreationInputTokens = value.cache_creation_input_tokens;
46690
46901
  const cacheReadInputTokens = value.cache_read_input_tokens;
46691
- if (!safeNonNegativeInteger(inputTokens) || !safeNonNegativeInteger(cacheCreationInputTokens) || !safeNonNegativeInteger(cacheReadInputTokens)) {
46902
+ if (!safeNonNegativeInteger(inputTokens) || !safeNonNegativeInteger(outputTokens) || !safeNonNegativeInteger(cacheCreationInputTokens) || !safeNonNegativeInteger(cacheReadInputTokens)) {
46692
46903
  return void 0;
46693
46904
  }
46694
- return { inputTokens, cacheCreationInputTokens, cacheReadInputTokens };
46905
+ const requestId = boundedString(attribution.requestId, 500);
46906
+ const model = boundedString(attribution.model, 500);
46907
+ const provider = boundedString(attribution.provider, 100);
46908
+ return {
46909
+ ...requestId ? { requestId } : {},
46910
+ ...model ? { model } : {},
46911
+ ...provider ? { provider } : {},
46912
+ inputTokens,
46913
+ outputTokens,
46914
+ cacheCreationInputTokens,
46915
+ cacheReadInputTokens
46916
+ };
46917
+ }
46918
+ function assistantRequestUsage(message5, provider) {
46919
+ if (!isRecord5(message5.message))
46920
+ return void 0;
46921
+ return parseLastRequestUsage(message5.message.usage, {
46922
+ requestId: message5.message.id ?? message5.request_id,
46923
+ model: message5.message.model,
46924
+ provider: message5.provider ?? message5.message.provider ?? provider
46925
+ });
46695
46926
  }
46696
46927
  function parseResultUsageEvent(message5) {
46697
46928
  const totalCostUsd = finiteNonNegativeNumber(message5.total_cost_usd) ? message5.total_cost_usd : void 0;
@@ -46826,6 +47057,7 @@ function taskStatus(value) {
46826
47057
  }
46827
47058
  }
46828
47059
  var ClaudeNativeTurnAccumulator = class {
47060
+ #provider;
46829
47061
  #activeRootStreamMessageId = null;
46830
47062
  #assistantErrors = [];
46831
47063
  #cancelRequested = false;
@@ -46837,6 +47069,9 @@ var ClaudeNativeTurnAccumulator = class {
46837
47069
  #protocolConflict = false;
46838
47070
  #textConflict = false;
46839
47071
  #tools = /* @__PURE__ */ new Map();
47072
+ constructor(options = {}) {
47073
+ this.#provider = options.provider;
47074
+ }
46840
47075
  requestCancel() {
46841
47076
  this.#cancelRequested = true;
46842
47077
  }
@@ -47080,7 +47315,7 @@ var ClaudeNativeTurnAccumulator = class {
47080
47315
  const state = this.#messageState(messageId);
47081
47316
  if (state.completed) {
47082
47317
  this.#consumeToolUseBlocks(message5, events, true);
47083
- const usage = isRecord5(message5.message) ? parseLastRequestUsage(message5.message.usage) : void 0;
47318
+ const usage = assistantRequestUsage(message5, this.#provider);
47084
47319
  if (usage && !state.usagePublished) {
47085
47320
  state.usagePublished = true;
47086
47321
  events.push({
@@ -47109,7 +47344,7 @@ var ClaudeNativeTurnAccumulator = class {
47109
47344
  }
47110
47345
  this.#consumeToolUseBlocks(message5, events, false);
47111
47346
  if (!this.#protocolConflict && !this.#textConflict) {
47112
- const usage = isRecord5(message5.message) ? parseLastRequestUsage(message5.message.usage) : void 0;
47347
+ const usage = assistantRequestUsage(message5, this.#provider);
47113
47348
  state.usagePublished = usage !== void 0;
47114
47349
  events.push({
47115
47350
  type: "message.completed",
@@ -47298,9 +47533,6 @@ function permissionModeFromMessage(value) {
47298
47533
  }
47299
47534
  return isClaudePermissionMode(value.permissionMode) ? value.permissionMode : void 0;
47300
47535
  }
47301
- function safeNonNegativeInteger2(value) {
47302
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
47303
- }
47304
47536
  function parseContextUsage(value) {
47305
47537
  if (!isRecord6(value))
47306
47538
  throw new Error("Claude SDK context Usage is invalid");
@@ -47312,53 +47544,6 @@ function parseContextUsage(value) {
47312
47544
  }
47313
47545
  return { usedTokens, maxTokens, model };
47314
47546
  }
47315
- function parseUsageQueryWindow(value) {
47316
- if (!isRecord6(value))
47317
- return void 0;
47318
- const utilization = value.utilization;
47319
- if (typeof utilization !== "number" || !Number.isFinite(utilization) || utilization < 0) {
47320
- return void 0;
47321
- }
47322
- const utilizationPercent = Math.min(100, Math.max(0, utilization));
47323
- const resetsAt = value.resets_at;
47324
- const resetsAtMs = typeof resetsAt === "string" ? Date.parse(resetsAt) : Number.NaN;
47325
- const resetsAtUnix = Number.isFinite(resetsAtMs) ? Math.floor(resetsAtMs / 1e3) : void 0;
47326
- return { utilizationPercent, ...resetsAtUnix !== void 0 ? { resetsAtUnix } : {} };
47327
- }
47328
- function parseUsageQueryPlanLimit(value) {
47329
- if (!isRecord6(value) || value.rate_limits_available !== true)
47330
- return null;
47331
- const rateLimits = value.rate_limits;
47332
- if (!isRecord6(rateLimits))
47333
- return null;
47334
- const fiveHour = parseUsageQueryWindow(rateLimits.five_hour);
47335
- const sevenDay = parseUsageQueryWindow(rateLimits.seven_day);
47336
- if (!fiveHour && !sevenDay)
47337
- return null;
47338
- return { ...fiveHour ? { fiveHour } : {}, ...sevenDay ? { sevenDay } : {} };
47339
- }
47340
- function parseUsageQuerySession(value) {
47341
- if (!isRecord6(value) || !isRecord6(value.session))
47342
- return null;
47343
- const session = value.session;
47344
- const totalCostUsd = session.total_cost_usd;
47345
- if (typeof totalCostUsd !== "number" || !Number.isFinite(totalCostUsd) || totalCostUsd < 0) {
47346
- return null;
47347
- }
47348
- const modelUsage = session.model_usage;
47349
- if (!isRecord6(modelUsage))
47350
- return { totalCostUsd };
47351
- let inputTokens = 0;
47352
- let outputTokens = 0;
47353
- for (const entry of Object.values(modelUsage)) {
47354
- if (!isRecord6(entry) || !safeNonNegativeInteger2(entry.inputTokens) || !safeNonNegativeInteger2(entry.outputTokens)) {
47355
- return { totalCostUsd };
47356
- }
47357
- inputTokens += entry.inputTokens;
47358
- outputTokens += entry.outputTokens;
47359
- }
47360
- return Number.isSafeInteger(inputTokens) && Number.isSafeInteger(outputTokens) ? { totalCostUsd, inputTokens, outputTokens } : { totalCostUsd };
47361
- }
47362
47547
  function parseQuestions(input) {
47363
47548
  if (!Array.isArray(input.questions) || input.questions.length < 1 || input.questions.length > 4) {
47364
47549
  return null;
@@ -47495,6 +47680,7 @@ var ClaudeSdkTransport = class {
47495
47680
  #consumeTask = null;
47496
47681
  #stderrTail = "";
47497
47682
  #interactionOrdinal = 0;
47683
+ #provider;
47498
47684
  #query = null;
47499
47685
  #started = false;
47500
47686
  constructor(options) {
@@ -47559,6 +47745,7 @@ var ClaudeSdkTransport = class {
47559
47745
  this.#query = activeQuery;
47560
47746
  try {
47561
47747
  await activeQuery.initializationResult();
47748
+ this.#provider = (await activeQuery.accountInfo().catch(() => void 0))?.apiProvider;
47562
47749
  } catch (error54) {
47563
47750
  activeQuery.close();
47564
47751
  this.#query = null;
@@ -47573,18 +47760,6 @@ var ClaudeSdkTransport = class {
47573
47760
  return null;
47574
47761
  return parseContextUsage(await activeQuery.getContextUsage());
47575
47762
  }
47576
- async getSessionUsage() {
47577
- const activeQuery = this.#query;
47578
- if (!this.#started || !activeQuery)
47579
- return null;
47580
- return parseUsageQuerySession(await activeQuery.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET());
47581
- }
47582
- async getPlanLimit() {
47583
- const activeQuery = this.#query;
47584
- if (!this.#started || !activeQuery)
47585
- return null;
47586
- return parseUsageQueryPlanLimit(await activeQuery.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET());
47587
- }
47588
47763
  getPermissionMode() {
47589
47764
  if (!this.#started || !this.#query)
47590
47765
  throw new Error("Claude SDK transport is not started");
@@ -47629,7 +47804,7 @@ var ClaudeSdkTransport = class {
47629
47804
  return Promise.reject(new Error("Claude SDK transport is busy"));
47630
47805
  const promise2 = new Promise((resolve2, reject) => {
47631
47806
  this.#active = {
47632
- accumulator: new ClaudeNativeTurnAccumulator(),
47807
+ accumulator: new ClaudeNativeTurnAccumulator(this.#provider ? { provider: this.#provider } : {}),
47633
47808
  controlRequestIds: /* @__PURE__ */ new Set(),
47634
47809
  interactions: /* @__PURE__ */ new Map(),
47635
47810
  onEvent,
@@ -47812,7 +47987,7 @@ var ClaudeSdkTransport = class {
47812
47987
  continue;
47813
47988
  }
47814
47989
  if (this.#idleLive && this.#idleHandler) {
47815
- const idle = this.#idleAccumulator ?? (this.#idleAccumulator = new ClaudeNativeTurnAccumulator());
47990
+ const idle = this.#idleAccumulator ?? (this.#idleAccumulator = new ClaudeNativeTurnAccumulator(this.#provider ? { provider: this.#provider } : {}));
47816
47991
  const interpreted2 = idle.consume(message5);
47817
47992
  for (const event of interpreted2.events)
47818
47993
  this.#idleHandler.onEvent(event);
@@ -47825,7 +48000,7 @@ var ClaudeSdkTransport = class {
47825
48000
  if (!this.#autonomousTurnHandler)
47826
48001
  continue;
47827
48002
  const autonomous = this.#autonomous ?? (this.#autonomous = {
47828
- accumulator: new ClaudeNativeTurnAccumulator(),
48003
+ accumulator: new ClaudeNativeTurnAccumulator(this.#provider ? { provider: this.#provider } : {}),
47829
48004
  events: [],
47830
48005
  nativeTurnKey: null
47831
48006
  });
@@ -48212,6 +48387,43 @@ var ClaudeToolLifecycle = class {
48212
48387
  }
48213
48388
  };
48214
48389
 
48390
+ // packages/adapters/claude-code/dist/usage-estimate.js
48391
+ var PER_MILLION = 1e6;
48392
+ function normalizedModel(model) {
48393
+ return model.trim().toLowerCase().replaceAll("_", "-");
48394
+ }
48395
+ function firstPartyPrice(model) {
48396
+ const value = normalizedModel(model);
48397
+ if (/claude-opus-4-(5|6|7|8)(?:-|$)/u.test(value)) {
48398
+ return { input: 5, cacheWrite: 6.25, cacheRead: 0.5, output: 25 };
48399
+ }
48400
+ if (/claude-opus-4-(0|1)(?:-|$)/u.test(value) || /claude-opus-4-2025/u.test(value)) {
48401
+ return { input: 15, cacheWrite: 18.75, cacheRead: 1.5, output: 75 };
48402
+ }
48403
+ if (/claude-sonnet-5(?:-|$)/u.test(value)) {
48404
+ return { input: 2, cacheWrite: 2.5, cacheRead: 0.2, output: 10 };
48405
+ }
48406
+ if (/claude-(?:3-7-)?sonnet-(?:4|3-7)(?:-|$)/u.test(value)) {
48407
+ return { input: 3, cacheWrite: 3.75, cacheRead: 0.3, output: 15 };
48408
+ }
48409
+ if (/claude-(?:3-5-)?haiku-(?:4-5|3-5)(?:-|$)/u.test(value)) {
48410
+ return value.includes("4-5") ? { input: 1, cacheWrite: 1.25, cacheRead: 0.1, output: 5 } : { input: 0.8, cacheWrite: 1, cacheRead: 0.08, output: 4 };
48411
+ }
48412
+ if (/claude-3-haiku(?:-|$)/u.test(value)) {
48413
+ return { input: 0.25, cacheWrite: 0.3, cacheRead: 0.03, output: 1.25 };
48414
+ }
48415
+ return null;
48416
+ }
48417
+ function estimateClaudeRequestCostUsd(usage) {
48418
+ if (!usage.model || usage.provider !== "firstParty")
48419
+ return void 0;
48420
+ const price = firstPartyPrice(usage.model);
48421
+ if (!price)
48422
+ return void 0;
48423
+ const cost = (usage.inputTokens * price.input + usage.cacheCreationInputTokens * price.cacheWrite + usage.cacheReadInputTokens * price.cacheRead + usage.outputTokens * price.output) / PER_MILLION;
48424
+ return Number.isFinite(cost) && cost >= 0 ? cost : void 0;
48425
+ }
48426
+
48215
48427
  // packages/adapters/claude-code/dist/claude-code-adapter.js
48216
48428
  var claudeCodeHarnessId2 = harnessIdSchema.parse("claude-code");
48217
48429
  var claudeCommandCatalog = harnessCommandCatalogSchema.parse({
@@ -48290,15 +48502,14 @@ function parseClaudeHarnessCommand(command) {
48290
48502
  var DEFAULT_CLOSE_TIMEOUT_MS = 7e3;
48291
48503
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
48292
48504
  var CONTEXT_USAGE_RETRY_DELAYS_MS = [0, 1e3, 2e3];
48293
- var ACTIVE_CONTEXT_USAGE_RETRY_DELAYS_MS = [0, 250, 1e3];
48505
+ var CONTEXT_USAGE_TTL_MS = 1e4;
48506
+ var CONTEXT_USAGE_FAILURE_COOLDOWN_MS = 5e3;
48294
48507
  var REQUEST_USAGE_RETRY_DELAYS_MS = [0, 100, 250, 500, 1e3];
48295
48508
  var DEFAULT_CONTINUATION_QUIESCENCE_MS = 2e3;
48296
- var PLAN_LIMIT_TTL_MS = 15e3;
48297
- var ACTIVE_PLAN_LIMIT_POLL_INTERVAL_MS = 5e3;
48298
48509
  function isRecord8(value) {
48299
48510
  return typeof value === "object" && value !== null && !Array.isArray(value);
48300
48511
  }
48301
- function safeNonNegativeInteger3(value) {
48512
+ function safeNonNegativeInteger2(value) {
48302
48513
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
48303
48514
  }
48304
48515
  function transcriptRequestUsage(messages, messageId) {
@@ -48308,10 +48519,19 @@ function transcriptRequestUsage(messages, messageId) {
48308
48519
  continue;
48309
48520
  }
48310
48521
  const inputTokens = entry.message.usage.input_tokens;
48522
+ const outputTokens = entry.message.usage.output_tokens;
48311
48523
  const cacheCreationInputTokens = entry.message.usage.cache_creation_input_tokens;
48312
48524
  const cacheReadInputTokens = entry.message.usage.cache_read_input_tokens;
48313
- if (safeNonNegativeInteger3(inputTokens) && safeNonNegativeInteger3(cacheCreationInputTokens) && safeNonNegativeInteger3(cacheReadInputTokens)) {
48314
- return { inputTokens, cacheCreationInputTokens, cacheReadInputTokens };
48525
+ if (safeNonNegativeInteger2(inputTokens) && safeNonNegativeInteger2(outputTokens) && safeNonNegativeInteger2(cacheCreationInputTokens) && safeNonNegativeInteger2(cacheReadInputTokens)) {
48526
+ return {
48527
+ requestId: typeof entry.request_id === "string" && entry.request_id.length > 0 ? entry.request_id : messageId,
48528
+ ...typeof entry.message.model === "string" && entry.message.model.length > 0 ? { model: entry.message.model } : {},
48529
+ ...typeof entry.provider === "string" && entry.provider.length > 0 ? { provider: entry.provider } : typeof entry.message.provider === "string" && entry.message.provider.length > 0 ? { provider: entry.message.provider } : {},
48530
+ inputTokens,
48531
+ outputTokens,
48532
+ cacheCreationInputTokens,
48533
+ cacheReadInputTokens
48534
+ };
48315
48535
  }
48316
48536
  }
48317
48537
  return void 0;
@@ -48424,8 +48644,6 @@ var ClaudeHarnessSession = class {
48424
48644
  #cwd;
48425
48645
  #nativeRef;
48426
48646
  #onClosed;
48427
- #onTurnFinished;
48428
- #onTurnStarted;
48429
48647
  #onPlanLimitObserved;
48430
48648
  #openMode;
48431
48649
  #randomUUID;
@@ -48448,24 +48666,25 @@ var ClaudeHarnessSession = class {
48448
48666
  #usageGeneration = 0;
48449
48667
  #latestUsage = null;
48450
48668
  #minimumContextUsedTokens = null;
48669
+ #calibratedInputTokens = 0;
48670
+ #calibratedOutputTokens = 0;
48671
+ #calibratedCostUsd = 0;
48451
48672
  #contextRefreshInFlight = null;
48452
48673
  #contextRefreshPending = null;
48453
48674
  #contextRefreshWake = null;
48454
- #sessionRefreshInFlight = null;
48455
- #sessionRefreshPending = null;
48675
+ #contextUsageFreshUntilMs = 0;
48676
+ #contextUsageCooldownUntilMs = 0;
48456
48677
  #requestUsageBoundary = 0;
48457
48678
  #autonomousOrdinal = 0;
48458
48679
  #occupancy = new ClaudeBackgroundOccupancy();
48459
48680
  #continuationQuiescence = null;
48460
- constructor(cwd, dependencies2, closeTimeoutMs, onClosed, onTurnStarted, onTurnFinished, onPlanLimitObserved, options) {
48681
+ constructor(cwd, dependencies2, closeTimeoutMs, onClosed, onPlanLimitObserved, options) {
48461
48682
  this.#cwd = cwd;
48462
48683
  this.#createTransport = dependencies2.createTransport;
48463
48684
  this.#randomUUID = dependencies2.randomUUID;
48464
48685
  this.#readSessionMessages = dependencies2.readSessionMessages;
48465
48686
  this.#closeTimeoutMs = closeTimeoutMs;
48466
48687
  this.#onClosed = onClosed;
48467
- this.#onTurnStarted = onTurnStarted;
48468
- this.#onTurnFinished = onTurnFinished;
48469
48688
  this.#onPlanLimitObserved = onPlanLimitObserved;
48470
48689
  this.#openMode = options.openMode;
48471
48690
  this.#requestedModel = options.requestedModel;
@@ -48599,6 +48818,8 @@ var ClaudeHarnessSession = class {
48599
48818
  if (startingTransport)
48600
48819
  this.#publishState();
48601
48820
  this.#usageGeneration += 1;
48821
+ this.#contextUsageFreshUntilMs = 0;
48822
+ this.#contextUsageCooldownUntilMs = 0;
48602
48823
  let resolveCompletion = () => void 0;
48603
48824
  const completion = new Promise((resolve2) => {
48604
48825
  resolveCompletion = resolve2;
@@ -48634,12 +48855,18 @@ var ClaudeHarnessSession = class {
48634
48855
  nativeTurnKey: nativeTurnKey4,
48635
48856
  nativeTurnRef: null,
48636
48857
  cancellationRequested: false,
48858
+ usageRequestIds: /* @__PURE__ */ new Set(),
48859
+ estimatedInputTokens: 0,
48860
+ estimatedOutputTokens: 0,
48861
+ estimatedCostUsd: 0,
48862
+ estimatedCostAvailable: false,
48863
+ usageTokensCalibrated: false,
48864
+ usageCostCalibrated: false,
48637
48865
  held: false,
48638
48866
  completion,
48639
48867
  resolveCompletion
48640
48868
  };
48641
48869
  this.#active = active;
48642
- this.#onTurnStarted();
48643
48870
  this.#event({ type: "turn.started", turnId: command.turnId });
48644
48871
  this.#event({ type: "item.started", turnId: command.turnId, item });
48645
48872
  try {
@@ -48692,6 +48919,8 @@ var ClaudeHarnessSession = class {
48692
48919
  if (startingTransport)
48693
48920
  this.#publishState();
48694
48921
  this.#usageGeneration += 1;
48922
+ this.#contextUsageFreshUntilMs = 0;
48923
+ this.#contextUsageCooldownUntilMs = 0;
48695
48924
  let resolveCompletion = () => void 0;
48696
48925
  const completion = new Promise((resolve2) => {
48697
48926
  resolveCompletion = resolve2;
@@ -48728,12 +48957,18 @@ var ClaudeHarnessSession = class {
48728
48957
  nativeTurnKey: nativeTurnKey4,
48729
48958
  nativeTurnRef: null,
48730
48959
  cancellationRequested: false,
48960
+ usageRequestIds: /* @__PURE__ */ new Set(),
48961
+ estimatedInputTokens: 0,
48962
+ estimatedOutputTokens: 0,
48963
+ estimatedCostUsd: 0,
48964
+ estimatedCostAvailable: false,
48965
+ usageTokensCalibrated: false,
48966
+ usageCostCalibrated: false,
48731
48967
  held: false,
48732
48968
  completion,
48733
48969
  resolveCompletion
48734
48970
  };
48735
48971
  this.#active = active;
48736
- this.#onTurnStarted();
48737
48972
  this.#event({ type: "turn.started", turnId: command.turnId });
48738
48973
  if (item)
48739
48974
  this.#event({ type: "item.started", turnId: command.turnId, item });
@@ -48745,6 +48980,16 @@ var ClaudeHarnessSession = class {
48745
48980
  }
48746
48981
  return { ok: true, value: { turnId: command.turnId } };
48747
48982
  }
48983
+ refreshUsage() {
48984
+ if (this.#phase !== "open" || !this.#transport)
48985
+ return Promise.resolve();
48986
+ const now = Date.now();
48987
+ if (now < this.#contextUsageFreshUntilMs || now < this.#contextUsageCooldownUntilMs) {
48988
+ return Promise.resolve();
48989
+ }
48990
+ this.#requestContextUsage(this.#transport, this.#active?.command.turnId, CONTEXT_USAGE_RETRY_DELAYS_MS);
48991
+ return this.#contextRefreshInFlight ?? Promise.resolve();
48992
+ }
48748
48993
  close() {
48749
48994
  if (!this.#closePromise)
48750
48995
  this.#closePromise = this.#close();
@@ -48775,6 +49020,8 @@ var ClaudeHarnessSession = class {
48775
49020
  };
48776
49021
  }
48777
49022
  this.#usageGeneration += 1;
49023
+ this.#contextUsageFreshUntilMs = 0;
49024
+ this.#contextUsageCooldownUntilMs = 0;
48778
49025
  let resolveConfiguration = () => void 0;
48779
49026
  this.#configurationTask = new Promise((resolve2) => {
48780
49027
  resolveConfiguration = resolve2;
@@ -48828,6 +49075,8 @@ var ClaudeHarnessSession = class {
48828
49075
  };
48829
49076
  }
48830
49077
  this.#usageGeneration += 1;
49078
+ this.#contextUsageFreshUntilMs = 0;
49079
+ this.#contextUsageCooldownUntilMs = 0;
48831
49080
  let resolveConfiguration = () => void 0;
48832
49081
  this.#configurationTask = new Promise((resolve2) => {
48833
49082
  resolveConfiguration = resolve2;
@@ -48881,6 +49130,8 @@ var ClaudeHarnessSession = class {
48881
49130
  };
48882
49131
  }
48883
49132
  this.#usageGeneration += 1;
49133
+ this.#contextUsageFreshUntilMs = 0;
49134
+ this.#contextUsageCooldownUntilMs = 0;
48884
49135
  let resolveConfiguration = () => void 0;
48885
49136
  this.#configurationTask = new Promise((resolve2) => {
48886
49137
  resolveConfiguration = resolve2;
@@ -49032,8 +49283,9 @@ var ClaudeHarnessSession = class {
49032
49283
  if (this.#phase === "closed")
49033
49284
  return;
49034
49285
  this.#usageGeneration += 1;
49286
+ this.#contextUsageFreshUntilMs = 0;
49287
+ this.#contextUsageCooldownUntilMs = 0;
49035
49288
  this.#contextRefreshPending = null;
49036
- this.#sessionRefreshPending = null;
49037
49289
  this.#requestUsageBoundary += 1;
49038
49290
  this.#contextRefreshWake?.();
49039
49291
  this.#contextRefreshWake = null;
@@ -49081,7 +49333,7 @@ var ClaudeHarnessSession = class {
49081
49333
  permissionMode,
49082
49334
  onPermissionModeChanged: (mode) => this.#handlePermissionModeChanged(mode),
49083
49335
  onFault: () => this.#fault(faultError()),
49084
- onPlanLimit: (planLimit) => this.#handlePlanLimit(planLimit, "push")
49336
+ onPlanLimit: (planLimit) => this.#handlePlanLimit(planLimit)
49085
49337
  });
49086
49338
  transport.setAutonomousTurnHandler((turn) => this.#handleAutonomousTurn(turn));
49087
49339
  transport.setIdleTurnHandler({
@@ -49170,9 +49422,6 @@ var ClaudeHarnessSession = class {
49170
49422
  } else {
49171
49423
  this.#requestLatestRequestUsage(active, event.messageId);
49172
49424
  }
49173
- const transport = this.#transport;
49174
- if (transport)
49175
- this.#refreshUsageSnapshot(transport, active.command.turnId, false);
49176
49425
  if (event.checkpointId)
49177
49426
  active.checkpointId = event.checkpointId;
49178
49427
  this.#completeReasoning(active, event.messageId, { status: "succeeded" });
@@ -49195,9 +49444,6 @@ var ClaudeHarnessSession = class {
49195
49444
  return;
49196
49445
  case "tool.completed":
49197
49446
  active.tools.complete(active.command.turnId, event, active.cancellationRequested);
49198
- if (this.#transport) {
49199
- this.#requestContextUsage(this.#transport, active.command.turnId, ACTIVE_CONTEXT_USAGE_RETRY_DELAYS_MS);
49200
- }
49201
49447
  return;
49202
49448
  case "subagent.started":
49203
49449
  this.#observeRootOutput();
@@ -49512,12 +49758,18 @@ var ClaudeHarnessSession = class {
49512
49758
  formatVersion: 1
49513
49759
  }),
49514
49760
  cancellationRequested: false,
49761
+ usageRequestIds: /* @__PURE__ */ new Set(),
49762
+ estimatedInputTokens: 0,
49763
+ estimatedOutputTokens: 0,
49764
+ estimatedCostUsd: 0,
49765
+ estimatedCostAvailable: false,
49766
+ usageTokensCalibrated: false,
49767
+ usageCostCalibrated: false,
49515
49768
  held: false,
49516
49769
  completion,
49517
49770
  resolveCompletion
49518
49771
  };
49519
49772
  this.#active = active;
49520
- this.#onTurnStarted();
49521
49773
  this.#event({ type: "turn.autonomous.started", turnId, input: [] });
49522
49774
  this.#event({ type: "turn.started", turnId });
49523
49775
  this.#event({ type: "item.started", turnId, item });
@@ -49549,7 +49801,6 @@ var ClaudeHarnessSession = class {
49549
49801
  #finishResult(active, result) {
49550
49802
  if (this.#active !== active)
49551
49803
  return;
49552
- const transport = this.#transport;
49553
49804
  if (result.status === "succeeded" && (active.tools.size > 0 || active.subagents.size > 0)) {
49554
49805
  this.#finishFailed(active, transportFailure("protocol"));
49555
49806
  } else if (result.status === "succeeded") {
@@ -49559,70 +49810,18 @@ var ClaudeHarnessSession = class {
49559
49810
  } else {
49560
49811
  this.#finishFailed(active, transportFailure(result.kind));
49561
49812
  }
49562
- if (transport && this.#phase === "open") {
49563
- this.#refreshUsageSnapshot(transport, active.command.turnId, true);
49564
- }
49565
- }
49566
- #refreshUsageSnapshot(transport, turnId, retryContext) {
49567
- if (this.#phase !== "open" || this.#transport !== transport)
49568
- return;
49569
- this.#requestSessionUsage(transport, turnId);
49570
- this.#requestContextUsage(transport, turnId, retryContext ? CONTEXT_USAGE_RETRY_DELAYS_MS : ACTIVE_CONTEXT_USAGE_RETRY_DELAYS_MS);
49571
- }
49572
- #requestSessionUsage(transport, turnId) {
49573
- if (this.#phase !== "open" || this.#transport !== transport)
49574
- return;
49575
- this.#sessionRefreshPending = {
49576
- transport,
49577
- turnId,
49578
- generation: this.#usageGeneration
49579
- };
49580
- if (this.#sessionRefreshInFlight)
49581
- return;
49582
- this.#sessionRefreshInFlight = this.#drainSessionUsage();
49583
- }
49584
- async #drainSessionUsage() {
49585
- try {
49586
- while (this.#sessionRefreshPending) {
49587
- const request = this.#sessionRefreshPending;
49588
- this.#sessionRefreshPending = null;
49589
- await this.#readSessionUsage(request);
49590
- }
49591
- } finally {
49592
- this.#sessionRefreshInFlight = null;
49593
- if (this.#sessionRefreshPending && this.#phase === "open") {
49594
- this.#sessionRefreshInFlight = this.#drainSessionUsage();
49595
- }
49596
- }
49597
- }
49598
- async #readSessionUsage(request) {
49599
- try {
49600
- const usage = await request.transport.getSessionUsage();
49601
- if (this.#phase !== "open" || this.#transport !== request.transport || this.#usageGeneration !== request.generation || this.#sessionRefreshPending !== null || !usage) {
49602
- return;
49603
- }
49604
- this.#mergeAndPublishUsage({
49605
- ...usage.totalCostUsd !== void 0 ? { totalCostUsd: usage.totalCostUsd } : {},
49606
- ...usage.inputTokens !== void 0 ? { inputTokens: usage.inputTokens } : {},
49607
- ...usage.outputTokens !== void 0 ? { outputTokens: usage.outputTokens } : {}
49608
- }, request.turnId);
49609
- } catch {
49610
- }
49611
49813
  }
49612
49814
  #requestContextUsage(transport, turnId, retryDelaysMs) {
49613
49815
  if (this.#phase !== "open" || this.#transport !== transport)
49614
49816
  return;
49817
+ if (this.#contextRefreshInFlight)
49818
+ return;
49615
49819
  this.#contextRefreshPending = {
49616
49820
  transport,
49617
- turnId,
49821
+ ...turnId !== void 0 ? { turnId } : {},
49618
49822
  generation: this.#usageGeneration,
49619
49823
  retryDelaysMs
49620
49824
  };
49621
- if (this.#contextRefreshInFlight) {
49622
- this.#contextRefreshWake?.();
49623
- this.#contextRefreshWake = null;
49624
- return;
49625
- }
49626
49825
  this.#contextRefreshInFlight = this.#drainContextUsage();
49627
49826
  }
49628
49827
  async #drainContextUsage() {
@@ -49653,13 +49852,19 @@ var ClaudeHarnessSession = class {
49653
49852
  }
49654
49853
  if (context === null)
49655
49854
  continue;
49855
+ this.#contextUsageFreshUntilMs = Date.now() + CONTEXT_USAGE_TTL_MS;
49856
+ this.#contextUsageCooldownUntilMs = 0;
49656
49857
  this.#mergeAndPublishUsage({
49657
49858
  contextUsedTokens: Math.max(context.usedTokens, this.#minimumContextUsedTokens ?? 0),
49658
49859
  contextWindowTokens: context.maxTokens
49659
49860
  }, request.turnId);
49861
+ return;
49660
49862
  } catch {
49661
49863
  }
49662
49864
  }
49865
+ if (this.#phase === "open" && this.#transport === request.transport && this.#usageGeneration === request.generation) {
49866
+ this.#contextUsageCooldownUntilMs = Date.now() + CONTEXT_USAGE_FAILURE_COOLDOWN_MS;
49867
+ }
49663
49868
  }
49664
49869
  async #waitForContextRetry(milliseconds) {
49665
49870
  let wake = () => void 0;
@@ -49709,6 +49914,17 @@ var ClaudeHarnessSession = class {
49709
49914
  }
49710
49915
  }
49711
49916
  #applyLatestRequestUsage(active, usage) {
49917
+ const requestId = usage.requestId ?? `${active.nativeTurnKey}:${usage.model ?? "unknown"}`;
49918
+ if (active.usageRequestIds.has(requestId))
49919
+ return;
49920
+ active.usageRequestIds.add(requestId);
49921
+ active.estimatedInputTokens += usage.inputTokens + usage.cacheCreationInputTokens + usage.cacheReadInputTokens;
49922
+ active.estimatedOutputTokens += usage.outputTokens;
49923
+ const estimatedCostUsd = estimateClaudeRequestCostUsd(usage);
49924
+ if (estimatedCostUsd !== void 0) {
49925
+ active.estimatedCostUsd += estimatedCostUsd;
49926
+ active.estimatedCostAvailable = true;
49927
+ }
49712
49928
  const promptTokens = usage.inputTokens + usage.cacheCreationInputTokens + usage.cacheReadInputTokens;
49713
49929
  if (promptTokens > 0)
49714
49930
  this.#minimumContextUsedTokens = promptTokens;
@@ -49716,13 +49932,21 @@ var ClaudeHarnessSession = class {
49716
49932
  const contextWindowTokens = this.#latestUsage?.contextWindowTokens;
49717
49933
  this.#mergeAndPublishUsage({
49718
49934
  ...cacheHitRatePercent !== void 0 ? { cacheHitRatePercent } : {},
49935
+ inputTokens: this.#calibratedInputTokens + active.estimatedInputTokens,
49936
+ outputTokens: this.#calibratedOutputTokens + active.estimatedOutputTokens,
49937
+ ...active.estimatedCostAvailable ? { totalCostUsd: this.#calibratedCostUsd + active.estimatedCostUsd } : {},
49719
49938
  ...contextWindowTokens !== void 0 && promptTokens > 0 ? { contextUsedTokens: promptTokens, contextWindowTokens } : {}
49720
49939
  }, active.command.turnId);
49721
49940
  }
49722
49941
  #applyResultUsage(active, event) {
49723
49942
  const delta = {};
49724
- if (event.totalCostUsd !== void 0)
49943
+ if (event.totalCostUsd !== void 0) {
49944
+ this.#calibratedCostUsd = event.totalCostUsd;
49945
+ active.estimatedCostUsd = 0;
49946
+ active.estimatedCostAvailable = false;
49947
+ active.usageCostCalibrated = true;
49725
49948
  delta.totalCostUsd = event.totalCostUsd;
49949
+ }
49726
49950
  if (event.modelUsage !== void 0) {
49727
49951
  let inputTokens = 0;
49728
49952
  let outputTokens = 0;
@@ -49731,6 +49955,11 @@ var ClaudeHarnessSession = class {
49731
49955
  outputTokens += model.outputTokens;
49732
49956
  }
49733
49957
  if (Number.isSafeInteger(inputTokens) && Number.isSafeInteger(outputTokens)) {
49958
+ this.#calibratedInputTokens = inputTokens;
49959
+ this.#calibratedOutputTokens = outputTokens;
49960
+ active.estimatedInputTokens = 0;
49961
+ active.estimatedOutputTokens = 0;
49962
+ active.usageTokensCalibrated = true;
49734
49963
  delta.inputTokens = inputTokens;
49735
49964
  delta.outputTokens = outputTokens;
49736
49965
  }
@@ -49742,27 +49971,6 @@ var ClaudeHarnessSession = class {
49742
49971
  }
49743
49972
  this.#mergeAndPublishUsage(delta, active.command.turnId);
49744
49973
  }
49745
- /**
49746
- * On-demand counterpart to the passive `rate_limit_event` push: asks this
49747
- * Session's live Transport to pull plan usage right now (if it has one —
49748
- * a Session with no Turn yet has never opened a live connection to pull
49749
- * through). Routes any answer through the same `#handlePlanLimit` path as
49750
- * the push, so it updates both the Adapter's shared cache and this
49751
- * Thread's own Usage snapshot identically either way.
49752
- */
49753
- async refreshPlanLimit() {
49754
- if (this.#phase !== "open" || !this.#transport)
49755
- return null;
49756
- let planLimit;
49757
- try {
49758
- planLimit = await this.#transport.getPlanLimit();
49759
- } catch {
49760
- return null;
49761
- }
49762
- if (planLimit)
49763
- this.#handlePlanLimit(planLimit, "pull");
49764
- return planLimit;
49765
- }
49766
49974
  /**
49767
49975
  * Plan usage is account-wide, not Thread-scoped, so every observation is
49768
49976
  * offered to the Adapter's shared cache regardless of this Session's own
@@ -49770,8 +49978,8 @@ var ClaudeHarnessSession = class {
49770
49978
  * *accepted*, not the raw observation: a rejected push must not leave this
49771
49979
  * Thread's Usage popover showing a number the credits pill disagrees with.
49772
49980
  */
49773
- #handlePlanLimit(planLimit, source) {
49774
- const effective = this.#onPlanLimitObserved(planLimit, source);
49981
+ #handlePlanLimit(planLimit) {
49982
+ const effective = this.#onPlanLimitObserved(planLimit);
49775
49983
  if (effective)
49776
49984
  this.publishPlanLimit(effective);
49777
49985
  }
@@ -49890,7 +50098,6 @@ var ClaudeHarnessSession = class {
49890
50098
  outcome: checkpoint ? { ...outcome, checkpoint } : outcome
49891
50099
  });
49892
50100
  this.#active = null;
49893
- this.#onTurnFinished();
49894
50101
  this.#occupancy.clear();
49895
50102
  this.#transport?.setIdleLive(false);
49896
50103
  active.resolveCompletion();
@@ -49899,8 +50106,9 @@ var ClaudeHarnessSession = class {
49899
50106
  if (this.#phase === "closed" || this.#phase === "closing" || this.#phase === "faulted")
49900
50107
  return;
49901
50108
  this.#usageGeneration += 1;
50109
+ this.#contextUsageFreshUntilMs = 0;
50110
+ this.#contextUsageCooldownUntilMs = 0;
49902
50111
  this.#contextRefreshPending = null;
49903
- this.#sessionRefreshPending = null;
49904
50112
  this.#requestUsageBoundary += 1;
49905
50113
  this.#contextRefreshWake?.();
49906
50114
  this.#contextRefreshWake = null;
@@ -49967,13 +50175,8 @@ var ClaudeCodeAdapter = class {
49967
50175
  #inspectionInFlight = /* @__PURE__ */ new Map();
49968
50176
  #inspectors = /* @__PURE__ */ new Set();
49969
50177
  #sessions = /* @__PURE__ */ new Set();
49970
- #activeTurnSessions = /* @__PURE__ */ new Set();
49971
50178
  #closePromise = null;
49972
50179
  #latestPlanLimit = null;
49973
- #planLimitFreshUntilMs = 0;
49974
- #planLimitRefresh = null;
49975
- #planLimitPullUnavailable = false;
49976
- #planLimitPoller = null;
49977
50180
  constructor(options = {}, dependencies2) {
49978
50181
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
49979
50182
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
@@ -50030,7 +50233,7 @@ var ClaudeCodeAdapter = class {
50030
50233
  error: invalidState("Claude Code Adapter is closing")
50031
50234
  };
50032
50235
  }
50033
- const cwd = path8.resolve(input.cwd ?? process.cwd());
50236
+ const cwd = path11.resolve(input.cwd ?? process.cwd());
50034
50237
  if (!input.refresh) {
50035
50238
  const cached2 = this.#inspectionCache.get(cwd);
50036
50239
  if (cached2)
@@ -50151,7 +50354,7 @@ var ClaudeCodeAdapter = class {
50151
50354
  let sourceSnapshot;
50152
50355
  try {
50153
50356
  const messages = await this.#dependencies.readSessionMessages({
50154
- cwd: path8.resolve(input.cwd),
50357
+ cwd: path11.resolve(input.cwd),
50155
50358
  sessionId: sourceRef.data.nativeSessionId
50156
50359
  });
50157
50360
  sourceSnapshot = mapClaudeSnapshot(messages, sourceRef.data.nativeSessionId);
@@ -50193,7 +50396,7 @@ var ClaudeCodeAdapter = class {
50193
50396
  } else {
50194
50397
  const forked2 = await forkClaudeSession({
50195
50398
  checkpoint: retained.checkpoint,
50196
- cwd: path8.resolve(input.cwd),
50399
+ cwd: path11.resolve(input.cwd),
50197
50400
  dependencies: this.#dependencies,
50198
50401
  harnessId: this.harnessId,
50199
50402
  sourceRef: sourceRef.data
@@ -50248,7 +50451,7 @@ var ClaudeCodeAdapter = class {
50248
50451
  }
50249
50452
  };
50250
50453
  }
50251
- const cwd = path8.resolve(input.cwd);
50454
+ const cwd = path11.resolve(input.cwd);
50252
50455
  const nativeRef2 = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
50253
50456
  if (nativeRef2 && (!nativeRef2.success || nativeRef2.data.harnessId !== this.harnessId)) {
50254
50457
  return {
@@ -50269,7 +50472,7 @@ var ClaudeCodeAdapter = class {
50269
50472
  }) : null;
50270
50473
  if (forked && !forked.ok)
50271
50474
  return forked;
50272
- const session = new ClaudeHarnessSession(cwd, this.#dependencies, this.#closeTimeoutMs, () => this.#sessions.delete(session), () => this.#startTurnCreditsPolling(session), () => this.#finishTurnCreditsPolling(session), (planLimit, source) => this.#recordPlanLimit(session, planLimit, source), {
50475
+ const session = new ClaudeHarnessSession(cwd, this.#dependencies, this.#closeTimeoutMs, () => this.#sessions.delete(session), (planLimit) => this.#recordPlanLimit(session, planLimit), {
50273
50476
  openMode: rollback?.openMode ?? (input.kind === "create" ? "create" : "resume"),
50274
50477
  sessionId: rollback?.sessionId ?? (forked?.ok ? forked.value.sessionId : nativeRef2?.success ? nativeRef2.data.nativeSessionId : this.#dependencies.randomUUID()),
50275
50478
  ...input.kind === "create" && input.model ? { requestedModel: input.model } : {},
@@ -50281,41 +50484,12 @@ var ClaudeCodeAdapter = class {
50281
50484
  this.#sessions.add(session);
50282
50485
  return { ok: true, value: session };
50283
50486
  }
50284
- /**
50285
- * Plan usage (`credits()`) is scoped to the Adapter, not a single Thread: the
50286
- * Claude.ai 5-hour / 7-day windows are account-wide and shared by every
50287
- * concurrent Session, so an observation from any one of them updates the
50288
- * value every Thread reads.
50289
- *
50290
- * Because every Session pushes into this one slot, an unarbitrated
50291
- * last-write-wins merge let an idle Session's hours-old `rate_limit_event`
50292
- * overwrite an active Session's just-pulled value — the credits pill visibly
50293
- * flapped between the two whenever more than one Session was open. Rather
50294
- * than ordering the writes after the fact, the slot has a single
50295
- * authoritative writer:
50296
- *
50297
- * 1. `"pull"` always writes, and marks the value fresh for `PLAN_LIMIT_TTL_MS`.
50298
- * 2. `"push"` never overwrites a window that already has a value; it expires
50299
- * the cache and immediately re-pulls through an open Session.
50300
- * 3. `"push"` may fill a window that is *empty*, so the pill lights up before
50301
- * the first pull lands, and may write freely if pulling has proven
50302
- * unavailable (an SDK without the experimental `/usage` query never
50303
- * answers, and freezing on a cold-start reading would be worse).
50304
- *
50305
- * The two windows are arbitrated independently: a push reporting only the
50306
- * 7-day window carries no opinion about the 5-hour one, so it must be able to
50307
- * fill an empty 7-day slot without being rejected for disagreeing about a
50308
- * window it never mentioned.
50309
- *
50310
- * Returns the value now in the slot so the calling Session can mirror it into
50311
- * its own Usage snapshot, keeping popover and pill in agreement.
50312
- */
50313
- #recordPlanLimit(origin, planLimit, source) {
50314
- const mayOverwrite = source === "pull" || this.#planLimitPullUnavailable;
50487
+ /** Account-level plan windows are shared, but only stable native pushes may update them. */
50488
+ #recordPlanLimit(origin, planLimit) {
50315
50489
  const next = { ...this.#latestPlanLimit ?? {} };
50316
- if (planLimit.fiveHour && (mayOverwrite || !next.fiveHour))
50490
+ if (planLimit.fiveHour)
50317
50491
  next.fiveHour = planLimit.fiveHour;
50318
- if (planLimit.sevenDay && (mayOverwrite || !next.sevenDay))
50492
+ if (planLimit.sevenDay)
50319
50493
  next.sevenDay = planLimit.sevenDay;
50320
50494
  this.#latestPlanLimit = next.fiveHour || next.sevenDay ? next : null;
50321
50495
  if (this.#latestPlanLimit) {
@@ -50324,79 +50498,14 @@ var ClaudeCodeAdapter = class {
50324
50498
  session.publishPlanLimit(this.#latestPlanLimit);
50325
50499
  }
50326
50500
  }
50327
- this.#planLimitFreshUntilMs = source === "pull" ? Date.now() + PLAN_LIMIT_TTL_MS : 0;
50328
- if (source === "push")
50329
- void this.#refreshCredits(true);
50330
50501
  return this.#latestPlanLimit;
50331
50502
  }
50332
50503
  credits() {
50333
50504
  return projectClaudePlanLimitToCredits(this.#latestPlanLimit);
50334
50505
  }
50335
- /**
50336
- * Unlike the passive `rate_limit_event` push, this asks an open Session's
50337
- * live Transport to pull plan usage on demand (Claude Code's `/usage`
50338
- * control channel) — so, like Grok's credits, a refresh can actually
50339
- * produce a fresher value instead of only replaying what was last observed.
50340
- *
50341
- * Serves the cached value while it is still fresh, and collapses concurrent
50342
- * callers onto one in-flight pull: every mounted composer inspects Usage
50343
- * independently, and letting those race produced overlapping pulls whose
50344
- * answers landed out of order.
50345
- */
50346
- refreshCredits() {
50347
- return this.#refreshCredits(false);
50348
- }
50349
- #refreshCredits(force) {
50350
- if (!force && this.#latestPlanLimit && Date.now() < this.#planLimitFreshUntilMs) {
50351
- return Promise.resolve(this.credits());
50352
- }
50353
- this.#planLimitRefresh ??= this.#pullPlanLimit().finally(() => {
50354
- this.#planLimitRefresh = null;
50355
- });
50356
- return this.#planLimitRefresh;
50357
- }
50358
- #startTurnCreditsPolling(session) {
50359
- this.#activeTurnSessions.add(session);
50360
- if (this.#planLimitPoller)
50361
- return;
50362
- this.#planLimitPoller = setInterval(() => {
50363
- void this.#refreshCredits(true);
50364
- }, ACTIVE_PLAN_LIMIT_POLL_INTERVAL_MS);
50365
- this.#planLimitPoller.unref();
50366
- }
50367
- #finishTurnCreditsPolling(session) {
50368
- if (!this.#activeTurnSessions.delete(session))
50369
- return;
50370
- void this.#refreshCredits(true);
50371
- if (this.#activeTurnSessions.size > 0 || !this.#planLimitPoller)
50372
- return;
50373
- clearInterval(this.#planLimitPoller);
50374
- this.#planLimitPoller = null;
50375
- }
50376
- /**
50377
- * Plan usage is account-wide, so any one open Session's answer updates the
50378
- * value every Thread reads; the first Session that manages to answer wins
50379
- * and the rest are left untried.
50380
- */
50381
- async #pullPlanLimit() {
50382
- let pulled = false;
50383
- const candidates2 = /* @__PURE__ */ new Set([...this.#activeTurnSessions, ...this.#sessions]);
50384
- for (const session of candidates2) {
50385
- if (await session.refreshPlanLimit()) {
50386
- pulled = true;
50387
- break;
50388
- }
50389
- }
50390
- this.#planLimitPullUnavailable = this.#sessions.size > 0 && !pulled;
50391
- return this.credits();
50392
- }
50393
50506
  close() {
50394
50507
  if (!this.#closePromise) {
50395
50508
  this.#inspectionCache.clear();
50396
- if (this.#planLimitPoller)
50397
- clearInterval(this.#planLimitPoller);
50398
- this.#planLimitPoller = null;
50399
- this.#activeTurnSessions.clear();
50400
50509
  this.#closePromise = Promise.all([
50401
50510
  ...[...this.#inspectors].map((inspector) => inspector.close()),
50402
50511
  ...[...this.#sessions].map((session) => session.close()),
@@ -50416,12 +50525,12 @@ var packageMetadata2 = {
50416
50525
 
50417
50526
  // packages/adapters/deepseek-harness/dist/deepseek-harness-adapter.js
50418
50527
  import { randomUUID as randomUUID3 } from "node:crypto";
50419
- import path10 from "node:path";
50528
+ import path13 from "node:path";
50420
50529
 
50421
50530
  // packages/adapters/deepseek-harness/dist/host-client.js
50422
50531
  import { spawn as spawn3 } from "node:child_process";
50423
50532
  import { accessSync, constants, statSync as statSync2 } from "node:fs";
50424
- import path9 from "node:path";
50533
+ import path12 from "node:path";
50425
50534
 
50426
50535
  // node_modules/@deepseek-ai/dsh-host-apiproxy/lib/types/api/rpc.schema.js
50427
50536
  var rpcIdSchema = external_exports.string();
@@ -51331,16 +51440,16 @@ var AbstractApiClient = class {
51331
51440
  * Shared POST leg of both C→S carriers (callUnary/respond): JSON body,
51332
51441
  * optional default timeout merged with the caller's external signal, non-2xx → transport throw.
51333
51442
  */
51334
- async postJson(path31, body, signal, timeoutPolicy = "default") {
51443
+ async postJson(path32, body, signal, timeoutPolicy = "default") {
51335
51444
  const requestSignal = timeoutPolicy === "default" ? signal === void 0 ? AbortSignal.timeout(this.timeoutMs) : AbortSignal.any([AbortSignal.timeout(this.timeoutMs), signal]) : signal;
51336
- const response = await this.doFetch(new URL(path31, this.resolveBase()), {
51445
+ const response = await this.doFetch(new URL(path32, this.resolveBase()), {
51337
51446
  method: "POST",
51338
51447
  headers: { "content-type": "application/json" },
51339
51448
  body: JSON.stringify(body),
51340
51449
  ...requestSignal === void 0 ? {} : { signal: requestSignal }
51341
51450
  });
51342
51451
  if (!response.ok)
51343
- throw new Error(`transport failure for ${path31}: HTTP ${response.status}`);
51452
+ throw new Error(`transport failure for ${path32}: HTTP ${response.status}`);
51344
51453
  return response;
51345
51454
  }
51346
51455
  /**
@@ -51376,10 +51485,10 @@ var AbstractApiClient = class {
51376
51485
  * either parse level is reported and skipped (one corrupt frame must not kill the stream; the
51377
51486
  * client's gap detection covers whatever the frame carried).
51378
51487
  */
51379
- async *readSse(path31, signal, frameSchema, onOpen) {
51380
- const response = await this.doFetch(new URL(path31, this.resolveBase()), { signal });
51488
+ async *readSse(path32, signal, frameSchema, onOpen) {
51489
+ const response = await this.doFetch(new URL(path32, this.resolveBase()), { signal });
51381
51490
  if (!response.ok || response.body === null)
51382
- throw new Error(`transport failure for ${path31}: HTTP ${response.status}`);
51491
+ throw new Error(`transport failure for ${path32}: HTTP ${response.status}`);
51383
51492
  onOpen?.();
51384
51493
  const reader = response.body.getReader();
51385
51494
  const decoder2 = new TextDecoder();
@@ -51403,7 +51512,7 @@ var AbstractApiClient = class {
51403
51512
  full = serverRequestSchema.parse(JSON.parse(data));
51404
51513
  frame = frameSchema.parse(full.payload);
51405
51514
  } catch (error54) {
51406
- console.error(`[apiproxy] dropping malformed SSE frame on ${path31}:`, error54);
51515
+ console.error(`[apiproxy] dropping malformed SSE frame on ${path32}:`, error54);
51407
51516
  continue;
51408
51517
  }
51409
51518
  this.onEnvelope(full);
@@ -51599,7 +51708,7 @@ var DEFAULT_ENDPOINT = "http://127.0.0.1:3080";
51599
51708
  var DEFAULT_STARTUP_TIMEOUT_MS = 2e4;
51600
51709
  var DEFAULT_COMMAND_TIMEOUT_MS = 5e3;
51601
51710
  var DEFAULT_CLOSE_TIMEOUT_MS2 = 3e3;
51602
- function environmentValue(environment, name) {
51711
+ function environmentValue2(environment, name) {
51603
51712
  return Object.entries(environment).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
51604
51713
  }
51605
51714
  function parseLoopbackEndpoint(endpoint) {
@@ -51619,12 +51728,12 @@ function parseLoopbackEndpoint(endpoint) {
51619
51728
  return parsed;
51620
51729
  }
51621
51730
  function executableCandidates(command, environment) {
51622
- const targetPath = process.platform === "win32" ? path9.win32 : path9.posix;
51623
- if (targetPath.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
51731
+ const targetPath2 = process.platform === "win32" ? path12.win32 : path12.posix;
51732
+ if (targetPath2.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
51624
51733
  return [command];
51625
51734
  }
51626
- const extensions = process.platform === "win32" && targetPath.extname(command) === "" ? (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
51627
- return (environmentValue(environment, "PATH") ?? "").split(targetPath.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath.join(directory, command + extension2)));
51735
+ const extensions = process.platform === "win32" && targetPath2.extname(command) === "" ? (environmentValue2(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
51736
+ return (environmentValue2(environment, "PATH") ?? "").split(targetPath2.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath2.join(directory, command + extension2)));
51628
51737
  }
51629
51738
  function resolveExecutable(command, environment) {
51630
51739
  const accessMode = process.platform === "win32" ? constants.F_OK : constants.X_OK;
@@ -51654,14 +51763,14 @@ function resolveDeepSeekCommand(configured, environment) {
51654
51763
  } : null;
51655
51764
  }
51656
51765
  function deepSeekProcessInvocation(command, arguments_2, environment, platform = process.platform) {
51657
- const extension2 = path9.win32.extname(command).toLowerCase();
51766
+ const extension2 = path12.win32.extname(command).toLowerCase();
51658
51767
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
51659
51768
  return { command, arguments: arguments_2, windowsVerbatimArguments: false };
51660
51769
  }
51661
51770
  const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
51662
51771
  const commandLine = [command, ...arguments_2].map(quote).join(" ");
51663
51772
  return {
51664
- command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
51773
+ command: environmentValue2(environment, "ComSpec") ?? "cmd.exe",
51665
51774
  arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
51666
51775
  windowsVerbatimArguments: true
51667
51776
  };
@@ -51714,8 +51823,15 @@ var DeepSeekHostConnection = class {
51714
51823
  return this.#stderrTail;
51715
51824
  }
51716
51825
  connect() {
51717
- this.#connectPromise ??= this.#performConnect();
51718
- return this.#connectPromise;
51826
+ if (this.#connectPromise)
51827
+ return this.#connectPromise;
51828
+ const attempt = this.#performConnect();
51829
+ this.#connectPromise = attempt;
51830
+ void attempt.catch(() => {
51831
+ if (this.#connectPromise === attempt)
51832
+ this.#connectPromise = null;
51833
+ });
51834
+ return attempt;
51719
51835
  }
51720
51836
  subscribe(sessionId, subscriber) {
51721
51837
  if (this.#subscribers.has(sessionId)) {
@@ -52015,16 +52131,16 @@ var Diff = class {
52015
52131
  }
52016
52132
  }
52017
52133
  }
52018
- addToPath(path31, added, removed, oldPosInc, options) {
52019
- const last = path31.lastComponent;
52134
+ addToPath(path32, added, removed, oldPosInc, options) {
52135
+ const last = path32.lastComponent;
52020
52136
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
52021
52137
  return {
52022
- oldPos: path31.oldPos + oldPosInc,
52138
+ oldPos: path32.oldPos + oldPosInc,
52023
52139
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
52024
52140
  };
52025
52141
  } else {
52026
52142
  return {
52027
- oldPos: path31.oldPos + oldPosInc,
52143
+ oldPos: path32.oldPos + oldPosInc,
52028
52144
  lastComponent: { count: 1, added, removed, previousComponent: last }
52029
52145
  };
52030
52146
  }
@@ -52894,7 +53010,7 @@ var DeepSeekHarnessSession = class {
52894
53010
  harnessId = deepSeekHarnessId;
52895
53011
  capabilities = {
52896
53012
  configuration: {
52897
- selectModel: false,
53013
+ selectModel: true,
52898
53014
  selectThinkingOption: false,
52899
53015
  selectPermissionMode: false
52900
53016
  },
@@ -52912,7 +53028,9 @@ var DeepSeekHarnessSession = class {
52912
53028
  #active = null;
52913
53029
  #closePromise = null;
52914
53030
  #closed = false;
53031
+ #configuring = false;
52915
53032
  #lastSeq;
53033
+ #reading = false;
52916
53034
  #model;
52917
53035
  #contextWindowTokens;
52918
53036
  #turns;
@@ -52946,16 +53064,17 @@ var DeepSeekHarnessSession = class {
52946
53064
  if (this.#closed) {
52947
53065
  return { ok: false, error: invalidState2("DeepSeek Harness Session is closed") };
52948
53066
  }
52949
- if (this.#active) {
53067
+ if (this.#active || this.#configuring || this.#reading) {
52950
53068
  return {
52951
53069
  ok: false,
52952
53070
  error: {
52953
53071
  code: "sessionBusy",
52954
- message: "DeepSeek Harness Session cannot read while a Turn is active",
53072
+ message: "DeepSeek Harness Session cannot read while another operation is active",
52955
53073
  retryable: true
52956
53074
  }
52957
53075
  };
52958
53076
  }
53077
+ this.#reading = true;
52959
53078
  try {
52960
53079
  const entries = await readAllDeepSeekHistory(this.#client, this.#nativeRef.nativeSessionId);
52961
53080
  const projection = projectDeepSeekHistory({
@@ -52987,6 +53106,8 @@ var DeepSeekHarnessSession = class {
52987
53106
  };
52988
53107
  } catch (error54) {
52989
53108
  return { ok: false, error: normalizedError(error54, "nativeFailure") };
53109
+ } finally {
53110
+ this.#reading = false;
52990
53111
  }
52991
53112
  }
52992
53113
  async execute(command) {
@@ -52996,18 +53117,20 @@ var DeepSeekHarnessSession = class {
52996
53117
  return this.#cancel(command);
52997
53118
  if (command.type === "interaction.respond")
52998
53119
  return this.#respond(command);
53120
+ if (command.type === "model.select")
53121
+ return this.#selectModel(command);
52999
53122
  if (command.type !== "turn.start") {
53000
53123
  return {
53001
53124
  ok: false,
53002
53125
  error: unsupported(`DeepSeek Harness does not support '${command.type}'`)
53003
53126
  };
53004
53127
  }
53005
- if (this.#active) {
53128
+ if (this.#active || this.#configuring || this.#reading) {
53006
53129
  return {
53007
53130
  ok: false,
53008
53131
  error: {
53009
53132
  code: "sessionBusy",
53010
- message: "DeepSeek Harness Session already has an active Turn",
53133
+ message: "DeepSeek Harness Session already has another active operation",
53011
53134
  retryable: true
53012
53135
  }
53013
53136
  };
@@ -53115,6 +53238,57 @@ var DeepSeekHarnessSession = class {
53115
53238
  this.#channel.end();
53116
53239
  this.#onClosed();
53117
53240
  }
53241
+ async #selectModel(command) {
53242
+ if (this.#active || this.#configuring || this.#reading) {
53243
+ return {
53244
+ ok: false,
53245
+ error: {
53246
+ code: "sessionBusy",
53247
+ message: "DeepSeek Harness Session cannot select a Model while another operation is active",
53248
+ retryable: true
53249
+ }
53250
+ };
53251
+ }
53252
+ let requested;
53253
+ try {
53254
+ requested = decodeDeepSeekHarnessModelRef(command.model);
53255
+ } catch (error54) {
53256
+ return { ok: false, error: normalizedError(error54, "invalidRequest") };
53257
+ }
53258
+ this.#configuring = true;
53259
+ try {
53260
+ try {
53261
+ unwrapRpc(await this.#client.sessions.selectModel({
53262
+ sessionId: this.#nativeRef.nativeSessionId,
53263
+ provider: requested.provider,
53264
+ model: requested.model
53265
+ }), "session.selectModel");
53266
+ const models = unwrapRpc(await this.#client.sessions.models({
53267
+ sessionId: this.#nativeRef.nativeSessionId
53268
+ }), "session.models");
53269
+ if (models.current.provider !== requested.provider || models.current.model !== requested.model) {
53270
+ return {
53271
+ ok: false,
53272
+ error: {
53273
+ code: "nativeFailure",
53274
+ message: "DeepSeek Harness did not activate the requested Model",
53275
+ retryable: false
53276
+ }
53277
+ };
53278
+ }
53279
+ this.#model = encodeDeepSeekHarnessModelRef(models.current);
53280
+ this.#emit({
53281
+ type: "session.state.changed",
53282
+ state: { nativeRef: this.#nativeRef, effectiveModel: this.#model }
53283
+ });
53284
+ return { ok: true, value: { completed: true } };
53285
+ } catch (error54) {
53286
+ return { ok: false, error: normalizedError(error54, "nativeFailure") };
53287
+ }
53288
+ } finally {
53289
+ this.#configuring = false;
53290
+ }
53291
+ }
53118
53292
  async #cancel(command) {
53119
53293
  const active = this.#active;
53120
53294
  if (!active || active.command.turnId !== command.turnId) {
@@ -53689,7 +53863,7 @@ var DeepSeekHarnessAdapter = class {
53689
53863
  }
53690
53864
  try {
53691
53865
  await this.#connection.connect();
53692
- const cwd = path10.resolve(input.cwd);
53866
+ const cwd = path13.resolve(input.cwd);
53693
53867
  let sessionId;
53694
53868
  if (input.kind === "create") {
53695
53869
  sessionId = `session-${this.#dependencies.randomUUID()}`;
@@ -53785,13 +53959,13 @@ var packageMetadata3 = {
53785
53959
 
53786
53960
  // packages/adapters/grok/dist/grok-adapter.js
53787
53961
  import { randomUUID as randomUUID4 } from "node:crypto";
53788
- import path17 from "node:path";
53962
+ import path20 from "node:path";
53789
53963
 
53790
53964
  // packages/adapters/grok/dist/acp-transport.js
53791
53965
  import { spawn as spawn4, spawnSync } from "node:child_process";
53792
53966
  import { readdir as readdir3, readFile as readFile5 } from "node:fs/promises";
53793
- import os4 from "node:os";
53794
- import path15 from "node:path";
53967
+ import os3 from "node:os";
53968
+ import path18 from "node:path";
53795
53969
  import { Readable, Writable } from "node:stream";
53796
53970
 
53797
53971
  // node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -57956,91 +58130,61 @@ var ClientSideConnection = class {
57956
58130
  };
57957
58131
 
57958
58132
  // packages/adapters/grok/dist/command.js
57959
- import fs2 from "node:fs";
57960
- import os3 from "node:os";
57961
- import path11 from "node:path";
58133
+ import path14 from "node:path";
57962
58134
  var GrokExecutableError = class extends Error {
57963
58135
  code = "GROK_NOT_FOUND";
57964
58136
  };
57965
- function pathValue2(environment) {
57966
- const key = Object.keys(environment).find((name) => name.toLowerCase() === "path");
57967
- return key ? environment[key] ?? "" : "";
57968
- }
57969
- function commandCandidates(command, platform, environment) {
57970
- if (path11.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
57971
- return [command];
57972
- }
57973
- const delimiter = platform === "win32" ? ";" : ":";
57974
- const extensions = platform === "win32" && path11.extname(command) === "" ? (environment.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";") : [""];
57975
- return pathValue2(environment).split(delimiter).filter(Boolean).flatMap((directory) => extensions.map((extension2) => path11.join(directory, command + extension2)));
57976
- }
57977
- function isExecutable2(candidate, platform) {
57978
- try {
57979
- fs2.accessSync(candidate, platform === "win32" ? fs2.constants.F_OK : fs2.constants.X_OK);
57980
- return fs2.statSync(candidate).isFile();
57981
- } catch {
57982
- return false;
58137
+ var grokDiscoverySpec = {
58138
+ id: "grok",
58139
+ command: "grok",
58140
+ commandEnvironmentVariable: "CODEXHOST_GROK_COMMAND",
58141
+ installRoots: {
58142
+ posix: [
58143
+ "~/.grok/bin",
58144
+ "~/.local/bin",
58145
+ VERSION_MANAGER_ROOTS,
58146
+ "/opt/homebrew/bin",
58147
+ "/usr/local/bin"
58148
+ ],
58149
+ windows: ["~/.grok/bin", "${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
57983
58150
  }
57984
- }
58151
+ };
57985
58152
  function resolveGrokExecutable(input = {}) {
57986
- const environment = input.environment ?? process.env;
57987
58153
  const platform = input.platform ?? process.platform;
57988
- const configured = input.command ?? environment.CODEXHOST_GROK_COMMAND;
57989
- const home = input.homeDirectory ?? environment.HOME ?? environment.USERPROFILE ?? os3.homedir();
57990
- const command = configured ?? "grok";
57991
- const userCandidates = platform === "win32" ? [
57992
- path11.join(home, ".grok", "bin", "grok.exe"),
57993
- path11.join(home, ".grok", "bin", "grok.cmd"),
57994
- path11.join(environment.APPDATA ?? path11.join(home, "AppData", "Roaming"), "npm", "grok.cmd")
57995
- ] : [
57996
- path11.join(home, ".grok", "bin", "grok"),
57997
- path11.join(home, ".local", "bin", "grok"),
57998
- "/opt/homebrew/bin/grok",
57999
- "/usr/local/bin/grok"
58000
- ];
58001
- const found = [
58002
- ...commandCandidates(command, platform, environment),
58003
- ...configured ? [] : userCandidates
58004
- ].find((candidate) => isExecutable2(candidate, platform));
58005
- if (!found)
58154
+ const resolution = resolveHarnessExecutable(grokDiscoverySpec, {
58155
+ ...input.command ? { command: input.command } : {},
58156
+ environment: input.environment ?? process.env,
58157
+ ...input.homeDirectory ? { homeDirectory: input.homeDirectory } : {},
58158
+ platform
58159
+ });
58160
+ if (!resolution)
58006
58161
  throw new GrokExecutableError("Grok CLI is not installed");
58007
- return path11.resolve(found);
58162
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path14.resolve(resolution.executable);
58008
58163
  }
58009
58164
  function grokInvocation(command, platform = process.platform) {
58010
- const arguments_2 = ["agent", "--no-leader", "stdio"];
58011
- const extension2 = path11.win32.extname(command).toLowerCase();
58012
- if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
58013
- return { command, arguments: arguments_2, windowsVerbatimArguments: false };
58014
- }
58015
- const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
58016
- const commandLine = [command, ...arguments_2].map(quote).join(" ");
58017
- return {
58018
- command: process.env.ComSpec ?? process.env.COMSPEC ?? "cmd.exe",
58019
- arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
58020
- windowsVerbatimArguments: true
58021
- };
58165
+ return commandInvocation(command, ["agent", "--no-leader", "stdio"], process.env, platform);
58022
58166
  }
58023
58167
 
58024
58168
  // packages/adapters/grok/dist/grok-fork.js
58025
58169
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
58026
- import path13 from "node:path";
58170
+ import path16 from "node:path";
58027
58171
 
58028
58172
  // packages/adapters/grok/dist/grok-file-change.js
58029
58173
  import { Buffer as Buffer4 } from "node:buffer";
58030
- import path12 from "node:path";
58174
+ import path15 from "node:path";
58031
58175
  var DEFAULT_GROK_FILE_CHANGE_TEXT_LIMIT = 4 * 1024 * 1024;
58032
58176
  var MAX_GROK_FILE_CHANGES_PER_TOOL = 32;
58033
58177
  function isRecord11(value) {
58034
58178
  return typeof value === "object" && value !== null && !Array.isArray(value);
58035
58179
  }
58036
58180
  function validAbsolutePath(value) {
58037
- return typeof value === "string" && path12.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
58181
+ return typeof value === "string" && path15.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
58038
58182
  }
58039
58183
  function displayPath2(nativePath, cwd) {
58040
- const resolvedCwd = path12.resolve(cwd);
58041
- const resolvedPath = path12.resolve(nativePath);
58042
- const relative = path12.relative(resolvedCwd, resolvedPath);
58043
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path12.sep}`);
58184
+ const resolvedCwd = path15.resolve(cwd);
58185
+ const resolvedPath = path15.resolve(nativePath);
58186
+ const relative = path15.relative(resolvedCwd, resolvedPath);
58187
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path15.sep}`);
58044
58188
  const selected = inside ? relative : resolvedPath;
58045
58189
  const normalized = selected.replaceAll("\\", "/");
58046
58190
  if (normalized.length === 0 || normalized === ".")
@@ -58079,17 +58223,17 @@ function projectDiff(value, cwd, remainingTextBytes) {
58079
58223
  function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHANGE_TEXT_LIMIT) {
58080
58224
  if (!Number.isSafeInteger(textLimit) || textLimit <= 0 || !Array.isArray(content))
58081
58225
  return null;
58082
- const candidates2 = [];
58226
+ const candidates = [];
58083
58227
  for (const entry of content) {
58084
58228
  if (isRecord11(entry) && entry.type === "diff")
58085
- candidates2.push(entry);
58229
+ candidates.push(entry);
58086
58230
  }
58087
- if (candidates2.length === 0 || candidates2.length > MAX_GROK_FILE_CHANGES_PER_TOOL)
58231
+ if (candidates.length === 0 || candidates.length > MAX_GROK_FILE_CHANGES_PER_TOOL)
58088
58232
  return null;
58089
58233
  const changes = [];
58090
58234
  const paths = /* @__PURE__ */ new Set();
58091
58235
  let textBytes = 0;
58092
- for (const candidate of candidates2) {
58236
+ for (const candidate of candidates) {
58093
58237
  const projected = projectDiff(candidate, cwd, textLimit - textBytes);
58094
58238
  if (!projected || paths.has(projected.change.path))
58095
58239
  return null;
@@ -58129,8 +58273,8 @@ function decodeBytes(value) {
58129
58273
  return void 0;
58130
58274
  }
58131
58275
  }
58132
- function firstReadableText(...candidates2) {
58133
- for (const candidate of candidates2) {
58276
+ function firstReadableText(...candidates) {
58277
+ for (const candidate of candidates) {
58134
58278
  if (typeof candidate === "string" && candidate.length > 0)
58135
58279
  return candidate;
58136
58280
  if (isRecord12(candidate)) {
@@ -58616,11 +58760,11 @@ function parseGrokForkResponse(value) {
58616
58760
  }
58617
58761
  function projectRelativePath(value, cwds) {
58618
58762
  const normalized = value.replaceAll("\\", "/");
58619
- if (!path13.isAbsolute(value))
58763
+ if (!path16.isAbsolute(value))
58620
58764
  return normalized;
58621
58765
  for (const cwd of cwds) {
58622
- const relative = path13.relative(path13.resolve(cwd), path13.resolve(value));
58623
- if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path13.sep}`)) {
58766
+ const relative = path16.relative(path16.resolve(cwd), path16.resolve(value));
58767
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path16.sep}`)) {
58624
58768
  return relative.replaceAll("\\", "/");
58625
58769
  }
58626
58770
  }
@@ -58685,8 +58829,8 @@ async function forkGrokSession(input) {
58685
58829
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
58686
58830
  };
58687
58831
  }
58688
- const sourceCwd = path13.resolve(located.cwd);
58689
- const targetCwd = path13.resolve(input.cwd);
58832
+ const sourceCwd = path16.resolve(located.cwd);
58833
+ const targetCwd = path16.resolve(input.cwd);
58690
58834
  const source = await readSnapshot2({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
58691
58835
  if (!source.ok)
58692
58836
  return source;
@@ -58868,7 +59012,7 @@ function parseGrokCompactResult(value, cancelled = false) {
58868
59012
  }
58869
59013
 
58870
59014
  // packages/adapters/grok/dist/grok-rewind.js
58871
- import path14 from "node:path";
59015
+ import path17 from "node:path";
58872
59016
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
58873
59017
  function error53(code, message5, retryable = false) {
58874
59018
  return { code, message: message5, retryable };
@@ -58941,8 +59085,8 @@ async function rewindGrokLastTurn(input) {
58941
59085
  error: error53("sessionNotFound", "Grok Native Session is unavailable")
58942
59086
  };
58943
59087
  }
58944
- const sourceCwd = path14.resolve(located.cwd);
58945
- const targetCwd = path14.resolve(input.cwd);
59088
+ const sourceCwd = path17.resolve(located.cwd);
59089
+ const targetCwd = path17.resolve(input.cwd);
58946
59090
  if (sourceCwd !== targetCwd) {
58947
59091
  return {
58948
59092
  ok: false,
@@ -59187,11 +59331,11 @@ function transportEvent(update, metadata) {
59187
59331
  }
59188
59332
  function grokHomeDir(options) {
59189
59333
  const environment = { ...process.env, ...options.environment };
59190
- const home = environment.HOME ?? environment.USERPROFILE ?? os4.homedir();
59191
- return environment.GROK_HOME ?? path15.join(home, ".grok");
59334
+ const home = environment.HOME ?? environment.USERPROFILE ?? os3.homedir();
59335
+ return environment.GROK_HOME ?? path18.join(home, ".grok");
59192
59336
  }
59193
59337
  function nativeSessionFile(options, sessionId, fileName) {
59194
- return path15.join(grokHomeDir(options), "sessions", encodeURIComponent(path15.resolve(options.cwd)), sessionId, fileName);
59338
+ return path18.join(grokHomeDir(options), "sessions", encodeURIComponent(path18.resolve(options.cwd)), sessionId, fileName);
59195
59339
  }
59196
59340
  function nativeHistoryPath(options, sessionId) {
59197
59341
  return nativeSessionFile(options, sessionId, "updates.jsonl");
@@ -59211,7 +59355,7 @@ async function locateGrokNativeSession(options, sessionId) {
59211
59355
  return null;
59212
59356
  let entries;
59213
59357
  try {
59214
- entries = await readdir3(path15.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
59358
+ entries = await readdir3(path18.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
59215
59359
  } catch (error54) {
59216
59360
  if (isMissingFile(error54))
59217
59361
  return null;
@@ -59225,7 +59369,7 @@ async function locateGrokNativeSession(options, sessionId) {
59225
59369
  continue;
59226
59370
  let summaryRaw;
59227
59371
  try {
59228
- summaryRaw = await readFile5(path15.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
59372
+ summaryRaw = await readFile5(path18.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
59229
59373
  } catch (error54) {
59230
59374
  if (isMissingFile(error54) || isRecord17(error54) && error54.code === "ENOTDIR")
59231
59375
  continue;
@@ -59242,8 +59386,8 @@ async function locateGrokNativeSession(options, sessionId) {
59242
59386
  if (!isRecord17(parsed))
59243
59387
  continue;
59244
59388
  const info = parsed.info;
59245
- const cwd = isRecord17(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path15.resolve(info.cwd) : path15.resolve(decodeURIComponent(entry.name));
59246
- const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path15.resolve(parsed.source_workspace_dir) : void 0;
59389
+ const cwd = isRecord17(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path18.resolve(info.cwd) : path18.resolve(decodeURIComponent(entry.name));
59390
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path18.resolve(parsed.source_workspace_dir) : void 0;
59247
59391
  matches.push({
59248
59392
  cwd,
59249
59393
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -59253,7 +59397,7 @@ async function locateGrokNativeSession(options, sessionId) {
59253
59397
  }
59254
59398
  async function readGrokNativeHistory(options, sessionId) {
59255
59399
  try {
59256
- return parseNativeHistory(await readFile5(nativeHistoryPath({ ...options, cwd: path15.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
59400
+ return parseNativeHistory(await readFile5(nativeHistoryPath({ ...options, cwd: path18.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
59257
59401
  } catch (error54) {
59258
59402
  if (isMissingFile(error54))
59259
59403
  return [];
@@ -59764,8 +59908,8 @@ function stateForGrokModel(modelState, nativeState, model = modelState.currentMo
59764
59908
 
59765
59909
  // packages/adapters/grok/dist/grok-credits.js
59766
59910
  import { readFile as readFile6 } from "node:fs/promises";
59767
- import os5 from "node:os";
59768
- import path16 from "node:path";
59911
+ import os4 from "node:os";
59912
+ import path19 from "node:path";
59769
59913
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
59770
59914
  var REQUEST_TIMEOUT_MS = 15e3;
59771
59915
  function isRecord19(value) {
@@ -59782,7 +59926,7 @@ function nonNegativeNumber(value) {
59782
59926
  return value;
59783
59927
  }
59784
59928
  function grokHome(environment) {
59785
- return environment.GROK_HOME ?? path16.join(environment.HOME ?? environment.USERPROFILE ?? os5.homedir(), ".grok");
59929
+ return environment.GROK_HOME ?? path19.join(environment.HOME ?? environment.USERPROFILE ?? os4.homedir(), ".grok");
59786
59930
  }
59787
59931
  function periodTypeFrom(value) {
59788
59932
  if (typeof value !== "string")
@@ -59845,7 +59989,7 @@ async function fetchGrokCredits(input = {}) {
59845
59989
  try {
59846
59990
  const environment = input.environment ?? process.env;
59847
59991
  const now = input.now ?? /* @__PURE__ */ new Date();
59848
- const authPath = path16.join(grokHome(environment), "auth.json");
59992
+ const authPath = path19.join(grokHome(environment), "auth.json");
59849
59993
  const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile6(authPath, "utf8");
59850
59994
  const token = selectAccessToken(JSON.parse(raw), now);
59851
59995
  if (!token)
@@ -60905,7 +61049,7 @@ var GrokAdapter = class {
60905
61049
  async inspect(input = {}) {
60906
61050
  if (this.#closePromise)
60907
61051
  return { status: "unavailable", error: invalidState3("Grok Adapter is closed") };
60908
- const cwd = path17.resolve(input.cwd ?? process.cwd());
61052
+ const cwd = path20.resolve(input.cwd ?? process.cwd());
60909
61053
  if (!input.refresh) {
60910
61054
  const cached2 = this.#inspectionCache.get(cwd);
60911
61055
  if (cached2)
@@ -60967,7 +61111,7 @@ var GrokAdapter = class {
60967
61111
  }
60968
61112
  };
60969
61113
  }
60970
- const cwd = path17.resolve(input.cwd);
61114
+ const cwd = path20.resolve(input.cwd);
60971
61115
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
60972
61116
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
60973
61117
  return {
@@ -61554,79 +61698,32 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
61554
61698
  // packages/adapters/pi/dist/pi-rpc-session.js
61555
61699
  import { spawn as spawn5, spawnSync as spawnSync2 } from "node:child_process";
61556
61700
  import { randomUUID as randomUUID5 } from "node:crypto";
61557
- import path19 from "node:path";
61701
+ import path21 from "node:path";
61558
61702
 
61559
61703
  // packages/adapters/pi/dist/command.js
61560
- import { accessSync as accessSync2, constants as constants2, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
61561
- import os6 from "node:os";
61562
- import path18 from "node:path";
61563
- function environmentValue2(environment, name) {
61564
- return Object.entries(environment).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
61565
- }
61566
- function isExecutable3(filePath, platform) {
61567
- try {
61568
- accessSync2(filePath, platform === "win32" ? constants2.F_OK : constants2.X_OK);
61569
- return statSync3(filePath).isFile();
61570
- } catch {
61571
- return false;
61572
- }
61573
- }
61574
- function pathCandidates(command, platform, environment) {
61575
- const targetPath = platform === "win32" ? path18.win32 : path18.posix;
61576
- if (targetPath.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
61577
- return [command];
61578
- }
61579
- const extensions = platform === "win32" && targetPath.extname(command) === "" ? (environmentValue2(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
61580
- return (environmentValue2(environment, "PATH") ?? "").split(targetPath.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath.join(directory, command + extension2)));
61581
- }
61582
- function nvmCandidates2(homeDirectory, executableName, targetPath) {
61583
- const versionsDirectory = targetPath.join(homeDirectory, ".nvm", "versions", "node");
61584
- try {
61585
- return readdirSync2(versionsDirectory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((left, right) => right.localeCompare(left, void 0, { numeric: true })).map((version2) => targetPath.join(versionsDirectory, version2, "bin", executableName));
61586
- } catch {
61587
- return [];
61588
- }
61589
- }
61590
- function userInstallCandidates2(platform, environment, homeDirectory) {
61591
- const targetPath = platform === "win32" ? path18.win32 : path18.posix;
61592
- if (platform === "win32") {
61593
- const appData = environment.APPDATA ?? targetPath.join(homeDirectory, "AppData", "Roaming");
61594
- return [
61595
- targetPath.join(appData, "npm", "pi.cmd"),
61596
- targetPath.join(homeDirectory, ".local", "bin", "pi.exe"),
61597
- targetPath.join(homeDirectory, ".local", "bin", "pi.cmd")
61598
- ];
61704
+ var piDiscoverySpec = {
61705
+ id: "pi",
61706
+ command: "pi",
61707
+ commandEnvironmentVariable: "PI_COMMAND",
61708
+ installRoots: {
61709
+ posix: [
61710
+ "~/.npm-global/bin",
61711
+ "~/.local/bin",
61712
+ VERSION_MANAGER_ROOTS,
61713
+ "/opt/homebrew/bin",
61714
+ "/usr/local/bin"
61715
+ ],
61716
+ windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
61599
61717
  }
61600
- return [
61601
- targetPath.join(homeDirectory, ".npm-global", "bin", "pi"),
61602
- targetPath.join(homeDirectory, ".local", "bin", "pi"),
61603
- ...nvmCandidates2(homeDirectory, "pi", targetPath),
61604
- "/opt/homebrew/bin/pi",
61605
- "/usr/local/bin/pi"
61606
- ];
61607
- }
61718
+ };
61608
61719
  function resolvePiExecutable(input, dependencies2 = {}) {
61609
- const platform = dependencies2.platform ?? process.platform;
61610
- const configuredCommand = input.command ?? input.environment.PI_COMMAND;
61611
- const command = configuredCommand ?? "pi";
61612
- const homeDirectory = dependencies2.homeDirectory ?? input.environment.HOME ?? input.environment.USERPROFILE ?? os6.homedir();
61613
- const candidates2 = [
61614
- ...pathCandidates(command, platform, input.environment),
61615
- ...configuredCommand ? [] : userInstallCandidates2(platform, input.environment, homeDirectory)
61616
- ];
61617
- const check2 = dependencies2.isExecutable ?? ((candidate) => isExecutable3(candidate, platform));
61618
- return candidates2.find(check2) ?? command;
61619
- }
61620
- function withNodeRuntimeOnPath2(environment, runtimeExecutable = process.execPath, platform = process.platform) {
61621
- const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
61622
- const delimiter = platform === "win32" ? ";" : ":";
61623
- const runtimeDirectory = path18.dirname(runtimeExecutable);
61624
- const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
61625
- const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
61626
- if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
61627
- directories.unshift(runtimeDirectory);
61628
- }
61629
- return { ...environment, [pathKey]: directories.join(delimiter) };
61720
+ const resolution = resolveHarnessExecutable(piDiscoverySpec, {
61721
+ ...input.command ? { command: input.command } : {},
61722
+ environment: input.environment,
61723
+ ...dependencies2.platform ? { platform: dependencies2.platform } : {},
61724
+ ...dependencies2.homeDirectory ? { homeDirectory: dependencies2.homeDirectory } : {}
61725
+ }, { ...dependencies2.isExecutable ? { isExecutable: dependencies2.isExecutable } : {} });
61726
+ return resolution?.executable ?? input.command ?? input.environment.PI_COMMAND ?? "pi";
61630
61727
  }
61631
61728
 
61632
61729
  // packages/adapters/pi/dist/pi-usage.js
@@ -61931,7 +62028,7 @@ function piRpcProcessCommand(options, dependencies2 = {}) {
61931
62028
  const sessionArguments = options.forkSessionFile ? ["--fork", options.forkSessionFile] : options.sessionFile ? ["--session", options.sessionFile] : [];
61932
62029
  const modelArguments = options.model ? ["--provider", options.model.provider, "--model", options.model.id] : [];
61933
62030
  const arguments_2 = ["--mode", "rpc", ...modelArguments, ...sessionArguments];
61934
- const extension2 = path19.win32.extname(command).toLowerCase();
62031
+ const extension2 = path21.win32.extname(command).toLowerCase();
61935
62032
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
61936
62033
  return { command, arguments: arguments_2, windowsVerbatimArguments: false };
61937
62034
  }
@@ -62002,7 +62099,7 @@ var PiRpcSession = class {
62002
62099
  const child = this.#processAdapter.spawn({
62003
62100
  cwd: this.#options.cwd,
62004
62101
  ...this.#options.command ? { command: this.#options.command } : {},
62005
- environment: withNodeRuntimeOnPath2({
62102
+ environment: withNodeRuntimeOnPath({
62006
62103
  ...process.env,
62007
62104
  ...this.#options.environment,
62008
62105
  PI_SKIP_VERSION_CHECK: "1",
@@ -62898,8 +62995,8 @@ function numberField2(value, key) {
62898
62995
  const field = value[key];
62899
62996
  return typeof field === "number" || field === null ? field : void 0;
62900
62997
  }
62901
- function stripDiffPrefix(path31) {
62902
- return path31.startsWith("a/") || path31.startsWith("b/") ? path31.slice(2) : path31;
62998
+ function stripDiffPrefix(path32) {
62999
+ return path32.startsWith("a/") || path32.startsWith("b/") ? path32.slice(2) : path32;
62903
63000
  }
62904
63001
  function reliableFileChange(result) {
62905
63002
  if (!isRecord25(result) || !isRecord25(result.details) || typeof result.details.patch !== "string") {
@@ -62918,10 +63015,10 @@ function reliableFileChange(result) {
62918
63015
  const oldFile = file2.oldFileName;
62919
63016
  const newFile = file2.newFileName;
62920
63017
  const kind = oldFile === "/dev/null" ? "add" : newFile === "/dev/null" ? "delete" : "update";
62921
- const path31 = stripDiffPrefix(kind === "delete" ? oldFile : newFile);
62922
- if (!path31 || path31 === "/dev/null")
63018
+ const path32 = stripDiffPrefix(kind === "delete" ? oldFile : newFile);
63019
+ if (!path32 || path32 === "/dev/null")
62923
63020
  return null;
62924
- return [{ path: path31, kind, unifiedDiff: patch }];
63021
+ return [{ path: path32, kind, unifiedDiff: patch }];
62925
63022
  }
62926
63023
  function delay4(milliseconds) {
62927
63024
  return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
@@ -64645,79 +64742,32 @@ async function rollbackOmpLastTurn(transport, sourceSessionId, cwd) {
64645
64742
  // packages/adapters/omp/dist/omp-rpc-session.js
64646
64743
  import { spawn as spawn6, spawnSync as spawnSync3 } from "node:child_process";
64647
64744
  import { randomUUID as randomUUID7 } from "node:crypto";
64648
- import path21 from "node:path";
64745
+ import path22 from "node:path";
64649
64746
 
64650
64747
  // packages/adapters/omp/dist/command.js
64651
- import { accessSync as accessSync3, constants as constants3, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
64652
- import os7 from "node:os";
64653
- import path20 from "node:path";
64654
- function environmentValue3(environment, name) {
64655
- return Object.entries(environment).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
64656
- }
64657
- function isExecutable4(filePath, platform) {
64658
- try {
64659
- accessSync3(filePath, platform === "win32" ? constants3.F_OK : constants3.X_OK);
64660
- return statSync4(filePath).isFile();
64661
- } catch {
64662
- return false;
64663
- }
64664
- }
64665
- function pathCandidates2(command, platform, environment) {
64666
- const targetPath = platform === "win32" ? path20.win32 : path20.posix;
64667
- if (targetPath.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
64668
- return [command];
64669
- }
64670
- const extensions = platform === "win32" && targetPath.extname(command) === "" ? (environmentValue3(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
64671
- return (environmentValue3(environment, "PATH") ?? "").split(targetPath.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath.join(directory, command + extension2)));
64672
- }
64673
- function nvmCandidates3(homeDirectory, executableName, targetPath) {
64674
- const versionsDirectory = targetPath.join(homeDirectory, ".nvm", "versions", "node");
64675
- try {
64676
- return readdirSync3(versionsDirectory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((left, right) => right.localeCompare(left, void 0, { numeric: true })).map((version2) => targetPath.join(versionsDirectory, version2, "bin", executableName));
64677
- } catch {
64678
- return [];
64679
- }
64680
- }
64681
- function userInstallCandidates3(platform, environment, homeDirectory) {
64682
- const targetPath = platform === "win32" ? path20.win32 : path20.posix;
64683
- if (platform === "win32") {
64684
- const appData = environment.APPDATA ?? targetPath.join(homeDirectory, "AppData", "Roaming");
64685
- return [
64686
- targetPath.join(appData, "npm", "omp.cmd"),
64687
- targetPath.join(homeDirectory, ".local", "bin", "omp.exe"),
64688
- targetPath.join(homeDirectory, ".local", "bin", "omp.cmd")
64689
- ];
64748
+ var ompDiscoverySpec = {
64749
+ id: "omp",
64750
+ command: "omp",
64751
+ commandEnvironmentVariable: "OMP_COMMAND",
64752
+ installRoots: {
64753
+ posix: [
64754
+ "~/.npm-global/bin",
64755
+ "~/.local/bin",
64756
+ VERSION_MANAGER_ROOTS,
64757
+ "/opt/homebrew/bin",
64758
+ "/usr/local/bin"
64759
+ ],
64760
+ windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
64690
64761
  }
64691
- return [
64692
- targetPath.join(homeDirectory, ".npm-global", "bin", "omp"),
64693
- targetPath.join(homeDirectory, ".local", "bin", "omp"),
64694
- ...nvmCandidates3(homeDirectory, "omp", targetPath),
64695
- "/opt/homebrew/bin/omp",
64696
- "/usr/local/bin/omp"
64697
- ];
64698
- }
64762
+ };
64699
64763
  function resolveOmpExecutable(input, dependencies2 = {}) {
64700
- const platform = dependencies2.platform ?? process.platform;
64701
- const configuredCommand = input.command ?? input.environment.OMP_COMMAND;
64702
- const command = configuredCommand ?? "omp";
64703
- const homeDirectory = dependencies2.homeDirectory ?? input.environment.HOME ?? input.environment.USERPROFILE ?? os7.homedir();
64704
- const candidates2 = [
64705
- ...pathCandidates2(command, platform, input.environment),
64706
- ...configuredCommand ? [] : userInstallCandidates3(platform, input.environment, homeDirectory)
64707
- ];
64708
- const check2 = dependencies2.isExecutable ?? ((candidate) => isExecutable4(candidate, platform));
64709
- return candidates2.find(check2) ?? command;
64710
- }
64711
- function withNodeRuntimeOnPath3(environment, runtimeExecutable = process.execPath, platform = process.platform) {
64712
- const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
64713
- const delimiter = platform === "win32" ? ";" : ":";
64714
- const runtimeDirectory = path20.dirname(runtimeExecutable);
64715
- const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
64716
- const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
64717
- if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
64718
- directories.unshift(runtimeDirectory);
64719
- }
64720
- return { ...environment, [pathKey]: directories.join(delimiter) };
64764
+ const resolution = resolveHarnessExecutable(ompDiscoverySpec, {
64765
+ ...input.command ? { command: input.command } : {},
64766
+ environment: input.environment,
64767
+ ...dependencies2.platform ? { platform: dependencies2.platform } : {},
64768
+ ...dependencies2.homeDirectory ? { homeDirectory: dependencies2.homeDirectory } : {}
64769
+ }, { ...dependencies2.isExecutable ? { isExecutable: dependencies2.isExecutable } : {} });
64770
+ return resolution?.executable ?? input.command ?? input.environment.OMP_COMMAND ?? "omp";
64721
64771
  }
64722
64772
 
64723
64773
  // packages/adapters/omp/dist/omp-usage.js
@@ -65139,7 +65189,7 @@ function ompRpcProcessCommand(options, dependencies2 = {}) {
65139
65189
  const sessionArguments = options.forkSessionFile ? ["--fork", options.forkSessionFile] : options.sessionFile ? ["--resume", options.sessionFile] : [];
65140
65190
  const modelArguments = options.model ? ["--provider", options.model.provider, "--model", options.model.id] : [];
65141
65191
  const arguments_2 = ["--mode", "rpc", ...modelArguments, ...sessionArguments];
65142
- const extension2 = path21.win32.extname(command).toLowerCase();
65192
+ const extension2 = path22.win32.extname(command).toLowerCase();
65143
65193
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
65144
65194
  return { command, arguments: arguments_2, windowsVerbatimArguments: false };
65145
65195
  }
@@ -65215,7 +65265,7 @@ var OmpRpcSession = class {
65215
65265
  const child = this.#processAdapter.spawn({
65216
65266
  cwd: this.#options.cwd,
65217
65267
  ...this.#options.command ? { command: this.#options.command } : {},
65218
- environment: withNodeRuntimeOnPath3({
65268
+ environment: withNodeRuntimeOnPath({
65219
65269
  ...process.env,
65220
65270
  ...this.#options.environment,
65221
65271
  OMP_SKIP_VERSION_CHECK: "1",
@@ -66229,8 +66279,8 @@ function numberField3(value, key) {
66229
66279
  const field = value[key];
66230
66280
  return typeof field === "number" || field === null ? field : void 0;
66231
66281
  }
66232
- function stripDiffPrefix2(path31) {
66233
- return path31.startsWith("a/") || path31.startsWith("b/") ? path31.slice(2) : path31;
66282
+ function stripDiffPrefix2(path32) {
66283
+ return path32.startsWith("a/") || path32.startsWith("b/") ? path32.slice(2) : path32;
66234
66284
  }
66235
66285
  function reliableFileChange2(result) {
66236
66286
  if (!isRecord30(result) || !isRecord30(result.details) || typeof result.details.patch !== "string") {
@@ -66249,10 +66299,10 @@ function reliableFileChange2(result) {
66249
66299
  const oldFile = file2.oldFileName;
66250
66300
  const newFile = file2.newFileName;
66251
66301
  const kind = oldFile === "/dev/null" ? "add" : newFile === "/dev/null" ? "delete" : "update";
66252
- const path31 = stripDiffPrefix2(kind === "delete" ? oldFile : newFile);
66253
- if (!path31 || path31 === "/dev/null")
66302
+ const path32 = stripDiffPrefix2(kind === "delete" ? oldFile : newFile);
66303
+ if (!path32 || path32 === "/dev/null")
66254
66304
  return null;
66255
- return [{ path: path31, kind, unifiedDiff: patch }];
66305
+ return [{ path: path32, kind, unifiedDiff: patch }];
66256
66306
  }
66257
66307
  function delay5(milliseconds) {
66258
66308
  return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
@@ -67739,9 +67789,9 @@ import nodePath from "node:path";
67739
67789
  // packages/mapping-store/dist/mapping-store.js
67740
67790
  import { execFileSync } from "node:child_process";
67741
67791
  import { randomUUID as randomUUID9 } from "node:crypto";
67742
- import { constants as constants4 } from "node:fs";
67792
+ import { constants as constants2 } from "node:fs";
67743
67793
  import { copyFile as copyFile2, mkdir as mkdir3, open as open5, readFile as readFile7, readdir as readdir4, rename as rename2, rm as rm4, stat as stat2 } from "node:fs/promises";
67744
- import path22 from "node:path";
67794
+ import path23 from "node:path";
67745
67795
 
67746
67796
  // packages/mapping-store/dist/records.js
67747
67797
  var nonBlankTextSchema3 = external_exports.string().refine((value) => value.trim().length > 0, {
@@ -67963,11 +68013,11 @@ var MappingStore = class {
67963
68013
  #initialized = false;
67964
68014
  #lockHandle = null;
67965
68015
  constructor(options) {
67966
- this.#directory = path22.resolve(options.directory);
67967
- this.#threadsDirectory = path22.join(this.#directory, "threads");
67968
- this.#backupsDirectory = path22.join(this.#directory, "backups");
67969
- this.#quarantineDirectory = path22.join(this.#directory, "quarantine");
67970
- this.#lockPath = path22.join(this.#directory, "store.lock");
68016
+ this.#directory = path23.resolve(options.directory);
68017
+ this.#threadsDirectory = path23.join(this.#directory, "threads");
68018
+ this.#backupsDirectory = path23.join(this.#directory, "backups");
68019
+ this.#quarantineDirectory = path23.join(this.#directory, "quarantine");
68020
+ this.#lockPath = path23.join(this.#directory, "store.lock");
67971
68021
  this.#instanceId = options.instanceId ?? randomUUID9();
67972
68022
  this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
67973
68023
  this.#beforeReplace = options.beforeReplace;
@@ -67985,8 +68035,8 @@ var MappingStore = class {
67985
68035
  await this.#cleanupTemps();
67986
68036
  const names = (await readdir4(this.#threadsDirectory)).filter((name) => name.endsWith(".json"));
67987
68037
  for (const name of names) {
67988
- const primary = path22.join(this.#threadsDirectory, name);
67989
- const backup = path22.join(this.#backupsDirectory, name);
68038
+ const primary = path23.join(this.#threadsDirectory, name);
68039
+ const backup = path23.join(this.#backupsDirectory, name);
67990
68040
  let record3 = null;
67991
68041
  try {
67992
68042
  record3 = await this.#readRecord(primary, name);
@@ -67995,7 +68045,7 @@ var MappingStore = class {
67995
68045
  record3 = await this.#readRecord(backup, name);
67996
68046
  await this.#replaceFile(primary, record3, false);
67997
68047
  } catch (backupError) {
67998
- const quarantine = path22.join(this.#quarantineDirectory, `${name}.${this.#now().getTime()}.invalid`);
68048
+ const quarantine = path23.join(this.#quarantineDirectory, `${name}.${this.#now().getTime()}.invalid`);
67999
68049
  await rename2(primary, quarantine).catch(() => void 0);
68000
68050
  void primaryError;
68001
68051
  void backupError;
@@ -68245,7 +68295,7 @@ var MappingStore = class {
68245
68295
  let handle = null;
68246
68296
  try {
68247
68297
  await this.#beforeReplace?.(cloneRecord(record3));
68248
- handle = await open5(temp, "wx", constants4.S_IRUSR | constants4.S_IWUSR);
68298
+ handle = await open5(temp, "wx", constants2.S_IRUSR | constants2.S_IWUSR);
68249
68299
  await handle.writeFile(`${JSON.stringify(record3, null, 2)}
68250
68300
  `, "utf8");
68251
68301
  await handle.sync();
@@ -68279,11 +68329,11 @@ var MappingStore = class {
68279
68329
  }
68280
68330
  async #cleanupTemps() {
68281
68331
  const names = await readdir4(this.#threadsDirectory);
68282
- await Promise.all(names.filter((name) => name.includes(".tmp-")).map((name) => rm4(path22.join(this.#threadsDirectory, name), { force: true })));
68332
+ await Promise.all(names.filter((name) => name.includes(".tmp-")).map((name) => rm4(path23.join(this.#threadsDirectory, name), { force: true })));
68283
68333
  }
68284
68334
  async #acquireLock() {
68285
68335
  const attempt = async () => {
68286
- const handle = await open5(this.#lockPath, "wx", constants4.S_IRUSR | constants4.S_IWUSR);
68336
+ const handle = await open5(this.#lockPath, "wx", constants2.S_IRUSR | constants2.S_IWUSR);
68287
68337
  const lock = {
68288
68338
  pid: process.pid,
68289
68339
  instanceId: this.#instanceId,
@@ -68372,10 +68422,10 @@ var MappingStore = class {
68372
68422
  }
68373
68423
  }
68374
68424
  #recordPath(hostThreadId) {
68375
- return path22.join(this.#threadsDirectory, `${hostThreadId}.json`);
68425
+ return path23.join(this.#threadsDirectory, `${hostThreadId}.json`);
68376
68426
  }
68377
68427
  #backupPath(hostThreadId) {
68378
- return path22.join(this.#backupsDirectory, `${hostThreadId}.json`);
68428
+ return path23.join(this.#backupsDirectory, `${hostThreadId}.json`);
68379
68429
  }
68380
68430
  #requireInitialized() {
68381
68431
  if (!this.#initialized) {
@@ -68774,17 +68824,17 @@ function rateLimitCandidates(value) {
68774
68824
  const result = isRecord33(value.result) ? value.result : value;
68775
68825
  if (!isRecord33(result))
68776
68826
  return [];
68777
- const candidates2 = [];
68827
+ const candidates = [];
68778
68828
  const base = parseRateLimitCandidate(result.rateLimits, { genericOnly: true });
68779
68829
  if (base)
68780
- candidates2.push(base);
68830
+ candidates.push(base);
68781
68831
  const notificationParams = isRecord33(value.params) ? value.params : void 0;
68782
68832
  const notificationSnapshot = parseRateLimitCandidate(notificationParams?.rateLimits, {
68783
68833
  genericOnly: true
68784
68834
  });
68785
68835
  if (notificationSnapshot)
68786
- candidates2.push(notificationSnapshot);
68787
- return candidates2;
68836
+ candidates.push(notificationSnapshot);
68837
+ return candidates;
68788
68838
  }
68789
68839
  function candidateScore(candidate) {
68790
68840
  return [candidate.primary, candidate.secondary].filter((window2) => window2?.windowDurationMins === 300 || window2?.windowDurationMins === 10080).length;
@@ -68919,8 +68969,8 @@ function projectItem(item, outcome, defaultCwd, includeCommandOutput = true, sen
68919
68969
  return {
68920
68970
  id: item.itemId,
68921
68971
  type: "fileChange",
68922
- changes: item.changes.map(({ path: path31, kind, unifiedDiff }) => ({
68923
- path: path31,
68972
+ changes: item.changes.map(({ path: path32, kind, unifiedDiff }) => ({
68973
+ path: path32,
68924
68974
  kind,
68925
68975
  diff: unifiedDiff
68926
68976
  })),
@@ -69367,8 +69417,8 @@ var CodexTurnProjector = class {
69367
69417
  return messages;
69368
69418
  }
69369
69419
  #fileChangeUpdates(itemId4, changes) {
69370
- const projectedChanges = changes.map(({ path: path31, kind, unifiedDiff }) => ({
69371
- path: path31,
69420
+ const projectedChanges = changes.map(({ path: path32, kind, unifiedDiff }) => ({
69421
+ path: path32,
69372
69422
  kind,
69373
69423
  diff: unifiedDiff
69374
69424
  }));
@@ -69451,13 +69501,13 @@ function decodeThreadForkRequest(request) {
69451
69501
  if (runtimeWorkspaceRoots !== void 0 && runtimeWorkspaceRoots !== null && (!Array.isArray(runtimeWorkspaceRoots) || runtimeWorkspaceRoots.some((root) => typeof root !== "string" || root.length === 0))) {
69452
69502
  throw new Error("thread/fork params.runtimeWorkspaceRoots must be text paths or null");
69453
69503
  }
69454
- const path31 = optionalText(params, "path", { allowEmpty: true });
69504
+ const path32 = optionalText(params, "path", { allowEmpty: true });
69455
69505
  const ephemeral = optionalBoolean(params, "ephemeral");
69456
69506
  return {
69457
69507
  threadId: threadId2,
69458
69508
  ...lastTurnText ? { lastTurnId: hostTurnIdSchema.parse(lastTurnText) } : {},
69459
69509
  ...beforeTurnText ? { beforeTurnId: hostTurnIdSchema.parse(beforeTurnText) } : {},
69460
- ...path31 ? { path: path31 } : {},
69510
+ ...path32 ? { path: path32 } : {},
69461
69511
  ...optionalField(params, "model"),
69462
69512
  ...optionalField(params, "modelProvider"),
69463
69513
  ...optionalField(params, "cwd"),
@@ -70192,8 +70242,8 @@ var packageMetadata7 = {
70192
70242
 
70193
70243
  // packages/host-runtime/src/external-thread-repository.ts
70194
70244
  import { randomUUID as randomUUID10 } from "node:crypto";
70195
- import os8 from "node:os";
70196
- import path23 from "node:path";
70245
+ import os5 from "node:os";
70246
+ import path24 from "node:path";
70197
70247
  function nativeTurnKey2(ref) {
70198
70248
  return `${ref.harnessId}\0${ref.nativeSessionId}\0${ref.nativeTurnKey}\0${ref.formatVersion}`;
70199
70249
  }
@@ -70202,8 +70252,8 @@ function sameMapping(left, right) {
70202
70252
  }
70203
70253
  function defaultMappingStoreDirectory(environment) {
70204
70254
  const dataDirectory = environment.CODEXHOST_DATA_DIR;
70205
- return path23.join(
70206
- dataDirectory ? path23.resolve(dataDirectory) : path23.join(os8.homedir(), ".codexhost"),
70255
+ return path24.join(
70256
+ dataDirectory ? path24.resolve(dataDirectory) : path24.join(os5.homedir(), ".codexhost"),
70207
70257
  "mapping-store"
70208
70258
  );
70209
70259
  }
@@ -71724,25 +71774,25 @@ function resolveExternalSessionTreeIds(records) {
71724
71774
  const resolve2 = (start) => {
71725
71775
  const cached2 = resolved.get(start.hostThreadId);
71726
71776
  if (cached2) return cached2;
71727
- const path31 = [];
71777
+ const path32 = [];
71728
71778
  const visited = /* @__PURE__ */ new Set();
71729
71779
  let current = start;
71730
71780
  while (true) {
71731
71781
  const known = resolved.get(current.hostThreadId);
71732
71782
  if (known) {
71733
- for (const record3 of path31) resolved.set(record3.hostThreadId, known);
71783
+ for (const record3 of path32) resolved.set(record3.hostThreadId, known);
71734
71784
  return known;
71735
71785
  }
71736
71786
  if (visited.has(current.hostThreadId)) {
71737
71787
  throw new Error("External Thread Fork tree contains a cycle");
71738
71788
  }
71739
71789
  visited.add(current.hostThreadId);
71740
- path31.push(current);
71790
+ path32.push(current);
71741
71791
  const sourceId = current.forkSource?.hostThreadId;
71742
71792
  const source = sourceId ? byId.get(sourceId) : void 0;
71743
71793
  if (!source) {
71744
71794
  const root = current.hostThreadId;
71745
- for (const record3 of path31) resolved.set(record3.hostThreadId, root);
71795
+ for (const record3 of path32) resolved.set(record3.hostThreadId, root);
71746
71796
  return root;
71747
71797
  }
71748
71798
  current = source;
@@ -71967,7 +72017,7 @@ function isRecord39(value) {
71967
72017
  return typeof value === "object" && value !== null && !Array.isArray(value);
71968
72018
  }
71969
72019
  function isCreditsAdapter(adapter) {
71970
- return typeof adapter.credits === "function" && typeof adapter.refreshCredits === "function";
72020
+ return typeof adapter.credits === "function";
71971
72021
  }
71972
72022
  function projectAccountCredits(value) {
71973
72023
  if (!isRecord39(value)) return null;
@@ -72803,6 +72853,12 @@ var AppServerHost = class {
72803
72853
  return;
72804
72854
  }
72805
72855
  if (resolution.kind === "official") {
72856
+ if (params.data.refresh !== void 0) {
72857
+ await this.#writer.json(
72858
+ rpcError(request, -32602, "Exact Usage refresh is only available for External Threads")
72859
+ );
72860
+ return;
72861
+ }
72806
72862
  const rateLimitRefresh = this.#refreshOfficialRateLimits();
72807
72863
  if (this.#officialUsageByThread.has(params.data.threadId)) {
72808
72864
  await rateLimitRefresh;
@@ -72816,8 +72872,9 @@ var AppServerHost = class {
72816
72872
  await this.#writer.json(rpcEnvelope(request, { result: jsonValueSchema.parse(result2) }));
72817
72873
  return;
72818
72874
  }
72875
+ if (params.data.refresh === "exact") void resolution.thread.session.refreshUsage?.();
72819
72876
  const adapter = this.#externalAdapters.get(resolution.thread.harnessId);
72820
- if (adapter && isCreditsAdapter(adapter)) void adapter.refreshCredits();
72877
+ if (adapter && isCreditsAdapter(adapter)) void adapter.refreshCredits?.();
72821
72878
  const credits = adapter && isCreditsAdapter(adapter) ? projectAccountCredits(adapter.credits()) : null;
72822
72879
  const result = threadUsageInspectionSchema.parse({
72823
72880
  threadId: params.data.threadId,
@@ -74437,7 +74494,7 @@ var AppServerHost = class {
74437
74494
  // packages/host-runtime/src/remote-control-app-server.ts
74438
74495
  import { randomUUID as randomUUID13 } from "node:crypto";
74439
74496
  import { mkdir as mkdir4, open as open6, rename as rename3, rm as rm5 } from "node:fs/promises";
74440
- import path24 from "node:path";
74497
+ import path25 from "node:path";
74441
74498
 
74442
74499
  // packages/host-runtime/src/remote-official-connection.ts
74443
74500
  import net from "node:net";
@@ -74627,8 +74684,8 @@ var BRIDGE_READY_METHOD = "codexhost/remote-control-bridge/ready";
74627
74684
  function absoluteEnvironmentPath2(environment, name, fallback, platform = process.platform) {
74628
74685
  const value = environment[name] ?? fallback;
74629
74686
  if (!value) return null;
74630
- if (path24.isAbsolute(value)) return path24.normalize(value);
74631
- return platform === "win32" && path24.win32.isAbsolute(value) ? path24.win32.normalize(value) : null;
74687
+ if (path25.isAbsolute(value)) return path25.normalize(value);
74688
+ return platform === "win32" && path25.win32.isAbsolute(value) ? path25.win32.normalize(value) : null;
74632
74689
  }
74633
74690
  function nodeCompatibleWindowsPath(value) {
74634
74691
  if (value.startsWith("\\\\?\\UNC\\")) return `\\\\${value.slice(8)}`;
@@ -74642,13 +74699,13 @@ function remoteControlBridgePipePath(processId = process.pid, instanceId = rando
74642
74699
  }
74643
74700
  function remoteControlBridgeDescriptorPath(environment) {
74644
74701
  const root = environment.LOCALAPPDATA;
74645
- if (!root || !path24.isAbsolute(root)) return null;
74646
- return path24.join(path24.normalize(root), "codexhost", REMOTE_CONTROL_BRIDGE_DESCRIPTOR_FILE);
74702
+ if (!root || !path25.isAbsolute(root)) return null;
74703
+ return path25.join(path25.normalize(root), "codexhost", REMOTE_CONTROL_BRIDGE_DESCRIPTOR_FILE);
74647
74704
  }
74648
74705
  async function publishRemoteControlAppServerDescriptor(plan) {
74649
- const directory = path24.dirname(plan.descriptorPath);
74706
+ const directory = path25.dirname(plan.descriptorPath);
74650
74707
  await mkdir4(directory, { recursive: true, mode: 448 });
74651
- const temporaryPath = path24.join(
74708
+ const temporaryPath = path25.join(
74652
74709
  directory,
74653
74710
  `.${REMOTE_CONTROL_BRIDGE_DESCRIPTOR_FILE}.${plan.descriptor.ownerPid}.${randomUUID13()}.tmp`
74654
74711
  );
@@ -74741,14 +74798,14 @@ async function runRemoteControlAppServerBridge(input = {}) {
74741
74798
  import { createServer } from "node:http";
74742
74799
  import net2 from "node:net";
74743
74800
  import { chmod as chmod3, lstat as lstat6, mkdir as mkdir6, rm as rm7 } from "node:fs/promises";
74744
- import path26 from "node:path";
74801
+ import path27 from "node:path";
74745
74802
  import { PassThrough as PassThrough2 } from "node:stream";
74746
74803
 
74747
74804
  // packages/host-runtime/src/remote-socket-lock.ts
74748
74805
  import { randomUUID as randomUUID14 } from "node:crypto";
74749
74806
  import { chmod as chmod2, lstat as lstat5, mkdir as mkdir5, open as open7, readFile as readFile8, readdir as readdir5, rename as rename4, rm as rm6 } from "node:fs/promises";
74750
74807
  import { uptime } from "node:os";
74751
- import path25 from "node:path";
74808
+ import path26 from "node:path";
74752
74809
  import { setTimeout as delay7 } from "node:timers/promises";
74753
74810
  var LOCK_RETRY_COUNT = 200;
74754
74811
  var LOCK_RETRY_DELAY_MS = 25;
@@ -74822,7 +74879,7 @@ async function readLockEntrySnapshot(filePath) {
74822
74879
  source,
74823
74880
  identity: { dev: metadata.dev, ino: metadata.ino },
74824
74881
  mtimeMs: metadata.mtimeMs,
74825
- record: record3 && path25.basename(filePath) === lockEntryName(record3.ownerToken) ? record3 : null
74882
+ record: record3 && path26.basename(filePath) === lockEntryName(record3.ownerToken) ? record3 : null
74826
74883
  };
74827
74884
  }
74828
74885
  function lockEntryIsAbandoned(snapshot) {
@@ -74843,7 +74900,7 @@ async function readLockEntryCatalog(lockDirectory) {
74843
74900
  let unsettled = false;
74844
74901
  for (const name of names) {
74845
74902
  if (!name.startsWith(LOCK_ENTRY_PREFIX) || !name.endsWith(LOCK_ENTRY_SUFFIX)) continue;
74846
- const snapshot = await readLockEntrySnapshot(path25.join(lockDirectory, name));
74903
+ const snapshot = await readLockEntrySnapshot(path26.join(lockDirectory, name));
74847
74904
  if (snapshot === null) continue;
74848
74905
  if (lockEntryIsAbandoned(snapshot)) {
74849
74906
  if (!await removeAbandonedLockEntry(snapshot)) unsettled = true;
@@ -74871,7 +74928,7 @@ async function preparePrivateLockDirectory(lockDirectory) {
74871
74928
  await chmod2(lockDirectory, 448);
74872
74929
  }
74873
74930
  async function writeLockRecordAtomic(lockDirectory, entryPath, record3) {
74874
- const temporary = path25.join(lockDirectory, `.tmp-${record3.ownerToken}-${randomUUID14()}`);
74931
+ const temporary = path26.join(lockDirectory, `.tmp-${record3.ownerToken}-${randomUUID14()}`);
74875
74932
  const handle = await open7(temporary, "wx", 384);
74876
74933
  try {
74877
74934
  await handle.writeFile(`${JSON.stringify(record3)}
@@ -74947,7 +75004,7 @@ async function withRemoteAppServerSocketInitializationLock(socketPath, action) {
74947
75004
  const lockDirectory = `${socketPath}.initializers`;
74948
75005
  await preparePrivateLockDirectory(lockDirectory);
74949
75006
  const ownerToken = randomUUID14();
74950
- const entryPath = path25.join(lockDirectory, lockEntryName(ownerToken));
75007
+ const entryPath = path26.join(lockDirectory, lockEntryName(ownerToken));
74951
75008
  const baseRecord = {
74952
75009
  version: 2,
74953
75010
  ownerToken,
@@ -75121,14 +75178,14 @@ function remoteAppServerSocketPath(environment, listenUrl = "unix://") {
75121
75178
  throw new Error("Remote app-server listener must use a Unix URL");
75122
75179
  }
75123
75180
  const explicit = listenUrl.slice("unix://".length);
75124
- if (explicit.length > 0) return path26.posix.resolve(decodeURIComponent(explicit));
75125
- const codexHome = environment.CODEX_HOME ?? (environment.HOME ? path26.posix.join(environment.HOME, ".codex") : void 0);
75181
+ if (explicit.length > 0) return path27.posix.resolve(decodeURIComponent(explicit));
75182
+ const codexHome = environment.CODEX_HOME ?? (environment.HOME ? path27.posix.join(environment.HOME, ".codex") : void 0);
75126
75183
  if (!codexHome)
75127
75184
  throw new Error("CODEX_HOME or HOME is required for the remote app-server socket");
75128
- return path26.posix.join(codexHome, "app-server-control", "app-server-control.sock");
75185
+ return path27.posix.join(codexHome, "app-server-control", "app-server-control.sock");
75129
75186
  }
75130
75187
  function officialListenerArgumentsForRemoteListener(arguments_2, socketPath) {
75131
- if (!path26.posix.isAbsolute(socketPath)) {
75188
+ if (!path27.posix.isAbsolute(socketPath)) {
75132
75189
  throw new Error("Shared official app-server socket path must be absolute");
75133
75190
  }
75134
75191
  if (remoteUnixListenerUrl(arguments_2) === null) {
@@ -75239,7 +75296,7 @@ async function removeStaleSocket(socketPath) {
75239
75296
  await rm7(socketPath, { force: true });
75240
75297
  }
75241
75298
  async function prepareRemoteAppServerSocketDirectory(socketPath) {
75242
- const socketDirectory = path26.dirname(socketPath);
75299
+ const socketDirectory = path27.dirname(socketPath);
75243
75300
  const existing = await lstat6(socketDirectory).catch((error54) => {
75244
75301
  if (error54.code === "ENOENT") return null;
75245
75302
  throw error54;
@@ -75422,18 +75479,18 @@ function createRemoteAppServerWebSocketListener(input) {
75422
75479
  import { spawn as spawn8 } from "node:child_process";
75423
75480
  import { randomUUID as randomUUID15 } from "node:crypto";
75424
75481
  import { lstat as lstat7, rm as rm8 } from "node:fs/promises";
75425
- import path27 from "node:path";
75482
+ import path28 from "node:path";
75426
75483
  var DEFAULT_CLOSE_TIMEOUT_MS4 = 2e3;
75427
75484
  var DEFAULT_LISTEN_TIMEOUT_MS = 1e4;
75428
75485
  function remoteOfficialAppServerSocketPath(desktopControlSocketPath, token = randomUUID15()) {
75429
- if (!path27.posix.isAbsolute(desktopControlSocketPath)) {
75486
+ if (!path28.posix.isAbsolute(desktopControlSocketPath)) {
75430
75487
  throw new Error("Desktop control socket path must be absolute");
75431
75488
  }
75432
75489
  if (!/^[A-Za-z0-9-]+$/u.test(token) || !/[A-Za-z0-9]/u.test(token)) {
75433
75490
  throw new Error("Shared official app-server socket token is invalid");
75434
75491
  }
75435
75492
  const compactToken = token.replaceAll("-", "").slice(0, 15);
75436
- return path27.posix.join(path27.posix.dirname(desktopControlSocketPath), `.c-${compactToken}.sock`);
75493
+ return path28.posix.join(path28.posix.dirname(desktopControlSocketPath), `.c-${compactToken}.sock`);
75437
75494
  }
75438
75495
  function errorMessage7(error54) {
75439
75496
  return error54 instanceof Error ? error54.message : String(error54);
@@ -75737,7 +75794,7 @@ function createHostUpdateCoordinator(options) {
75737
75794
  async function installable(context, release) {
75738
75795
  if (context.installation.kind === "npm") return true;
75739
75796
  const target = context.metadata.target;
75740
- if (target === "linux-x64") return false;
75797
+ if (target === "linux-x64" || target === "linux-arm64") return false;
75741
75798
  try {
75742
75799
  selectInstallerReleaseArtifact(release, target);
75743
75800
  return true;
@@ -75838,7 +75895,7 @@ function createHostUpdateCoordinator(options) {
75838
75895
  });
75839
75896
  } else {
75840
75897
  const target = context.metadata.target;
75841
- if (target === "linux-x64") {
75898
+ if (target === "linux-x64" || target === "linux-arm64") {
75842
75899
  throw new Error("Linux installer updates are unsupported");
75843
75900
  }
75844
75901
  const artifact = selectInstallerReleaseArtifact(release, target).source;
@@ -75899,9 +75956,9 @@ function hasLauncherManagedUpdateRuntime(environment, hostRuntimePath) {
75899
75956
  if (!environment[UPDATE_RUNTIME_ENV.launcherPid]) return false;
75900
75957
  const npmPackageRoot = environment[UPDATE_RUNTIME_ENV.npmPackageRoot];
75901
75958
  if (!npmPackageRoot || !hostRuntimePath) return true;
75902
- if (!path28.isAbsolute(npmPackageRoot) || !path28.isAbsolute(hostRuntimePath)) return false;
75903
- const runtimePackageRoot = path28.dirname(path28.dirname(path28.normalize(hostRuntimePath)));
75904
- return path28.relative(path28.normalize(npmPackageRoot), runtimePackageRoot) === "";
75959
+ if (!path29.isAbsolute(npmPackageRoot) || !path29.isAbsolute(hostRuntimePath)) return false;
75960
+ const runtimePackageRoot = path29.dirname(path29.dirname(path29.normalize(hostRuntimePath)));
75961
+ return path29.relative(path29.normalize(npmPackageRoot), runtimePackageRoot) === "";
75905
75962
  }
75906
75963
  function requiredRuntimeConfiguration(environment) {
75907
75964
  const stockCodexPath = environment[STOCK_CODEX_PATH_ENV];
@@ -76106,7 +76163,7 @@ import {
76106
76163
  stat as stat3,
76107
76164
  writeFile as writeFile3
76108
76165
  } from "node:fs/promises";
76109
- import path29 from "node:path";
76166
+ import path30 from "node:path";
76110
76167
  var MANIFEST_FORMAT = 1;
76111
76168
  var WRAPPER_MARKER = "# codexhost remote SSH wrapper v1";
76112
76169
  var PROFILE_START = "# >>> codexhost remote SSH >>>";
@@ -76117,25 +76174,25 @@ function resolvePaths(options) {
76117
76174
  if (!configuredHome) {
76118
76175
  throw new Error("A non-root HOME is required for remote Host installation");
76119
76176
  }
76120
- const home = path29.resolve(configuredHome);
76121
- if (!home || home === path29.parse(home).root) {
76177
+ const home = path30.resolve(configuredHome);
76178
+ if (!home || home === path30.parse(home).root) {
76122
76179
  throw new Error("A non-root HOME is required for remote Host installation");
76123
76180
  }
76124
- const installRoot = path29.resolve(options.installRoot ?? path29.join(home, ".codexhost", "remote"));
76125
- const profilePath = path29.resolve(
76126
- options.profilePath ?? path29.join(
76181
+ const installRoot = path30.resolve(options.installRoot ?? path30.join(home, ".codexhost", "remote"));
76182
+ const profilePath = path30.resolve(
76183
+ options.profilePath ?? path30.join(
76127
76184
  home,
76128
- path29.basename(environment.SHELL ?? "") === "zsh" ? ".zshenv" : path29.basename(environment.SHELL ?? "") === "bash" ? ".bashrc" : ".profile"
76185
+ path30.basename(environment.SHELL ?? "") === "zsh" ? ".zshenv" : path30.basename(environment.SHELL ?? "") === "bash" ? ".bashrc" : ".profile"
76129
76186
  )
76130
76187
  );
76131
- const binDirectory = path29.join(installRoot, "bin");
76188
+ const binDirectory = path30.join(installRoot, "bin");
76132
76189
  return {
76133
76190
  home,
76134
76191
  installRoot,
76135
76192
  binDirectory,
76136
- wrapperPath: path29.join(binDirectory, "codex"),
76137
- manifestPath: path29.join(installRoot, "manifest.json"),
76138
- dataDirectory: path29.join(installRoot, "data"),
76193
+ wrapperPath: path30.join(binDirectory, "codex"),
76194
+ manifestPath: path30.join(installRoot, "manifest.json"),
76195
+ dataDirectory: path30.join(installRoot, "data"),
76139
76196
  profilePath
76140
76197
  };
76141
76198
  }
@@ -76154,7 +76211,7 @@ async function fileSha256(filePath) {
76154
76211
  return createHash3("sha256").update(await readFile9(filePath)).digest("hex");
76155
76212
  }
76156
76213
  async function executable(filePath, label) {
76157
- const absolute = path29.resolve(filePath);
76214
+ const absolute = path30.resolve(filePath);
76158
76215
  try {
76159
76216
  if (!(await stat3(absolute)).isFile()) throw new Error("not a regular file");
76160
76217
  await access(absolute, fsConstants.X_OK);
@@ -76164,7 +76221,7 @@ async function executable(filePath, label) {
76164
76221
  return absolute;
76165
76222
  }
76166
76223
  async function existingFile2(filePath, label) {
76167
- const absolute = path29.resolve(filePath);
76224
+ const absolute = path30.resolve(filePath);
76168
76225
  try {
76169
76226
  const metadata = await stat3(absolute);
76170
76227
  if (!metadata.isFile()) throw new Error("not a regular file");
@@ -76174,9 +76231,9 @@ async function existingFile2(filePath, label) {
76174
76231
  return absolute;
76175
76232
  }
76176
76233
  async function discoverExecutable(name, environment) {
76177
- for (const directory of (environment.PATH ?? "").split(path29.delimiter)) {
76234
+ for (const directory of (environment.PATH ?? "").split(path30.delimiter)) {
76178
76235
  if (!directory) continue;
76179
- const candidate = path29.resolve(directory, name);
76236
+ const candidate = path30.resolve(directory, name);
76180
76237
  try {
76181
76238
  await access(candidate, fsConstants.X_OK);
76182
76239
  return candidate;
@@ -76187,10 +76244,10 @@ async function discoverExecutable(name, environment) {
76187
76244
  return null;
76188
76245
  }
76189
76246
  async function writeAtomic(filePath, contents, mode) {
76190
- await mkdir7(path29.dirname(filePath), { recursive: true, mode: 448 });
76191
- const temporary = path29.join(
76192
- path29.dirname(filePath),
76193
- `.${path29.basename(filePath)}.${process.pid}.${randomUUID16()}.tmp`
76247
+ await mkdir7(path30.dirname(filePath), { recursive: true, mode: 448 });
76248
+ const temporary = path30.join(
76249
+ path30.dirname(filePath),
76250
+ `.${path30.basename(filePath)}.${process.pid}.${randomUUID16()}.tmp`
76194
76251
  );
76195
76252
  try {
76196
76253
  if (typeof contents === "string") {
@@ -76211,10 +76268,10 @@ async function writeAtomic(filePath, contents, mode) {
76211
76268
  }
76212
76269
  }
76213
76270
  async function writeAtomicExecutable(filePath, sourcePath) {
76214
- await mkdir7(path29.dirname(filePath), { recursive: true, mode: 448 });
76215
- const temporary = path29.join(
76216
- path29.dirname(filePath),
76217
- `.${path29.basename(filePath)}.${process.pid}.${randomUUID16()}.tmp`
76271
+ await mkdir7(path30.dirname(filePath), { recursive: true, mode: 448 });
76272
+ const temporary = path30.join(
76273
+ path30.dirname(filePath),
76274
+ `.${path30.basename(filePath)}.${process.pid}.${randomUUID16()}.tmp`
76218
76275
  );
76219
76276
  try {
76220
76277
  await copyFile3(sourcePath, temporary);
@@ -76255,7 +76312,7 @@ function removeManagedProfileBlock(contents) {
76255
76312
  function installManagedProfileBlock(contents, manifest) {
76256
76313
  const base = removeManagedProfileBlock(contents);
76257
76314
  const environment = [
76258
- `export CODEX_INSTALL_DIR=${shellQuote(path29.dirname(manifest.wrapperPath))}`,
76315
+ `export CODEX_INSTALL_DIR=${shellQuote(path30.dirname(manifest.wrapperPath))}`,
76259
76316
  `export CODEXHOST_STOCK_CODEX_PATH=${shellQuote(manifest.stockCodexPath)}`,
76260
76317
  `export CODEXHOST_HOST_NODE_PATH=${shellQuote(manifest.nodePath)}`,
76261
76318
  `export CODEXHOST_HOST_RUNTIME_PATH=${shellQuote(manifest.hostRuntimePath)}`,
@@ -76272,7 +76329,7 @@ function installManagedProfileBlock(contents, manifest) {
76272
76329
  PROFILE_END,
76273
76330
  ""
76274
76331
  ].join("\n");
76275
- if (path29.basename(manifest.profilePath) === ".bashrc") return `${block}${base}`;
76332
+ if (path30.basename(manifest.profilePath) === ".bashrc") return `${block}${base}`;
76276
76333
  const separator = base.length > 0 && !base.endsWith("\n") ? "\n" : "";
76277
76334
  return `${base}${separator}${block}`;
76278
76335
  }
@@ -76337,9 +76394,9 @@ async function readManifest(filePath) {
76337
76394
  ];
76338
76395
  const optionalPaths = ["claudeCommand", "profileBackupPath"];
76339
76396
  if (manifest.format !== MANIFEST_FORMAT || Object.keys(manifest).some((key) => !allowed2.has(key)) || requiredPaths.some(
76340
- (key) => typeof manifest[key] !== "string" || !path29.isAbsolute(manifest[key])
76397
+ (key) => typeof manifest[key] !== "string" || !path30.isAbsolute(manifest[key])
76341
76398
  ) || optionalPaths.some(
76342
- (key) => manifest[key] !== void 0 && (typeof manifest[key] !== "string" || !path29.isAbsolute(manifest[key]))
76399
+ (key) => manifest[key] !== void 0 && (typeof manifest[key] !== "string" || !path30.isAbsolute(manifest[key]))
76343
76400
  ) || manifest.entrypointSha256 !== void 0 && (typeof manifest.entrypointSha256 !== "string" || !/^[a-f0-9]{64}$/u.test(manifest.entrypointSha256))) {
76344
76401
  throw new Error("Remote Host manifest has an unsupported format");
76345
76402
  }
@@ -76568,7 +76625,7 @@ async function uninstallRemoteHost(options) {
76568
76625
  import { spawn as spawn9 } from "node:child_process";
76569
76626
  import { stat as stat4 } from "node:fs/promises";
76570
76627
  import net3 from "node:net";
76571
- import path30 from "node:path";
76628
+ import path31 from "node:path";
76572
76629
  import { Duplex } from "node:stream";
76573
76630
  var CODEXHOST_STATUS_METHOD = "codexhost/update/status";
76574
76631
  var DIRECT_PROBE_TIMEOUT_MS = 5e3;
@@ -76587,9 +76644,9 @@ function classifyRemoteHostProbeResponse(response, socketPath) {
76587
76644
  }
76588
76645
  var lifecycleDependencyOverrides = {};
76589
76646
  function socketPathFor(environment) {
76590
- const codexHome = environment.CODEX_HOME ?? (environment.HOME ? path30.join(environment.HOME, ".codex") : void 0);
76647
+ const codexHome = environment.CODEX_HOME ?? (environment.HOME ? path31.join(environment.HOME, ".codex") : void 0);
76591
76648
  if (!codexHome) throw new Error("CODEX_HOME or HOME is required for remote Host lifecycle");
76592
- return path30.join(codexHome, "app-server-control", "app-server-control.sock");
76649
+ return path31.join(codexHome, "app-server-control", "app-server-control.sock");
76593
76650
  }
76594
76651
  async function defaultSocketExists(socketPath) {
76595
76652
  const metadata = await stat4(socketPath).catch((error54) => {
@@ -76716,7 +76773,7 @@ function installedManifest(status) {
76716
76773
  function managedEnvironment(manifest, environment) {
76717
76774
  return {
76718
76775
  ...environment,
76719
- CODEX_INSTALL_DIR: path30.dirname(manifest.wrapperPath),
76776
+ CODEX_INSTALL_DIR: path31.dirname(manifest.wrapperPath),
76720
76777
  CODEXHOST_STOCK_CODEX_PATH: manifest.stockCodexPath,
76721
76778
  CODEXHOST_HOST_NODE_PATH: manifest.nodePath,
76722
76779
  CODEXHOST_HOST_RUNTIME_PATH: manifest.hostRuntimePath,
@@ -76724,7 +76781,7 @@ function managedEnvironment(manifest, environment) {
76724
76781
  CODEXHOST_DEFAULT_AGENT: "codex",
76725
76782
  CODEXHOST_REMOTE_SSH_MANAGED: "1",
76726
76783
  ...manifest.claudeCommand ? { CODEXHOST_CLAUDE_COMMAND: manifest.claudeCommand } : {},
76727
- PATH: `${path30.dirname(manifest.wrapperPath)}${path30.delimiter}${path30.dirname(manifest.stockCodexPath)}${path30.delimiter}${environment.PATH ?? "/usr/bin:/bin"}`
76784
+ PATH: `${path31.dirname(manifest.wrapperPath)}${path31.delimiter}${path31.dirname(manifest.stockCodexPath)}${path31.delimiter}${environment.PATH ?? "/usr/bin:/bin"}`
76728
76785
  };
76729
76786
  }
76730
76787
  async function defaultRunTerminator(manifest, socketPath, role, environment) {