@liberseek/boft-cli-win32-arm64 0.8.0 → 0.8.1

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"]),
@@ -20076,6 +20114,8 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
20076
20114
  harness,
20077
20115
  sessionId: external_exports.string().min(1).max(512),
20078
20116
  project: project.nullable(),
20117
+ /** Persisted Desktop title for a mapped Session, otherwise its native name; may be absent. */
20118
+ title: external_exports.string().min(1).max(200).optional(),
20079
20119
  /** Models the session used, most requests first. */
20080
20120
  models: external_exports.array(model).max(16),
20081
20121
  firstAtMs: count,
@@ -20142,7 +20182,12 @@ var usageStatisticsResultSchema = external_exports.strictObject({
20142
20182
  * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
20143
20183
  * requests without a native session are not listed here but count everywhere else.
20144
20184
  */
20145
- sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
20185
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100),
20186
+ /**
20187
+ * The sessions last active in the range, newest first, all filters applied. Optional for older
20188
+ * Hosts; missing is treated as no list rather than no sessions.
20189
+ */
20190
+ recentSessions: external_exports.array(usageStatisticsSessionSchema).max(100).optional()
20146
20191
  });
20147
20192
 
20148
20193
  // packages/shared-contracts/dist/ids.js
@@ -21479,14 +21524,37 @@ var RuntimeMaintenance = class {
21479
21524
  options2.environment.CODEXHOST_DATA_DIR ?? path7.join(home, ".codexhost", "remote", "data"),
21480
21525
  "remote-update.json"
21481
21526
  );
21527
+ this.#cancelPath = path7.join(path7.dirname(this.#statusPath), "remote-update.cancel");
21482
21528
  }
21483
21529
  options;
21484
21530
  #running;
21485
21531
  #statusPath;
21532
+ #cancelPath;
21486
21533
  #update = { phase: "idle", targetVersion: null, error: null };
21487
21534
  #blocked = false;
21535
+ #watch = null;
21488
21536
  #starting = null;
21489
21537
  #startingVersion = null;
21538
+ #ensureWatching() {
21539
+ if (this.#watch) return;
21540
+ this.#watch = setInterval(() => {
21541
+ void this.status().catch(() => void 0).then(() => {
21542
+ if (!this.#blocked && this.#watch) {
21543
+ clearInterval(this.#watch);
21544
+ this.#watch = null;
21545
+ }
21546
+ });
21547
+ }, UPDATER_WATCH_INTERVAL_MS);
21548
+ this.#watch.unref();
21549
+ }
21550
+ async #recordStartFailure(version2, failure) {
21551
+ await writeFile3(this.#cancelPath, JSON.stringify({ targetVersion: version2 }), { mode: 384 });
21552
+ await writeFile3(
21553
+ this.#statusPath,
21554
+ JSON.stringify({ phase: "failed", targetVersion: version2, error: failure }),
21555
+ { mode: 384 }
21556
+ );
21557
+ }
21490
21558
  #sshPending = /* @__PURE__ */ new Set();
21491
21559
  async setupSsh(input) {
21492
21560
  if (this.options.remote) throw new Error("SSH installation must run from the local computer");
@@ -21547,7 +21615,7 @@ var RuntimeMaintenance = class {
21547
21615
  installation(this.options.runtimePath, this.options.environment),
21548
21616
  this.#resources()
21549
21617
  ]);
