@liberseek/boft-cli-linux-x64 0.8.0 → 0.8.2

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.
@@ -4295,9 +4295,11 @@ async function runDelegationCli(input) {
4295
4295
  "INVALID_ARGUMENT",
4296
4296
  "--host conflicts with the Thread reference"
4297
4297
  );
4298
+ const caller = command === "read" ? callerThreadId(environment) : void 0;
4298
4299
  const body = {
4299
4300
  ...reference,
4300
4301
  ...hostId2 ? { hostId: hostId2 } : {},
4302
+ ...caller ? { callerThreadId: normalizeThreadId(caller) } : {},
4301
4303
  view,
4302
4304
  ...value(parsed2, "--cursor") ? { cursor: value(parsed2, "--cursor") } : {},
4303
4305
  ...value(parsed2, "--limit") ? { limit: positiveInteger(value(parsed2, "--limit"), "--limit", MAX_LIMIT) } : {},
@@ -4434,6 +4436,7 @@ import {
4434
4436
  realpath,
4435
4437
  stat,
4436
4438
  readdir as readdir2,
4439
+ unlink,
4437
4440
  writeFile as writeFile3
4438
4441
  } from "node:fs/promises";
4439
4442
  import { homedir } from "node:os";
@@ -4672,7 +4675,7 @@ async function readRuntimeMetadata(entryPath, environment = process.env) {
4672
4675
  }
4673
4676
 
4674
4677
  // packages/update-manager/dist/github-release.js
4675
- var CODEXHOST_LATEST_RELEASE_URL = "https://api.github.com/repos/LiberSeek/BOFT-CLI/releases/latest";
4678
+ var CODEXHOST_LATEST_RELEASE_URL = "https://api.github.com/repos/LIBERSEEK/BOFT-CLI/releases/latest";
4676
4679
  var SHA256_DIGEST_PATTERN = /^sha256:([0-9a-f]{64})$/u;
4677
4680
  var RELEASE_NOTES_URL_PATTERN = /^https:\/\/github\.com\/(LiberSeek|LIBERSEEK)\/BOFT-CLI\/releases\/tag\/(v[0-9A-Za-z.+-]+)$/u;
4678
4681
  var DOWNLOAD_URL_PREFIXES = [
@@ -4810,7 +4813,7 @@ function selectInstallerReleaseArtifact(release, target) {
4810
4813
  // packages/update-manager/dist/github-cli-release.js
4811
4814
  import { execFile } from "node:child_process";
4812
4815
  import path3 from "node:path";
4813
- var GITHUB_LATEST_RELEASE_ENDPOINT = "repos/BytePioneer-AI/codex-host/releases/latest";
4816
+ var GITHUB_LATEST_RELEASE_ENDPOINT = "repos/LIBERSEEK/BOFT-CLI/releases/latest";
4814
4817
  var MAX_RELEASE_RESPONSE_BYTES = 1024 * 1024;
4815
4818
  var GITHUB_CLI_TIMEOUT_MS = 5e3;
4816
4819
  function defaultExecutableCandidates(environment, platform) {
@@ -4899,39 +4902,25 @@ async function regularFile(filePath) {
4899
4902
  throw error51;
4900
4903
  }
4901
4904
  }
4902
- async function isUpdateOperationActive(stateDirectory) {
4905
+ async function discoverActiveUpdateStatus(stateDirectory) {
4903
4906
  if (!path4.isAbsolute(stateDirectory))
4904
4907
  throw new Error("update state directory must be absolute");
4905
- return regularFile(path4.join(stateDirectory, LOCK_FILE));
4906
- }
4907
- async function discoverLatestUpdateStatus(stateDirectory) {
4908
- if (!path4.isAbsolute(stateDirectory))
4909
- throw new Error("update state directory must be absolute");
4910
- let entries;
4908
+ const lockPath = path4.join(stateDirectory, LOCK_FILE);
4909
+ if (!await regularFile(lockPath))
4910
+ return null;
4911
4911
  try {
4912
- entries = await readdir(stateDirectory, { withFileTypes: true });
4913
- } catch (error51) {
4914
- if (error51.code === "ENOENT")
4912
+ const lock = JSON.parse(await readFile3(lockPath, "utf8"));
4913
+ if (typeof lock.statusPath !== "string" || !path4.isAbsolute(lock.statusPath))
4915
4914
  return null;
4916
- throw error51;
4917
- }
4918
- const candidates = [];
4919
- for (const entry of entries) {
4920
- if (!entry.isDirectory() || entry.isSymbolicLink() || !entry.name.startsWith("update-"))
4921
- continue;
4922
- const statusPath = path4.join(stateDirectory, entry.name, STATUS_FILE);
4923
- if (!await regularFile(statusPath))
4924
- continue;
4925
- try {
4926
- candidates.push({
4927
- statusPath,
4928
- status: parseUpdateStatus(JSON.parse(await readFile3(statusPath, "utf8")))
4929
- });
4930
- } catch {
4931
- }
4915
+ if (!await regularFile(lock.statusPath))
4916
+ return null;
4917
+ const status2 = parseUpdateStatus(JSON.parse(await readFile3(lock.statusPath, "utf8")));
4918
+ if (TERMINAL_PHASES.has(status2.phase))
4919
+ return null;
4920
+ return { statusPath: lock.statusPath, status: status2 };
4921
+ } catch {
4922
+ return null;
4932
4923
  }
4933
- candidates.sort((left, right) => right.status.updatedAt - left.status.updatedAt);
4934
- return candidates[0] ?? null;
4935
4924
  }
4936
4925
  async function cleanupTerminalUpdateState(stateDirectory, options2 = {}) {
4937
4926
  const now = Math.floor((options2.now ?? Date.now()) / 1e3);
@@ -5129,6 +5118,48 @@ async function verifyDownloadedArtifact(source, filePath, result) {
5129
5118
  }
5130
5119
  }
5131
5120
 
5121
+ // packages/update-manager/dist/updater-ready.js
5122
+ import { setTimeout as delay } from "node:timers/promises";
5123
+ async function waitForUpdaterReady(child, readStatus, timeoutMs = 1e4) {
5124
+ let failure;
5125
+ const onError = (error51) => {
5126
+ failure = error51;
5127
+ };
5128
+ const onExit = () => {
5129
+ failure = new Error("Background Updater exited before completing handoff");
5130
+ };
5131
+ child.on("error", onError);
5132
+ child.on("exit", onExit);
5133
+ const deadline = performance.now() + timeoutMs;
5134
+ try {
5135
+ while (true) {
5136
+ const status2 = await readStatus();
5137
+ if (status2?.phase === "failed")
5138
+ throw new Error(status2.error ?? "Background Updater failed");
5139
+ if (failure)
5140
+ throw failure;
5141
+ if (child.exitCode != null || child.signalCode != null) {
5142
+ throw new Error("Background Updater exited before completing handoff");
5143
+ }
5144
+ if (status2?.phase === "waiting-for-exit")
5145
+ return;
5146
+ if (status2 && status2.phase !== "prepared") {
5147
+ throw new Error(`Unexpected Updater phase during handoff: ${status2.phase}`);
5148
+ }
5149
+ if (performance.now() >= deadline) {
5150
+ throw new Error("Background Updater did not confirm handoff before the startup timeout");
5151
+ }
5152
+ await delay(20);
5153
+ }
5154
+ } catch (error51) {
5155
+ child.kill();
5156
+ throw error51;
5157
+ } finally {
5158
+ child.removeListener("error", onError);
5159
+ child.removeListener("exit", onExit);
5160
+ }
5161
+ }
5162
+
5132
5163
  // packages/update-manager/dist/update-manager.js
5133
5164
  var REQUEST_SCHEMA_VERSION = 1;
5134
5165
  var WINDOWS_RENAME_RETRY_DELAYS_MS = [10, 30, 70, 150, 300];
@@ -5138,7 +5169,7 @@ function errorMessage(error51) {
5138
5169
  function systemErrorCode(error51) {
5139
5170
  return typeof error51 === "object" && error51 !== null && "code" in error51 ? String(error51.code) : null;
5140
5171
  }
5141
- function delay(milliseconds) {
5172
+ function delay2(milliseconds) {
5142
5173
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
5143
5174
  }
5144
5175
  async function replaceStatusFile(temporaryPath, statusPath) {
@@ -5154,7 +5185,7 @@ async function replaceStatusFile(temporaryPath, statusPath) {
5154
5185
  throw error51;
5155
5186
  }
5156
5187
  retryIndex += 1;
5157
- await delay(retryDelay);
5188
+ await delay2(retryDelay);
5158
5189
  }
5159
5190
  }
5160
5191
  }
@@ -5374,14 +5405,20 @@ function createBackgroundUpdateManager(dependencies2 = {}) {
5374
5405
  app_path: appPath
5375
5406
  }, artifact.artifactPath);
5376
5407
  },
5377
- start(prepared) {
5408
+ async start(prepared) {
5378
5409
  if (!preparedRequests.delete(prepared.requestPath)) {
5379
5410
  throw new Error("background update was not prepared by this manager or was already started");
5380
5411
  }
5381
- const child = spawnUpdater(prepared.helperPath, prepared.requestPath);
5382
- if (child.pid === void 0)
5383
- throw new Error("background Updater did not report a process ID");
5384
- return Object.freeze({ ...prepared, updaterPid: child.pid });
5412
+ try {
5413
+ const child = spawnUpdater(prepared.helperPath, prepared.requestPath);
5414
+ await waitForUpdaterReady(child, () => this.readStatus(prepared.statusPath));
5415
+ if (child.pid === void 0)
5416
+ throw new Error("background Updater did not report a process ID");
5417
+ return Object.freeze({ ...prepared, updaterPid: child.pid });
5418
+ } catch (error51) {
5419
+ await writeFailedStatus(prepared.statusPath, prepared.version, prepared.installation, error51);
5420
+ throw error51;
5421
+ }
5385
5422
  },
5386
5423
  async readStatus(statusPathValue) {
5387
5424
  const statusPath = requireAbsolutePath(statusPathValue, "update status path");
@@ -19914,6 +19951,7 @@ config(en_default());
19914
19951
  var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
19915
19952
  var REMOTE_THREAD_CONTROL_TIMEOUT_MS = 4e4;
19916
19953
  var DELEGATION_READ_METHOD = "codexhost/thread/delegation-read";
19954
+ var THREAD_REFERENCE_SOURCE_HOST_PARAM = "codexhostSourceHostId";
19917
19955
  var delegationReadParamsSchema = external_exports.strictObject({
19918
19956
  threadId: external_exports.string().min(1).max(1024),
19919
19957
  view: external_exports.enum(["result", "messages"]),
@@ -19994,6 +20032,15 @@ var harnessDisplaySetSchema = external_exports.strictObject({
19994
20032
  initializeOnly: external_exports.boolean().optional()
19995
20033
  });
19996
20034
 
20035
+ // packages/shared-contracts/dist/harness-presentation.js
20036
+ var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
20037
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text2) => text2.trim().length > 0);
20038
+ var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
20039
+ label: displayText(256).optional(),
20040
+ description: displayText(1024).optional()
20041
+ }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
20042
+ var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
20043
+
19997
20044
  // packages/shared-contracts/dist/model-price-overrides.js
19998
20045
  var MODEL_PRICE_OVERRIDES_GET_METHOD = "codexhost/usage/model-prices/get";
19999
20046
  var MODEL_PRICE_OVERRIDES_SET_METHOD = "codexhost/usage/model-prices/set";
@@ -20076,6 +20123,8 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
20076
20123
  harness,
20077
20124
  sessionId: external_exports.string().min(1).max(512),
20078
20125
  project: project.nullable(),
20126
+ /** Persisted Desktop title for a mapped Session, otherwise its native name; may be absent. */
20127
+ title: external_exports.string().min(1).max(200).optional(),
20079
20128
  /** Models the session used, most requests first. */
20080
20129
  models: external_exports.array(model).max(16),
20081
20130
  firstAtMs: count,
@@ -20142,7 +20191,12 @@ var usageStatisticsResultSchema = external_exports.strictObject({
20142
20191
  * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
20143
20192
  * requests without a native session are not listed here but count everywhere else.
20144
20193
  */
20145
- sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
20194
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100),
20195
+ /**
20196
+ * The sessions last active in the range, newest first, all filters applied. Optional for older
20197
+ * Hosts; missing is treated as no list rather than no sessions.
20198
+ */
20199
+ recentSessions: external_exports.array(usageStatisticsSessionSchema).max(100).optional()
20146
20200
  });
20147
20201
 
20148
20202
  // packages/shared-contracts/dist/ids.js
@@ -20421,8 +20475,24 @@ var threadUsageSnapshotSchema = external_exports.object({
20421
20475
  }
20422
20476
  });
20423
20477
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
20478
+ var accountCreditsPeriodSchema = external_exports.enum([
20479
+ "weekly",
20480
+ "monthly",
20481
+ "five_hour",
20482
+ "seven_day",
20483
+ "unknown"
20484
+ ]);
20485
+ var accountCreditsScopeSchema = external_exports.object({
20486
+ id: external_exports.string().min(1).max(256),
20487
+ label: external_exports.string().min(1).max(256),
20488
+ localizations: harnessLocalizationsSchema.optional()
20489
+ }).strict();
20424
20490
  var accountCreditsProductUsageSchema = external_exports.object({
20425
20491
  product: external_exports.string().min(1),
20492
+ /** Native period and scope, never inferred from the display name. */
20493
+ periodType: accountCreditsPeriodSchema.optional(),
20494
+ scope: accountCreditsScopeSchema.optional(),
20495
+ localizations: harnessLocalizationsSchema.optional(),
20426
20496
  used: external_exports.number().finite().nonnegative().optional(),
20427
20497
  // Zero is a real empty cap, not an absent field.
20428
20498
  limit: external_exports.number().finite().nonnegative().optional(),
@@ -20444,8 +20514,10 @@ var accountCreditsSnapshotSchema = external_exports.object({
20444
20514
  label: external_exports.string().min(1).optional(),
20445
20515
  usedPercent: usagePercentSchema.optional(),
20446
20516
  remaining: external_exports.number().finite().optional(),
20517
+ scope: accountCreditsScopeSchema.optional(),
20518
+ localizations: harnessLocalizationsSchema.optional(),
20447
20519
  resetsAt: external_exports.string().min(1).optional(),
20448
- periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
20520
+ periodType: accountCreditsPeriodSchema,
20449
20521
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
20450
20522
  resetCredits: accountResetCreditsSchema.optional()
20451
20523
  }).strict().superRefine((credits, context) => {
@@ -20470,7 +20542,9 @@ var threadUsageInspectionParamsSchema = external_exports.object({
20470
20542
  var threadUsageInspectionSchema = external_exports.object({
20471
20543
  threadId: hostThreadIdSchema,
20472
20544
  usage: threadUsageSnapshotSchema.nullable(),
20473
- accountCredits: accountCreditsSnapshotSchema.optional()
20545
+ accountCredits: accountCreditsSnapshotSchema.optional(),
20546
+ /** Whether this source can provide cached account quota independently of usage. */
20547
+ accountCreditsSupported: external_exports.boolean().optional()
20474
20548
  }).strict();
20475
20549
 
20476
20550
  // packages/shared-contracts/dist/harness-accounts.js
@@ -20597,7 +20671,8 @@ var harnessPermissionModeSchema = external_exports.object({
20597
20671
  id: harnessPermissionModeIdSchema,
20598
20672
  label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
20599
20673
  description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
20600
- dangerous: external_exports.boolean().optional()
20674
+ dangerous: external_exports.boolean().optional(),
20675
+ localizations: harnessLocalizationsSchema.optional()
20601
20676
  }).strict();
20602
20677
  var harnessPermissionModeCatalogSchema = external_exports.object({
20603
20678
  modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
@@ -20956,6 +21031,8 @@ var harnessInstallationStateSchema = external_exports.object({
20956
21031
  // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
20957
21032
  message: external_exports.string().max(2048).optional(),
20958
21033
  messageCode: external_exports.string().min(1).max(128).optional(),
21034
+ /** Safe plugin-owned explanation, distinct from raw diagnostic message. */
21035
+ notice: harnessLocalizedTextSchema.optional(),
20959
21036
  latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
20960
21037
  }).strict();
20961
21038
 
@@ -21099,6 +21176,7 @@ var harnessCommandDescriptorSchema = external_exports.object({
21099
21176
  invocation: commandInvocationSchema,
21100
21177
  label: commandLabelSchema,
21101
21178
  description: commandDescriptionSchema.optional(),
21179
+ localizations: harnessLocalizationsSchema.optional(),
21102
21180
  argumentMode: external_exports.enum(["none", "text"]),
21103
21181
  /**
21104
21182
  * Native distinction reported by the Harness. Omitted when the Harness does
@@ -21479,14 +21557,40 @@ var RuntimeMaintenance = class {
21479
21557
  options2.environment.CODEXHOST_DATA_DIR ?? path7.join(home, ".codexhost", "remote", "data"),
21480
21558
  "remote-update.json"
21481
21559
  );
21560
+ this.#cancelPath = path7.join(path7.dirname(this.#statusPath), "remote-update.cancel");
21482
21561
  }
21483
21562
  options;
21484
21563
  #running;
21485
21564
  #statusPath;
21565
+ #cancelPath;
21486
21566
  #update = { phase: "idle", targetVersion: null, error: null };
21487
21567
  #blocked = false;
21568
+ #watch = null;
21488
21569
  #starting = null;
21489
21570
  #startingVersion = null;
21571
+ get #startTimeoutMs() {
21572
+ return this.options.updaterStartTimeoutMs ?? UPDATER_START_TIMEOUT_MS;
21573
+ }
21574
+ #ensureWatching() {
21575
+ if (this.#watch) return;
21576
+ this.#watch = setInterval(() => {
21577
+ void this.status().catch(() => void 0).then(() => {
21578
+ if (!this.#blocked && this.#watch) {
21579
+ clearInterval(this.#watch);
21580
+ this.#watch = null;
21581
+ }
21582
+ });
21583
+ }, UPDATER_WATCH_INTERVAL_MS);
21584
+ this.#watch.unref();
21585
+ }
21586
+ async #recordStartFailure(version2, failure) {
21587
+ await writeFile3(this.#cancelPath, JSON.stringify({ targetVersion: version2 }), { mode: 384 });
21588
+ await writeFile3(
21589
+ this.#statusPath,
21590
+ JSON.stringify({ phase: "failed", targetVersion: version2, error: failure }),
21591
+ { mode: 384 }
21592
+ );
21593
+ }
21490
21594
  #sshPending = /* @__PURE__ */ new Set();
21491
21595
  async setupSsh(input) {
21492
21596
  if (this.options.remote) throw new Error("SSH installation must run from the local computer");
@@ -21547,7 +21651,7 @@ var RuntimeMaintenance = class {
21547
21651
  installation(this.options.runtimePath, this.options.environment),
21548
21652
  this.#resources()
21549
21653
  ]);
21550
- if (this.#update.phase === "idle" || this.#blocked) {
21654
+ if (this.#update.phase === "idle" || this.#blocked || this.#update.phase === "failed") {
21551
21655
  try {
21552
21656
  const value2 = JSON.parse(await readFile5(this.#statusPath, "utf8"));
21553
21657
  const parsed2 = runtimeStatusSchema.shape.update.parse(value2);
@@ -21563,15 +21667,22 @@ var RuntimeMaintenance = class {
21563
21667
  }
21564
21668
  } else {
21565
21669
  const written = (await stat(this.#statusPath)).mtimeMs;
21566
- alive = Date.now() - written < UPDATER_START_TIMEOUT_MS * 2;
21670
+ alive = Date.now() - written < this.#startTimeoutMs * 2;
21567
21671
  }
21568
21672
  if (!alive) {
21569
21673
  parsed2.phase = "failed";
21570
21674
  parsed2.error = "The previous remote update was interrupted; retry the update";
21571
21675
  }
21572
21676
  }
21573
- if (this.#update === observedUpdate) this.#update = parsed2;
21574
- if (["failed", "succeeded"].includes(this.#update.phase)) this.#blocked = false;
21677
+ if (this.#update === observedUpdate) {
21678
+ this.#update = parsed2;
21679
+ if (["installing", "restarting"].includes(this.#update.phase)) {
21680
+ this.#blocked = true;
21681
+ this.#ensureWatching();
21682
+ } else if (["failed", "succeeded"].includes(this.#update.phase)) {
21683
+ this.#blocked = false;
21684
+ }
21685
+ }
21575
21686
  } catch {
21576
21687
  }
21577
21688
  }
@@ -21643,6 +21754,7 @@ var RuntimeMaintenance = class {
21643
21754
  await chmod2(helper, 448);
21644
21755
  const request = path7.join(work, "request.json");
21645
21756
  this.#update = { phase: "installing", targetVersion: version2, error: null };
21757
+ await unlink(this.#cancelPath).catch(() => void 0);
21646
21758
  await writeFile3(this.#statusPath, JSON.stringify(this.#update), { mode: 384 });
21647
21759
  await writeFile3(
21648
21760
  request,
@@ -21661,35 +21773,38 @@ var RuntimeMaintenance = class {
21661
21773
  );
21662
21774
  const starter = spawn3(
21663
21775
  "/bin/sh",
21664
- ["-c", '"$0" remote --request "$1" </dev/null >/dev/null 2>&1 &', helper, request],
21665
- { detached: true, stdio: "ignore", env: this.options.environment }
21776
+ ["-c", '"$0" remote --request "$1" </dev/null >/dev/null 2>&1 & echo $!', helper, request],
21777
+ { detached: true, stdio: ["ignore", "pipe", "ignore"], env: this.options.environment }
21666
21778
  );
21779
+ let pidOutput = "";
21780
+ starter.stdout?.on("data", (chunk) => {
21781
+ pidOutput += typeof chunk === "string" ? chunk : chunk.toString("utf8");
21782
+ });
21667
21783
  await new Promise((resolve, reject) => {
21668
21784
  starter.once("error", reject);
21669
21785
  starter.once(
21670
- "exit",
21786
+ "close",
21671
21787
  (code) => code === 0 ? resolve() : reject(new Error("Remote updater could not be started"))
21672
21788
  );
21673
21789
  });
21674
- const deadline = Date.now() + UPDATER_START_TIMEOUT_MS;
21790
+ const helperPid = Number.parseInt(pidOutput.trim(), 10);
21791
+ if (!Number.isSafeInteger(helperPid) || helperPid <= 0) {
21792
+ throw new Error("Remote updater could not be started");
21793
+ }
21794
+ const deadline = Date.now() + this.#startTimeoutMs;
21675
21795
  while (!await this.#helperReported()) {
21676
21796
  if (Date.now() >= deadline) {
21797
+ try {
21798
+ process.kill(helperPid);
21799
+ } catch {
21800
+ }
21677
21801
  const failure = "Remote updater did not start";
21678
- await writeFile3(
21679
- this.#statusPath,
21680
- JSON.stringify({ phase: "failed", targetVersion: version2, error: failure }),
21681
- { mode: 384 }
21682
- );
21802
+ await this.#recordStartFailure(version2, failure);
21683
21803
  throw new Error(failure);
21684
21804
  }
21685
21805
  await new Promise((resolve) => setTimeout(resolve, 50));
21686
21806
  }
21687
- const watch = setInterval(() => {
21688
- void this.status().catch(() => void 0).then(() => {
21689
- if (!this.#blocked) clearInterval(watch);
21690
- });
21691
- }, UPDATER_WATCH_INTERVAL_MS);
21692
- watch.unref();
21807
+ this.#ensureWatching();
21693
21808
  }
21694
21809
  async #helperReported() {
21695
21810
  try {
@@ -21703,6 +21818,7 @@ var RuntimeMaintenance = class {
21703
21818
 
21704
21819
  // packages/host-runtime/src/run-host-runtime.ts
21705
21820
  import { randomBytes as randomBytes4 } from "node:crypto";
21821
+ import { statSync } from "node:fs";
21706
21822
  import path38 from "node:path";
21707
21823
  import { homedir as homedir4 } from "node:os";
21708
21824
  import { fileURLToPath as fileURLToPath2 } from "node:url";
@@ -25011,6 +25127,16 @@ function rewriteDelegationMentionInput(input, skill) {
25011
25127
  return rewritten;
25012
25128
  }
25013
25129
 
25130
+ // packages/harness-adapter/dist/account-credits.js
25131
+ function parseHarnessAccountCredits(value2) {
25132
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
25133
+ return null;
25134
+ const publicValue = { ...value2 };
25135
+ delete publicValue.fetchedAt;
25136
+ const parsed2 = accountCreditsSnapshotSchema.safeParse(publicValue);
25137
+ return parsed2.success ? parsed2.data : null;
25138
+ }
25139
+
25014
25140
  // packages/harness-adapter/dist/output-channel.js
25015
25141
  var HarnessOutputChannel = class {
25016
25142
  outputs;
@@ -27007,61 +27133,6 @@ function finitePercent(value2) {
27007
27133
  function optionalReset(value2) {
27008
27134
  return nonNegativeSafeInteger(value2);
27009
27135
  }
27010
- function addBreakdown(target, source) {
27011
- if (!source)
27012
- return;
27013
- const fields = [
27014
- ["totalTokens", "totalTokens"],
27015
- ["inputTokens", "inputTokens"],
27016
- ["cachedInputTokens", "cachedInputTokens"],
27017
- ["cacheWriteInputTokens", "cacheWriteInputTokens"],
27018
- ["outputTokens", "outputTokens"],
27019
- ["reasoningOutputTokens", "reasoningOutputTokens"]
27020
- ];
27021
- for (const [sourceField, targetField] of fields) {
27022
- const value2 = nonNegativeSafeInteger(source[sourceField]);
27023
- if (value2 !== void 0)
27024
- target[targetField] = value2;
27025
- }
27026
- }
27027
- function observeCodexTokenUsage(value2) {
27028
- if (!isRecord9(value2) || value2.method !== "thread/tokenUsage/updated")
27029
- return null;
27030
- const params = value2.params;
27031
- if (!isRecord9(params))
27032
- return null;
27033
- const threadId2 = hostThreadIdSchema.safeParse(params.threadId);
27034
- const turnId = hostTurnIdSchema.safeParse(params.turnId);
27035
- if (!threadId2.success || !turnId.success)
27036
- return null;
27037
- const tokenUsage = params.tokenUsage;
27038
- if (!isRecord9(tokenUsage))
27039
- return null;
27040
- const total = isRecord9(tokenUsage.total) ? tokenUsage.total : void 0;
27041
- const last = isRecord9(tokenUsage.last) ? tokenUsage.last : void 0;
27042
- const usage = {};
27043
- addBreakdown(usage, total);
27044
- const contextUsedTokens = nonNegativeSafeInteger(last?.totalTokens);
27045
- const contextWindowTokens = nonNegativeSafeInteger(tokenUsage.modelContextWindow);
27046
- if (contextUsedTokens !== void 0 && contextWindowTokens !== void 0 && contextWindowTokens > 0) {
27047
- usage.contextUsedTokens = contextUsedTokens;
27048
- usage.contextWindowTokens = contextWindowTokens;
27049
- }
27050
- const inputTokens = nonNegativeSafeInteger(last?.inputTokens);
27051
- const cachedInputTokens = nonNegativeSafeInteger(last?.cachedInputTokens);
27052
- if (inputTokens !== void 0 && cachedInputTokens !== void 0 && inputTokens > 0) {
27053
- usage.cacheHitRatePercent = Math.min(100, cachedInputTokens / inputTokens * 100);
27054
- }
27055
- try {
27056
- return {
27057
- threadId: threadId2.data,
27058
- turnId: turnId.data,
27059
- usage: parseHostUsage(usage)
27060
- };
27061
- } catch {
27062
- return null;
27063
- }
27064
- }
27065
27136
  function parseRateLimitWindow(value2) {
27066
27137
  if (!isRecord9(value2))
27067
27138
  return null;
@@ -27190,6 +27261,7 @@ function projectCodexRateLimitsToCredits(usage, resetCredits) {
27190
27261
  const resetsAtUnix = hasFiveHour ? usage.planFiveHourResetsAtUnix : usage.planSevenDayResetsAtUnix;
27191
27262
  const secondary = hasFiveHour && hasSevenDay && usage.planSevenDayUsedPercent !== void 0 ? {
27192
27263
  product: "7-day window",
27264
+ periodType: "seven_day",
27193
27265
  usagePercent: usage.planSevenDayUsedPercent,
27194
27266
  ...usage.planSevenDayResetsAtUnix !== void 0 ? { resetsAt: isoFromUnix(usage.planSevenDayResetsAtUnix) } : {}
27195
27267
  } : void 0;
@@ -31923,6 +31995,16 @@ var ExternalThreadIdleRelease = class {
31923
31995
  const state = this.#activity.get(thread);
31924
31996
  if (state) state.outputFailed = true;
31925
31997
  }
31998
+ /** After a successful Session revival, allow idle release again. */
31999
+ clearOutputFailed(thread) {
32000
+ const state = this.#activity.get(thread);
32001
+ if (state) {
32002
+ state.outputFailed = false;
32003
+ state.lastActivity = Date.now();
32004
+ } else {
32005
+ this.touch(thread);
32006
+ }
32007
+ }
31926
32008
  failure(thread) {
31927
32009
  return this.#activity.get(thread)?.closeFailed ? CLOSE_FAILURE : void 0;
31928
32010
  }
@@ -32071,6 +32153,80 @@ var ExternalThreadIdleRelease = class {
32071
32153
  }
32072
32154
  };
32073
32155
 
32156
+ // packages/host-runtime/src/external-thread-lifecycle.ts
32157
+ var RELEASE_TIMEOUT_MS = 6e4;
32158
+ var ExternalSessionReleaseError = class extends Error {
32159
+ constructor(cause) {
32160
+ super(
32161
+ "External Session shutdown could not be confirmed. Retry to confirm release; recovery is blocked until the old Session closes and its output drains. If the Harness cannot retry shutdown, stop residual processes and restart Codex Desktop.",
32162
+ { cause }
32163
+ );
32164
+ this.name = "ExternalSessionReleaseError";
32165
+ }
32166
+ };
32167
+ var ExternalThreadLifecycle = class {
32168
+ #pending = /* @__PURE__ */ new Map();
32169
+ #closing = /* @__PURE__ */ new WeakMap();
32170
+ #releasing = /* @__PURE__ */ new Map();
32171
+ busy(id2) {
32172
+ return this.#pending.has(id2) || this.#releasing.has(id2);
32173
+ }
32174
+ pending() {
32175
+ return [...this.#pending];
32176
+ }
32177
+ run(id2, operation) {
32178
+ const previous = this.#pending.get(id2) ?? Promise.resolve();
32179
+ const task = previous.then(async () => {
32180
+ const releasing = this.#releasing.get(id2);
32181
+ if (releasing) await this.release(id2, releasing.session, releasing.output);
32182
+ return operation();
32183
+ });
32184
+ const settled = task.then(
32185
+ () => void 0,
32186
+ () => void 0
32187
+ );
32188
+ this.#pending.set(id2, settled);
32189
+ void settled.then(() => {
32190
+ if (this.#pending.get(id2) === settled) this.#pending.delete(id2);
32191
+ });
32192
+ return task;
32193
+ }
32194
+ /** Call inside the Thread's lifecycle operation. A timeout never cancels the owned close. */
32195
+ async release(id2, session, output) {
32196
+ this.#releasing.set(id2, { session, output });
32197
+ let closing = this.#closing.get(session);
32198
+ if (!closing) {
32199
+ closing = Promise.resolve().then(() => session.close());
32200
+ this.#closing.set(session, closing);
32201
+ const attempt = closing;
32202
+ void closing.catch(() => {
32203
+ if (this.#closing.get(session) === attempt) this.#closing.delete(session);
32204
+ });
32205
+ }
32206
+ let timeout;
32207
+ try {
32208
+ await Promise.race([
32209
+ closing.then(() => output),
32210
+ new Promise((_, reject) => {
32211
+ timeout = setTimeout(
32212
+ () => reject(new Error("Session shutdown timed out")),
32213
+ RELEASE_TIMEOUT_MS
32214
+ );
32215
+ timeout.unref();
32216
+ })
32217
+ ]);
32218
+ this.#releasing.delete(id2);
32219
+ } catch (error51) {
32220
+ throw new ExternalSessionReleaseError(error51);
32221
+ } finally {
32222
+ if (timeout) clearTimeout(timeout);
32223
+ }
32224
+ }
32225
+ async drain() {
32226
+ while (this.#pending.size) await Promise.all(this.#pending.values());
32227
+ }
32228
+ };
32229
+
32074
32230
  // packages/host-runtime/src/usage-metering.ts
32075
32231
  var TOKENS_PER_PRICE_UNIT = 1e6;
32076
32232
  var UsageMeter = class {
@@ -32086,6 +32242,8 @@ var UsageMeter = class {
32086
32242
  #turnOutputMs = 0;
32087
32243
  #timeToFirstOutputMs;
32088
32244
  #outputTokensPerSecond;
32245
+ #timingUnavailable = false;
32246
+ #timedRequests = /* @__PURE__ */ new Set();
32089
32247
  get metered() {
32090
32248
  return this.#metered;
32091
32249
  }
@@ -32102,12 +32260,53 @@ var UsageMeter = class {
32102
32260
  this.#requests.set(request.requestId, request);
32103
32261
  const duration4 = request.startedAtMs !== void 0 && request.completedAtMs !== void 0 ? request.completedAtMs - request.startedAtMs : 0;
32104
32262
  if (!request.historical && duration4 > 0 && activeTurnId !== null && activeTurnId === this.#turnId) {
32105
- this.#turnOutputTokens += request.outputTokens;
32106
- this.#turnOutputMs += duration4;
32107
- this.#outputTokensPerSecond = this.#turnOutputTokens / (this.#turnOutputMs / 1e3);
32263
+ this.recordOutputTiming(
32264
+ {
32265
+ requestId: request.requestId,
32266
+ outputTokens: request.outputTokens,
32267
+ startedAtMs: request.startedAtMs ?? 0,
32268
+ completedAtMs: request.completedAtMs ?? 0
32269
+ },
32270
+ activeTurnId
32271
+ );
32272
+ }
32273
+ return true;
32274
+ }
32275
+ /** Live timing is independent of history replacement and cannot create billing entries. */
32276
+ recordOutputTiming(request, turnId) {
32277
+ if (turnId !== this.#turnId || this.#timingUnavailable || this.#timedRequests.has(request.requestId))
32278
+ return false;
32279
+ if (!request.requestId || ![request.outputTokens, request.startedAtMs, request.completedAtMs].every(
32280
+ (value2) => Number.isSafeInteger(value2) && value2 >= 0
32281
+ ) || request.completedAtMs <= request.startedAtMs) {
32282
+ this.invalidateOutputTiming(turnId);
32283
+ return true;
32108
32284
  }
32285
+ this.#timedRequests.add(request.requestId);
32286
+ this.#turnOutputTokens += request.outputTokens;
32287
+ this.#turnOutputMs += request.completedAtMs - request.startedAtMs;
32288
+ this.#outputTokensPerSecond = this.#turnOutputTokens / (this.#turnOutputMs / 1e3);
32109
32289
  return true;
32110
32290
  }
32291
+ invalidateOutputTiming(turnId) {
32292
+ if (turnId !== this.#turnId) return;
32293
+ this.#timingUnavailable = true;
32294
+ }
32295
+ /** Discard in-flight timing across connections, but keep the last valid displayed speed. */
32296
+ resetTurnTiming() {
32297
+ this.#turnId = null;
32298
+ this.#turnStartedAtMs = null;
32299
+ this.#timeToFirstOutputMs = void 0;
32300
+ this.#timedRequests.clear();
32301
+ this.#timingUnavailable = false;
32302
+ }
32303
+ /** Replace a read-only session history after recovery, append, rollback or file replacement. */
32304
+ replaceHistory(requests, complete) {
32305
+ this.#requests.clear();
32306
+ this.#invalidRecord = false;
32307
+ for (const request of requests) this.recordRequest({ ...request, historical: true }, null);
32308
+ this.recordHistory(complete);
32309
+ }
32111
32310
  recordHistory(complete) {
32112
32311
  this.#metered = true;
32113
32312
  this.#historyComplete = complete;
@@ -32118,6 +32317,8 @@ var UsageMeter = class {
32118
32317
  this.#turnOutputObserved = false;
32119
32318
  this.#turnOutputTokens = 0;
32120
32319
  this.#turnOutputMs = 0;
32320
+ this.#timedRequests.clear();
32321
+ this.#timingUnavailable = false;
32121
32322
  }
32122
32323
  /** Returns true when this is the Turn's first visible output. */
32123
32324
  outputObserved(turnId, nowMs) {
@@ -32130,7 +32331,6 @@ var UsageMeter = class {
32130
32331
  }
32131
32332
  turnCompleted(turnId) {
32132
32333
  if (turnId !== this.#turnId) return;
32133
- if (this.#turnOutputMs === 0) this.#outputTokensPerSecond = void 0;
32134
32334
  this.#turnId = null;
32135
32335
  this.#turnStartedAtMs = null;
32136
32336
  }
@@ -32165,12 +32365,12 @@ var UsageMeter = class {
32165
32365
  const cacheHitRate = this.#sessionCacheHitRatePercent();
32166
32366
  if (cacheHitRate !== null) usage.sessionCacheHitRatePercent = cacheHitRate;
32167
32367
  }
32168
- if (this.#outputTokensPerSecond !== void 0) {
32169
- usage.outputTokensPerSecond = this.#outputTokensPerSecond;
32170
- }
32171
32368
  } else if (usage.totalCostUsd !== void 0) {
32172
32369
  usage.costSource = "native";
32173
32370
  }
32371
+ if (this.#timingUnavailable) delete usage.outputTokensPerSecond;
32372
+ if (this.#outputTokensPerSecond !== void 0)
32373
+ usage.outputTokensPerSecond = this.#outputTokensPerSecond;
32174
32374
  if (this.#timeToFirstOutputMs !== void 0) {
32175
32375
  usage.timeToFirstOutputMs = this.#timeToFirstOutputMs;
32176
32376
  }
@@ -32309,6 +32509,11 @@ var ExternalThreadOpenError = class extends Error {
32309
32509
  function errorMessage3(error51) {
32310
32510
  return error51 instanceof Error ? error51.message : String(error51);
32311
32511
  }
32512
+ function recoveryError(error51) {
32513
+ if (error51 instanceof ExternalThreadOpenError) return error51.rpcError;
32514
+ if (error51 instanceof ExternalSessionReleaseError) return { code: -32075, message: error51.message };
32515
+ return { code: -32076, message: "External Thread recovery failed; retry the request" };
32516
+ }
32312
32517
  var ExternalThreadRuntime = class {
32313
32518
  idleRelease;
32314
32519
  #adapters;
@@ -32316,7 +32521,8 @@ var ExternalThreadRuntime = class {
32316
32521
  #diagnose;
32317
32522
  #environment;
32318
32523
  #repository;
32319
- #restores = /* @__PURE__ */ new Map();
32524
+ #lifecycle = new ExternalThreadLifecycle();
32525
+ #hasRunningDescendants;
32320
32526
  #subagentRunning;
32321
32527
  #threads = /* @__PURE__ */ new Map();
32322
32528
  constructor(input) {
@@ -32326,12 +32532,13 @@ var ExternalThreadRuntime = class {
32326
32532
  this.#consumeOutputs = input.consumeOutputs;
32327
32533
  this.#diagnose = input.diagnose;
32328
32534
  this.#subagentRunning = input.subagentRunning ?? (() => false);
32535
+ this.#hasRunningDescendants = input.hasRunningDescendants ?? (() => false);
32329
32536
  this.idleRelease = new ExternalThreadIdleRelease({
32330
32537
  threads: () => this.values(),
32331
32538
  get: (id2) => this.get(id2),
32332
32539
  remove: (id2) => this.remove(id2),
32333
32540
  queue: input.idleRelease?.queue ?? new DesktopRequestQueue(),
32334
- canRelease: input.idleRelease?.canRelease ?? (() => false),
32541
+ canRelease: (thread) => !thread.sessionUnavailable && !this.#lifecycle.busy(thread.id) && (input.idleRelease?.canRelease(thread) ?? false),
32335
32542
  ...input.idleRelease?.onClosed ? { onClosed: input.idleRelease.onClosed } : {},
32336
32543
  diagnose: input.diagnose
32337
32544
  });
@@ -32347,7 +32554,45 @@ var ExternalThreadRuntime = class {
32347
32554
  }
32348
32555
  clear() {
32349
32556
  this.#threads.clear();
32350
- this.#restores.clear();
32557
+ }
32558
+ drain() {
32559
+ return this.#lifecycle.drain();
32560
+ }
32561
+ #withLifecycle(threadId2, operation) {
32562
+ return this.#lifecycle.run(threadId2, async () => {
32563
+ await this.idleRelease.waitForClose(threadId2);
32564
+ return operation();
32565
+ });
32566
+ }
32567
+ markSessionUnavailable(thread) {
32568
+ thread.sessionUnavailable = true;
32569
+ }
32570
+ #idleForRestore(thread) {
32571
+ if (thread.running || thread.activeTurnId !== null) return false;
32572
+ if (thread.session.hasBackgroundWork?.()) return false;
32573
+ if (this.#hasRunningDescendants(thread.id)) return false;
32574
+ return true;
32575
+ }
32576
+ async #dropIdleSession(thread) {
32577
+ if (this.#threads.get(thread.id) !== thread) return;
32578
+ thread.sessionUnavailable = true;
32579
+ await this.#lifecycle.release(thread.id, thread.session, thread.outputTask);
32580
+ if (this.#threads.get(thread.id) !== thread) return;
32581
+ await this.#retireSubagents(thread);
32582
+ if (this.#threads.get(thread.id) === thread) this.#threads.delete(thread.id);
32583
+ }
32584
+ /** Called without awaiting from the output consumer: release itself drains that consumer. */
32585
+ async discardUnavailableIdle(thread) {
32586
+ const session = thread.session;
32587
+ try {
32588
+ await this.#withLifecycle(thread.id, async () => {
32589
+ if (this.#threads.get(thread.id) !== thread || thread.session !== session || !thread.sessionUnavailable || !this.#idleForRestore(thread))
32590
+ return;
32591
+ await this.#dropIdleSession(thread);
32592
+ });
32593
+ } catch (error51) {
32594
+ this.#diagnose(error51);
32595
+ }
32351
32596
  }
32352
32597
  register(input) {
32353
32598
  const harnessId = input.record.harnessId;
@@ -32392,7 +32637,8 @@ var ExternalThreadRuntime = class {
32392
32637
  ephemeralTurnIds: /* @__PURE__ */ new Set(),
32393
32638
  persistenceError: null,
32394
32639
  projectedTerminalTurnId: null,
32395
- ignoredInteractionIds: /* @__PURE__ */ new Set()
32640
+ ignoredInteractionIds: /* @__PURE__ */ new Set(),
32641
+ sessionUnavailable: false
32396
32642
  };
32397
32643
  this.idleRelease.touch(externalThread);
32398
32644
  externalThread.outputTask = this.#consumeOutputs(externalThread);
@@ -32419,11 +32665,12 @@ var ExternalThreadRuntime = class {
32419
32665
  } catch (error51) {
32420
32666
  this.#diagnose(error51);
32421
32667
  }
32422
- await this.#retireSubagents(current.id);
32668
+ await this.#retireSubagents(current, true);
32423
32669
  this.#threads.delete(current.id);
32424
32670
  return this.register(input);
32425
32671
  }
32426
- async #retireSubagents(parentId) {
32672
+ async #retireSubagents(parent, bestEffort = false) {
32673
+ const parentId = parent.id;
32427
32674
  const ancestors = /* @__PURE__ */ new Map();
32428
32675
  const descendant = async (record4) => {
32429
32676
  const visited = /* @__PURE__ */ new Set();
@@ -32440,24 +32687,35 @@ var ExternalThreadRuntime = class {
32440
32687
  }
32441
32688
  return false;
32442
32689
  };
32443
- for (const [id2, restoring] of [...this.#restores]) {
32444
- if (await descendant(await this.#repository.find(id2))) {
32445
- await restoring.catch(this.#diagnose);
32446
- }
32690
+ for (const [id2, pending] of this.#lifecycle.pending()) {
32691
+ if (id2 !== parentId && await descendant(await this.#repository.find(id2))) await pending;
32447
32692
  }
32448
- for (const child of this.#threads.values()) {
32693
+ for (const child of [...this.#threads.values()]) {
32449
32694
  if (!await descendant(child.record)) continue;
32450
- this.#threads.delete(child.id);
32451
- try {
32452
- await child.session.close();
32453
- await child.outputTask;
32454
- } catch (error51) {
32455
- this.#diagnose(error51);
32456
- }
32695
+ const retire = async () => {
32696
+ if (this.#threads.get(parentId) !== parent || this.#threads.get(child.id) !== child) return;
32697
+ if (bestEffort) {
32698
+ this.#threads.delete(child.id);
32699
+ await child.session.close();
32700
+ await child.outputTask;
32701
+ } else {
32702
+ child.sessionUnavailable = true;
32703
+ await this.#lifecycle.release(child.id, child.session, child.outputTask);
32704
+ if (this.#threads.get(child.id) === child) this.#threads.delete(child.id);
32705
+ }
32706
+ };
32707
+ if (bestEffort) await retire().catch(this.#diagnose);
32708
+ else await this.#withLifecycle(child.id, retire);
32457
32709
  }
32458
32710
  }
32459
32711
  async locate(threadId2) {
32460
- await this.idleRelease.waitForClose(threadId2);
32712
+ try {
32713
+ return await this.#withLifecycle(threadId2, () => this.#locate(threadId2));
32714
+ } catch (error51) {
32715
+ return { kind: "error", error: recoveryError(error51) };
32716
+ }
32717
+ }
32718
+ async #locate(threadId2) {
32461
32719
  const loaded = this.#threads.get(threadId2);
32462
32720
  if (loaded) {
32463
32721
  const failure = this.idleRelease.failure(loaded);
@@ -32483,37 +32741,61 @@ var ExternalThreadRuntime = class {
32483
32741
  return { kind: "external", record: record4, thread: null };
32484
32742
  }
32485
32743
  async resolve(threadId2) {
32486
- const location = await this.locate(threadId2);
32487
- if (location.kind !== "external") return location;
32488
- if (location.thread) {
32489
- this.idleRelease.touch(location.thread);
32490
- return { kind: "external", thread: location.thread, historyFresh: false };
32491
- }
32492
- const { record: record4 } = location;
32493
- let restoring = this.#restores.get(threadId2);
32494
- if (!restoring) {
32495
- const restored = this.#threads.get(threadId2);
32496
- if (restored) {
32497
- this.idleRelease.touch(restored);
32498
- return { kind: "external", thread: restored, historyFresh: false };
32499
- }
32500
- restoring = this.#restore(record4).finally(() => {
32501
- this.#restores.delete(threadId2);
32744
+ try {
32745
+ return await this.#withLifecycle(threadId2, async () => {
32746
+ const location = await this.#locate(threadId2);
32747
+ if (location.kind !== "external") return location;
32748
+ if (location.thread) {
32749
+ if (location.thread.sessionUnavailable && this.#idleForRestore(location.thread)) {
32750
+ await this.#dropIdleSession(location.thread);
32751
+ const current = this.#threads.get(threadId2);
32752
+ if (current) return { kind: "external", thread: current, historyFresh: false };
32753
+ } else {
32754
+ this.idleRelease.touch(location.thread);
32755
+ return { kind: "external", thread: location.thread, historyFresh: false };
32756
+ }
32757
+ }
32758
+ return {
32759
+ kind: "external",
32760
+ thread: await this.#restore(location.record),
32761
+ historyFresh: true
32762
+ };
32502
32763
  });
32503
- this.#restores.set(threadId2, restoring);
32764
+ } catch (error51) {
32765
+ return { kind: "error", error: recoveryError(error51) };
32504
32766
  }
32767
+ }
32768
+ async refresh(thread) {
32505
32769
  try {
32506
- return { kind: "external", thread: await restoring, historyFresh: true };
32770
+ return await this.#withLifecycle(thread.id, () => this.#refresh(thread));
32507
32771
  } catch (error51) {
32772
+ return recoveryError(error51);
32773
+ }
32774
+ }
32775
+ async #refresh(thread) {
32776
+ if (this.#threads.get(thread.id) !== thread) {
32508
32777
  return {
32509
- kind: "error",
32510
- error: error51 instanceof ExternalThreadOpenError ? error51.rpcError : { code: -32076, message: "External Thread recovery failed" }
32778
+ code: -32076,
32779
+ message: "External Session changed during recovery; retry the request"
32511
32780
  };
32512
32781
  }
32513
- }
32514
- async refresh(thread) {
32515
- const snapshot2 = await thread.session.readSnapshot();
32516
- if (!snapshot2.ok) return mapExternalThreadHarnessError(snapshot2.error, "read");
32782
+ const failure = this.idleRelease.failure(thread);
32783
+ if (failure) return { code: -32075, message: failure };
32784
+ if (thread.sessionUnavailable && this.#idleForRestore(thread)) {
32785
+ const revived = await this.#reviveIdleSession(thread);
32786
+ if (revived) return revived;
32787
+ }
32788
+ let snapshot2 = await thread.session.readSnapshot();
32789
+ if (!snapshot2.ok) {
32790
+ if (snapshot2.error.code === "invalidState" && this.#idleForRestore(thread) && this.#threads.get(thread.id) === thread) {
32791
+ const revived = await this.#reviveIdleSession(thread);
32792
+ if (revived) return revived;
32793
+ snapshot2 = await thread.session.readSnapshot();
32794
+ if (!snapshot2.ok) return mapExternalThreadHarnessError(snapshot2.error, "read");
32795
+ } else {
32796
+ return mapExternalThreadHarnessError(snapshot2.error, "read");
32797
+ }
32798
+ }
32517
32799
  try {
32518
32800
  const aligned = await this.#repository.alignSnapshot(thread.record, snapshot2.value);
32519
32801
  thread.record = aligned.record;
@@ -32530,6 +32812,122 @@ var ExternalThreadRuntime = class {
32530
32812
  return { code: -32081, message: "External Thread history could not be persisted" };
32531
32813
  }
32532
32814
  }
32815
+ async #reviveIdleSession(thread) {
32816
+ thread.sessionUnavailable = true;
32817
+ const harnessId = thread.record.harnessId;
32818
+ const adapter = this.#adapters.get(harnessId);
32819
+ if (!adapter || !thread.record.nativeSessionRef) {
32820
+ await this.#dropIdleSession(thread);
32821
+ return { code: -32077, message: "External Harness is unavailable" };
32822
+ }
32823
+ await this.#lifecycle.release(thread.id, thread.session, thread.outputTask);
32824
+ await this.#retireSubagents(thread);
32825
+ if (this.#threads.get(thread.id) !== thread) {
32826
+ return { code: -32076, message: "External Thread recovery failed" };
32827
+ }
32828
+ const restoredSelection = decodeExternalTransportSelection(
32829
+ harnessId,
32830
+ thread.record.transportModelId
32831
+ );
32832
+ const opened = await adapter.open({
32833
+ kind: "resume",
32834
+ cwd: thread.record.cwd,
32835
+ environment: { ...this.#environment, [DELEGATION_THREAD_ID_ENV]: thread.record.hostThreadId },
32836
+ nativeRef: thread.record.nativeSessionRef,
32837
+ knownTurnRefs: thread.record.turnMappings.map(({ nativeTurnRef }) => nativeTurnRef),
32838
+ ...restoredSelection?.model ? { model: restoredSelection.model } : {},
32839
+ ...restoredSelection?.thinkingOptionId ? { thinkingOptionId: restoredSelection.thinkingOptionId } : {},
32840
+ ...restoredSelection?.permissionModeId ? { permissionModeId: restoredSelection.permissionModeId } : {}
32841
+ });
32842
+ if (!opened.ok) {
32843
+ await this.#dropIdleSession(thread);
32844
+ return mapExternalThreadHarnessError(opened.error, "resume");
32845
+ }
32846
+ const session = opened.value;
32847
+ if (this.#threads.get(thread.id) !== thread) {
32848
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32849
+ return { code: -32076, message: "External Thread recovery failed" };
32850
+ }
32851
+ try {
32852
+ const snapshot2 = await session.readSnapshot();
32853
+ if (!snapshot2.ok) {
32854
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32855
+ await this.#dropIdleSession(thread);
32856
+ return mapExternalThreadHarnessError(snapshot2.error, "read");
32857
+ }
32858
+ let aligned = await this.#repository.alignSnapshot(thread.record, snapshot2.value);
32859
+ if (this.#threads.get(thread.id) !== thread) {
32860
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32861
+ return { code: -32076, message: "External Thread recovery failed" };
32862
+ }
32863
+ const restoredState = snapshot2.value.state;
32864
+ const effectiveModel = restoredState ? restoredState.effectiveModel : restoredSelection?.model;
32865
+ const effectiveThinkingOptionId = restoredState ? restoredState.effectiveThinkingOptionId : restoredSelection?.thinkingOptionId;
32866
+ const effectivePermissionModeId = restoredState ? restoredState.effectivePermissionModeId : restoredSelection?.permissionModeId;
32867
+ let transportModelId = aligned.record.transportModelId;
32868
+ if (restoredState && effectiveModel) {
32869
+ const liveSelection = {
32870
+ model: effectiveModel,
32871
+ ...effectiveThinkingOptionId ? { thinkingOptionId: effectiveThinkingOptionId } : {},
32872
+ ...effectivePermissionModeId ? { permissionModeId: effectivePermissionModeId } : {}
32873
+ };
32874
+ transportModelId = encodeExternalTransportSelection(harnessId, liveSelection);
32875
+ if (transportModelId !== aligned.record.transportModelId) {
32876
+ try {
32877
+ aligned = {
32878
+ ...aligned,
32879
+ record: await this.#repository.setTransportModelId(
32880
+ aligned.record.hostThreadId,
32881
+ transportModelId
32882
+ )
32883
+ };
32884
+ } catch (error51) {
32885
+ this.#diagnose(error51);
32886
+ }
32887
+ }
32888
+ }
32889
+ if (this.#threads.get(thread.id) !== thread) {
32890
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32891
+ return { code: -32076, message: "External Thread recovery failed" };
32892
+ }
32893
+ const initialState = restoredState ?? session.initialState;
32894
+ const observerState = {
32895
+ ...initialState,
32896
+ ...effectiveModel ? { effectiveModel } : {},
32897
+ ...effectiveThinkingOptionId ? { effectiveThinkingOptionId } : {},
32898
+ ...effectivePermissionModeId ? { effectivePermissionModeId } : {}
32899
+ };
32900
+ thread.session = session;
32901
+ thread.record = aligned.record;
32902
+ thread.turns = aligned.turns;
32903
+ thread.historyHydrated = true;
32904
+ thread.sessionUnavailable = false;
32905
+ thread.persistenceError = null;
32906
+ thread.transportModelId = transportModelId;
32907
+ if (effectiveModel) thread.requestedModel = effectiveModel;
32908
+ if (effectiveThinkingOptionId) thread.requestedThinkingOptionId = effectiveThinkingOptionId;
32909
+ if (effectivePermissionModeId) thread.requestedPermissionModeId = effectivePermissionModeId;
32910
+ thread.stateObserver = new SessionStateObserver(observerState);
32911
+ thread.latestUsage = session.initialUsage;
32912
+ thread.usageMeter = new UsageMeter();
32913
+ thread.usageTurnId = null;
32914
+ thread.thread = externalThreadValue({
32915
+ record: aligned.record,
32916
+ turns: aligned.turns,
32917
+ sessionId: thread.sessionId,
32918
+ running: thread.running
32919
+ });
32920
+ thread.outputTask = this.#consumeOutputs(thread);
32921
+ this.idleRelease.clearOutputFailed(thread);
32922
+ return null;
32923
+ } catch (error51) {
32924
+ if (error51 instanceof ExternalSessionReleaseError) throw error51;
32925
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32926
+ this.#diagnose(error51);
32927
+ await this.#dropIdleSession(thread);
32928
+ return { code: -32081, message: "External Thread history could not be persisted" };
32929
+ }
32930
+ }
32533
32931
  async persistTerminalIdentity(thread, event) {
32534
32932
  if (thread.persistenceError) return thread.persistenceError;
32535
32933
  if (!event.nativeTurnRef) {
@@ -32668,7 +33066,8 @@ var ExternalThreadRuntime = class {
32668
33066
  transportModelId
32669
33067
  });
32670
33068
  } catch (error51) {
32671
- await session.close().catch(() => void 0);
33069
+ if (error51 instanceof ExternalSessionReleaseError) throw error51;
33070
+ await this.#lifecycle.release(record4.hostThreadId, session, Promise.resolve());
32672
33071
  throw error51;
32673
33072
  }
32674
33073
  }
@@ -33085,7 +33484,7 @@ function sanitizeDelegationTitle(task) {
33085
33484
  const cutLength = Math.max(0, DELEGATION_TITLE_MAX_LENGTH - DELEGATION_TITLE_ELLIPSIS.length);
33086
33485
  return `${trimmed.slice(0, cutLength)}${DELEGATION_TITLE_ELLIPSIS}`;
33087
33486
  }
33088
- function delay2(milliseconds) {
33487
+ function delay3(milliseconds) {
33089
33488
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
33090
33489
  }
33091
33490
  function terminal(status2) {
@@ -33475,7 +33874,7 @@ var HarnessDelegationCoordinator = class {
33475
33874
  if (terminal(snapshot2.status)) return { ...snapshot2, timedOut: false };
33476
33875
  const remaining = deadline - Date.now();
33477
33876
  if (remaining <= 0) return { ...snapshot2, timedOut: true };
33478
- await delay2(Math.min(100, remaining));
33877
+ await delay3(Math.min(100, remaining));
33479
33878
  }
33480
33879
  }
33481
33880
  async list(input) {
@@ -35609,15 +36008,23 @@ var HarnessPluginRegistry = class {
35609
36008
  };
35610
36009
 
35611
36010
  // packages/host-runtime/src/harness-plugin-loader.ts
36011
+ function hasValidSessionUsage(value2) {
36012
+ const capability = Reflect.get(value2, "sessionUsage");
36013
+ return capability === void 0 || capability !== null && typeof capability === "object" && ["observe", "read"].every((key) => typeof Reflect.get(capability, key) === "function") && ["requestOptions", "shouldForwardNotification", "reset"].every(
36014
+ (key) => Reflect.get(capability, key) === void 0 || typeof Reflect.get(capability, key) === "function"
36015
+ );
36016
+ }
35612
36017
  function isAdapter(value2) {
35613
36018
  if (!value2 || typeof value2 !== "object") return false;
35614
- return ["inspect", "open", "close"].every((key) => typeof Reflect.get(value2, key) === "function");
36019
+ return hasValidSessionUsage(value2) && ["inspect", "open", "close"].every((key) => typeof Reflect.get(value2, key) === "function") && ["credits", "refreshCredits"].every(
36020
+ (key) => Reflect.get(value2, key) === void 0 || typeof Reflect.get(value2, key) === "function"
36021
+ );
35615
36022
  }
35616
36023
  function isUsageAdapter(value2) {
35617
36024
  if (!value2 || typeof value2 !== "object" || typeof Reflect.get(value2, "close") !== "function")
35618
36025
  return false;
35619
36026
  const capability = Reflect.get(value2, "usageStatistics");
35620
- return !!capability && typeof capability === "object" && ["listSources", "readSource"].every(
36027
+ return hasValidSessionUsage(value2) && !!capability && typeof capability === "object" && ["listSources", "readSource"].every(
35621
36028
  (key) => typeof Reflect.get(capability, key) === "function"
35622
36029
  ) && !("open" in value2) && !("inspect" in value2);
35623
36030
  }
@@ -35758,11 +36165,12 @@ async function loadHarnessPlugins(options2) {
35758
36165
  }
35759
36166
  if (options2.signal?.aborted) return registry2;
35760
36167
  let next = 0;
36168
+ let batch = pending;
35761
36169
  const loaded = /* @__PURE__ */ new Map();
35762
36170
  const worker = async () => {
35763
36171
  for (; ; ) {
35764
36172
  if (options2.signal?.aborted) return;
35765
- const candidate = pending[next++];
36173
+ const candidate = batch[next++];
35766
36174
  if (!candidate) return;
35767
36175
  if (options2.signal?.aborted) return;
35768
36176
  const { manifest } = candidate;
@@ -35808,10 +36216,19 @@ async function loadHarnessPlugins(options2) {
35808
36216
  loaded.set(candidate, { descriptor, adapter });
35809
36217
  }
35810
36218
  };
35811
- await Promise.all(Array.from({ length: Math.min(4, pending.length) }, () => worker()));
35812
- for (const candidate of pending) {
35813
- const entry = loaded.get(candidate);
35814
- if (entry) await registry2.register(entry.descriptor, entry.adapter);
36219
+ const batches = options2.onUsageAdaptersLoaded ? [
36220
+ pending.filter((c) => c.manifest.kind === "usage"),
36221
+ pending.filter((c) => c.manifest.kind !== "usage")
36222
+ ] : [pending];
36223
+ for (const [index, candidates2] of batches.entries()) {
36224
+ batch = candidates2;
36225
+ next = 0;
36226
+ await Promise.all(Array.from({ length: Math.min(4, batch.length) }, () => worker()));
36227
+ for (const candidate of batch) {
36228
+ const entry = loaded.get(candidate);
36229
+ if (entry) await registry2.register(entry.descriptor, entry.adapter);
36230
+ }
36231
+ if (index === 0) options2.onUsageAdaptersLoaded?.(registry2.usageAdapters);
35815
36232
  }
35816
36233
  return registry2;
35817
36234
  }
@@ -37017,16 +37434,16 @@ var OfficialRuntimeScope = class {
37017
37434
  #scheduleRecovery() {
37018
37435
  if (!this.#recovery || this.#closed || this.#recoveryTimer || this.#starting) return;
37019
37436
  const { delaysMs } = this.#recovery;
37020
- const delay5 = delaysMs[Math.min(this.#recoveryAttempt, delaysMs.length - 1)] ?? 0;
37437
+ const delay6 = delaysMs[Math.min(this.#recoveryAttempt, delaysMs.length - 1)] ?? 0;
37021
37438
  this.#recoveryAttempt++;
37022
37439
  this.#diagnosticOutput.write(
37023
- `codexhost: official Codex is unavailable; restarting in ${String(delay5)}ms
37440
+ `codexhost: official Codex is unavailable; restarting in ${String(delay6)}ms
37024
37441
  `
37025
37442
  );
37026
37443
  const timer = setTimeout(() => {
37027
37444
  this.#recoveryTimer = void 0;
37028
37445
  this.start().catch(() => void 0);
37029
- }, delay5);
37446
+ }, delay6);
37030
37447
  timer.unref();
37031
37448
  this.#recoveryTimer = timer;
37032
37449
  }
@@ -37777,11 +38194,173 @@ async function moveThreadSection(input) {
37777
38194
  }
37778
38195
  }
37779
38196
 
38197
+ // packages/host-runtime/src/external-thread-official-defaults.ts
38198
+ var EMPTY_RESULTS = /* @__PURE__ */ new Map([
38199
+ ["thread/attachment/list", () => ({ data: [], nextCursor: null })],
38200
+ ["thread/queue/list", () => ({ data: [], nextCursor: null })],
38201
+ ["thread/settings/update", () => ({})]
38202
+ ]);
38203
+ function externalThreadEmptyOfficialResult(method) {
38204
+ return EMPTY_RESULTS.get(method)?.();
38205
+ }
38206
+
38207
+ // packages/host-runtime/src/observed-session-usage.ts
38208
+ var ObservedSessionUsage = class {
38209
+ constructor(providers, prices, diagnose) {
38210
+ this.providers = providers;
38211
+ this.prices = prices;
38212
+ this.diagnose = diagnose;
38213
+ }
38214
+ providers;
38215
+ prices;
38216
+ diagnose;
38217
+ #states = /* @__PURE__ */ new Map();
38218
+ #pending = /* @__PURE__ */ new Map();
38219
+ #abort = new AbortController();
38220
+ #initializeParams = null;
38221
+ initialized(params) {
38222
+ this.#initializeParams = params;
38223
+ for (const state of this.#states.values()) {
38224
+ state.meter.resetTurnTiming();
38225
+ state.activeTurnId = null;
38226
+ }
38227
+ for (const provider of this.providers()) {
38228
+ try {
38229
+ provider.reset?.();
38230
+ } catch (error51) {
38231
+ this.diagnose(error51);
38232
+ }
38233
+ }
38234
+ }
38235
+ requestOptions(method, params) {
38236
+ if (this.#abort.signal.aborted) return null;
38237
+ let result = null;
38238
+ for (const provider of this.providers()) {
38239
+ try {
38240
+ const patch = provider.requestOptions?.({
38241
+ method,
38242
+ params,
38243
+ initializeParams: this.#initializeParams
38244
+ });
38245
+ if (patch) result = Object.assign(result ?? {}, jsonObjectSchema.parse(patch));
38246
+ } catch (error51) {
38247
+ this.diagnose(error51);
38248
+ }
38249
+ }
38250
+ return result;
38251
+ }
38252
+ shouldForwardNotification(message2) {
38253
+ if (this.#abort.signal.aborted) return true;
38254
+ for (const provider of this.providers()) {
38255
+ try {
38256
+ if (provider.shouldForwardNotification?.(message2) === false) return false;
38257
+ } catch (error51) {
38258
+ this.diagnose(error51);
38259
+ }
38260
+ }
38261
+ return true;
38262
+ }
38263
+ observe(message2, now = Date.now()) {
38264
+ if (this.#abort.signal.aborted) return [];
38265
+ const changed = /* @__PURE__ */ new Set();
38266
+ for (const provider of this.providers()) {
38267
+ try {
38268
+ const observation = provider.observe(message2, now);
38269
+ if (!observation) continue;
38270
+ const state = this.#state(observation.sessionId, provider);
38271
+ if (state.provider !== provider) continue;
38272
+ if (observation.usage) {
38273
+ state.live = parseHostUsage(observation.usage);
38274
+ state.revision++;
38275
+ }
38276
+ const turn = observation.turn;
38277
+ if (turn?.phase === "started" && state.activeTurnId !== turn.id) {
38278
+ state.meter.resetTurnTiming();
38279
+ state.meter.turnStarted(turn.id, now);
38280
+ state.activeTurnId = turn.id;
38281
+ }
38282
+ const timing = observation.requestTiming;
38283
+ if (timing) state.meter.recordOutputTiming(timing, timing.turnId);
38284
+ if (observation.timingUnavailable)
38285
+ state.meter.invalidateOutputTiming(observation.timingUnavailable.turnId);
38286
+ if (turn?.phase === "completed") {
38287
+ state.meter.turnCompleted(turn.id);
38288
+ if (state.activeTurnId === turn.id) state.activeTurnId = null;
38289
+ }
38290
+ const firstOutput = turn?.phase === "output" && state.meter.outputObserved(turn.id, now);
38291
+ if (observation.usage || firstOutput || timing || observation.timingUnavailable || turn?.phase === "started" || turn?.phase === "completed")
38292
+ changed.add(observation.sessionId);
38293
+ } catch (error51) {
38294
+ this.diagnose(error51);
38295
+ }
38296
+ }
38297
+ return [...changed];
38298
+ }
38299
+ async read(sessionId) {
38300
+ if (this.#abort.signal.aborted) return null;
38301
+ let pending = this.#pending.get(sessionId);
38302
+ if (!pending) {
38303
+ pending = this.#refresh(sessionId).finally(() => this.#pending.delete(sessionId));
38304
+ this.#pending.set(sessionId, pending);
38305
+ }
38306
+ await pending;
38307
+ const state = this.#states.get(sessionId);
38308
+ if (!state || this.#abort.signal.aborted) return null;
38309
+ const native = state.live ?? state.history;
38310
+ const result = state.meter.derive(native, await this.prices.lookup());
38311
+ if (result?.unpricedModels?.length) this.prices.missing();
38312
+ return result;
38313
+ }
38314
+ async #refresh(sessionId) {
38315
+ const existing = this.#states.get(sessionId);
38316
+ for (const provider of existing ? [existing.provider] : this.providers()) {
38317
+ const revision = existing?.revision ?? 0;
38318
+ try {
38319
+ const history = await provider.read(sessionId, this.#abort.signal);
38320
+ if (this.#abort.signal.aborted) return;
38321
+ if (!history) {
38322
+ if (existing?.meter.metered) existing.meter.recordHistory(false);
38323
+ continue;
38324
+ }
38325
+ const state = this.#state(sessionId, provider);
38326
+ state.history = history.usage ? parseHostUsage(history.usage) : null;
38327
+ state.meter.replaceHistory(
38328
+ history.requests,
38329
+ history.complete && state.revision === revision
38330
+ );
38331
+ return;
38332
+ } catch (error51) {
38333
+ existing?.meter.recordHistory(false);
38334
+ if (!this.#abort.signal.aborted) this.diagnose(error51);
38335
+ }
38336
+ }
38337
+ }
38338
+ #state(id2, provider) {
38339
+ let state = this.#states.get(id2);
38340
+ if (!state) {
38341
+ state = {
38342
+ provider,
38343
+ meter: new UsageMeter(),
38344
+ live: null,
38345
+ history: null,
38346
+ revision: 0,
38347
+ activeTurnId: null
38348
+ };
38349
+ this.#states.set(id2, state);
38350
+ }
38351
+ return state;
38352
+ }
38353
+ close() {
38354
+ this.#abort.abort();
38355
+ this.#states.clear();
38356
+ }
38357
+ };
38358
+
37780
38359
  // packages/host-runtime/src/app-server-host.ts
37781
38360
  var CONSOLE_REQUEST_TIMEOUT_MS = 12e4;
37782
38361
  var SUBAGENT_TERMINAL_REFRESH_DELAYS_MS = [0, 50, 100, 150];
37783
38362
  var THREAD_USAGE_UPDATED_METHOD = "codexhost/thread/usage/updated";
37784
- function delay3(milliseconds) {
38363
+ function delay4(milliseconds) {
37785
38364
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
37786
38365
  }
37787
38366
  function isRecord19(value2) {
@@ -37793,16 +38372,6 @@ function officialThreadBusy(thread) {
37793
38372
  const latestTurn = turns.at(-1);
37794
38373
  return isRecord19(latestTurn) && (latestTurn.status === "inProgress" || latestTurn.status === "running");
37795
38374
  }
37796
- function isCreditsAdapter(adapter) {
37797
- return typeof adapter.credits === "function";
37798
- }
37799
- function projectAccountCredits(value2) {
37800
- if (!isRecord19(value2)) return null;
37801
- const rest = { ...value2 };
37802
- delete rest.fetchedAt;
37803
- const parsed2 = accountCreditsSnapshotSchema.safeParse(rest);
37804
- return parsed2.success ? parsed2.data : null;
37805
- }
37806
38375
  function errorMessage4(error51) {
37807
38376
  return error51 instanceof Error ? error51.message : String(error51);
37808
38377
  }
@@ -37978,10 +38547,12 @@ var AppServerHost = class {
37978
38547
  #launchSettings;
37979
38548
  #accountInspections = new HarnessAccountInspectionCache();
37980
38549
  #externalRuntime;
38550
+ #executionHosts = /* @__PURE__ */ new WeakMap();
37981
38551
  #externalPrewarms = new ExternalThreadPrewarms();
37982
38552
  #externalSteering = new ExternalTurnSteering();
37983
38553
  #liveCommandCache = new LiveCommandCatalogCache();
37984
38554
  #modelPrices;
38555
+ #observedSessionUsage;
37985
38556
  #repository;
37986
38557
  #pendingDesktopApprovals = /* @__PURE__ */ new Map();
37987
38558
  #pendingDesktopQuestions = /* @__PURE__ */ new Map();
@@ -37998,7 +38569,6 @@ var AppServerHost = class {
37998
38569
  #activeWorkDrainWaiters = /* @__PURE__ */ new Set();
37999
38570
  #pendingOfficialDelegationThreads = /* @__PURE__ */ new Set();
38000
38571
  #pendingOfficialTerminalStatuses = /* @__PURE__ */ new Map();
38001
- #officialUsageByThread = /* @__PURE__ */ new Map();
38002
38572
  #officialRateLimits = new AccountRateLimits();
38003
38573
  #routeObservationTracker = new RequestRouteObservationTracker();
38004
38574
  #officialServerRequests = /* @__PURE__ */ new Map();
@@ -38016,6 +38586,7 @@ var AppServerHost = class {
38016
38586
  #closeRequested = false;
38017
38587
  #pluginLoadAbort = new AbortController();
38018
38588
  #pluginLoading;
38589
+ #usagePluginsReady;
38019
38590
  #desktopRequests = new DesktopRequestQueue();
38020
38591
  #drainActiveWorkOnInputEnd = false;
38021
38592
  #desktopInputEnded = false;
@@ -38027,6 +38598,13 @@ var AppServerHost = class {
38027
38598
  ...options2
38028
38599
  };
38029
38600
  this.#modelPrices = options2.modelPrices ?? new ModelPriceCatalog();
38601
+ this.#observedSessionUsage = new ObservedSessionUsage(
38602
+ () => [...this.#externalAdapters.values(), ...this.#usageOnlyAdapters].flatMap(
38603
+ (adapter) => adapter.sessionUsage ? [adapter.sessionUsage] : []
38604
+ ),
38605
+ this.#modelPrices,
38606
+ (error51) => this.#diagnose(error51)
38607
+ );
38030
38608
  this.#writer = new OrderedWriter(this.#options.desktopOutput, (value2) => {
38031
38609
  this.#noteDesktopReply(value2);
38032
38610
  return this.#takeConsoleReply(value2);
@@ -38110,6 +38688,7 @@ var AppServerHost = class {
38110
38688
  consumeOutputs: (thread) => this.#consumeHarnessOutputs(thread),
38111
38689
  diagnose: (error51) => this.#diagnose(error51),
38112
38690
  subagentRunning: (threadId2) => this.#subagentThreadStatuses.get(threadId2) === "active",
38691
+ hasRunningDescendants: (threadId2) => this.#hasRunningSubagents(threadId2),
38113
38692
  idleRelease: {
38114
38693
  queue: this.#desktopRequests,
38115
38694
  onClosed: async (thread) => {
@@ -38168,7 +38747,11 @@ var AppServerHost = class {
38168
38747
  wait: (input) => this.#waitForPlugins().then(() => this.#delegationCoordinator.wait(input)),
38169
38748
  list: (input) => this.#waitForPlugins().then(() => this.#delegationCoordinator.list(input)),
38170
38749
  canHandleStart: (input) => this.#canHandleDelegationStart(input),
38171
- ownsThread: (threadId2) => this.#ownsDelegationThread(threadId2)
38750
+ ownsThread: (threadId2) => this.#ownsDelegationThread(threadId2),
38751
+ executionHostId: (threadId2) => {
38752
+ const thread = this.#externalRuntime.get(threadId2);
38753
+ return thread ? this.#executionHosts.get(thread) : void 0;
38754
+ }
38172
38755
  });
38173
38756
  this.#unregisterDelegationApi = typeof unregisterDelegationApi === "function" ? unregisterDelegationApi : void 0;
38174
38757
  }
@@ -38200,18 +38783,29 @@ var AppServerHost = class {
38200
38783
  this.#options.usageStatistics?.attach(
38201
38784
  () => [.../* @__PURE__ */ new Set([...this.#externalAdapters.values(), ...this.#usageOnlyAdapters])].flatMap(
38202
38785
  (adapter) => adapter.usageStatistics ? [{ harness: adapter.harnessId, capability: adapter.usageStatistics }] : []
38203
- )
38786
+ ),
38787
+ () => this.#repository.list()
38204
38788
  );
38205
38789
  }
38206
38790
  #waitForPlugins() {
38207
- return this.#pluginLoading ??= this.#loadInstalledPlugins().catch((error51) => {
38208
- this.#diagnose(`Harness plugin load failed: ${errorMessage4(error51)}`);
38209
- });
38791
+ if (!this.#pluginLoading) {
38792
+ const ready = Promise.withResolvers();
38793
+ const usageReady = () => ready.resolve(void 0);
38794
+ this.#usagePluginsReady = ready.promise;
38795
+ this.#pluginLoading = this.#loadInstalledPlugins(usageReady).catch((error51) => {
38796
+ this.#diagnose(`Harness plugin load failed: ${errorMessage4(error51)}`);
38797
+ }).finally(usageReady);
38798
+ }
38799
+ return this.#pluginLoading;
38210
38800
  }
38211
- async #loadInstalledPlugins() {
38801
+ async #loadInstalledPlugins(usageReady) {
38212
38802
  if (!this.#options.pluginRoots || this.#pluginLoadAbort.signal.aborted) return;
38213
38803
  const plugins = await loadHarnessPlugins({
38214
38804
  roots: this.#options.pluginRoots,
38805
+ onUsageAdaptersLoaded: (adapters) => {
38806
+ if (!this.#pluginLoadAbort.signal.aborted) this.#usageOnlyAdapters = [...adapters.values()];
38807
+ usageReady();
38808
+ },
38215
38809
  launchCommandForPlugin: (id2) => this.#launchSettings.initialCommand(id2),
38216
38810
  context: this.#options.pluginContext ?? {
38217
38811
  environment: this.#options.environment ?? process.env,
@@ -38232,6 +38826,7 @@ var AppServerHost = class {
38232
38826
  for (const [id2, adapter] of plugins.adapters) this.#externalAdapters.set(id2, adapter);
38233
38827
  }
38234
38828
  async #closeAdapters() {
38829
+ this.#observedSessionUsage.close();
38235
38830
  const results = await Promise.allSettled([
38236
38831
  this.#plugins?.close(),
38237
38832
  ...[...new Set(this.#options.externalAdapters?.values())].map(
@@ -38293,6 +38888,7 @@ var AppServerHost = class {
38293
38888
  await Promise.allSettled(threads.map(({ session }) => session.close()));
38294
38889
  await Promise.allSettled(threads.map(({ outputTask }) => outputTask));
38295
38890
  await this.#closeAdapters();
38891
+ await this.#externalRuntime.drain();
38296
38892
  for (const pending of [...this.#pendingDesktopApprovals.values()]) {
38297
38893
  await this.#resolveDesktopApproval(pending.interaction.interactionId).catch(
38298
38894
  () => void 0
@@ -38435,7 +39031,13 @@ var AppServerHost = class {
38435
39031
  if (request.method === "initialize") {
38436
39032
  try {
38437
39033
  const nativeGeneration = this.#officialRuntimeScope.gate.phase === "ready" ? this.#officialRuntimeScope.owner.generation : void 0;
38438
- const response = await this.#officialRuntime.initializeProtocol(requestObject(request));
39034
+ void this.#waitForPlugins();
39035
+ await this.#usagePluginsReady;
39036
+ const params = requestObject(request);
39037
+ const options2 = this.#observedSessionUsage.requestOptions("initialize", params);
39038
+ const nativeParams = options2 ? { ...params, ...options2 } : params;
39039
+ const response = await this.#officialRuntime.initializeProtocol(nativeParams);
39040
+ if (!isRecord19(response.error)) this.#observedSessionUsage.initialized(nativeParams);
38439
39041
  await this.#writer.json({ ...response, id: request.id });
38440
39042
  this.#nativeAccountObserver?.initialized(nativeGeneration);
38441
39043
  } catch (error51) {
@@ -39247,8 +39849,9 @@ var AppServerHost = class {
39247
39849
  const location = await this.#locateExternalThread(request.params.threadId);
39248
39850
  if (await this.#writeResolutionError(request, location)) return;
39249
39851
  if (location.kind === "external") {
39852
+ const emptyResult = externalThreadEmptyOfficialResult(request.method);
39250
39853
  await this.#writer.json(
39251
- rpcError(request, -32076, `External Thread does not support ${request.method}`)
39854
+ emptyResult ? rpcEnvelope(request, { result: emptyResult }) : rpcError(request, -32076, `External Thread does not support ${request.method}`)
39252
39855
  );
39253
39856
  return;
39254
39857
  }
@@ -39297,6 +39900,15 @@ var AppServerHost = class {
39297
39900
  return;
39298
39901
  }
39299
39902
  try {
39903
+ const options2 = isRecord19(request.params) ? this.#observedSessionUsage.requestOptions(request.method, request.params) : null;
39904
+ if (options2) {
39905
+ const original = parseJsonFrame(frame);
39906
+ if (isRecord19(original))
39907
+ frame = encodeJsonFrame({
39908
+ ...original,
39909
+ params: { ...isRecord19(original.params) ? original.params : {}, ...options2 }
39910
+ });
39911
+ }
39300
39912
  await this.#officialRuntime.sendFrame(frame);
39301
39913
  this.#markDesktopRequestAnswered(request.id);
39302
39914
  } catch {
@@ -39315,6 +39927,7 @@ var AppServerHost = class {
39315
39927
  return;
39316
39928
  }
39317
39929
  const parsed2 = input.value;
39930
+ const observedAtMs = Date.now();
39318
39931
  this.#observeOfficialTurnStartResponse(parsed2);
39319
39932
  let forwarded = parsed2;
39320
39933
  if (isRecord19(parsed2) && typeof parsed2.method === "string" && "id" in parsed2) {
@@ -39329,17 +39942,6 @@ var AppServerHost = class {
39329
39942
  if (accountScopedNotification) {
39330
39943
  if (parsed2.method === "account/updated") this.#officialRateLimits.reset(input.accountId);
39331
39944
  }
39332
- const tokenUsage = observeCodexTokenUsage(parsed2);
39333
- if (tokenUsage) {
39334
- const previous = this.#officialUsageByThread.get(tokenUsage.threadId);
39335
- try {
39336
- this.#officialUsageByThread.set(
39337
- tokenUsage.threadId,
39338
- parseHostUsage({ ...previous ?? {}, ...tokenUsage.usage })
39339
- );
39340
- } catch {
39341
- }
39342
- }
39343
39945
  const rateLimits = observeCodexRateLimits(parsed2);
39344
39946
  if (rateLimits) this.#officialRateLimits.observe(input.accountId, rateLimits);
39345
39947
  try {
@@ -39348,8 +39950,16 @@ var AppServerHost = class {
39348
39950
  this.#diagnose(error51);
39349
39951
  }
39350
39952
  this.#routeObservationTracker.bindOfficialResponse(parsed2);
39351
- if (forwarded === parsed2) await this.#writer.frame(input.frame);
39352
- else await this.#writer.json(forwarded);
39953
+ const privateTelemetry = isRecord19(parsed2) && typeof parsed2.method === "string" && !("id" in parsed2) && !this.#observedSessionUsage.shouldForwardNotification(parsed2);
39954
+ if (!privateTelemetry) {
39955
+ if (forwarded === parsed2) await this.#writer.frame(input.frame);
39956
+ else await this.#writer.json(forwarded);
39957
+ }
39958
+ void (this.#usagePluginsReady ?? Promise.resolve()).then(async () => {
39959
+ for (const threadId2 of this.#observedSessionUsage.observe(parsed2, observedAtMs)) {
39960
+ await this.#writer.json({ method: THREAD_USAGE_UPDATED_METHOD, params: { threadId: threadId2 } });
39961
+ }
39962
+ }).catch((error51) => this.#diagnose(error51));
39353
39963
  this.#nativeAccountObserver?.observe(parsed2);
39354
39964
  const deletedProjectId = observeDeletedProject(parsed2);
39355
39965
  if (deletedProjectId) {
@@ -40382,12 +40992,14 @@ var AppServerHost = class {
40382
40992
  );
40383
40993
  return;
40384
40994
  }
40995
+ await this.#waitForPlugins();
40385
40996
  const accountId = await this.#currentCodexAccountId();
40386
40997
  if (accountId) await this.#refreshOfficialRateLimits(accountId);
40387
40998
  const accountCredits = this.#officialAccountCredits(accountId ?? void 0);
40388
40999
  const result2 = threadUsageInspectionSchema.parse({
40389
41000
  threadId: params.data.threadId,
40390
- usage: this.#officialUsageByThread.get(params.data.threadId) ?? null,
41001
+ usage: await this.#observedSessionUsage.read(params.data.threadId),
41002
+ accountCreditsSupported: true,
40391
41003
  ...accountCredits ? { accountCredits } : {}
40392
41004
  });
40393
41005
  await this.#writer.json(rpcEnvelope(request, { result: jsonValueSchema.parse(result2) }));
@@ -40395,11 +41007,17 @@ var AppServerHost = class {
40395
41007
  }
40396
41008
  if (params.data.refresh === "exact") void resolution.thread.session.refreshUsage?.();
40397
41009
  const adapter = this.#externalAdapters.get(resolution.thread.harnessId);
40398
- if (adapter && isCreditsAdapter(adapter)) void adapter.refreshCredits?.();
40399
- const credits = adapter && isCreditsAdapter(adapter) ? projectAccountCredits(adapter.credits()) : null;
41010
+ if (adapter?.credits && adapter.refreshCredits)
41011
+ void Promise.resolve().then(() => adapter.refreshCredits?.()).catch(() => void 0);
41012
+ let credits = null;
41013
+ try {
41014
+ credits = parseHarnessAccountCredits(adapter?.credits?.());
41015
+ } catch {
41016
+ }
40400
41017
  const result = threadUsageInspectionSchema.parse({
40401
41018
  threadId: params.data.threadId,
40402
41019
  usage: await this.#threadUsage(resolution.thread),
41020
+ accountCreditsSupported: typeof adapter?.credits === "function",
40403
41021
  ...credits ? { accountCredits: credits } : {}
40404
41022
  });
40405
41023
  await this.#writer.json(rpcEnvelope(request, { result: jsonValueSchema.parse(result) }));
@@ -40595,7 +41213,7 @@ var AppServerHost = class {
40595
41213
  this.#pendingExternalCommandRequests.delete(thread.id);
40596
41214
  }
40597
41215
  }
40598
- async #beginExternalCommand(thread, descriptor, arguments_2, requestedTurnId) {
41216
+ async #beginExternalCommand(thread, descriptor, arguments_2, requestedTurnId, sourceHostId) {
40599
41217
  const commands = thread.session.commands;
40600
41218
  if (!commands) {
40601
41219
  throw new ExternalCommandError(-32078, "External Harness does not expose commands");
@@ -40624,6 +41242,7 @@ var AppServerHost = class {
40624
41242
  thread.ephemeralTurnIds.add(turnId);
40625
41243
  if (descriptor.invocation === "/compact") this.#manualCompactionTurns.set(thread, turnId);
40626
41244
  else this.#manualCompactionTurns.delete(thread);
41245
+ const restoreExecutionHost = this.#setExecutionHost(thread, sourceHostId);
40627
41246
  try {
40628
41247
  if (thread.unsubmittedPrewarm && await this.#externalRuntime.submitPrewarm(thread)) {
40629
41248
  await this.#notifyExternalThreadStarted(thread.thread);
@@ -40636,6 +41255,7 @@ var AppServerHost = class {
40636
41255
  if (!result.ok) throw new ExternalCommandError(-32073, result.error.message);
40637
41256
  return { turnId: result.value.turnId, turn: projection.projector.pendingTurn(), gate };
40638
41257
  } catch (error51) {
41258
+ restoreExecutionHost();
40639
41259
  thread.running = false;
40640
41260
  thread.activeTurnId = null;
40641
41261
  thread.projectedTurns.delete(turnId);
@@ -41415,7 +42035,8 @@ var AppServerHost = class {
41415
42035
  thread,
41416
42036
  text2,
41417
42037
  void 0,
41418
- typeof params.clientUserMessageId === "string" ? params.clientUserMessageId : void 0
42038
+ typeof params.clientUserMessageId === "string" ? params.clientUserMessageId : void 0,
42039
+ params[THREAD_REFERENCE_SOURCE_HOST_PARAM]
41419
42040
  );
41420
42041
  try {
41421
42042
  await this.#writer.json(rpcEnvelope(request, { result: { turn: started.turn } }));
@@ -41441,7 +42062,8 @@ var AppServerHost = class {
41441
42062
  thread,
41442
42063
  text2,
41443
42064
  assertActive,
41444
- typeof requestObject(request).clientUserMessageId === "string" ? requestObject(request).clientUserMessageId : void 0
42065
+ typeof requestObject(request).clientUserMessageId === "string" ? requestObject(request).clientUserMessageId : void 0,
42066
+ requestObject(request)[THREAD_REFERENCE_SOURCE_HOST_PARAM]
41445
42067
  )
41446
42068
  );
41447
42069
  try {
@@ -41462,12 +42084,12 @@ var AppServerHost = class {
41462
42084
  }
41463
42085
  }
41464
42086
  /** Keep command restoration and dispatch identical for start and steer submissions. */
41465
- async #beginExternalInputTurn(thread, inputText, assertActive, clientUserMessageId) {
42087
+ async #beginExternalInputTurn(thread, inputText, assertActive, clientUserMessageId, sourceHostId) {
41466
42088
  const text2 = restoreHarnessCommandMentions(inputText);
41467
42089
  const commands = thread.session.commands;
41468
42090
  if (!commands || !isExternalCommandCandidate(text2)) {
41469
42091
  assertActive?.();
41470
- return this.#beginExternalTurn(thread, text2, clientUserMessageId);
42092
+ return this.#beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId);
41471
42093
  }
41472
42094
  this.#pendingExternalCommandRequests.add(thread.id);
41473
42095
  try {
@@ -41478,9 +42100,15 @@ var AppServerHost = class {
41478
42100
  assertActive?.();
41479
42101
  if (!command) {
41480
42102
  this.#pendingExternalCommandRequests.delete(thread.id);
41481
- return await this.#beginExternalTurn(thread, text2, clientUserMessageId);
42103
+ return await this.#beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId);
41482
42104
  }
41483
- return await this.#beginExternalCommand(thread, command.descriptor, command.arguments);
42105
+ return await this.#beginExternalCommand(
42106
+ thread,
42107
+ command.descriptor,
42108
+ command.arguments,
42109
+ void 0,
42110
+ sourceHostId
42111
+ );
41484
42112
  } catch (error51) {
41485
42113
  if (error51 instanceof ExternalCommandError || error51 instanceof ExternalSteerError) throw error51;
41486
42114
  this.#diagnose(error51);
@@ -41492,7 +42120,20 @@ var AppServerHost = class {
41492
42120
  this.#pendingExternalCommandRequests.delete(thread.id);
41493
42121
  }
41494
42122
  }
41495
- async #beginExternalTurn(thread, text2, clientUserMessageId) {
42123
+ /** Apply context before native execution; a rejected start restores the prior identity. */
42124
+ #setExecutionHost(thread, sourceHostId) {
42125
+ const previousHostId = this.#executionHosts.get(thread);
42126
+ if (typeof sourceHostId === "string" && sourceHostId.length > 0 && sourceHostId.length <= 1024 && !/[\u0000-\u0020\u007f]/u.test(sourceHostId)) {
42127
+ this.#executionHosts.set(thread, sourceHostId);
42128
+ } else {
42129
+ this.#executionHosts.delete(thread);
42130
+ }
42131
+ return () => {
42132
+ if (previousHostId === void 0) this.#executionHosts.delete(thread);
42133
+ else this.#executionHosts.set(thread, previousHostId);
42134
+ };
42135
+ }
42136
+ async #beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId) {
41496
42137
  if (this.#closeRequested || this.#externalRuntime.get(thread.id) !== thread) {
41497
42138
  throw new ExternalSteerError(-32073, "External Thread is no longer available");
41498
42139
  }
@@ -41519,6 +42160,7 @@ var AppServerHost = class {
41519
42160
  thread.projectedTerminalTurnId = null;
41520
42161
  thread.projectedTurns.set(turnId, projection);
41521
42162
  thread.responseGates.set(turnId, gate);
42163
+ const restoreExecutionHost = this.#setExecutionHost(thread, sourceHostId);
41522
42164
  try {
41523
42165
  if (thread.unsubmittedPrewarm && await this.#externalRuntime.submitPrewarm(thread)) {
41524
42166
  await this.#notifyExternalThreadStarted(thread.thread);
@@ -41531,6 +42173,7 @@ var AppServerHost = class {
41531
42173
  if (!result.ok) throw new ExternalSteerError(-32073, result.error.message);
41532
42174
  return { turnId, turn: projection.projector.pendingTurn(), gate };
41533
42175
  } catch (error51) {
42176
+ restoreExecutionHost();
41534
42177
  thread.running = false;
41535
42178
  thread.activeTurnId = null;
41536
42179
  thread.projectedTurns.delete(turnId);
@@ -41839,7 +42482,11 @@ var AppServerHost = class {
41839
42482
  if (event.type === "session.faulted") {
41840
42483
  this.#externalSteering.fault(thread.id, new Error(event.error.message));
41841
42484
  thread.stateObserver.fault(new Error(event.error.message));
42485
+ this.#externalRuntime.markSessionUnavailable(thread);
41842
42486
  this.#diagnose(`${thread.harnessId} Harness Session faulted: ${event.error.message}`);
42487
+ if (!thread.running && !thread.activeTurnId && !this.#hasRunningSubagents(thread.id) && !thread.session.hasBackgroundWork?.()) {
42488
+ void this.#externalRuntime.discardUnavailableIdle(thread);
42489
+ }
41843
42490
  return;
41844
42491
  }
41845
42492
  if (event.type === "turn.autonomous.started") {
@@ -41968,6 +42615,11 @@ var AppServerHost = class {
41968
42615
  return { ...subagent, subagentId: record4.hostThreadId };
41969
42616
  }
41970
42617
  async #refreshOpenSubagentThread(threadId2, terminal3 = true) {
42618
+ await this.#desktopRequests.run(threadId2, async () => {
42619
+ await this.#refreshOpenSubagentThreadBody(threadId2, terminal3);
42620
+ });
42621
+ }
42622
+ async #refreshOpenSubagentThreadBody(threadId2, terminal3) {
41971
42623
  const child = this.#externalRuntime.get(threadId2);
41972
42624
  if (!child) return;
41973
42625
  const previousItems = new Map(
@@ -42067,7 +42719,7 @@ var AppServerHost = class {
42067
42719
  }
42068
42720
  if (status2 === "idle" && previousStatus === "active") {
42069
42721
  for (const [index, waitMs] of SUBAGENT_TERMINAL_REFRESH_DELAYS_MS.entries()) {
42070
- if (waitMs > 0) await delay3(waitMs);
42722
+ if (waitMs > 0) await delay4(waitMs);
42071
42723
  await this.#refreshOpenSubagentThread(
42072
42724
  threadId2,
42073
42725
  index === SUBAGENT_TERMINAL_REFRESH_DELAYS_MS.length - 1
@@ -42445,7 +43097,7 @@ import { randomUUID as randomUUID15 } from "node:crypto";
42445
43097
  import { chmod as chmod3, lstat as lstat5, mkdir as mkdir12, open as open9, readFile as readFile17, readdir as readdir5, rename as rename11, rm as rm11 } from "node:fs/promises";
42446
43098
  import { uptime } from "node:os";
42447
43099
  import path27 from "node:path";
42448
- import { setTimeout as delay4 } from "node:timers/promises";
43100
+ import { setTimeout as delay5 } from "node:timers/promises";
42449
43101
  var LOCK_RETRY_COUNT = 200;
42450
43102
  var LOCK_RETRY_DELAY_MS = 25;
42451
43103
  var LOCK_MALFORMED_GRACE_MS = 1e3;
@@ -42701,7 +43353,7 @@ async function withRemoteAppServerSocketInitializationLock(socketPath, action) {
42701
43353
  return await action();
42702
43354
  }
42703
43355
  }
42704
- await delay4(LOCK_RETRY_DELAY_MS);
43356
+ await delay5(LOCK_RETRY_DELAY_MS);
42705
43357
  }
42706
43358
  throw new Error(
42707
43359
  `Remote app-server socket initialization is already in progress at ${socketPath}`
@@ -43992,15 +44644,28 @@ var DelegationControlRegistry = class {
43992
44644
  return (await this.#registrationForThread(input.threadId)).cancel(input);
43993
44645
  }
43994
44646
  async read(input) {
43995
- if (input.hostId !== void 0 && input.hostId !== "local") {
43996
- if (!input.hostId || !this.#remoteRead)
44647
+ const { callerThreadId: callerThreadId2, ...read } = input;
44648
+ if (read.hostId !== void 0 && read.hostId !== "local") {
44649
+ if (typeof callerThreadId2 === "string" && callerThreadId2) {
44650
+ const callers = await this.#matching(
44651
+ (registration) => registration.executionHostId?.(callerThreadId2) === read.hostId && registration.ownsThread(callerThreadId2)
44652
+ );
44653
+ if (callers.length > 1)
44654
+ only(callers, "Calling Thread has ambiguous execution Host context");
44655
+ if (callers.length === 1) {
44656
+ const { hostId: hostId2, ...local } = read;
44657
+ const snapshot2 = await (await this.#registrationForThread(local.threadId)).read(local);
44658
+ return { ...snapshot2, hostId: hostId2 };
44659
+ }
44660
+ }
44661
+ if (!read.hostId || !this.#remoteRead)
43997
44662
  throw new DelegationControlError(
43998
44663
  "RUNTIME_UNREACHABLE",
43999
44664
  "Remote Thread reading is unavailable"
44000
44665
  );
44001
- return this.#remoteRead(input);
44666
+ return this.#remoteRead(read);
44002
44667
  }
44003
- return (await this.#registrationForThread(input.threadId)).read(input);
44668
+ return (await this.#registrationForThread(read.threadId)).read(read);
44004
44669
  }
44005
44670
  async wait(input) {
44006
44671
  if (input.hostId !== void 0 && input.hostId !== "local")
@@ -45195,13 +45860,15 @@ function createHostUpdateCoordinator(options2) {
45195
45860
  return authenticated ?? fetchLatestGitHubRelease({ signal: requestSignal });
45196
45861
  });
45197
45862
  let candidate = null;
45863
+ let currentStatusPath = null;
45198
45864
  async function latestStatus(context) {
45199
- const discovered = await discoverLatestUpdateStatus(context.common.stateDirectory);
45200
- if (!discovered) return null;
45201
- if (discovered.status.phase !== "succeeded" && discovered.status.phase !== "failed" && !await isUpdateOperationActive(context.common.stateDirectory)) {
45202
- return null;
45865
+ if (!currentStatusPath) {
45866
+ const active = await discoverActiveUpdateStatus(context.common.stateDirectory);
45867
+ if (!active) return null;
45868
+ currentStatusPath = active.statusPath;
45203
45869
  }
45204
- return publicStatus(discovered.status);
45870
+ const status2 = await manager.readStatus(currentStatusPath);
45871
+ return status2 ? publicStatus(status2) : null;
45205
45872
  }
45206
45873
  async function installable(context, release) {
45207
45874
  if (context.installation.kind === "npm") return true;
@@ -45285,6 +45952,7 @@ function createHostUpdateCoordinator(options2) {
45285
45952
  if (existing) return { status: existing };
45286
45953
  throw new Error("Another update operation is already active");
45287
45954
  }
45955
+ currentStatusPath = null;
45288
45956
  let resolvePrepared;
45289
45957
  let rejectPrepared;
45290
45958
  const preparedReady = new Promise((resolve, reject) => {
@@ -45298,6 +45966,7 @@ function createHostUpdateCoordinator(options2) {
45298
45966
  }
45299
45967
  const onPrepared = async (info) => {
45300
45968
  await lock.setStatusPath(info.statusPath);
45969
+ currentStatusPath = info.statusPath;
45301
45970
  resolvePrepared(info);
45302
45971
  };
45303
45972
  const prepareAndStart = async () => {
@@ -45327,7 +45996,7 @@ function createHostUpdateCoordinator(options2) {
45327
45996
  onPrepared
45328
45997
  });
45329
45998
  }
45330
- if (platform !== "darwin") manager.start(prepared2);
45999
+ if (platform !== "darwin") await manager.start(prepared2);
45331
46000
  } catch (error51) {
45332
46001
  await lock.release();
45333
46002
  rejectPrepared(error51);
@@ -45364,6 +46033,20 @@ import { setImmediate as yieldToEventLoop } from "node:timers/promises";
45364
46033
  // packages/harness-adapter/dist/usage-statistics.js
45365
46034
  var MAX_SESSION_ID_LENGTH = 512;
45366
46035
  var MAX_CWD_LENGTH = 4096;
46036
+ var MAX_SESSION_TITLE_LENGTH = 200;
46037
+ function usageSessionTitle(value2) {
46038
+ if (typeof value2 !== "string")
46039
+ return void 0;
46040
+ const normalized = value2.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
46041
+ if (!normalized)
46042
+ return void 0;
46043
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
46044
+ return normalized;
46045
+ const characters = [...normalized];
46046
+ if (characters.length <= MAX_SESSION_TITLE_LENGTH)
46047
+ return normalized;
46048
+ return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
46049
+ }
45367
46050
  function sessionIdOk(value2) {
45368
46051
  return typeof value2 === "string" && value2.length > 0 && value2.length <= MAX_SESSION_ID_LENGTH;
45369
46052
  }
@@ -45407,6 +46090,12 @@ function parseHarnessUsageEntry(value2) {
45407
46090
  return null;
45408
46091
  if (entry.cwd !== void 0 && !cwdOk(entry.cwd))
45409
46092
  return null;
46093
+ if (entry.sessionTitle !== void 0) {
46094
+ const sessionTitle = usageSessionTitle(entry.sessionTitle);
46095
+ if (sessionTitle === void 0)
46096
+ return null;
46097
+ entry.sessionTitle = sessionTitle;
46098
+ }
45410
46099
  if (entry.tokensUnknown !== void 0 && entry.tokensUnknown !== true)
45411
46100
  return null;
45412
46101
  if (entry.costUsd !== void 0 && (typeof entry.costUsd !== "number" || !Number.isFinite(entry.costUsd) || entry.costUsd < 0)) {
@@ -45418,8 +46107,31 @@ function parseHarnessUsageEntry(value2) {
45418
46107
  return entry;
45419
46108
  }
45420
46109
 
46110
+ // packages/host-runtime/src/usage-session-titles.ts
46111
+ function withHostSessionTitles(result, records) {
46112
+ const titles = /* @__PURE__ */ new Map();
46113
+ for (const record4 of records) {
46114
+ const ref = record4.nativeSessionRef;
46115
+ const title = usageSessionTitle(record4.title);
46116
+ if (record4.state !== "ready" || !ref || ref.harnessId !== record4.harnessId || !title) continue;
46117
+ const key = `${record4.harnessId}\0${ref.nativeSessionId}`;
46118
+ const previous = titles.get(key);
46119
+ if (!previous || record4.updatedAt > previous.updatedAt)
46120
+ titles.set(key, { title, updatedAt: record4.updatedAt });
46121
+ }
46122
+ const decorate = (sessions) => sessions.map((session) => {
46123
+ const title = titles.get(`${session.harness}\0${session.sessionId}`)?.title;
46124
+ return title ? { ...session, title } : session;
46125
+ });
46126
+ return {
46127
+ ...result,
46128
+ sessions: decorate(result.sessions),
46129
+ ...result.recentSessions ? { recentSessions: decorate(result.recentSessions) } : {}
46130
+ };
46131
+ }
46132
+
45421
46133
  // packages/host-runtime/src/usage-statistics.ts
45422
- var CACHE_VERSION = 6;
46134
+ var CACHE_VERSION = 7;
45423
46135
  var STALE_AFTER_MS = 1e4;
45424
46136
  var WARM_DELAY_MS = 3e3;
45425
46137
  var PERSIST_INTERVAL_MS = 6e4;
@@ -45439,7 +46151,8 @@ function compact(entry) {
45439
46151
  entry.cwd ?? null,
45440
46152
  entry.costUsd ?? null,
45441
46153
  entry.credits ?? null,
45442
- entry.tokensUnknown === true
46154
+ entry.tokensUnknown === true,
46155
+ entry.sessionTitle ?? null
45443
46156
  ];
45444
46157
  }
45445
46158
  function interner() {
@@ -45453,9 +46166,9 @@ function interner() {
45453
46166
  };
45454
46167
  }
45455
46168
  function expand(value2, intern) {
45456
- if (!Array.isArray(value2) || value2.length !== 14) return null;
46169
+ if (!Array.isArray(value2) || value2.length !== 15) return null;
45457
46170
  const [id2, occurredAtMs, model2, input, cached2, written, written1h, output, reasoning] = value2;
45458
- const [sessionId, cwd, costUsd, credits, tokensUnknown] = value2.slice(9);
46171
+ const [sessionId, cwd, costUsd, credits, tokensUnknown, sessionTitle] = value2.slice(9);
45459
46172
  return parseHarnessUsageEntry({
45460
46173
  id: id2,
45461
46174
  occurredAtMs,
@@ -45470,7 +46183,8 @@ function expand(value2, intern) {
45470
46183
  ...cwd !== null ? { cwd: intern(cwd) } : {},
45471
46184
  ...costUsd !== null ? { costUsd } : {},
45472
46185
  ...credits !== null ? { credits } : {},
45473
- ...tokensUnknown === true ? { tokensUnknown } : {}
46186
+ ...tokensUnknown === true ? { tokensUnknown } : {},
46187
+ ...sessionTitle !== null ? { sessionTitle: intern(sessionTitle) } : {}
45474
46188
  });
45475
46189
  }
45476
46190
  function message(error51) {
@@ -45561,6 +46275,7 @@ var UsageStatistics = class {
45561
46275
  #caches = /* @__PURE__ */ new Map();
45562
46276
  #failures = /* @__PURE__ */ new Map();
45563
46277
  #sources = null;
46278
+ #readThreadTitles;
45564
46279
  #loaded = null;
45565
46280
  #refreshing = null;
45566
46281
  #refreshedAtMs = 0;
@@ -45575,9 +46290,10 @@ var UsageStatistics = class {
45575
46290
  this.#options = options2;
45576
46291
  this.#directory = path37.join(options2.directory, `v${CACHE_VERSION}`);
45577
46292
  }
45578
- /** The Harnesses to read; call once their plugins are loaded. */
45579
- attach(sources) {
46293
+ /** Attach native storage and, optionally, fresh persisted Desktop title metadata. */
46294
+ attach(sources, readThreadTitles) {
45580
46295
  this.#sources = sources;
46296
+ this.#readThreadTitles = readThreadTitles;
45581
46297
  this.#scheduleWarm();
45582
46298
  }
45583
46299
  /** Reads every source in the background soon after the sources are attached. */
@@ -45604,11 +46320,19 @@ var UsageStatistics = class {
45604
46320
  }
45605
46321
  const now = this.#now();
45606
46322
  if (!this.#refreshing && now - this.#refreshedAtMs > STALE_AFTER_MS) this.#startRefresh();
45607
- return this.#aggregate(
46323
+ const result = this.#aggregate(
45608
46324
  typeof params === "string" ? { range: params } : params,
45609
46325
  now,
45610
46326
  await this.#options.prices.lookup()
45611
46327
  );
46328
+ if (this.#readThreadTitles && (result.sessions.length || result.recentSessions?.length)) {
46329
+ try {
46330
+ return withHostSessionTitles(result, await this.#readThreadTitles());
46331
+ } catch (error51) {
46332
+ this.#options.diagnose?.(`Usage statistics Thread titles unavailable: ${message(error51)}`);
46333
+ }
46334
+ }
46335
+ return result;
45612
46336
  }
45613
46337
  /** Completes the current refresh, for tests and callers that need a settled result. */
45614
46338
  async settled() {
@@ -45886,6 +46610,10 @@ var UsageStatistics = class {
45886
46610
  sessions.set(key, session);
45887
46611
  }
45888
46612
  session.project ??= project2;
46613
+ if (entry.sessionTitle && (session.titleAtMs === void 0 || entry.occurredAtMs >= session.titleAtMs)) {
46614
+ session.title = entry.sessionTitle;
46615
+ session.titleAtMs = entry.occurredAtMs;
46616
+ }
45889
46617
  if (model2 !== null) session.models.set(model2, (session.models.get(model2) ?? 0) + 1);
45890
46618
  session.firstAtMs = Math.min(session.firstAtMs, entry.occurredAtMs);
45891
46619
  session.lastAtMs = Math.max(session.lastAtMs, entry.occurredAtMs);
@@ -45893,21 +46621,26 @@ var UsageStatistics = class {
45893
46621
  }
45894
46622
  }
45895
46623
  const allSessions = [...sessions.values()];
45896
- const top = /* @__PURE__ */ new Set([
45897
- ...[...allSessions].sort((left, right) => right.totals.costUsd - left.totals.costUsd).slice(0, SESSIONS_PER_MEASURE),
45898
- ...[...allSessions].sort((left, right) => tokensWithoutCache(right.totals) - tokensWithoutCache(left.totals)).slice(0, SESSIONS_PER_MEASURE)
45899
- ]);
45900
- const sessionList = [...top].map((session) => ({
46624
+ const toSession = (session) => ({
45901
46625
  harness: session.harness,
45902
46626
  sessionId: session.sessionId,
45903
46627
  project: session.project,
46628
+ ...session.title ? { title: session.title } : {},
45904
46629
  models: [...session.models].sort((left, right) => right[1] - left[1]).slice(0, MODELS_PER_SESSION).map(([name]) => name),
45905
46630
  firstAtMs: session.firstAtMs,
45906
46631
  lastAtMs: session.lastAtMs,
45907
46632
  ...session.totals
45908
- })).sort(
46633
+ });
46634
+ const top = /* @__PURE__ */ new Set([
46635
+ ...[...allSessions].sort((left, right) => right.totals.costUsd - left.totals.costUsd).slice(0, SESSIONS_PER_MEASURE),
46636
+ ...[...allSessions].sort((left, right) => tokensWithoutCache(right.totals) - tokensWithoutCache(left.totals)).slice(0, SESSIONS_PER_MEASURE)
46637
+ ]);
46638
+ const sessionList = [...top].map(toSession).sort(
45909
46639
  (left, right) => right.costUsd - left.costUsd || tokensWithoutCache(right) - tokensWithoutCache(left)
45910
46640
  );
46641
+ const recentSessions = [...allSessions].sort(
46642
+ (left, right) => right.lastAtMs - left.lastAtMs || right.firstAtMs - left.firstAtMs || left.sessionId.localeCompare(right.sessionId)
46643
+ ).slice(0, SESSIONS_PER_MEASURE).map(toSession);
45911
46644
  if (unlistedModel) this.#options.prices.missing();
45912
46645
  const byName = (left, right) => left === right ? 0 : left === null ? 1 : right === null ? -1 : left.localeCompare(right);
45913
46646
  return {
@@ -45952,7 +46685,8 @@ var UsageStatistics = class {
45952
46685
  byHarness: grouped(byHarness, (name) => ({ harness: name })),
45953
46686
  byModel: grouped(byModel, (name) => ({ model: name })).slice(0, 4096).map((row) => ({ ...row, harnessPricedRequests: harnessPriced.get(row.model) ?? 0 })),
45954
46687
  byProject: grouped(byProject, (name) => ({ project: name })).slice(0, 4096),
45955
- sessions: sessionList
46688
+ sessions: sessionList,
46689
+ recentSessions
45956
46690
  };
45957
46691
  }
45958
46692
  };
@@ -45987,9 +46721,21 @@ function requiredRuntimeConfiguration(environment) {
45987
46721
  if (!stockCodexPath) throw new Error(`${STOCK_CODEX_PATH_ENV} is required`);
45988
46722
  return { stockCodexPath };
45989
46723
  }
45990
- function delegationCliEnvironment(environment) {
45991
- const cliPath = environment[DELEGATION_CLI_PATH_ENV] ?? environment[UPDATE_RUNTIME_ENV.launcherExecutable];
45992
- const nodePath2 = environment[UPDATE_RUNTIME_ENV.npmNodePath];
46724
+ function delegationCliEnvironment(environment, hostRuntimePath) {
46725
+ let packagedCli;
46726
+ if (hostRuntimePath && path38.isAbsolute(hostRuntimePath)) {
46727
+ const candidate = path38.resolve(
46728
+ path38.dirname(hostRuntimePath),
46729
+ "../bin",
46730
+ process.platform === "win32" ? "codexhost.exe" : "codexhost"
46731
+ );
46732
+ try {
46733
+ if (statSync(candidate).isFile()) packagedCli = candidate;
46734
+ } catch {
46735
+ }
46736
+ }
46737
+ const cliPath = environment[DELEGATION_CLI_PATH_ENV] ?? environment[UPDATE_RUNTIME_ENV.launcherExecutable] ?? packagedCli;
46738
+ const nodePath2 = environment[DELEGATION_CLI_NODE_PATH_ENV] ?? environment[UPDATE_RUNTIME_ENV.npmNodePath] ?? (packagedCli && cliPath === packagedCli ? process.execPath : void 0);
45993
46739
  return {
45994
46740
  ...cliPath ? { [DELEGATION_CLI_PATH_ENV]: cliPath } : {},
45995
46741
  ...nodePath2 && path38.isAbsolute(nodePath2) ? { [DELEGATION_CLI_NODE_PATH_ENV]: nodePath2 } : {}
@@ -46007,7 +46753,7 @@ async function prepareDelegationRuntime(input) {
46007
46753
  const server = await startDelegationControlServer({ token, api: registry2, watchApi: registry2 });
46008
46754
  const environment = {
46009
46755
  ...input.environment,
46010
- ...delegationCliEnvironment(input.environment),
46756
+ ...delegationCliEnvironment(input.environment, input.hostRuntimePath),
46011
46757
  [DELEGATION_RUNTIME_ENDPOINT_ENV]: server.endpoint,
46012
46758
  [DELEGATION_RUNTIME_TOKEN_ENV]: token
46013
46759
  };
@@ -46083,6 +46829,7 @@ async function runHostRuntime(input) {
46083
46829
  const environment = remoteControlPlan?.environment ?? input.environment;
46084
46830
  return prepareDelegationRuntime({
46085
46831
  environment,
46832
+ ...hostRuntimePath ? { hostRuntimePath } : {},
46086
46833
  createHost: async (delegationEnvironment, onDelegationApi, registry2) => {
46087
46834
  const official = await prepareLocalCodex({
46088
46835
  stockCodexPath,
@@ -46193,6 +46940,7 @@ async function runHostRuntime(input) {
46193
46940
  if (!listenUrl) throw new Error("Remote app-server listener URL is unavailable");
46194
46941
  return prepareDelegationRuntime({
46195
46942
  environment: input.environment,
46943
+ ...hostRuntimePath ? { hostRuntimePath } : {},
46196
46944
  createHost: async (delegationEnvironment, _onDelegationApi, registry2) => {
46197
46945
  const socketPath = remoteAppServerSocketPath(delegationEnvironment, listenUrl);
46198
46946
  const officialPlan = createRemoteOfficialAppServerPlan(input.arguments, socketPath);
@@ -47933,8 +48681,11 @@ async function startHarnessBrokerServer(input) {
47933
48681
  retireWhenIdle = false;
47934
48682
  if (request.method === "adapter.credits") {
47935
48683
  harnessAccountListParamsSchema.parse(request.params);
47936
- const adapter = input.adapter;
47937
- return accountCreditsSnapshotSchema.nullable().parse(adapter.credits?.() ?? null);
48684
+ const value2 = input.adapter.credits?.();
48685
+ const credits = parseHarnessAccountCredits(value2);
48686
+ if (value2 != null && !credits)
48687
+ throw new Error("Invalid account credits snapshot");
48688
+ return credits;
47938
48689
  }
47939
48690
  if (request.method === "adapter.inspectAccount") {
47940
48691
  harnessAccountListParamsSchema.parse(request.params);
@@ -48505,7 +49256,7 @@ import {
48505
49256
  readdirSync,
48506
49257
  renameSync,
48507
49258
  rmSync,
48508
- statSync,
49259
+ statSync as statSync2,
48509
49260
  writeFileSync
48510
49261
  } from "node:fs";
48511
49262
  import os12 from "node:os";
@@ -48535,7 +49286,7 @@ function pruneRuntimeLogs(input) {
48535
49286
  if (!Number.isSafeInteger(pid)) continue;
48536
49287
  try {
48537
49288
  const filePath = path43.join(input.directory, entry.name);
48538
- const stats = statSync(filePath);
49289
+ const stats = statSync2(filePath);
48539
49290
  files.push({
48540
49291
  filePath,
48541
49292
  pid,