21550
- if (this.#update.phase === "idle" || this.#blocked) {
21618
+ if (this.#update.phase === "idle" || this.#blocked || this.#update.phase === "failed") {
21551
21619
  try {
21552
21620
  const value2 = JSON.parse(await readFile5(this.#statusPath, "utf8"));
21553
21621
  const parsed2 = runtimeStatusSchema.shape.update.parse(value2);
@@ -21570,8 +21638,15 @@ var RuntimeMaintenance = class {
21570
21638
  parsed2.error = "The previous remote update was interrupted; retry the update";
21571
21639
  }
21572
21640
  }
21573
- if (this.#update === observedUpdate) this.#update = parsed2;
21574
- if (["failed", "succeeded"].includes(this.#update.phase)) this.#blocked = false;
21641
+ if (this.#update === observedUpdate) {
21642
+ this.#update = parsed2;
21643
+ if (["installing", "restarting"].includes(this.#update.phase)) {
21644
+ this.#blocked = true;
21645
+ this.#ensureWatching();
21646
+ } else if (["failed", "succeeded"].includes(this.#update.phase)) {
21647
+ this.#blocked = false;
21648
+ }
21649
+ }
21575
21650
  } catch {
21576
21651
  }
21577
21652
  }
@@ -21643,6 +21718,7 @@ var RuntimeMaintenance = class {
21643
21718
  await chmod2(helper, 448);
21644
21719
  const request = path7.join(work, "request.json");
21645
21720
  this.#update = { phase: "installing", targetVersion: version2, error: null };
21721
+ await unlink(this.#cancelPath).catch(() => void 0);
21646
21722
  await writeFile3(this.#statusPath, JSON.stringify(this.#update), { mode: 384 });
21647
21723
  await writeFile3(
21648
21724
  request,
@@ -21661,35 +21737,38 @@ var RuntimeMaintenance = class {
21661
21737
  );
21662
21738
  const starter = spawn3(
21663
21739
  "/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 }
21740
+ ["-c", '"$0" remote --request "$1" </dev/null >/dev/null 2>&1 & echo $!', helper, request],
21741
+ { detached: true, stdio: ["ignore", "pipe", "ignore"], env: this.options.environment }
21666
21742
  );
21743
+ let pidOutput = "";
21744
+ starter.stdout?.on("data", (chunk) => {
21745
+ pidOutput += typeof chunk === "string" ? chunk : chunk.toString("utf8");
21746
+ });
21667
21747
  await new Promise((resolve, reject) => {
21668
21748
  starter.once("error", reject);
21669
21749
  starter.once(
21670
- "exit",
21750
+ "close",
21671
21751
  (code) => code === 0 ? resolve() : reject(new Error("Remote updater could not be started"))
21672
21752
  );
21673
21753
  });
21754
+ const helperPid = Number.parseInt(pidOutput.trim(), 10);
21755
+ if (!Number.isSafeInteger(helperPid) || helperPid <= 0) {
21756
+ throw new Error("Remote updater could not be started");
21757
+ }
21674
21758
  const deadline = Date.now() + UPDATER_START_TIMEOUT_MS;
21675
21759
  while (!await this.#helperReported()) {
21676
21760
  if (Date.now() >= deadline) {
21761
+ try {
21762
+ process.kill(helperPid);
21763
+ } catch {
21764
+ }
21677
21765
  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
- );
21766
+ await this.#recordStartFailure(version2, failure);
21683
21767
  throw new Error(failure);
21684
21768
  }
21685
21769
  await new Promise((resolve) => setTimeout(resolve, 50));
21686
21770
  }
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();
21771
+ this.#ensureWatching();
21693
21772
  }
21694
21773
  async #helperReported() {
21695
21774
  try {
@@ -21703,6 +21782,7 @@ var RuntimeMaintenance = class {
21703
21782
 
21704
21783
  // packages/host-runtime/src/run-host-runtime.ts
21705
21784
  import { randomBytes as randomBytes4 } from "node:crypto";
21785
+ import { statSync } from "node:fs";
21706
21786
  import path38 from "node:path";
21707
21787
  import { homedir as homedir4 } from "node:os";
21708
21788
  import { fileURLToPath as fileURLToPath2 } from "node:url";
@@ -27007,61 +27087,6 @@ function finitePercent(value2) {
27007
27087
  function optionalReset(value2) {
27008
27088
  return nonNegativeSafeInteger(value2);
27009
27089
  }
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
27090
  function parseRateLimitWindow(value2) {
27066
27091
  if (!isRecord9(value2))
27067
27092
  return null;
@@ -31923,6 +31948,16 @@ var ExternalThreadIdleRelease = class {
31923
31948
  const state = this.#activity.get(thread);
31924
31949
  if (state) state.outputFailed = true;
31925
31950
  }
31951
+ /** After a successful Session revival, allow idle release again. */
31952
+ clearOutputFailed(thread) {
31953
+ const state = this.#activity.get(thread);
31954
+ if (state) {
31955
+ state.outputFailed = false;
31956
+ state.lastActivity = Date.now();
31957
+ } else {
31958
+ this.touch(thread);
31959
+ }
31960
+ }
31926
31961
  failure(thread) {
31927
31962
  return this.#activity.get(thread)?.closeFailed ? CLOSE_FAILURE : void 0;
31928
31963
  }
@@ -32071,6 +32106,80 @@ var ExternalThreadIdleRelease = class {
32071
32106
  }
32072
32107
  };
32073
32108
 
32109
+ // packages/host-runtime/src/external-thread-lifecycle.ts
32110
+ var RELEASE_TIMEOUT_MS = 6e4;
32111
+ var ExternalSessionReleaseError = class extends Error {
32112
+ constructor(cause) {
32113
+ super(
32114
+ "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.",
32115
+ { cause }
32116
+ );
32117
+ this.name = "ExternalSessionReleaseError";
32118
+ }
32119
+ };
32120
+ var ExternalThreadLifecycle = class {
32121
+ #pending = /* @__PURE__ */ new Map();
32122
+ #closing = /* @__PURE__ */ new WeakMap();
32123
+ #releasing = /* @__PURE__ */ new Map();
32124
+ busy(id2) {
32125
+ return this.#pending.has(id2) || this.#releasing.has(id2);
32126
+ }
32127
+ pending() {
32128
+ return [...this.#pending];
32129
+ }
32130
+ run(id2, operation) {
32131
+ const previous = this.#pending.get(id2) ?? Promise.resolve();
32132
+ const task = previous.then(async () => {
32133
+ const releasing = this.#releasing.get(id2);
32134
+ if (releasing) await this.release(id2, releasing.session, releasing.output);
32135
+ return operation();
32136
+ });
32137
+ const settled = task.then(
32138
+ () => void 0,
32139
+ () => void 0
32140
+ );
32141
+ this.#pending.set(id2, settled);
32142
+ void settled.then(() => {
32143
+ if (this.#pending.get(id2) === settled) this.#pending.delete(id2);
32144
+ });
32145
+ return task;
32146
+ }
32147
+ /** Call inside the Thread's lifecycle operation. A timeout never cancels the owned close. */
32148
+ async release(id2, session, output) {
32149
+ this.#releasing.set(id2, { session, output });
32150
+ let closing = this.#closing.get(session);
32151
+ if (!closing) {
32152
+ closing = Promise.resolve().then(() => session.close());
32153
+ this.#closing.set(session, closing);
32154
+ const attempt = closing;
32155
+ void closing.catch(() => {
32156
+ if (this.#closing.get(session) === attempt) this.#closing.delete(session);
32157
+ });
32158
+ }
32159
+ let timeout;
32160
+ try {
32161
+ await Promise.race([
32162
+ closing.then(() => output),
32163
+ new Promise((_, reject) => {
32164
+ timeout = setTimeout(
32165
+ () => reject(new Error("Session shutdown timed out")),
32166
+ RELEASE_TIMEOUT_MS
32167
+ );
32168
+ timeout.unref();
32169
+ })
32170
+ ]);
32171
+ this.#releasing.delete(id2);
32172
+ } catch (error51) {
32173
+ throw new ExternalSessionReleaseError(error51);
32174
+ } finally {
32175
+ if (timeout) clearTimeout(timeout);
32176
+ }
32177
+ }
32178
+ async drain() {
32179
+ while (this.#pending.size) await Promise.all(this.#pending.values());
32180
+ }
32181
+ };
32182
+
32074
32183
  // packages/host-runtime/src/usage-metering.ts
32075
32184
  var TOKENS_PER_PRICE_UNIT = 1e6;
32076
32185
  var UsageMeter = class {
@@ -32086,6 +32195,8 @@ var UsageMeter = class {
32086
32195
  #turnOutputMs = 0;
32087
32196
  #timeToFirstOutputMs;
32088
32197
  #outputTokensPerSecond;
32198
+ #timingUnavailable = false;
32199
+ #timedRequests = /* @__PURE__ */ new Set();
32089
32200
  get metered() {
32090
32201
  return this.#metered;
32091
32202
  }
@@ -32102,12 +32213,53 @@ var UsageMeter = class {
32102
32213
  this.#requests.set(request.requestId, request);
32103
32214
  const duration4 = request.startedAtMs !== void 0 && request.completedAtMs !== void 0 ? request.completedAtMs - request.startedAtMs : 0;
32104
32215
  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);
32216
+ this.recordOutputTiming(
32217
+ {
32218
+ requestId: request.requestId,
32219
+ outputTokens: request.outputTokens,
32220
+ startedAtMs: request.startedAtMs ?? 0,
32221
+ completedAtMs: request.completedAtMs ?? 0
32222
+ },
32223
+ activeTurnId
32224
+ );
32108
32225
  }
32109
32226
  return true;
32110
32227
  }
32228
+ /** Live timing is independent of history replacement and cannot create billing entries. */
32229
+ recordOutputTiming(request, turnId) {
32230
+ if (turnId !== this.#turnId || this.#timingUnavailable || this.#timedRequests.has(request.requestId))
32231
+ return false;
32232
+ if (!request.requestId || ![request.outputTokens, request.startedAtMs, request.completedAtMs].every(
32233
+ (value2) => Number.isSafeInteger(value2) && value2 >= 0
32234
+ ) || request.completedAtMs <= request.startedAtMs) {
32235
+ this.invalidateOutputTiming(turnId);
32236
+ return true;
32237
+ }
32238
+ this.#timedRequests.add(request.requestId);
32239
+ this.#turnOutputTokens += request.outputTokens;
32240
+ this.#turnOutputMs += request.completedAtMs - request.startedAtMs;
32241
+ this.#outputTokensPerSecond = this.#turnOutputTokens / (this.#turnOutputMs / 1e3);
32242
+ return true;
32243
+ }
32244
+ invalidateOutputTiming(turnId) {
32245
+ if (turnId !== this.#turnId) return;
32246
+ this.#timingUnavailable = true;
32247
+ }
32248
+ /** Discard in-flight timing across connections, but keep the last valid displayed speed. */
32249
+ resetTurnTiming() {
32250
+ this.#turnId = null;
32251
+ this.#turnStartedAtMs = null;
32252
+ this.#timeToFirstOutputMs = void 0;
32253
+ this.#timedRequests.clear();
32254
+ this.#timingUnavailable = false;
32255
+ }
32256
+ /** Replace a read-only session history after recovery, append, rollback or file replacement. */
32257
+ replaceHistory(requests, complete) {
32258
+ this.#requests.clear();
32259
+ this.#invalidRecord = false;
32260
+ for (const request of requests) this.recordRequest({ ...request, historical: true }, null);
32261
+ this.recordHistory(complete);
32262
+ }
32111
32263
  recordHistory(complete) {
32112
32264
  this.#metered = true;
32113
32265
  this.#historyComplete = complete;
@@ -32118,6 +32270,8 @@ var UsageMeter = class {
32118
32270
  this.#turnOutputObserved = false;
32119
32271
  this.#turnOutputTokens = 0;
32120
32272
  this.#turnOutputMs = 0;
32273
+ this.#timedRequests.clear();
32274
+ this.#timingUnavailable = false;
32121
32275
  }
32122
32276
  /** Returns true when this is the Turn's first visible output. */
32123
32277
  outputObserved(turnId, nowMs) {
@@ -32130,7 +32284,6 @@ var UsageMeter = class {
32130
32284
  }
32131
32285
  turnCompleted(turnId) {
32132
32286
  if (turnId !== this.#turnId) return;
32133
- if (this.#turnOutputMs === 0) this.#outputTokensPerSecond = void 0;
32134
32287
  this.#turnId = null;
32135
32288
  this.#turnStartedAtMs = null;
32136
32289
  }
@@ -32165,12 +32318,12 @@ var UsageMeter = class {
32165
32318
  const cacheHitRate = this.#sessionCacheHitRatePercent();
32166
32319
  if (cacheHitRate !== null) usage.sessionCacheHitRatePercent = cacheHitRate;
32167
32320
  }
32168
- if (this.#outputTokensPerSecond !== void 0) {
32169
- usage.outputTokensPerSecond = this.#outputTokensPerSecond;
32170
- }
32171
32321
  } else if (usage.totalCostUsd !== void 0) {
32172
32322
  usage.costSource = "native";
32173
32323
  }
32324
+ if (this.#timingUnavailable) delete usage.outputTokensPerSecond;
32325
+ if (this.#outputTokensPerSecond !== void 0)
32326
+ usage.outputTokensPerSecond = this.#outputTokensPerSecond;
32174
32327
  if (this.#timeToFirstOutputMs !== void 0) {
32175
32328
  usage.timeToFirstOutputMs = this.#timeToFirstOutputMs;
32176
32329
  }
@@ -32309,6 +32462,11 @@ var ExternalThreadOpenError = class extends Error {
32309
32462
  function errorMessage3(error51) {
32310
32463
  return error51 instanceof Error ? error51.message : String(error51);
32311
32464
  }
32465
+ function recoveryError(error51) {
32466
+ if (error51 instanceof ExternalThreadOpenError) return error51.rpcError;
32467
+ if (error51 instanceof ExternalSessionReleaseError) return { code: -32075, message: error51.message };
32468
+ return { code: -32076, message: "External Thread recovery failed; retry the request" };
32469
+ }
32312
32470
  var ExternalThreadRuntime = class {
32313
32471
  idleRelease;
32314
32472
  #adapters;
@@ -32316,7 +32474,8 @@ var ExternalThreadRuntime = class {
32316
32474
  #diagnose;
32317
32475
  #environment;
32318
32476
  #repository;
32319
- #restores = /* @__PURE__ */ new Map();
32477
+ #lifecycle = new ExternalThreadLifecycle();
32478
+ #hasRunningDescendants;
32320
32479
  #subagentRunning;
32321
32480
  #threads = /* @__PURE__ */ new Map();
32322
32481
  constructor(input) {
@@ -32326,12 +32485,13 @@ var ExternalThreadRuntime = class {
32326
32485
  this.#consumeOutputs = input.consumeOutputs;
32327
32486
  this.#diagnose = input.diagnose;
32328
32487
  this.#subagentRunning = input.subagentRunning ?? (() => false);
32488
+ this.#hasRunningDescendants = input.hasRunningDescendants ?? (() => false);
32329
32489
  this.idleRelease = new ExternalThreadIdleRelease({
32330
32490
  threads: () => this.values(),
32331
32491
  get: (id2) => this.get(id2),
32332
32492
  remove: (id2) => this.remove(id2),
32333
32493
  queue: input.idleRelease?.queue ?? new DesktopRequestQueue(),
32334
- canRelease: input.idleRelease?.canRelease ?? (() => false),
32494
+ canRelease: (thread) => !thread.sessionUnavailable && !this.#lifecycle.busy(thread.id) && (input.idleRelease?.canRelease(thread) ?? false),
32335
32495
  ...input.idleRelease?.onClosed ? { onClosed: input.idleRelease.onClosed } : {},
32336
32496
  diagnose: input.diagnose
32337
32497
  });
@@ -32347,7 +32507,45 @@ var ExternalThreadRuntime = class {
32347
32507
  }
32348
32508
  clear() {
32349
32509
  this.#threads.clear();
32350
- this.#restores.clear();
32510
+ }
32511
+ drain() {
32512
+ return this.#lifecycle.drain();
32513
+ }
32514
+ #withLifecycle(threadId2, operation) {
32515
+ return this.#lifecycle.run(threadId2, async () => {
32516
+ await this.idleRelease.waitForClose(threadId2);
32517
+ return operation();
32518
+ });
32519
+ }
32520
+ markSessionUnavailable(thread) {
32521
+ thread.sessionUnavailable = true;
32522
+ }
32523
+ #idleForRestore(thread) {
32524
+ if (thread.running || thread.activeTurnId !== null) return false;
32525
+ if (thread.session.hasBackgroundWork?.()) return false;
32526
+ if (this.#hasRunningDescendants(thread.id)) return false;
32527
+ return true;
32528
+ }
32529
+ async #dropIdleSession(thread) {
32530
+ if (this.#threads.get(thread.id) !== thread) return;
32531
+ thread.sessionUnavailable = true;
32532
+ await this.#lifecycle.release(thread.id, thread.session, thread.outputTask);
32533
+ if (this.#threads.get(thread.id) !== thread) return;
32534
+ await this.#retireSubagents(thread);
32535
+ if (this.#threads.get(thread.id) === thread) this.#threads.delete(thread.id);
32536
+ }
32537
+ /** Called without awaiting from the output consumer: release itself drains that consumer. */
32538
+ async discardUnavailableIdle(thread) {
32539
+ const session = thread.session;
32540
+ try {
32541
+ await this.#withLifecycle(thread.id, async () => {
32542
+ if (this.#threads.get(thread.id) !== thread || thread.session !== session || !thread.sessionUnavailable || !this.#idleForRestore(thread))
32543
+ return;
32544
+ await this.#dropIdleSession(thread);
32545
+ });
32546
+ } catch (error51) {
32547
+ this.#diagnose(error51);
32548
+ }
32351
32549
  }
32352
32550
  register(input) {
32353
32551
  const harnessId = input.record.harnessId;
@@ -32392,7 +32590,8 @@ var ExternalThreadRuntime = class {
32392
32590
  ephemeralTurnIds: /* @__PURE__ */ new Set(),
32393
32591
  persistenceError: null,
32394
32592
  projectedTerminalTurnId: null,
32395
- ignoredInteractionIds: /* @__PURE__ */ new Set()
32593
+ ignoredInteractionIds: /* @__PURE__ */ new Set(),
32594
+ sessionUnavailable: false
32396
32595
  };
32397
32596
  this.idleRelease.touch(externalThread);
32398
32597
  externalThread.outputTask = this.#consumeOutputs(externalThread);
@@ -32419,11 +32618,12 @@ var ExternalThreadRuntime = class {
32419
32618
  } catch (error51) {
32420
32619
  this.#diagnose(error51);
32421
32620
  }
32422
- await this.#retireSubagents(current.id);
32621
+ await this.#retireSubagents(current, true);
32423
32622
  this.#threads.delete(current.id);
32424
32623
  return this.register(input);
32425
32624
  }
32426
- async #retireSubagents(parentId) {
32625
+ async #retireSubagents(parent, bestEffort = false) {
32626
+ const parentId = parent.id;
32427
32627
  const ancestors = /* @__PURE__ */ new Map();
32428
32628
  const descendant = async (record4) => {
32429
32629
  const visited = /* @__PURE__ */ new Set();
@@ -32440,24 +32640,35 @@ var ExternalThreadRuntime = class {
32440
32640
  }
32441
32641
  return false;
32442
32642
  };
32443
- for (const [id2, restoring] of [...this.#restores]) {
32444
- if (await descendant(await this.#repository.find(id2))) {
32445
- await restoring.catch(this.#diagnose);
32446
- }
32643
+ for (const [id2, pending] of this.#lifecycle.pending()) {
32644
+ if (id2 !== parentId && await descendant(await this.#repository.find(id2))) await pending;
32447
32645
  }
32448
- for (const child of this.#threads.values()) {
32646
+ for (const child of [...this.#threads.values()]) {
32449
32647
  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
- }
32648
+ const retire = async () => {
32649
+ if (this.#threads.get(parentId) !== parent || this.#threads.get(child.id) !== child) return;
32650
+ if (bestEffort) {
32651
+ this.#threads.delete(child.id);
32652
+ await child.session.close();
32653
+ await child.outputTask;
32654
+ } else {
32655
+ child.sessionUnavailable = true;
32656
+ await this.#lifecycle.release(child.id, child.session, child.outputTask);
32657
+ if (this.#threads.get(child.id) === child) this.#threads.delete(child.id);
32658
+ }
32659
+ };
32660
+ if (bestEffort) await retire().catch(this.#diagnose);
32661
+ else await this.#withLifecycle(child.id, retire);
32457
32662
  }
32458
32663
  }
32459
32664
  async locate(threadId2) {
32460
- await this.idleRelease.waitForClose(threadId2);
32665
+ try {
32666
+ return await this.#withLifecycle(threadId2, () => this.#locate(threadId2));
32667
+ } catch (error51) {
32668
+ return { kind: "error", error: recoveryError(error51) };
32669
+ }
32670
+ }
32671
+ async #locate(threadId2) {
32461
32672
  const loaded = this.#threads.get(threadId2);
32462
32673
  if (loaded) {
32463
32674
  const failure = this.idleRelease.failure(loaded);
@@ -32483,37 +32694,61 @@ var ExternalThreadRuntime = class {
32483
32694
  return { kind: "external", record: record4, thread: null };
32484
32695
  }
32485
32696
  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);
32697
+ try {
32698
+ return await this.#withLifecycle(threadId2, async () => {
32699
+ const location = await this.#locate(threadId2);
32700
+ if (location.kind !== "external") return location;
32701
+ if (location.thread) {
32702
+ if (location.thread.sessionUnavailable && this.#idleForRestore(location.thread)) {
32703
+ await this.#dropIdleSession(location.thread);
32704
+ const current = this.#threads.get(threadId2);
32705
+ if (current) return { kind: "external", thread: current, historyFresh: false };
32706
+ } else {
32707
+ this.idleRelease.touch(location.thread);
32708
+ return { kind: "external", thread: location.thread, historyFresh: false };
32709
+ }
32710
+ }
32711
+ return {
32712
+ kind: "external",
32713
+ thread: await this.#restore(location.record),
32714
+ historyFresh: true
32715
+ };
32502
32716
  });
32503
- this.#restores.set(threadId2, restoring);
32717
+ } catch (error51) {
32718
+ return { kind: "error", error: recoveryError(error51) };
32504
32719
  }
32720
+ }
32721
+ async refresh(thread) {
32505
32722
  try {
32506
- return { kind: "external", thread: await restoring, historyFresh: true };
32723
+ return await this.#withLifecycle(thread.id, () => this.#refresh(thread));
32507
32724
  } catch (error51) {
32725
+ return recoveryError(error51);
32726
+ }
32727
+ }
32728
+ async #refresh(thread) {
32729
+ if (this.#threads.get(thread.id) !== thread) {
32508
32730
  return {
32509
- kind: "error",
32510
- error: error51 instanceof ExternalThreadOpenError ? error51.rpcError : { code: -32076, message: "External Thread recovery failed" }
32731
+ code: -32076,
32732
+ message: "External Session changed during recovery; retry the request"
32511
32733
  };
32512
32734
  }
32513
- }
32514
- async refresh(thread) {
32515
- const snapshot2 = await thread.session.readSnapshot();
32516
- if (!snapshot2.ok) return mapExternalThreadHarnessError(snapshot2.error, "read");
32735
+ const failure = this.idleRelease.failure(thread);
32736
+ if (failure) return { code: -32075, message: failure };
32737
+ if (thread.sessionUnavailable && this.#idleForRestore(thread)) {
32738
+ const revived = await this.#reviveIdleSession(thread);
32739
+ if (revived) return revived;
32740
+ }
32741
+ let snapshot2 = await thread.session.readSnapshot();
32742
+ if (!snapshot2.ok) {
32743
+ if (snapshot2.error.code === "invalidState" && this.#idleForRestore(thread) && this.#threads.get(thread.id) === thread) {
32744
+ const revived = await this.#reviveIdleSession(thread);
32745
+ if (revived) return revived;
32746
+ snapshot2 = await thread.session.readSnapshot();
32747
+ if (!snapshot2.ok) return mapExternalThreadHarnessError(snapshot2.error, "read");
32748
+ } else {
32749
+ return mapExternalThreadHarnessError(snapshot2.error, "read");
32750
+ }
32751
+ }
32517
32752
  try {
32518
32753
  const aligned = await this.#repository.alignSnapshot(thread.record, snapshot2.value);
32519
32754
  thread.record = aligned.record;
@@ -32530,6 +32765,122 @@ var ExternalThreadRuntime = class {
32530
32765
  return { code: -32081, message: "External Thread history could not be persisted" };
32531
32766
  }
32532
32767
  }
32768
+ async #reviveIdleSession(thread) {
32769
+ thread.sessionUnavailable = true;
32770
+ const harnessId = thread.record.harnessId;
32771
+ const adapter = this.#adapters.get(harnessId);
32772
+ if (!adapter || !thread.record.nativeSessionRef) {
32773
+ await this.#dropIdleSession(thread);
32774
+ return { code: -32077, message: "External Harness is unavailable" };
32775
+ }
32776
+ await this.#lifecycle.release(thread.id, thread.session, thread.outputTask);
32777
+ await this.#retireSubagents(thread);
32778
+ if (this.#threads.get(thread.id) !== thread) {
32779
+ return { code: -32076, message: "External Thread recovery failed" };
32780
+ }
32781
+ const restoredSelection = decodeExternalTransportSelection(
32782
+ harnessId,
32783
+ thread.record.transportModelId
32784
+ );
32785
+ const opened = await adapter.open({
32786
+ kind: "resume",
32787
+ cwd: thread.record.cwd,
32788
+ environment: { ...this.#environment, [DELEGATION_THREAD_ID_ENV]: thread.record.hostThreadId },
32789
+ nativeRef: thread.record.nativeSessionRef,
32790
+ knownTurnRefs: thread.record.turnMappings.map(({ nativeTurnRef }) => nativeTurnRef),
32791
+ ...restoredSelection?.model ? { model: restoredSelection.model } : {},
32792
+ ...restoredSelection?.thinkingOptionId ? { thinkingOptionId: restoredSelection.thinkingOptionId } : {},
32793
+ ...restoredSelection?.permissionModeId ? { permissionModeId: restoredSelection.permissionModeId } : {}
32794
+ });
32795
+ if (!opened.ok) {
32796
+ await this.#dropIdleSession(thread);
32797
+ return mapExternalThreadHarnessError(opened.error, "resume");
32798
+ }
32799
+ const session = opened.value;
32800
+ if (this.#threads.get(thread.id) !== thread) {
32801
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32802
+ return { code: -32076, message: "External Thread recovery failed" };
32803
+ }
32804
+ try {
32805
+ const snapshot2 = await session.readSnapshot();
32806
+ if (!snapshot2.ok) {
32807
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32808
+ await this.#dropIdleSession(thread);
32809
+ return mapExternalThreadHarnessError(snapshot2.error, "read");
32810
+ }
32811
+ let aligned = await this.#repository.alignSnapshot(thread.record, snapshot2.value);
32812
+ if (this.#threads.get(thread.id) !== thread) {
32813
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32814
+ return { code: -32076, message: "External Thread recovery failed" };
32815
+ }
32816
+ const restoredState = snapshot2.value.state;
32817
+ const effectiveModel = restoredState ? restoredState.effectiveModel : restoredSelection?.model;
32818
+ const effectiveThinkingOptionId = restoredState ? restoredState.effectiveThinkingOptionId : restoredSelection?.thinkingOptionId;
32819
+ const effectivePermissionModeId = restoredState ? restoredState.effectivePermissionModeId : restoredSelection?.permissionModeId;
32820
+ let transportModelId = aligned.record.transportModelId;
32821
+ if (restoredState && effectiveModel) {
32822
+ const liveSelection = {
32823
+ model: effectiveModel,
32824
+ ...effectiveThinkingOptionId ? { thinkingOptionId: effectiveThinkingOptionId } : {},
32825
+ ...effectivePermissionModeId ? { permissionModeId: effectivePermissionModeId } : {}
32826
+ };
32827
+ transportModelId = encodeExternalTransportSelection(harnessId, liveSelection);
32828
+ if (transportModelId !== aligned.record.transportModelId) {
32829
+ try {
32830
+ aligned = {
32831
+ ...aligned,
32832
+ record: await this.#repository.setTransportModelId(
32833
+ aligned.record.hostThreadId,
32834
+ transportModelId
32835
+ )
32836
+ };
32837
+ } catch (error51) {
32838
+ this.#diagnose(error51);
32839
+ }
32840
+ }
32841
+ }
32842
+ if (this.#threads.get(thread.id) !== thread) {
32843
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32844
+ return { code: -32076, message: "External Thread recovery failed" };
32845
+ }
32846
+ const initialState = restoredState ?? session.initialState;
32847
+ const observerState = {
32848
+ ...initialState,
32849
+ ...effectiveModel ? { effectiveModel } : {},
32850
+ ...effectiveThinkingOptionId ? { effectiveThinkingOptionId } : {},
32851
+ ...effectivePermissionModeId ? { effectivePermissionModeId } : {}
32852
+ };
32853
+ thread.session = session;
32854
+ thread.record = aligned.record;
32855
+ thread.turns = aligned.turns;
32856
+ thread.historyHydrated = true;
32857
+ thread.sessionUnavailable = false;
32858
+ thread.persistenceError = null;
32859
+ thread.transportModelId = transportModelId;
32860
+ if (effectiveModel) thread.requestedModel = effectiveModel;
32861
+ if (effectiveThinkingOptionId) thread.requestedThinkingOptionId = effectiveThinkingOptionId;
32862
+ if (effectivePermissionModeId) thread.requestedPermissionModeId = effectivePermissionModeId;
32863
+ thread.stateObserver = new SessionStateObserver(observerState);
32864
+ thread.latestUsage = session.initialUsage;
32865
+ thread.usageMeter = new UsageMeter();
32866
+ thread.usageTurnId = null;
32867
+ thread.thread = externalThreadValue({
32868
+ record: aligned.record,
32869
+ turns: aligned.turns,
32870
+ sessionId: thread.sessionId,
32871
+ running: thread.running
32872
+ });
32873
+ thread.outputTask = this.#consumeOutputs(thread);
32874
+ this.idleRelease.clearOutputFailed(thread);
32875
+ return null;
32876
+ } catch (error51) {
32877
+ if (error51 instanceof ExternalSessionReleaseError) throw error51;
32878
+ await this.#lifecycle.release(thread.id, session, Promise.resolve());
32879
+ this.#diagnose(error51);
32880
+ await this.#dropIdleSession(thread);
32881
+ return { code: -32081, message: "External Thread history could not be persisted" };
32882
+ }
32883
+ }
32533
32884
  async persistTerminalIdentity(thread, event) {
32534
32885
  if (thread.persistenceError) return thread.persistenceError;
32535
32886
  if (!event.nativeTurnRef) {
@@ -32668,7 +33019,8 @@ var ExternalThreadRuntime = class {
32668
33019
  transportModelId
32669
33020
  });
32670
33021
  } catch (error51) {
32671
- await session.close().catch(() => void 0);
33022
+ if (error51 instanceof ExternalSessionReleaseError) throw error51;
33023
+ await this.#lifecycle.release(record4.hostThreadId, session, Promise.resolve());
32672
33024
  throw error51;
32673
33025
  }
32674
33026
  }
@@ -33085,7 +33437,7 @@ function sanitizeDelegationTitle(task) {
33085
33437
  const cutLength = Math.max(0, DELEGATION_TITLE_MAX_LENGTH - DELEGATION_TITLE_ELLIPSIS.length);
33086
33438
  return `${trimmed.slice(0, cutLength)}${DELEGATION_TITLE_ELLIPSIS}`;
33087
33439
  }
33088
- function delay2(milliseconds) {
33440
+ function delay3(milliseconds) {
33089
33441
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
33090
33442
  }
33091
33443
  function terminal(status2) {
@@ -33475,7 +33827,7 @@ var HarnessDelegationCoordinator = class {
33475
33827
  if (terminal(snapshot2.status)) return { ...snapshot2, timedOut: false };
33476
33828
  const remaining = deadline - Date.now();
33477
33829
  if (remaining <= 0) return { ...snapshot2, timedOut: true };
33478
- await delay2(Math.min(100, remaining));
33830
+ await delay3(Math.min(100, remaining));
33479
33831
  }
33480
33832
  }
33481
33833
  async list(input) {
@@ -35609,15 +35961,21 @@ var HarnessPluginRegistry = class {
35609
35961
  };
35610
35962
 
35611
35963
  // packages/host-runtime/src/harness-plugin-loader.ts
35964
+ function hasValidSessionUsage(value2) {
35965
+ const capability = Reflect.get(value2, "sessionUsage");
35966
+ return capability === void 0 || capability !== null && typeof capability === "object" && ["observe", "read"].every((key) => typeof Reflect.get(capability, key) === "function") && ["requestOptions", "shouldForwardNotification", "reset"].every(
35967
+ (key) => Reflect.get(capability, key) === void 0 || typeof Reflect.get(capability, key) === "function"
35968
+ );
35969
+ }
35612
35970
  function isAdapter(value2) {
35613
35971
  if (!value2 || typeof value2 !== "object") return false;
35614
- return ["inspect", "open", "close"].every((key) => typeof Reflect.get(value2, key) === "function");
35972
+ return hasValidSessionUsage(value2) && ["inspect", "open", "close"].every((key) => typeof Reflect.get(value2, key) === "function");
35615
35973
  }
35616
35974
  function isUsageAdapter(value2) {
35617
35975
  if (!value2 || typeof value2 !== "object" || typeof Reflect.get(value2, "close") !== "function")
35618
35976
  return false;
35619
35977
  const capability = Reflect.get(value2, "usageStatistics");
35620
- return !!capability && typeof capability === "object" && ["listSources", "readSource"].every(
35978
+ return hasValidSessionUsage(value2) && !!capability && typeof capability === "object" && ["listSources", "readSource"].every(
35621
35979
  (key) => typeof Reflect.get(capability, key) === "function"
35622
35980
  ) && !("open" in value2) && !("inspect" in value2);
35623
35981
  }
@@ -35758,11 +36116,12 @@ async function loadHarnessPlugins(options2) {
35758
36116
  }
35759
36117
  if (options2.signal?.aborted) return registry2;
35760
36118
  let next = 0;
36119
+ let batch = pending;
35761
36120
  const loaded = /* @__PURE__ */ new Map();
35762
36121
  const worker = async () => {
35763
36122
  for (; ; ) {
35764
36123
  if (options2.signal?.aborted) return;
35765
- const candidate = pending[next++];
36124
+ const candidate = batch[next++];
35766
36125
  if (!candidate) return;
35767
36126
  if (options2.signal?.aborted) return;
35768
36127
  const { manifest } = candidate;
@@ -35808,10 +36167,19 @@ async function loadHarnessPlugins(options2) {
35808
36167
  loaded.set(candidate, { descriptor, adapter });
35809
36168
  }
35810
36169
  };
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);
36170
+ const batches = options2.onUsageAdaptersLoaded ? [
36171
+ pending.filter((c) => c.manifest.kind === "usage"),
36172
+ pending.filter((c) => c.manifest.kind !== "usage")
36173
+ ] : [pending];
36174
+ for (const [index, candidates2] of batches.entries()) {
36175
+ batch = candidates2;
36176
+ next = 0;
36177
+ await Promise.all(Array.from({ length: Math.min(4, batch.length) }, () => worker()));
36178
+ for (const candidate of batch) {
36179
+ const entry = loaded.get(candidate);
36180
+ if (entry) await registry2.register(entry.descriptor, entry.adapter);
36181
+ }
36182
+ if (index === 0) options2.onUsageAdaptersLoaded?.(registry2.usageAdapters);
35815
36183
  }
35816
36184
  return registry2;
35817
36185
  }
@@ -37017,16 +37385,16 @@ var OfficialRuntimeScope = class {
37017
37385
  #scheduleRecovery() {
37018
37386
  if (!this.#recovery || this.#closed || this.#recoveryTimer || this.#starting) return;
37019
37387
  const { delaysMs } = this.#recovery;
37020
- const delay5 = delaysMs[Math.min(this.#recoveryAttempt, delaysMs.length - 1)] ?? 0;
37388
+ const delay6 = delaysMs[Math.min(this.#recoveryAttempt, delaysMs.length - 1)] ?? 0;
37021
37389
  this.#recoveryAttempt++;
37022
37390
  this.#diagnosticOutput.write(
37023
- `codexhost: official Codex is unavailable; restarting in ${String(delay5)}ms
37391
+ `codexhost: official Codex is unavailable; restarting in ${String(delay6)}ms
37024
37392
  `
37025
37393
  );
37026
37394
  const timer = setTimeout(() => {
37027
37395
  this.#recoveryTimer = void 0;
37028
37396
  this.start().catch(() => void 0);
37029
- }, delay5);
37397
+ }, delay6);
37030
37398
  timer.unref();
37031
37399
  this.#recoveryTimer = timer;
37032
37400
  }
@@ -37777,11 +38145,163 @@ async function moveThreadSection(input) {
37777
38145
  }
37778
38146
  }
37779
38147
 
38148
+ // packages/host-runtime/src/observed-session-usage.ts
38149
+ var ObservedSessionUsage = class {
38150
+ constructor(providers, prices, diagnose) {
38151
+ this.providers = providers;
38152
+ this.prices = prices;
38153
+ this.diagnose = diagnose;
38154
+ }
38155
+ providers;
38156
+ prices;
38157
+ diagnose;
38158
+ #states = /* @__PURE__ */ new Map();
38159
+ #pending = /* @__PURE__ */ new Map();
38160
+ #abort = new AbortController();
38161
+ #initializeParams = null;
38162
+ initialized(params) {
38163
+ this.#initializeParams = params;
38164
+ for (const state of this.#states.values()) {
38165
+ state.meter.resetTurnTiming();
38166
+ state.activeTurnId = null;
38167
+ }
38168
+ for (const provider of this.providers()) {
38169
+ try {
38170
+ provider.reset?.();
38171
+ } catch (error51) {
38172
+ this.diagnose(error51);
38173
+ }
38174
+ }
38175
+ }
38176
+ requestOptions(method, params) {
38177
+ if (this.#abort.signal.aborted) return null;
38178
+ let result = null;
38179
+ for (const provider of this.providers()) {
38180
+ try {
38181
+ const patch = provider.requestOptions?.({
38182
+ method,
38183
+ params,
38184
+ initializeParams: this.#initializeParams
38185
+ });
38186
+ if (patch) result = Object.assign(result ?? {}, jsonObjectSchema.parse(patch));
38187
+ } catch (error51) {
38188
+ this.diagnose(error51);
38189
+ }
38190
+ }
38191
+ return result;
38192
+ }
38193
+ shouldForwardNotification(message2) {
38194
+ if (this.#abort.signal.aborted) return true;
38195
+ for (const provider of this.providers()) {
38196
+ try {
38197
+ if (provider.shouldForwardNotification?.(message2) === false) return false;
38198
+ } catch (error51) {
38199
+ this.diagnose(error51);
38200
+ }
38201
+ }
38202
+ return true;
38203
+ }
38204
+ observe(message2, now = Date.now()) {
38205
+ if (this.#abort.signal.aborted) return [];
38206
+ const changed = /* @__PURE__ */ new Set();
38207
+ for (const provider of this.providers()) {
38208
+ try {
38209
+ const observation = provider.observe(message2, now);
38210
+ if (!observation) continue;
38211
+ const state = this.#state(observation.sessionId, provider);
38212
+ if (state.provider !== provider) continue;
38213
+ if (observation.usage) {
38214
+ state.live = parseHostUsage(observation.usage);
38215
+ state.revision++;
38216
+ }
38217
+ const turn = observation.turn;
38218
+ if (turn?.phase === "started" && state.activeTurnId !== turn.id) {
38219
+ state.meter.resetTurnTiming();
38220
+ state.meter.turnStarted(turn.id, now);
38221
+ state.activeTurnId = turn.id;
38222
+ }
38223
+ const timing = observation.requestTiming;
38224
+ if (timing) state.meter.recordOutputTiming(timing, timing.turnId);
38225
+ if (observation.timingUnavailable)
38226
+ state.meter.invalidateOutputTiming(observation.timingUnavailable.turnId);
38227
+ if (turn?.phase === "completed") {
38228
+ state.meter.turnCompleted(turn.id);
38229
+ if (state.activeTurnId === turn.id) state.activeTurnId = null;
38230
+ }
38231
+ const firstOutput = turn?.phase === "output" && state.meter.outputObserved(turn.id, now);
38232
+ if (observation.usage || firstOutput || timing || observation.timingUnavailable || turn?.phase === "started" || turn?.phase === "completed")
38233
+ changed.add(observation.sessionId);
38234
+ } catch (error51) {
38235
+ this.diagnose(error51);
38236
+ }
38237
+ }
38238
+ return [...changed];
38239
+ }
38240
+ async read(sessionId) {
38241
+ if (this.#abort.signal.aborted) return null;
38242
+ let pending = this.#pending.get(sessionId);
38243
+ if (!pending) {
38244
+ pending = this.#refresh(sessionId).finally(() => this.#pending.delete(sessionId));
38245
+ this.#pending.set(sessionId, pending);
38246
+ }
38247
+ await pending;
38248
+ const state = this.#states.get(sessionId);
38249
+ if (!state || this.#abort.signal.aborted) return null;
38250
+ const native = state.live ?? state.history;
38251
+ const result = state.meter.derive(native, await this.prices.lookup());
38252
+ if (result?.unpricedModels?.length) this.prices.missing();
38253
+ return result;
38254
+ }
38255
+ async #refresh(sessionId) {
38256
+ const existing = this.#states.get(sessionId);
38257
+ for (const provider of existing ? [existing.provider] : this.providers()) {
38258
+ const revision = existing?.revision ?? 0;
38259
+ try {
38260
+ const history = await provider.read(sessionId, this.#abort.signal);
38261
+ if (this.#abort.signal.aborted) return;
38262
+ if (!history) {
38263
+ if (existing?.meter.metered) existing.meter.recordHistory(false);
38264
+ continue;
38265
+ }
38266
+ const state = this.#state(sessionId, provider);
38267
+ state.history = history.usage ? parseHostUsage(history.usage) : null;
38268
+ state.meter.replaceHistory(
38269
+ history.requests,
38270
+ history.complete && state.revision === revision
38271
+ );
38272
+ return;
38273
+ } catch (error51) {
38274
+ existing?.meter.recordHistory(false);
38275
+ if (!this.#abort.signal.aborted) this.diagnose(error51);
38276
+ }
38277
+ }
38278
+ }
38279
+ #state(id2, provider) {
38280
+ let state = this.#states.get(id2);
38281
+ if (!state) {
38282
+ state = {
38283
+ provider,
38284
+ meter: new UsageMeter(),
38285
+ live: null,
38286
+ history: null,
38287
+ revision: 0,
38288
+ activeTurnId: null
38289
+ };
38290
+ this.#states.set(id2, state);
38291
+ }
38292
+ return state;
38293
+ }
38294
+ close() {
38295
+ this.#abort.abort();
38296
+ this.#states.clear();
38297
+ }
38298
+ };
38299
+
37780
38300
  // packages/host-runtime/src/app-server-host.ts
37781
38301
  var CONSOLE_REQUEST_TIMEOUT_MS = 12e4;
37782
38302
  var SUBAGENT_TERMINAL_REFRESH_DELAYS_MS = [0, 50, 100, 150];
37783
38303
  var THREAD_USAGE_UPDATED_METHOD = "codexhost/thread/usage/updated";
37784
- function delay3(milliseconds) {
38304
+ function delay4(milliseconds) {
37785
38305
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
37786
38306
  }
37787
38307
  function isRecord19(value2) {
@@ -37978,10 +38498,12 @@ var AppServerHost = class {
37978
38498
  #launchSettings;
37979
38499
  #accountInspections = new HarnessAccountInspectionCache();
37980
38500
  #externalRuntime;
38501
+ #executionHosts = /* @__PURE__ */ new WeakMap();
37981
38502
  #externalPrewarms = new ExternalThreadPrewarms();
37982
38503
  #externalSteering = new ExternalTurnSteering();
37983
38504
  #liveCommandCache = new LiveCommandCatalogCache();
37984
38505
  #modelPrices;
38506
+ #observedSessionUsage;
37985
38507
  #repository;
37986
38508
  #pendingDesktopApprovals = /* @__PURE__ */ new Map();
37987
38509
  #pendingDesktopQuestions = /* @__PURE__ */ new Map();
@@ -37998,7 +38520,6 @@ var AppServerHost = class {
37998
38520
  #activeWorkDrainWaiters = /* @__PURE__ */ new Set();
37999
38521
  #pendingOfficialDelegationThreads = /* @__PURE__ */ new Set();
38000
38522
  #pendingOfficialTerminalStatuses = /* @__PURE__ */ new Map();
38001
- #officialUsageByThread = /* @__PURE__ */ new Map();
38002
38523
  #officialRateLimits = new AccountRateLimits();
38003
38524
  #routeObservationTracker = new RequestRouteObservationTracker();
38004
38525
  #officialServerRequests = /* @__PURE__ */ new Map();
@@ -38016,6 +38537,7 @@ var AppServerHost = class {
38016
38537
  #closeRequested = false;
38017
38538
  #pluginLoadAbort = new AbortController();
38018
38539
  #pluginLoading;
38540
+ #usagePluginsReady;
38019
38541
  #desktopRequests = new DesktopRequestQueue();
38020
38542
  #drainActiveWorkOnInputEnd = false;
38021
38543
  #desktopInputEnded = false;
@@ -38027,6 +38549,13 @@ var AppServerHost = class {
38027
38549
  ...options2
38028
38550
  };
38029
38551
  this.#modelPrices = options2.modelPrices ?? new ModelPriceCatalog();
38552
+ this.#observedSessionUsage = new ObservedSessionUsage(
38553
+ () => [...this.#externalAdapters.values(), ...this.#usageOnlyAdapters].flatMap(
38554
+ (adapter) => adapter.sessionUsage ? [adapter.sessionUsage] : []
38555
+ ),
38556
+ this.#modelPrices,
38557
+ (error51) => this.#diagnose(error51)
38558
+ );
38030
38559
  this.#writer = new OrderedWriter(this.#options.desktopOutput, (value2) => {
38031
38560
  this.#noteDesktopReply(value2);
38032
38561
  return this.#takeConsoleReply(value2);
@@ -38110,6 +38639,7 @@ var AppServerHost = class {
38110
38639
  consumeOutputs: (thread) => this.#consumeHarnessOutputs(thread),
38111
38640
  diagnose: (error51) => this.#diagnose(error51),
38112
38641
  subagentRunning: (threadId2) => this.#subagentThreadStatuses.get(threadId2) === "active",
38642
+ hasRunningDescendants: (threadId2) => this.#hasRunningSubagents(threadId2),
38113
38643
  idleRelease: {
38114
38644
  queue: this.#desktopRequests,
38115
38645
  onClosed: async (thread) => {
@@ -38168,7 +38698,11 @@ var AppServerHost = class {
38168
38698
  wait: (input) => this.#waitForPlugins().then(() => this.#delegationCoordinator.wait(input)),
38169
38699
  list: (input) => this.#waitForPlugins().then(() => this.#delegationCoordinator.list(input)),
38170
38700
  canHandleStart: (input) => this.#canHandleDelegationStart(input),
38171
- ownsThread: (threadId2) => this.#ownsDelegationThread(threadId2)
38701
+ ownsThread: (threadId2) => this.#ownsDelegationThread(threadId2),
38702
+ executionHostId: (threadId2) => {
38703
+ const thread = this.#externalRuntime.get(threadId2);
38704
+ return thread ? this.#executionHosts.get(thread) : void 0;
38705
+ }
38172
38706
  });
38173
38707
  this.#unregisterDelegationApi = typeof unregisterDelegationApi === "function" ? unregisterDelegationApi : void 0;
38174
38708
  }
@@ -38200,18 +38734,29 @@ var AppServerHost = class {
38200
38734
  this.#options.usageStatistics?.attach(
38201
38735
  () => [.../* @__PURE__ */ new Set([...this.#externalAdapters.values(), ...this.#usageOnlyAdapters])].flatMap(
38202
38736
  (adapter) => adapter.usageStatistics ? [{ harness: adapter.harnessId, capability: adapter.usageStatistics }] : []
38203
- )
38737
+ ),
38738
+ () => this.#repository.list()
38204
38739
  );
38205
38740
  }
38206
38741
  #waitForPlugins() {
38207
- return this.#pluginLoading ??= this.#loadInstalledPlugins().catch((error51) => {
38208
- this.#diagnose(`Harness plugin load failed: ${errorMessage4(error51)}`);
38209
- });
38742
+ if (!this.#pluginLoading) {
38743
+ const ready = Promise.withResolvers();
38744
+ const usageReady = () => ready.resolve(void 0);
38745
+ this.#usagePluginsReady = ready.promise;
38746
+ this.#pluginLoading = this.#loadInstalledPlugins(usageReady).catch((error51) => {
38747
+ this.#diagnose(`Harness plugin load failed: ${errorMessage4(error51)}`);
38748
+ }).finally(usageReady);
38749
+ }
38750
+ return this.#pluginLoading;
38210
38751
  }
38211
- async #loadInstalledPlugins() {
38752
+ async #loadInstalledPlugins(usageReady) {
38212
38753
  if (!this.#options.pluginRoots || this.#pluginLoadAbort.signal.aborted) return;
38213
38754
  const plugins = await loadHarnessPlugins({
38214
38755
  roots: this.#options.pluginRoots,
38756
+ onUsageAdaptersLoaded: (adapters) => {
38757
+ if (!this.#pluginLoadAbort.signal.aborted) this.#usageOnlyAdapters = [...adapters.values()];
38758
+ usageReady();
38759
+ },
38215
38760
  launchCommandForPlugin: (id2) => this.#launchSettings.initialCommand(id2),
38216
38761
  context: this.#options.pluginContext ?? {
38217
38762
  environment: this.#options.environment ?? process.env,
@@ -38232,6 +38777,7 @@ var AppServerHost = class {
38232
38777
  for (const [id2, adapter] of plugins.adapters) this.#externalAdapters.set(id2, adapter);
38233
38778
  }
38234
38779
  async #closeAdapters() {
38780
+ this.#observedSessionUsage.close();
38235
38781
  const results = await Promise.allSettled([
38236
38782
  this.#plugins?.close(),
38237
38783
  ...[...new Set(this.#options.externalAdapters?.values())].map(
@@ -38293,6 +38839,7 @@ var AppServerHost = class {
38293
38839
  await Promise.allSettled(threads.map(({ session }) => session.close()));
38294
38840
  await Promise.allSettled(threads.map(({ outputTask }) => outputTask));
38295
38841
  await this.#closeAdapters();
38842
+ await this.#externalRuntime.drain();
38296
38843
  for (const pending of [...this.#pendingDesktopApprovals.values()]) {
38297
38844
  await this.#resolveDesktopApproval(pending.interaction.interactionId).catch(
38298
38845
  () => void 0
@@ -38435,7 +38982,13 @@ var AppServerHost = class {
38435
38982
  if (request.method === "initialize") {
38436
38983
  try {
38437
38984
  const nativeGeneration = this.#officialRuntimeScope.gate.phase === "ready" ? this.#officialRuntimeScope.owner.generation : void 0;
38438
- const response = await this.#officialRuntime.initializeProtocol(requestObject(request));
38985
+ void this.#waitForPlugins();
38986
+ await this.#usagePluginsReady;
38987
+ const params = requestObject(request);
38988
+ const options2 = this.#observedSessionUsage.requestOptions("initialize", params);
38989
+ const nativeParams = options2 ? { ...params, ...options2 } : params;
38990
+ const response = await this.#officialRuntime.initializeProtocol(nativeParams);
38991
+ if (!isRecord19(response.error)) this.#observedSessionUsage.initialized(nativeParams);
38439
38992
  await this.#writer.json({ ...response, id: request.id });
38440
38993
  this.#nativeAccountObserver?.initialized(nativeGeneration);
38441
38994
  } catch (error51) {
@@ -39297,6 +39850,15 @@ var AppServerHost = class {
39297
39850
  return;
39298
39851
  }
39299
39852
  try {
39853
+ const options2 = isRecord19(request.params) ? this.#observedSessionUsage.requestOptions(request.method, request.params) : null;
39854
+ if (options2) {
39855
+ const original = parseJsonFrame(frame);
39856
+ if (isRecord19(original))
39857
+ frame = encodeJsonFrame({
39858
+ ...original,
39859
+ params: { ...isRecord19(original.params) ? original.params : {}, ...options2 }
39860
+ });
39861
+ }
39300
39862
  await this.#officialRuntime.sendFrame(frame);
39301
39863
  this.#markDesktopRequestAnswered(request.id);
39302
39864
  } catch {
@@ -39315,6 +39877,7 @@ var AppServerHost = class {
39315
39877
  return;
39316
39878
  }
39317
39879
  const parsed2 = input.value;
39880
+ const observedAtMs = Date.now();
39318
39881
  this.#observeOfficialTurnStartResponse(parsed2);
39319
39882
  let forwarded = parsed2;
39320
39883
  if (isRecord19(parsed2) && typeof parsed2.method === "string" && "id" in parsed2) {
@@ -39329,17 +39892,6 @@ var AppServerHost = class {
39329
39892
  if (accountScopedNotification) {
39330
39893
  if (parsed2.method === "account/updated") this.#officialRateLimits.reset(input.accountId);
39331
39894
  }
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
39895
  const rateLimits = observeCodexRateLimits(parsed2);
39344
39896
  if (rateLimits) this.#officialRateLimits.observe(input.accountId, rateLimits);
39345
39897
  try {
@@ -39348,8 +39900,16 @@ var AppServerHost = class {
39348
39900
  this.#diagnose(error51);
39349
39901
  }
39350
39902
  this.#routeObservationTracker.bindOfficialResponse(parsed2);
39351
- if (forwarded === parsed2) await this.#writer.frame(input.frame);
39352
- else await this.#writer.json(forwarded);
39903
+ const privateTelemetry = isRecord19(parsed2) && typeof parsed2.method === "string" && !("id" in parsed2) && !this.#observedSessionUsage.shouldForwardNotification(parsed2);
39904
+ if (!privateTelemetry) {
39905
+ if (forwarded === parsed2) await this.#writer.frame(input.frame);
39906
+ else await this.#writer.json(forwarded);
39907
+ }
39908
+ void (this.#usagePluginsReady ?? Promise.resolve()).then(async () => {
39909
+ for (const threadId2 of this.#observedSessionUsage.observe(parsed2, observedAtMs)) {
39910
+ await this.#writer.json({ method: THREAD_USAGE_UPDATED_METHOD, params: { threadId: threadId2 } });
39911
+ }
39912
+ }).catch((error51) => this.#diagnose(error51));
39353
39913
  this.#nativeAccountObserver?.observe(parsed2);
39354
39914
  const deletedProjectId = observeDeletedProject(parsed2);
39355
39915
  if (deletedProjectId) {
@@ -40382,12 +40942,13 @@ var AppServerHost = class {
40382
40942
  );
40383
40943
  return;
40384
40944
  }
40945
+ await this.#waitForPlugins();
40385
40946
  const accountId = await this.#currentCodexAccountId();
40386
40947
  if (accountId) await this.#refreshOfficialRateLimits(accountId);
40387
40948
  const accountCredits = this.#officialAccountCredits(accountId ?? void 0);
40388
40949
  const result2 = threadUsageInspectionSchema.parse({
40389
40950
  threadId: params.data.threadId,
40390
- usage: this.#officialUsageByThread.get(params.data.threadId) ?? null,
40951
+ usage: await this.#observedSessionUsage.read(params.data.threadId),
40391
40952
  ...accountCredits ? { accountCredits } : {}
40392
40953
  });
40393
40954
  await this.#writer.json(rpcEnvelope(request, { result: jsonValueSchema.parse(result2) }));
@@ -40595,7 +41156,7 @@ var AppServerHost = class {
40595
41156
  this.#pendingExternalCommandRequests.delete(thread.id);
40596
41157
  }
40597
41158
  }
40598
- async #beginExternalCommand(thread, descriptor, arguments_2, requestedTurnId) {
41159
+ async #beginExternalCommand(thread, descriptor, arguments_2, requestedTurnId, sourceHostId) {
40599
41160
  const commands = thread.session.commands;
40600
41161
  if (!commands) {
40601
41162
  throw new ExternalCommandError(-32078, "External Harness does not expose commands");
@@ -40624,6 +41185,7 @@ var AppServerHost = class {
40624
41185
  thread.ephemeralTurnIds.add(turnId);
40625
41186
  if (descriptor.invocation === "/compact") this.#manualCompactionTurns.set(thread, turnId);
40626
41187
  else this.#manualCompactionTurns.delete(thread);
41188
+ const restoreExecutionHost = this.#setExecutionHost(thread, sourceHostId);
40627
41189
  try {
40628
41190
  if (thread.unsubmittedPrewarm && await this.#externalRuntime.submitPrewarm(thread)) {
40629
41191
  await this.#notifyExternalThreadStarted(thread.thread);
@@ -40636,6 +41198,7 @@ var AppServerHost = class {
40636
41198
  if (!result.ok) throw new ExternalCommandError(-32073, result.error.message);
40637
41199
  return { turnId: result.value.turnId, turn: projection.projector.pendingTurn(), gate };
40638
41200
  } catch (error51) {
41201
+ restoreExecutionHost();
40639
41202
  thread.running = false;
40640
41203
  thread.activeTurnId = null;
40641
41204
  thread.projectedTurns.delete(turnId);
@@ -41415,7 +41978,8 @@ var AppServerHost = class {
41415
41978
  thread,
41416
41979
  text2,
41417
41980
  void 0,
41418
- typeof params.clientUserMessageId === "string" ? params.clientUserMessageId : void 0
41981
+ typeof params.clientUserMessageId === "string" ? params.clientUserMessageId : void 0,
41982
+ params[THREAD_REFERENCE_SOURCE_HOST_PARAM]
41419
41983
  );
41420
41984
  try {
41421
41985
  await this.#writer.json(rpcEnvelope(request, { result: { turn: started.turn } }));
@@ -41441,7 +42005,8 @@ var AppServerHost = class {
41441
42005
  thread,
41442
42006
  text2,
41443
42007
  assertActive,
41444
- typeof requestObject(request).clientUserMessageId === "string" ? requestObject(request).clientUserMessageId : void 0
42008
+ typeof requestObject(request).clientUserMessageId === "string" ? requestObject(request).clientUserMessageId : void 0,
42009
+ requestObject(request)[THREAD_REFERENCE_SOURCE_HOST_PARAM]
41445
42010
  )
41446
42011
  );
41447
42012
  try {
@@ -41462,12 +42027,12 @@ var AppServerHost = class {
41462
42027
  }
41463
42028
  }
41464
42029
  /** Keep command restoration and dispatch identical for start and steer submissions. */
41465
- async #beginExternalInputTurn(thread, inputText, assertActive, clientUserMessageId) {
42030
+ async #beginExternalInputTurn(thread, inputText, assertActive, clientUserMessageId, sourceHostId) {
41466
42031
  const text2 = restoreHarnessCommandMentions(inputText);
41467
42032
  const commands = thread.session.commands;
41468
42033
  if (!commands || !isExternalCommandCandidate(text2)) {
41469
42034
  assertActive?.();
41470
- return this.#beginExternalTurn(thread, text2, clientUserMessageId);
42035
+ return this.#beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId);
41471
42036
  }
41472
42037
  this.#pendingExternalCommandRequests.add(thread.id);
41473
42038
  try {
@@ -41478,9 +42043,15 @@ var AppServerHost = class {
41478
42043
  assertActive?.();
41479
42044
  if (!command) {
41480
42045
  this.#pendingExternalCommandRequests.delete(thread.id);
41481
- return await this.#beginExternalTurn(thread, text2, clientUserMessageId);
42046
+ return await this.#beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId);
41482
42047
  }
41483
- return await this.#beginExternalCommand(thread, command.descriptor, command.arguments);
42048
+ return await this.#beginExternalCommand(
42049
+ thread,
42050
+ command.descriptor,
42051
+ command.arguments,
42052
+ void 0,
42053
+ sourceHostId
42054
+ );
41484
42055
  } catch (error51) {
41485
42056
  if (error51 instanceof ExternalCommandError || error51 instanceof ExternalSteerError) throw error51;
41486
42057
  this.#diagnose(error51);
@@ -41492,7 +42063,20 @@ var AppServerHost = class {
41492
42063
  this.#pendingExternalCommandRequests.delete(thread.id);
41493
42064
  }
41494
42065
  }
41495
- async #beginExternalTurn(thread, text2, clientUserMessageId) {
42066
+ /** Apply context before native execution; a rejected start restores the prior identity. */
42067
+ #setExecutionHost(thread, sourceHostId) {
42068
+ const previousHostId = this.#executionHosts.get(thread);
42069
+ if (typeof sourceHostId === "string" && sourceHostId.length > 0 && sourceHostId.length <= 1024 && !/[\u0000-\u0020\u007f]/u.test(sourceHostId)) {
42070
+ this.#executionHosts.set(thread, sourceHostId);
42071
+ } else {
42072
+ this.#executionHosts.delete(thread);
42073
+ }
42074
+ return () => {
42075
+ if (previousHostId === void 0) this.#executionHosts.delete(thread);
42076
+ else this.#executionHosts.set(thread, previousHostId);
42077
+ };
42078
+ }
42079
+ async #beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId) {
41496
42080
  if (this.#closeRequested || this.#externalRuntime.get(thread.id) !== thread) {
41497
42081
  throw new ExternalSteerError(-32073, "External Thread is no longer available");
41498
42082
  }
@@ -41519,6 +42103,7 @@ var AppServerHost = class {
41519
42103
  thread.projectedTerminalTurnId = null;
41520
42104
  thread.projectedTurns.set(turnId, projection);
41521
42105
  thread.responseGates.set(turnId, gate);
42106
+ const restoreExecutionHost = this.#setExecutionHost(thread, sourceHostId);
41522
42107
  try {
41523
42108
  if (thread.unsubmittedPrewarm && await this.#externalRuntime.submitPrewarm(thread)) {
41524
42109
  await this.#notifyExternalThreadStarted(thread.thread);
@@ -41531,6 +42116,7 @@ var AppServerHost = class {
41531
42116
  if (!result.ok) throw new ExternalSteerError(-32073, result.error.message);
41532
42117
  return { turnId, turn: projection.projector.pendingTurn(), gate };
41533
42118
  } catch (error51) {
42119
+ restoreExecutionHost();
41534
42120
  thread.running = false;
41535
42121
  thread.activeTurnId = null;
41536
42122
  thread.projectedTurns.delete(turnId);
@@ -41839,7 +42425,11 @@ var AppServerHost = class {
41839
42425
  if (event.type === "session.faulted") {
41840
42426
  this.#externalSteering.fault(thread.id, new Error(event.error.message));
41841
42427
  thread.stateObserver.fault(new Error(event.error.message));
42428
+ this.#externalRuntime.markSessionUnavailable(thread);
41842
42429
  this.#diagnose(`${thread.harnessId} Harness Session faulted: ${event.error.message}`);
42430
+ if (!thread.running && !thread.activeTurnId && !this.#hasRunningSubagents(thread.id) && !thread.session.hasBackgroundWork?.()) {
42431
+ void this.#externalRuntime.discardUnavailableIdle(thread);
42432
+ }
41843
42433
  return;
41844
42434
  }
41845
42435
  if (event.type === "turn.autonomous.started") {
@@ -41968,6 +42558,11 @@ var AppServerHost = class {
41968
42558
  return { ...subagent, subagentId: record4.hostThreadId };
41969
42559
  }
41970
42560
  async #refreshOpenSubagentThread(threadId2, terminal3 = true) {
42561
+ await this.#desktopRequests.run(threadId2, async () => {
42562
+ await this.#refreshOpenSubagentThreadBody(threadId2, terminal3);
42563
+ });
42564
+ }
42565
+ async #refreshOpenSubagentThreadBody(threadId2, terminal3) {
41971
42566
  const child = this.#externalRuntime.get(threadId2);
41972
42567
  if (!child) return;
41973
42568
  const previousItems = new Map(
@@ -42067,7 +42662,7 @@ var AppServerHost = class {
42067
42662
  }
42068
42663
  if (status2 === "idle" && previousStatus === "active") {
42069
42664
  for (const [index, waitMs] of SUBAGENT_TERMINAL_REFRESH_DELAYS_MS.entries()) {
42070
- if (waitMs > 0) await delay3(waitMs);
42665
+ if (waitMs > 0) await delay4(waitMs);
42071
42666
  await this.#refreshOpenSubagentThread(
42072
42667
  threadId2,
42073
42668
  index === SUBAGENT_TERMINAL_REFRESH_DELAYS_MS.length - 1
@@ -42445,7 +43040,7 @@ import { randomUUID as randomUUID15 } from "node:crypto";
42445
43040
  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
43041
  import { uptime } from "node:os";
42447
43042
  import path27 from "node:path";
42448
- import { setTimeout as delay4 } from "node:timers/promises";
43043
+ import { setTimeout as delay5 } from "node:timers/promises";
42449
43044
  var LOCK_RETRY_COUNT = 200;
42450
43045
  var LOCK_RETRY_DELAY_MS = 25;
42451
43046
  var LOCK_MALFORMED_GRACE_MS = 1e3;
@@ -42701,7 +43296,7 @@ async function withRemoteAppServerSocketInitializationLock(socketPath, action) {
42701
43296
  return await action();
42702
43297
  }
42703
43298
  }
42704
- await delay4(LOCK_RETRY_DELAY_MS);
43299
+ await delay5(LOCK_RETRY_DELAY_MS);
42705
43300
  }
42706
43301
  throw new Error(
42707
43302
  `Remote app-server socket initialization is already in progress at ${socketPath}`
@@ -43992,15 +44587,28 @@ var DelegationControlRegistry = class {
43992
44587
  return (await this.#registrationForThread(input.threadId)).cancel(input);
43993
44588
  }
43994
44589
  async read(input) {
43995
- if (input.hostId !== void 0 && input.hostId !== "local") {
43996
- if (!input.hostId || !this.#remoteRead)
44590
+ const { callerThreadId: callerThreadId2, ...read } = input;
44591
+ if (read.hostId !== void 0 && read.hostId !== "local") {
44592
+ if (typeof callerThreadId2 === "string" && callerThreadId2) {
44593
+ const callers = await this.#matching(
44594
+ (registration) => registration.executionHostId?.(callerThreadId2) === read.hostId && registration.ownsThread(callerThreadId2)
44595
+ );
44596
+ if (callers.length > 1)
44597
+ only(callers, "Calling Thread has ambiguous execution Host context");
44598
+ if (callers.length === 1) {
44599
+ const { hostId: hostId2, ...local } = read;
44600
+ const snapshot2 = await (await this.#registrationForThread(local.threadId)).read(local);
44601
+ return { ...snapshot2, hostId: hostId2 };
44602
+ }
44603
+ }
44604
+ if (!read.hostId || !this.#remoteRead)
43997
44605
  throw new DelegationControlError(
43998
44606
  "RUNTIME_UNREACHABLE",
43999
44607
  "Remote Thread reading is unavailable"
44000
44608
  );
44001
- return this.#remoteRead(input);
44609
+ return this.#remoteRead(read);
44002
44610
  }
44003
- return (await this.#registrationForThread(input.threadId)).read(input);
44611
+ return (await this.#registrationForThread(read.threadId)).read(read);
44004
44612
  }
44005
44613
  async wait(input) {
44006
44614
  if (input.hostId !== void 0 && input.hostId !== "local")
@@ -45195,13 +45803,15 @@ function createHostUpdateCoordinator(options2) {
45195
45803
  return authenticated ?? fetchLatestGitHubRelease({ signal: requestSignal });
45196
45804
  });
45197
45805
  let candidate = null;
45806
+ let currentStatusPath = null;
45198
45807
  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;
45808
+ if (!currentStatusPath) {
45809
+ const active = await discoverActiveUpdateStatus(context.common.stateDirectory);
45810
+ if (!active) return null;
45811
+ currentStatusPath = active.statusPath;
45203
45812
  }
45204
- return publicStatus(discovered.status);
45813
+ const status2 = await manager.readStatus(currentStatusPath);
45814
+ return status2 ? publicStatus(status2) : null;
45205
45815
  }
45206
45816
  async function installable(context, release) {
45207
45817
  if (context.installation.kind === "npm") return true;
@@ -45285,6 +45895,7 @@ function createHostUpdateCoordinator(options2) {
45285
45895
  if (existing) return { status: existing };
45286
45896
  throw new Error("Another update operation is already active");
45287
45897
  }
45898
+ currentStatusPath = null;
45288
45899
  let resolvePrepared;
45289
45900
  let rejectPrepared;
45290
45901
  const preparedReady = new Promise((resolve, reject) => {
@@ -45298,6 +45909,7 @@ function createHostUpdateCoordinator(options2) {
45298
45909
  }
45299
45910
  const onPrepared = async (info) => {
45300
45911
  await lock.setStatusPath(info.statusPath);
45912
+ currentStatusPath = info.statusPath;
45301
45913
  resolvePrepared(info);
45302
45914
  };
45303
45915
  const prepareAndStart = async () => {
@@ -45327,7 +45939,7 @@ function createHostUpdateCoordinator(options2) {
45327
45939
  onPrepared
45328
45940
  });
45329
45941
  }
45330
- if (platform !== "darwin") manager.start(prepared2);
45942
+ if (platform !== "darwin") await manager.start(prepared2);
45331
45943
  } catch (error51) {
45332
45944
  await lock.release();
45333
45945
  rejectPrepared(error51);
@@ -45364,6 +45976,20 @@ import { setImmediate as yieldToEventLoop } from "node:timers/promises";
45364
45976
  // packages/harness-adapter/dist/usage-statistics.js
45365
45977
  var MAX_SESSION_ID_LENGTH = 512;
45366
45978
  var MAX_CWD_LENGTH = 4096;
45979
+ var MAX_SESSION_TITLE_LENGTH = 200;
45980
+ function usageSessionTitle(value2) {
45981
+ if (typeof value2 !== "string")
45982
+ return void 0;
45983
+ const normalized = value2.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
45984
+ if (!normalized)
45985
+ return void 0;
45986
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
45987
+ return normalized;
45988
+ const characters = [...normalized];
45989
+ if (characters.length <= MAX_SESSION_TITLE_LENGTH)
45990
+ return normalized;
45991
+ return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
45992
+ }
45367
45993
  function sessionIdOk(value2) {
45368
45994
  return typeof value2 === "string" && value2.length > 0 && value2.length <= MAX_SESSION_ID_LENGTH;
45369
45995
  }
@@ -45407,6 +46033,12 @@ function parseHarnessUsageEntry(value2) {
45407
46033
  return null;
45408
46034
  if (entry.cwd !== void 0 && !cwdOk(entry.cwd))
45409
46035
  return null;
46036
+ if (entry.sessionTitle !== void 0) {
46037
+ const sessionTitle = usageSessionTitle(entry.sessionTitle);
46038
+ if (sessionTitle === void 0)
46039
+ return null;
46040
+ entry.sessionTitle = sessionTitle;
46041
+ }
45410
46042
  if (entry.tokensUnknown !== void 0 && entry.tokensUnknown !== true)
45411
46043
  return null;
45412
46044
  if (entry.costUsd !== void 0 && (typeof entry.costUsd !== "number" || !Number.isFinite(entry.costUsd) || entry.costUsd < 0)) {
@@ -45418,8 +46050,31 @@ function parseHarnessUsageEntry(value2) {
45418
46050
  return entry;
45419
46051
  }
45420
46052
 
46053
+ // packages/host-runtime/src/usage-session-titles.ts
46054
+ function withHostSessionTitles(result, records) {
46055
+ const titles = /* @__PURE__ */ new Map();
46056
+ for (const record4 of records) {
46057
+ const ref = record4.nativeSessionRef;
46058
+ const title = usageSessionTitle(record4.title);
46059
+ if (record4.state !== "ready" || !ref || ref.harnessId !== record4.harnessId || !title) continue;
46060
+ const key = `${record4.harnessId}\0${ref.nativeSessionId}`;
46061
+ const previous = titles.get(key);
46062
+ if (!previous || record4.updatedAt > previous.updatedAt)
46063
+ titles.set(key, { title, updatedAt: record4.updatedAt });
46064
+ }
46065
+ const decorate = (sessions) => sessions.map((session) => {
46066
+ const title = titles.get(`${session.harness}\0${session.sessionId}`)?.title;
46067
+ return title ? { ...session, title } : session;
46068
+ });
46069
+ return {
46070
+ ...result,
46071
+ sessions: decorate(result.sessions),
46072
+ ...result.recentSessions ? { recentSessions: decorate(result.recentSessions) } : {}
46073
+ };
46074
+ }
46075
+
45421
46076
  // packages/host-runtime/src/usage-statistics.ts
45422
- var CACHE_VERSION = 6;
46077
+ var CACHE_VERSION = 7;
45423
46078
  var STALE_AFTER_MS = 1e4;
45424
46079
  var WARM_DELAY_MS = 3e3;
45425
46080
  var PERSIST_INTERVAL_MS = 6e4;
@@ -45439,7 +46094,8 @@ function compact(entry) {
45439
46094
  entry.cwd ?? null,
45440
46095
  entry.costUsd ?? null,
45441
46096
  entry.credits ?? null,
45442
- entry.tokensUnknown === true
46097
+ entry.tokensUnknown === true,
46098
+ entry.sessionTitle ?? null
45443
46099
  ];
45444
46100
  }
45445
46101
  function interner() {
@@ -45453,9 +46109,9 @@ function interner() {
45453
46109
  };
45454
46110
  }
45455
46111
  function expand(value2, intern) {
45456
- if (!Array.isArray(value2) || value2.length !== 14) return null;
46112
+ if (!Array.isArray(value2) || value2.length !== 15) return null;
45457
46113
  const [id2, occurredAtMs, model2, input, cached2, written, written1h, output, reasoning] = value2;
45458
- const [sessionId, cwd, costUsd, credits, tokensUnknown] = value2.slice(9);
46114
+ const [sessionId, cwd, costUsd, credits, tokensUnknown, sessionTitle] = value2.slice(9);
45459
46115
  return parseHarnessUsageEntry({
45460
46116
  id: id2,
45461
46117
  occurredAtMs,
@@ -45470,7 +46126,8 @@ function expand(value2, intern) {
45470
46126
  ...cwd !== null ? { cwd: intern(cwd) } : {},
45471
46127
  ...costUsd !== null ? { costUsd } : {},
45472
46128
  ...credits !== null ? { credits } : {},
45473
- ...tokensUnknown === true ? { tokensUnknown } : {}
46129
+ ...tokensUnknown === true ? { tokensUnknown } : {},
46130
+ ...sessionTitle !== null ? { sessionTitle: intern(sessionTitle) } : {}
45474
46131
  });
45475
46132
  }
45476
46133
  function message(error51) {
@@ -45561,6 +46218,7 @@ var UsageStatistics = class {
45561
46218
  #caches = /* @__PURE__ */ new Map();
45562
46219
  #failures = /* @__PURE__ */ new Map();
45563
46220
  #sources = null;
46221
+ #readThreadTitles;
45564
46222
  #loaded = null;
45565
46223
  #refreshing = null;
45566
46224
  #refreshedAtMs = 0;
@@ -45575,9 +46233,10 @@ var UsageStatistics = class {
45575
46233
  this.#options = options2;
45576
46234
  this.#directory = path37.join(options2.directory, `v${CACHE_VERSION}`);
45577
46235
  }
45578
- /** The Harnesses to read; call once their plugins are loaded. */
45579
- attach(sources) {
46236
+ /** Attach native storage and, optionally, fresh persisted Desktop title metadata. */
46237
+ attach(sources, readThreadTitles) {
45580
46238
  this.#sources = sources;
46239
+ this.#readThreadTitles = readThreadTitles;
45581
46240
  this.#scheduleWarm();
45582
46241
  }
45583
46242
  /** Reads every source in the background soon after the sources are attached. */
@@ -45604,11 +46263,19 @@ var UsageStatistics = class {
45604
46263
  }
45605
46264
  const now = this.#now();
45606
46265
  if (!this.#refreshing && now - this.#refreshedAtMs > STALE_AFTER_MS) this.#startRefresh();
45607
- return this.#aggregate(
46266
+ const result = this.#aggregate(
45608
46267
  typeof params === "string" ? { range: params } : params,
45609
46268
  now,
45610
46269
  await this.#options.prices.lookup()
45611
46270
  );
46271
+ if (this.#readThreadTitles && (result.sessions.length || result.recentSessions?.length)) {
46272
+ try {
46273
+ return withHostSessionTitles(result, await this.#readThreadTitles());
46274
+ } catch (error51) {
46275
+ this.#options.diagnose?.(`Usage statistics Thread titles unavailable: ${message(error51)}`);
46276
+ }
46277
+ }
46278
+ return result;
45612
46279
  }
45613
46280
  /** Completes the current refresh, for tests and callers that need a settled result. */
45614
46281
  async settled() {
@@ -45886,6 +46553,10 @@ var UsageStatistics = class {
45886
46553
  sessions.set(key, session);
45887
46554
  }
45888
46555
  session.project ??= project2;
46556
+ if (entry.sessionTitle && (session.titleAtMs === void 0 || entry.occurredAtMs >= session.titleAtMs)) {
46557
+ session.title = entry.sessionTitle;
46558
+ session.titleAtMs = entry.occurredAtMs;
46559
+ }
45889
46560
  if (model2 !== null) session.models.set(model2, (session.models.get(model2) ?? 0) + 1);
45890
46561
  session.firstAtMs = Math.min(session.firstAtMs, entry.occurredAtMs);
45891
46562
  session.lastAtMs = Math.max(session.lastAtMs, entry.occurredAtMs);
@@ -45893,21 +46564,26 @@ var UsageStatistics = class {
45893
46564
  }
45894
46565
  }
45895
46566
  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) => ({
46567
+ const toSession = (session) => ({
45901
46568
  harness: session.harness,
45902
46569
  sessionId: session.sessionId,
45903
46570
  project: session.project,
46571
+ ...session.title ? { title: session.title } : {},
45904
46572
  models: [...session.models].sort((left, right) => right[1] - left[1]).slice(0, MODELS_PER_SESSION).map(([name]) => name),
45905
46573
  firstAtMs: session.firstAtMs,
45906
46574
  lastAtMs: session.lastAtMs,
45907
46575
  ...session.totals
45908
- })).sort(
46576
+ });
46577
+ const top = /* @__PURE__ */ new Set([
46578
+ ...[...allSessions].sort((left, right) => right.totals.costUsd - left.totals.costUsd).slice(0, SESSIONS_PER_MEASURE),
46579
+ ...[...allSessions].sort((left, right) => tokensWithoutCache(right.totals) - tokensWithoutCache(left.totals)).slice(0, SESSIONS_PER_MEASURE)
46580
+ ]);
46581
+ const sessionList = [...top].map(toSession).sort(
45909
46582
  (left, right) => right.costUsd - left.costUsd || tokensWithoutCache(right) - tokensWithoutCache(left)
45910
46583
  );
46584
+ const recentSessions = [...allSessions].sort(
46585
+ (left, right) => right.lastAtMs - left.lastAtMs || right.firstAtMs - left.firstAtMs || left.sessionId.localeCompare(right.sessionId)
46586
+ ).slice(0, SESSIONS_PER_MEASURE).map(toSession);
45911
46587
  if (unlistedModel) this.#options.prices.missing();
45912
46588
  const byName = (left, right) => left === right ? 0 : left === null ? 1 : right === null ? -1 : left.localeCompare(right);
45913
46589
  return {
@@ -45952,7 +46628,8 @@ var UsageStatistics = class {
45952
46628
  byHarness: grouped(byHarness, (name) => ({ harness: name })),
45953
46629
  byModel: grouped(byModel, (name) => ({ model: name })).slice(0, 4096).map((row) => ({ ...row, harnessPricedRequests: harnessPriced.get(row.model) ?? 0 })),
45954
46630
  byProject: grouped(byProject, (name) => ({ project: name })).slice(0, 4096),
45955
- sessions: sessionList
46631
+ sessions: sessionList,
46632
+ recentSessions
45956
46633
  };
45957
46634
  }
45958
46635
  };
@@ -45987,9 +46664,21 @@ function requiredRuntimeConfiguration(environment) {
45987
46664
  if (!stockCodexPath) throw new Error(`${STOCK_CODEX_PATH_ENV} is required`);
45988
46665
  return { stockCodexPath };
45989
46666
  }
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];
46667
+ function delegationCliEnvironment(environment, hostRuntimePath) {
46668
+ let packagedCli;
46669
+ if (hostRuntimePath && path38.isAbsolute(hostRuntimePath)) {
46670
+ const candidate = path38.resolve(
46671
+ path38.dirname(hostRuntimePath),
46672
+ "../bin",
46673
+ process.platform === "win32" ? "codexhost.exe" : "codexhost"
46674
+ );
46675
+ try {
46676
+ if (statSync(candidate).isFile()) packagedCli = candidate;
46677
+ } catch {
46678
+ }
46679
+ }
46680
+ const cliPath = environment[DELEGATION_CLI_PATH_ENV] ?? environment[UPDATE_RUNTIME_ENV.launcherExecutable] ?? packagedCli;
46681
+ const nodePath2 = environment[DELEGATION_CLI_NODE_PATH_ENV] ?? environment[UPDATE_RUNTIME_ENV.npmNodePath] ?? (packagedCli && cliPath === packagedCli ? process.execPath : void 0);
45993
46682
  return {
45994
46683
  ...cliPath ? { [DELEGATION_CLI_PATH_ENV]: cliPath } : {},
45995
46684
  ...nodePath2 && path38.isAbsolute(nodePath2) ? { [DELEGATION_CLI_NODE_PATH_ENV]: nodePath2 } : {}
@@ -46007,7 +46696,7 @@ async function prepareDelegationRuntime(input) {
46007
46696
  const server = await startDelegationControlServer({ token, api: registry2, watchApi: registry2 });
46008
46697
  const environment = {
46009
46698
  ...input.environment,
46010
- ...delegationCliEnvironment(input.environment),
46699
+ ...delegationCliEnvironment(input.environment, input.hostRuntimePath),
46011
46700
  [DELEGATION_RUNTIME_ENDPOINT_ENV]: server.endpoint,
46012
46701
  [DELEGATION_RUNTIME_TOKEN_ENV]: token
46013
46702
  };
@@ -46083,6 +46772,7 @@ async function runHostRuntime(input) {
46083
46772
  const environment = remoteControlPlan?.environment ?? input.environment;
46084
46773
  return prepareDelegationRuntime({
46085
46774
  environment,
46775
+ ...hostRuntimePath ? { hostRuntimePath } : {},
46086
46776
  createHost: async (delegationEnvironment, onDelegationApi, registry2) => {
46087
46777
  const official = await prepareLocalCodex({
46088
46778
  stockCodexPath,
@@ -46193,6 +46883,7 @@ async function runHostRuntime(input) {
46193
46883
  if (!listenUrl) throw new Error("Remote app-server listener URL is unavailable");
46194
46884
  return prepareDelegationRuntime({
46195
46885
  environment: input.environment,
46886
+ ...hostRuntimePath ? { hostRuntimePath } : {},
46196
46887
  createHost: async (delegationEnvironment, _onDelegationApi, registry2) => {
46197
46888
  const socketPath = remoteAppServerSocketPath(delegationEnvironment, listenUrl);
46198
46889
  const officialPlan = createRemoteOfficialAppServerPlan(input.arguments, socketPath);
@@ -48505,7 +49196,7 @@ import {
48505
49196
  readdirSync,
48506
49197
  renameSync,
48507
49198
  rmSync,
48508
- statSync,
49199
+ statSync as statSync2,
48509
49200
  writeFileSync
48510
49201
  } from "node:fs";
48511
49202
  import os12 from "node:os";
@@ -48535,7 +49226,7 @@ function pruneRuntimeLogs(input) {
48535
49226
  if (!Number.isSafeInteger(pid)) continue;
48536
49227
  try {
48537
49228
  const filePath = path43.join(input.directory, entry.name);
48538
- const stats = statSync(filePath);
49229
+ const stats = statSync2(filePath);
48539
49230
  files.push({
48540
49231
  filePath,
48541
49232
  pid,