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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14598,6 +14598,15 @@ var harnessDisplaySetSchema = external_exports.strictObject({
14598
14598
  initializeOnly: external_exports.boolean().optional()
14599
14599
  });
14600
14600
 
14601
+ // ../../shared-contracts/dist/harness-presentation.js
14602
+ var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
14603
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text2) => text2.trim().length > 0);
14604
+ var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
14605
+ label: displayText(256).optional(),
14606
+ description: displayText(1024).optional()
14607
+ }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
14608
+ var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
14609
+
14601
14610
  // ../../shared-contracts/dist/model-price-overrides.js
14602
14611
  var usdPerMillionTokens = external_exports.number().finite().nonnegative();
14603
14612
  var modelPriceOverrideSchema = external_exports.strictObject({
@@ -14676,6 +14685,8 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
14676
14685
  harness,
14677
14686
  sessionId: external_exports.string().min(1).max(512),
14678
14687
  project: project.nullable(),
14688
+ /** Persisted Desktop title for a mapped Session, otherwise its native name; may be absent. */
14689
+ title: external_exports.string().min(1).max(200).optional(),
14679
14690
  /** Models the session used, most requests first. */
14680
14691
  models: external_exports.array(model).max(16),
14681
14692
  firstAtMs: count,
@@ -14742,7 +14753,12 @@ var usageStatisticsResultSchema = external_exports.strictObject({
14742
14753
  * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
14743
14754
  * requests without a native session are not listed here but count everywhere else.
14744
14755
  */
14745
- sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
14756
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100),
14757
+ /**
14758
+ * The sessions last active in the range, newest first, all filters applied. Optional for older
14759
+ * Hosts; missing is treated as no list rather than no sessions.
14760
+ */
14761
+ recentSessions: external_exports.array(usageStatisticsSessionSchema).max(100).optional()
14746
14762
  });
14747
14763
 
14748
14764
  // ../../shared-contracts/dist/ids.js
@@ -15011,8 +15027,24 @@ var threadUsageSnapshotSchema = external_exports.object({
15011
15027
  }
15012
15028
  });
15013
15029
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
15030
+ var accountCreditsPeriodSchema = external_exports.enum([
15031
+ "weekly",
15032
+ "monthly",
15033
+ "five_hour",
15034
+ "seven_day",
15035
+ "unknown"
15036
+ ]);
15037
+ var accountCreditsScopeSchema = external_exports.object({
15038
+ id: external_exports.string().min(1).max(256),
15039
+ label: external_exports.string().min(1).max(256),
15040
+ localizations: harnessLocalizationsSchema.optional()
15041
+ }).strict();
15014
15042
  var accountCreditsProductUsageSchema = external_exports.object({
15015
15043
  product: external_exports.string().min(1),
15044
+ /** Native period and scope, never inferred from the display name. */
15045
+ periodType: accountCreditsPeriodSchema.optional(),
15046
+ scope: accountCreditsScopeSchema.optional(),
15047
+ localizations: harnessLocalizationsSchema.optional(),
15016
15048
  used: external_exports.number().finite().nonnegative().optional(),
15017
15049
  // Zero is a real empty cap, not an absent field.
15018
15050
  limit: external_exports.number().finite().nonnegative().optional(),
@@ -15034,8 +15066,10 @@ var accountCreditsSnapshotSchema = external_exports.object({
15034
15066
  label: external_exports.string().min(1).optional(),
15035
15067
  usedPercent: usagePercentSchema.optional(),
15036
15068
  remaining: external_exports.number().finite().optional(),
15069
+ scope: accountCreditsScopeSchema.optional(),
15070
+ localizations: harnessLocalizationsSchema.optional(),
15037
15071
  resetsAt: external_exports.string().min(1).optional(),
15038
- periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
15072
+ periodType: accountCreditsPeriodSchema,
15039
15073
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
15040
15074
  resetCredits: accountResetCreditsSchema.optional()
15041
15075
  }).strict().superRefine((credits, context) => {
@@ -15060,7 +15094,9 @@ var threadUsageInspectionParamsSchema = external_exports.object({
15060
15094
  var threadUsageInspectionSchema = external_exports.object({
15061
15095
  threadId: hostThreadIdSchema,
15062
15096
  usage: threadUsageSnapshotSchema.nullable(),
15063
- accountCredits: accountCreditsSnapshotSchema.optional()
15097
+ accountCredits: accountCreditsSnapshotSchema.optional(),
15098
+ /** Whether this source can provide cached account quota independently of usage. */
15099
+ accountCreditsSupported: external_exports.boolean().optional()
15064
15100
  }).strict();
15065
15101
 
15066
15102
  // ../../shared-contracts/dist/harness-accounts.js
@@ -15187,7 +15223,8 @@ var harnessPermissionModeSchema = external_exports.object({
15187
15223
  id: harnessPermissionModeIdSchema,
15188
15224
  label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
15189
15225
  description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
15190
- dangerous: external_exports.boolean().optional()
15226
+ dangerous: external_exports.boolean().optional(),
15227
+ localizations: harnessLocalizationsSchema.optional()
15191
15228
  }).strict();
15192
15229
  var harnessPermissionModeCatalogSchema = external_exports.object({
15193
15230
  modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
@@ -15510,6 +15547,8 @@ var harnessInstallationStateSchema = external_exports.object({
15510
15547
  // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
15511
15548
  message: external_exports.string().max(2048).optional(),
15512
15549
  messageCode: external_exports.string().min(1).max(128).optional(),
15550
+ /** Safe plugin-owned explanation, distinct from raw diagnostic message. */
15551
+ notice: harnessLocalizedTextSchema.optional(),
15513
15552
  latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
15514
15553
  }).strict();
15515
15554
 
@@ -15648,6 +15687,7 @@ var harnessCommandDescriptorSchema = external_exports.object({
15648
15687
  invocation: commandInvocationSchema,
15649
15688
  label: commandLabelSchema,
15650
15689
  description: commandDescriptionSchema.optional(),
15690
+ localizations: harnessLocalizationsSchema.optional(),
15651
15691
  argumentMode: external_exports.enum(["none", "text"]),
15652
15692
  /**
15653
15693
  * Native distinction reported by the Harness. Omitted when the Harness does
@@ -15909,8 +15949,24 @@ import path from "node:path";
15909
15949
  import { setImmediate as yieldToEventLoop } from "node:timers/promises";
15910
15950
 
15911
15951
  // ../../harness-adapter/dist/usage-statistics.js
15952
+ import { createReadStream } from "node:fs";
15953
+ import { createInterface } from "node:readline";
15912
15954
  var MAX_SESSION_ID_LENGTH = 512;
15913
15955
  var MAX_CWD_LENGTH = 4096;
15956
+ var MAX_SESSION_TITLE_LENGTH = 200;
15957
+ function usageSessionTitle(value) {
15958
+ if (typeof value !== "string")
15959
+ return void 0;
15960
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
15961
+ if (!normalized)
15962
+ return void 0;
15963
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
15964
+ return normalized;
15965
+ const characters = [...normalized];
15966
+ if (characters.length <= MAX_SESSION_TITLE_LENGTH)
15967
+ return normalized;
15968
+ return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
15969
+ }
15914
15970
  function sessionIdOk(value) {
15915
15971
  return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
15916
15972
  }
@@ -15920,12 +15976,14 @@ function cwdOk(value) {
15920
15976
  function withUsageSession(entry, session) {
15921
15977
  const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
15922
15978
  const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
15979
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
15923
15980
  if (sessionId === void 0 && cwd === void 0)
15924
15981
  return entry;
15925
15982
  return {
15926
15983
  ...entry,
15927
15984
  ...sessionId !== void 0 ? { sessionId } : {},
15928
- ...cwd !== void 0 ? { cwd } : {}
15985
+ ...cwd !== void 0 ? { cwd } : {},
15986
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
15929
15987
  };
15930
15988
  }
15931
15989
  function tokenCount(value) {
@@ -15965,6 +16023,12 @@ function parseHarnessUsageEntry(value) {
15965
16023
  return null;
15966
16024
  if (entry.cwd !== void 0 && !cwdOk(entry.cwd))
15967
16025
  return null;
16026
+ if (entry.sessionTitle !== void 0) {
16027
+ const sessionTitle = usageSessionTitle(entry.sessionTitle);
16028
+ if (sessionTitle === void 0)
16029
+ return null;
16030
+ entry.sessionTitle = sessionTitle;
16031
+ }
15968
16032
  if (entry.tokensUnknown !== void 0 && entry.tokensUnknown !== true)
15969
16033
  return null;
15970
16034
  if (entry.costUsd !== void 0 && (typeof entry.costUsd !== "number" || !Number.isFinite(entry.costUsd) || entry.costUsd < 0)) {
@@ -15975,6 +16039,25 @@ function parseHarnessUsageEntry(value) {
15975
16039
  }
15976
16040
  return entry;
15977
16041
  }
16042
+ async function* jsonlRecords(file2, marker, signal) {
16043
+ const lines = createInterface({
16044
+ input: createReadStream(file2, { encoding: "utf8", signal }),
16045
+ crlfDelay: Infinity
16046
+ });
16047
+ for await (const line of lines) {
16048
+ if (!line.includes(marker))
16049
+ continue;
16050
+ let value;
16051
+ try {
16052
+ value = JSON.parse(line);
16053
+ } catch {
16054
+ continue;
16055
+ }
16056
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
16057
+ yield value;
16058
+ }
16059
+ }
16060
+ }
15978
16061
  function nativeTimeMs(value) {
15979
16062
  const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
15980
16063
  return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
@@ -16383,7 +16466,7 @@ var CodexCounters = class {
16383
16466
  };
16384
16467
 
16385
16468
  // dist/rollout-io.js
16386
- import { createReadStream } from "node:fs";
16469
+ import { createReadStream as createReadStream2 } from "node:fs";
16387
16470
  import { StringDecoder } from "node:string_decoder";
16388
16471
  import { promisify } from "node:util";
16389
16472
  import { zstdDecompress } from "node:zlib";
@@ -16448,7 +16531,7 @@ function frameSize(data) {
16448
16531
  }
16449
16532
  async function* rolloutBytes(file2, signal) {
16450
16533
  signal.throwIfAborted();
16451
- const stream = createReadStream(file2, { signal });
16534
+ const stream = createReadStream2(file2, { signal });
16452
16535
  let pending = Buffer.alloc(0);
16453
16536
  try {
16454
16537
  for await (const value of stream) {
@@ -16540,32 +16623,84 @@ async function copyRelation(a, b, signal) {
16540
16623
  // dist/usage-statistics.js
16541
16624
  var ROLLOUT = /^rollout-.*?([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})(?:[_-][0-9a-f-]+)?\.jsonl(?:\.zst)?$/iu;
16542
16625
  var text = (value) => typeof value === "string" ? value : "";
16626
+ var ROW_KINDS = /* @__PURE__ */ new Set([
16627
+ "session_meta",
16628
+ "turn_context",
16629
+ "token_usage_record",
16630
+ "compacted",
16631
+ "event_msg",
16632
+ "response_item"
16633
+ ]);
16634
+ var HEAD_TYPE = /"type"\s*:\s*"([^"]+)"/u;
16635
+ var TAIL_TYPE = /"type"\s*:\s*"([^"]+)"\s*\}\s*$/u;
16636
+ function rowKind(line) {
16637
+ const head = HEAD_TYPE.exec(line.slice(0, 1024))?.[1];
16638
+ if (head && ROW_KINDS.has(head))
16639
+ return head;
16640
+ return TAIL_TYPE.exec(line.slice(-1024))?.[1] ?? head;
16641
+ }
16543
16642
  async function stamp(file2) {
16544
16643
  const s = await lstat(file2, { bigint: true });
16545
16644
  if (!s.isFile())
16546
16645
  throw new Error("Codex rollout is not a regular file");
16547
16646
  return `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
16548
16647
  }
16549
- function fingerprint(files) {
16550
- return createHash("sha256").update(JSON.stringify(files)).digest("hex");
16648
+ function fingerprint(files, extra = "") {
16649
+ return createHash("sha256").update(JSON.stringify(files)).update(extra).digest("hex");
16551
16650
  }
16552
- async function readCodexRollouts(files, thread, signal) {
16651
+ function typedPrompt(value) {
16652
+ if (typeof value !== "string")
16653
+ return void 0;
16654
+ const text2 = value.trim();
16655
+ if (!text2 || text2.startsWith("<") || text2.startsWith("# AGENTS.md") || text2.startsWith("<!--")) {
16656
+ return void 0;
16657
+ }
16658
+ return usageSessionTitle(text2);
16659
+ }
16660
+ function userItemPrompt(payload) {
16661
+ if (!payload || payload.type !== "message" || payload.role !== "user")
16662
+ return void 0;
16663
+ if (!Array.isArray(payload.content))
16664
+ return typedPrompt(payload.content);
16665
+ for (const part of payload.content) {
16666
+ if (typeof part !== "object" || part === null)
16667
+ continue;
16668
+ const block = part;
16669
+ if (block.type === "input_text" || block.type === "text") {
16670
+ const prompt = typedPrompt(block.text);
16671
+ if (prompt)
16672
+ return prompt;
16673
+ }
16674
+ }
16675
+ return void 0;
16676
+ }
16677
+ async function readThreadNames(home, signal) {
16678
+ const names = /* @__PURE__ */ new Map();
16679
+ try {
16680
+ for await (const line of jsonlRecords(path.join(home, "session_index.jsonl"), '"thread_name"', signal)) {
16681
+ const id = text(line.id);
16682
+ const name = usageSessionTitle(line.thread_name);
16683
+ if (id && name)
16684
+ names.set(id, name);
16685
+ }
16686
+ } catch (error51) {
16687
+ if (error51.code !== "ENOENT")
16688
+ throw error51;
16689
+ }
16690
+ return names;
16691
+ }
16692
+ async function readCodexRollouts(files, thread, signal, options = {}) {
16553
16693
  const counters = new CodexCounters();
16554
- let model2 = "", cwd = "", ownFrom = null, firstMeta = false, forkAt = 0, seen = 0;
16694
+ let model2 = "", cwd = "", ownFrom = null, firstMeta = false, forkAt = 0, seen = 0, firstPrompt;
16555
16695
  for (const file2 of files) {
16556
16696
  for await (const line of rolloutLines(file2, signal)) {
16557
16697
  signal.throwIfAborted();
16558
16698
  if (++seen % 128 === 0)
16559
16699
  await yieldToEventLoop(void 0, { signal });
16560
- const kind = /"type"\s*:\s*"([^"]+)"/u.exec(line.slice(0, 1024))?.[1];
16561
- if (!kind || ![
16562
- "session_meta",
16563
- "turn_context",
16564
- "token_usage_record",
16565
- "compacted",
16566
- "event_msg",
16567
- "response_item"
16568
- ].includes(kind))
16700
+ const kind = rowKind(line);
16701
+ if (!kind && line.trim())
16702
+ options.onIncomplete?.();
16703
+ if (!kind || !ROW_KINDS.has(kind))
16569
16704
  continue;
16570
16705
  if (kind === "response_item" && !/"role"\s*:\s*"user"/u.test(line.slice(0, 1024)))
16571
16706
  continue;
@@ -16575,19 +16710,24 @@ async function readCodexRollouts(files, thread, signal) {
16575
16710
  try {
16576
16711
  row = object2(JSON.parse(line));
16577
16712
  } catch {
16713
+ options.onIncomplete?.();
16578
16714
  continue;
16579
16715
  }
16580
16716
  const p = object2(row?.payload);
16581
16717
  const at = nativeTimeMs(row?.timestamp);
16582
- if (!row || !p || at === null)
16718
+ if (!row || !p || at === null) {
16719
+ options.onIncomplete?.();
16583
16720
  continue;
16721
+ }
16584
16722
  switch (row.type) {
16585
16723
  case "session_meta": {
16586
16724
  if (!firstMeta) {
16587
16725
  if (text(p.id) !== thread)
16588
16726
  throw new Error("Codex rollout identity does not match its source");
16589
- if (p.forked_from_id || p.parent_thread_id || p.subagent_history_start_ordinal)
16727
+ if (p.forked_from_id || p.parent_thread_id || p.subagent_history_start_ordinal) {
16590
16728
  forkAt = nativeTimeMs(p.timestamp) ?? at;
16729
+ options.onIncomplete?.();
16730
+ }
16591
16731
  cwd = text(p.cwd);
16592
16732
  firstMeta = true;
16593
16733
  }
@@ -16601,30 +16741,41 @@ async function readCodexRollouts(files, thread, signal) {
16601
16741
  counters.context("", text(p.turn_id), model2);
16602
16742
  break;
16603
16743
  case "token_usage_record":
16744
+ if (!usage(p.usage) || !text(p.response_id))
16745
+ options.onIncomplete?.();
16604
16746
  counters.record(at, model2, p);
16605
16747
  break;
16606
16748
  case "compacted": {
16607
16749
  const record2 = object2(p.latest_token_usage_record);
16608
- if (record2 && p.compaction_response_id && record2.response_id === p.compaction_response_id)
16750
+ if (record2 && p.compaction_response_id && record2.response_id === p.compaction_response_id) {
16751
+ if (!usage(record2.usage))
16752
+ options.onIncomplete?.();
16609
16753
  counters.record(at, model2, record2, true);
16754
+ }
16610
16755
  break;
16611
16756
  }
16612
16757
  case "response_item":
16613
16758
  counters.boundary();
16759
+ firstPrompt ??= userItemPrompt(p);
16614
16760
  break;
16615
16761
  case "event_msg":
16616
16762
  if (p.type === "task_started") {
16617
16763
  counters.context("", text(p.turn_id), "");
16618
16764
  counters.boundary();
16619
16765
  }
16620
- if (p.type === "user_message")
16766
+ if (p.type === "user_message") {
16621
16767
  counters.boundary();
16768
+ firstPrompt ??= typedPrompt(p.message);
16769
+ }
16622
16770
  if (p.type === "thread_settings_applied") {
16623
16771
  model2 = text(object2(p.thread_settings)?.model) || model2;
16624
16772
  counters.context("", "", model2);
16625
16773
  }
16626
16774
  if (p.type === "token_count") {
16627
16775
  const info = object2(p.info);
16776
+ options.onTokenCount?.(info);
16777
+ if (info && !usage(info.total_token_usage))
16778
+ options.onIncomplete?.();
16628
16779
  if (info)
16629
16780
  counters.count(at, model2, usage(info.total_token_usage), usage(info.last_token_usage));
16630
16781
  }
@@ -16651,12 +16802,22 @@ async function readCodexRollouts(files, thread, signal) {
16651
16802
  ...v.usage.known & 8 ? { cacheWriteInputTokens: written } : {},
16652
16803
  ...v.usage.known & 16 ? { reasoningOutputTokens: reasoning } : {}
16653
16804
  });
16654
- return entry ? [withUsageSession(entry, { sessionId: thread, cwd })] : [];
16805
+ return entry ? [withUsageSession(entry, { sessionId: thread, cwd, title: firstPrompt })] : [];
16655
16806
  });
16656
16807
  }
16657
- function createCodexUsageStatistics(environment) {
16808
+ function createCodexUsageStatistics(environment, options = {}) {
16658
16809
  const home = path.resolve(environment.CODEX_HOME || path.join(environment.HOME || environment.USERPROFILE || os.homedir(), ".codex"));
16659
16810
  const groups = /* @__PURE__ */ new Map();
16811
+ let names = /* @__PURE__ */ new Map();
16812
+ let namesStamp = "";
16813
+ async function threadNames(signal) {
16814
+ const current = await stamp(path.join(home, "session_index.jsonl")).catch(() => "-");
16815
+ if (namesStamp === current)
16816
+ return names;
16817
+ names = await readThreadNames(home, signal);
16818
+ namesStamp = current;
16819
+ return names;
16820
+ }
16660
16821
  return {
16661
16822
  async listSources(signal) {
16662
16823
  const found = /* @__PURE__ */ new Map();
@@ -16675,7 +16836,7 @@ function createCodexUsageStatistics(environment) {
16675
16836
  if (!entry.isFile())
16676
16837
  continue;
16677
16838
  const thread = ROLLOUT.exec(entry.name)?.[1];
16678
- if (!thread)
16839
+ if (!thread || options.sessionId && thread !== options.sessionId)
16679
16840
  continue;
16680
16841
  const list = found.get(thread) ?? [];
16681
16842
  list.push({ file: file2, fingerprint: await stamp(file2) });
@@ -16684,13 +16845,14 @@ function createCodexUsageStatistics(environment) {
16684
16845
  }
16685
16846
  await visit(path.join(home, "sessions"), 0);
16686
16847
  await visit(path.join(home, "archived_sessions"), 0);
16848
+ const indexStamp = options.sessionId ? "" : await stamp(path.join(home, "session_index.jsonl")).catch(() => "-");
16687
16849
  const result = [];
16688
16850
  groups.clear();
16689
16851
  for (const [thread, files] of found) {
16690
16852
  files.sort((a, b) => path.basename(a.file).localeCompare(path.basename(b.file)) || a.file.localeCompare(b.file));
16691
16853
  const id = path.join(home, `usage-thread-${thread}`);
16692
16854
  groups.set(id, { thread, files });
16693
- result.push({ id, fingerprint: fingerprint(files) });
16855
+ result.push({ id, fingerprint: fingerprint(files, indexStamp) });
16694
16856
  }
16695
16857
  return result;
16696
16858
  },
@@ -16721,11 +16883,517 @@ function createCodexUsageStatistics(environment) {
16721
16883
  if (!duplicate)
16722
16884
  kept.push(candidate);
16723
16885
  }
16724
- const entries = await readCodexRollouts(kept.map(({ file: file2 }) => file2), group.thread, signal);
16886
+ const entries = await readCodexRollouts(kept.map(({ file: file2 }) => file2), group.thread, signal, options);
16725
16887
  for (const file2 of group.files)
16726
16888
  if (await stamp(file2.file) !== file2.fingerprint)
16727
16889
  throw new Error("Codex rollout changed while reading; refresh to retry");
16728
- return entries;
16890
+ const named = options.sessionId ? void 0 : (await threadNames(signal)).get(group.thread);
16891
+ return named ? entries.map((entry) => withUsageSession(entry, {
16892
+ sessionId: entry.sessionId,
16893
+ cwd: entry.cwd,
16894
+ title: named
16895
+ })) : entries;
16896
+ }
16897
+ };
16898
+ }
16899
+
16900
+ // dist/session-usage.js
16901
+ import { setTimeout as delay } from "node:timers/promises";
16902
+
16903
+ // ../../harness-adapter/dist/usage.js
16904
+ var tokenFields = [
16905
+ "inputTokens",
16906
+ "cachedInputTokens",
16907
+ "cacheWriteInputTokens",
16908
+ "outputTokens",
16909
+ "reasoningOutputTokens",
16910
+ "totalTokens",
16911
+ "contextWindowTokens",
16912
+ "contextUsedTokens"
16913
+ ];
16914
+ var safeIntegerFields = [
16915
+ "planFiveHourResetsAtUnix",
16916
+ "planSevenDayResetsAtUnix",
16917
+ "timeToFirstOutputMs"
16918
+ ];
16919
+ var percentFields = [
16920
+ "cacheHitRatePercent",
16921
+ "sessionCacheHitRatePercent",
16922
+ "planFiveHourUsedPercent",
16923
+ "planSevenDayUsedPercent"
16924
+ ];
16925
+ var usageFields = /* @__PURE__ */ new Set([
16926
+ ...tokenFields,
16927
+ ...safeIntegerFields,
16928
+ ...percentFields,
16929
+ "sessionCacheUsage",
16930
+ "totalCostUsd",
16931
+ "totalCredits",
16932
+ "contextUsagePercent",
16933
+ "outputTokensPerSecond",
16934
+ "apiOutputTokensPerSecond",
16935
+ "costSource",
16936
+ "unpricedModels"
16937
+ ]);
16938
+ function isRecord(value) {
16939
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16940
+ }
16941
+ function parseHostUsage(value) {
16942
+ if (!isRecord(value))
16943
+ throw new Error("Harness Usage must be an object");
16944
+ const keys = Object.keys(value);
16945
+ if (keys.length === 0)
16946
+ throw new Error("Harness Usage must contain a reliable field");
16947
+ for (const key2 of keys) {
16948
+ if (!usageFields.has(key2)) {
16949
+ throw new Error(`Harness Usage contains unknown field '${key2}'`);
16950
+ }
16951
+ }
16952
+ for (const field of [
16953
+ "totalCredits",
16954
+ "contextUsagePercent",
16955
+ "apiOutputTokensPerSecond"
16956
+ ]) {
16957
+ const candidate = value[field];
16958
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16959
+ throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16960
+ }
16961
+ }
16962
+ for (const field of tokenFields) {
16963
+ const candidate = value[field];
16964
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16965
+ throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16966
+ }
16967
+ }
16968
+ for (const field of safeIntegerFields) {
16969
+ const candidate = value[field];
16970
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16971
+ throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16972
+ }
16973
+ }
16974
+ if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
16975
+ throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
16976
+ }
16977
+ if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
16978
+ throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
16979
+ }
16980
+ for (const field of ["totalCredits", "contextUsagePercent"]) {
16981
+ const candidate = value[field];
16982
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16983
+ throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16984
+ }
16985
+ }
16986
+ for (const field of percentFields) {
16987
+ const candidate = value[field];
16988
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
16989
+ throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16990
+ }
16991
+ }
16992
+ if (value.sessionCacheUsage !== void 0) {
16993
+ const totals2 = value.sessionCacheUsage;
16994
+ if (!isRecord(totals2) || Object.keys(totals2).some((key2) => key2 !== "inputTokens" && key2 !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
16995
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
16996
+ }
16997
+ }
16998
+ const hasContextUsed = value.contextUsedTokens !== void 0;
16999
+ const hasContextWindow = value.contextWindowTokens !== void 0;
17000
+ if (hasContextUsed !== hasContextWindow) {
17001
+ throw new Error("Harness Usage context fields must be provided together");
17002
+ }
17003
+ if (hasContextWindow && value.contextWindowTokens === 0) {
17004
+ throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
17005
+ }
17006
+ if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
17007
+ throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
17008
+ }
17009
+ if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
17010
+ throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
17011
+ }
17012
+ if (value.costSource !== void 0) {
17013
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
17014
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
17015
+ }
17016
+ if (value.totalCostUsd === void 0) {
17017
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
17018
+ }
17019
+ }
17020
+ if (value.unpricedModels !== void 0) {
17021
+ const models = value.unpricedModels;
17022
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
17023
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
17024
+ }
17025
+ if (value.costSource !== "publicPrice") {
17026
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
17027
+ }
17028
+ return { ...value, unpricedModels: [...models] };
17029
+ }
17030
+ return { ...value };
17031
+ }
17032
+ var requestTokenFields = [
17033
+ "inputTokens",
17034
+ "cachedInputTokens",
17035
+ "cacheWriteInputTokens",
17036
+ "cacheWrite1hInputTokens",
17037
+ "outputTokens",
17038
+ "reasoningOutputTokens",
17039
+ "startedAtMs",
17040
+ "completedAtMs"
17041
+ ];
17042
+ var requestFields = /* @__PURE__ */ new Set([
17043
+ ...requestTokenFields,
17044
+ "requestId",
17045
+ "historical",
17046
+ "model",
17047
+ "provider"
17048
+ ]);
17049
+ function parseHostUsageRequest(value) {
17050
+ if (!isRecord(value))
17051
+ throw new Error("Harness Usage request must be an object");
17052
+ for (const key2 of Object.keys(value)) {
17053
+ if (!requestFields.has(key2)) {
17054
+ throw new Error(`Harness Usage request contains unknown field '${key2}'`);
17055
+ }
17056
+ }
17057
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17058
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17059
+ }
17060
+ for (const field of ["model", "provider"]) {
17061
+ const candidate = value[field];
17062
+ if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17063
+ throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
17064
+ }
17065
+ }
17066
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17067
+ throw new Error("Harness Usage request 'historical' must be a boolean");
17068
+ }
17069
+ for (const field of requestTokenFields) {
17070
+ const candidate = value[field];
17071
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17072
+ throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
17073
+ }
17074
+ }
17075
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17076
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
17077
+ }
17078
+ const request = value;
17079
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17080
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17081
+ }
17082
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17083
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17084
+ }
17085
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17086
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17087
+ }
17088
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17089
+ throw new Error("Harness Usage request timing fields must be provided together");
17090
+ }
17091
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17092
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17093
+ }
17094
+ return { ...request };
17095
+ }
17096
+
17097
+ // dist/session-observation.js
17098
+ var integer2 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
17099
+ function tokenSnapshot(value) {
17100
+ const token = object2(value);
17101
+ if (!token)
17102
+ return null;
17103
+ const total = object2(token.total);
17104
+ const last = object2(token.last);
17105
+ const result = {};
17106
+ for (const field of [
17107
+ "totalTokens",
17108
+ "inputTokens",
17109
+ "cachedInputTokens",
17110
+ "cacheWriteInputTokens",
17111
+ "outputTokens",
17112
+ "reasoningOutputTokens"
17113
+ ]) {
17114
+ const n = integer2(total?.[field]);
17115
+ if (n !== void 0)
17116
+ result[field] = n;
17117
+ }
17118
+ const used = integer2(last?.totalTokens);
17119
+ const window = integer2(token.modelContextWindow);
17120
+ if (used !== void 0 && window !== void 0 && window > 0) {
17121
+ result.contextUsedTokens = used;
17122
+ result.contextWindowTokens = window;
17123
+ }
17124
+ const input = integer2(last?.inputTokens);
17125
+ const cached2 = integer2(last?.cachedInputTokens);
17126
+ if (input && cached2 !== void 0 && cached2 <= input)
17127
+ result.cacheHitRatePercent = cached2 / input * 100;
17128
+ if (result.inputTokens && result.cachedInputTokens !== void 0) {
17129
+ result.sessionCacheUsage = {
17130
+ inputTokens: result.inputTokens,
17131
+ cachedInputTokens: result.cachedInputTokens
17132
+ };
17133
+ }
17134
+ try {
17135
+ return Object.keys(result).length ? parseHostUsage(result) : null;
17136
+ } catch {
17137
+ return null;
17138
+ }
17139
+ }
17140
+ function observeSessionUsage(message) {
17141
+ const frame = object2(message);
17142
+ const params = object2(frame?.params);
17143
+ if (!params || typeof params.threadId !== "string" || !params.threadId)
17144
+ return null;
17145
+ const sessionId = params.threadId;
17146
+ if (frame?.method === "thread/tokenUsage/updated") {
17147
+ const usage2 = tokenSnapshot(params.tokenUsage);
17148
+ return usage2 ? { sessionId, usage: usage2 } : null;
17149
+ }
17150
+ if (frame?.method === "turn/started" || frame?.method === "turn/completed") {
17151
+ const turn = object2(params.turn);
17152
+ return typeof turn?.id === "string" && turn.id ? {
17153
+ sessionId,
17154
+ turn: { id: turn.id, phase: frame.method === "turn/started" ? "started" : "completed" }
17155
+ } : null;
17156
+ }
17157
+ if (typeof params.turnId !== "string" || !params.turnId)
17158
+ return null;
17159
+ if ([
17160
+ "item/agentMessage/delta",
17161
+ "item/reasoning/textDelta",
17162
+ "item/reasoning/summaryTextDelta"
17163
+ ].includes(String(frame?.method)) && typeof params.delta === "string" && params.delta.length > 0) {
17164
+ return { sessionId, turn: { id: params.turnId, phase: "output" } };
17165
+ }
17166
+ return null;
17167
+ }
17168
+ function rolloutTokenSnapshot(info) {
17169
+ const record2 = object2(info);
17170
+ if (!record2)
17171
+ return null;
17172
+ const convert = (value) => {
17173
+ const u = object2(value);
17174
+ return u && {
17175
+ totalTokens: u.total_tokens,
17176
+ inputTokens: u.input_tokens,
17177
+ cachedInputTokens: u.cached_input_tokens,
17178
+ cacheWriteInputTokens: u.cache_write_input_tokens,
17179
+ outputTokens: u.output_tokens,
17180
+ reasoningOutputTokens: u.reasoning_output_tokens
17181
+ };
17182
+ };
17183
+ return tokenSnapshot({
17184
+ total: convert(record2.total_token_usage),
17185
+ last: convert(record2.last_token_usage),
17186
+ modelContextWindow: record2.model_context_window
17187
+ });
17188
+ }
17189
+
17190
+ // dist/response-timing.js
17191
+ var nonNegativeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
17192
+ var CodexResponseTiming = class {
17193
+ #turns = /* @__PURE__ */ new Map();
17194
+ reset() {
17195
+ this.#turns.clear();
17196
+ }
17197
+ observe(message, now) {
17198
+ const frame = object2(message);
17199
+ const params = object2(frame?.params);
17200
+ if (!params || typeof params.threadId !== "string")
17201
+ return null;
17202
+ const sessionId = params.threadId;
17203
+ const turn = object2(params.turn);
17204
+ if (frame?.method === "turn/started" && typeof turn?.id === "string") {
17205
+ if (this.#turns.get(sessionId)?.id !== turn.id) {
17206
+ this.#turns.set(sessionId, {
17207
+ id: turn.id,
17208
+ pending: false,
17209
+ unavailable: false,
17210
+ seen: /* @__PURE__ */ new Set()
17211
+ });
17212
+ }
17213
+ return null;
17214
+ }
17215
+ const state = this.#turns.get(sessionId);
17216
+ if (!state)
17217
+ return null;
17218
+ const unavailable = () => {
17219
+ state.unavailable = true;
17220
+ return { sessionId, timingUnavailable: { turnId: state.id } };
17221
+ };
17222
+ if (frame?.method === "thread/closed") {
17223
+ this.#turns.delete(sessionId);
17224
+ return unavailable();
17225
+ }
17226
+ if (frame?.method === "turn/completed" && turn?.id === state.id) {
17227
+ this.#turns.delete(sessionId);
17228
+ return state.pending || state.unavailable ? unavailable() : null;
17229
+ }
17230
+ if (params.turnId !== state.id)
17231
+ return null;
17232
+ if (frame?.method === "error")
17233
+ return unavailable();
17234
+ if (frame?.method === "rawResponse/completed") {
17235
+ const id = params.responseId;
17236
+ if (typeof id !== "string" || !id)
17237
+ return unavailable();
17238
+ if (state.seen.has(id))
17239
+ return null;
17240
+ state.seen.add(id);
17241
+ const usage2 = object2(params.usage);
17242
+ const startedAtMs = state.firstOutputAtMs;
17243
+ state.firstOutputAtMs = void 0;
17244
+ state.pending = false;
17245
+ if (state.unavailable || startedAtMs === void 0 || !nonNegativeInteger(now) || now <= startedAtMs || !nonNegativeInteger(usage2?.outputTokens) || usage2.reasoningOutputTokens != null && (!nonNegativeInteger(usage2.reasoningOutputTokens) || usage2.reasoningOutputTokens > usage2.outputTokens)) {
17246
+ return unavailable();
17247
+ }
17248
+ return {
17249
+ sessionId,
17250
+ requestTiming: {
17251
+ requestId: id,
17252
+ turnId: state.id,
17253
+ outputTokens: usage2.outputTokens,
17254
+ startedAtMs,
17255
+ completedAtMs: now
17256
+ }
17257
+ };
17258
+ }
17259
+ if (frame?.method === "rawResponseItem/completed") {
17260
+ const item = object2(params.item);
17261
+ if (item?.type === "message" && item.role === "assistant" || [
17262
+ "reasoning",
17263
+ "function_call",
17264
+ "custom_tool_call",
17265
+ "local_shell_call",
17266
+ "web_search_call",
17267
+ "image_generation_call",
17268
+ "tool_search_call"
17269
+ ].includes(String(item?.type)))
17270
+ state.pending = true;
17271
+ return null;
17272
+ }
17273
+ if (frame?.method === "item/started") {
17274
+ const item = object2(params.item);
17275
+ if (item?.type === "agentMessage" || item?.type === "reasoning" || item?.type === "plan") {
17276
+ state.pending = true;
17277
+ state.firstOutputAtMs ??= now;
17278
+ }
17279
+ return null;
17280
+ }
17281
+ const reasoning = frame?.method === "item/reasoning/textDelta" || frame?.method === "item/reasoning/summaryTextDelta";
17282
+ if ((reasoning || frame?.method === "item/agentMessage/delta" || frame?.method === "item/plan/delta") && typeof params.delta === "string" && params.delta.length > 0) {
17283
+ state.pending = true;
17284
+ state.firstOutputAtMs ??= now;
17285
+ }
17286
+ return null;
17287
+ }
17288
+ };
17289
+
17290
+ // dist/session-usage.js
17291
+ function createCodexSessionUsage(environment, closed) {
17292
+ const timing = new CodexResponseTiming();
17293
+ const rawCompleted = "rawResponse/completed";
17294
+ let hideRawCompleted = false;
17295
+ const live = /* @__PURE__ */ new Map();
17296
+ const cache = /* @__PURE__ */ new Map();
17297
+ return {
17298
+ requestOptions({ method, params, initializeParams }) {
17299
+ if (closed.aborted)
17300
+ return null;
17301
+ if (method === "initialize") {
17302
+ const capabilities2 = object2(params.capabilities);
17303
+ const excluded2 = capabilities2?.optOutNotificationMethods;
17304
+ hideRawCompleted = false;
17305
+ if (capabilities2?.experimentalApi !== true || !Array.isArray(excluded2))
17306
+ return null;
17307
+ if (!excluded2.includes(rawCompleted))
17308
+ return null;
17309
+ hideRawCompleted = true;
17310
+ return {
17311
+ capabilities: {
17312
+ ...capabilities2,
17313
+ optOutNotificationMethods: excluded2.filter((method2) => method2 !== rawCompleted)
17314
+ }
17315
+ };
17316
+ }
17317
+ const capabilities = object2(initializeParams?.capabilities);
17318
+ const excluded = capabilities?.optOutNotificationMethods;
17319
+ return method === "thread/start" && capabilities?.experimentalApi === true && !(Array.isArray(excluded) && excluded.includes(rawCompleted)) && (params.experimentalRawEvents === void 0 || params.experimentalRawEvents === false) ? { experimentalRawEvents: true } : null;
17320
+ },
17321
+ shouldForwardNotification(message) {
17322
+ return closed.aborted || !hideRawCompleted || object2(message)?.method !== rawCompleted;
17323
+ },
17324
+ reset() {
17325
+ timing.reset();
17326
+ },
17327
+ observe(message, observedAtMs = Date.now()) {
17328
+ if (closed.aborted)
17329
+ return null;
17330
+ const observation = observeSessionUsage(message);
17331
+ const measured = timing.observe(message, observedAtMs);
17332
+ if (observation?.usage)
17333
+ live.set(observation.sessionId, observation.usage);
17334
+ return measured ? { ...observation, ...measured } : observation;
17335
+ },
17336
+ async read(sessionId, signal) {
17337
+ signal = AbortSignal.any([signal, closed]);
17338
+ signal.throwIfAborted();
17339
+ for (let attempt = 0; ; attempt++) {
17340
+ let snapshot = null;
17341
+ let complete = true;
17342
+ const reader = createCodexUsageStatistics(environment, {
17343
+ sessionId,
17344
+ onTokenCount: (info) => {
17345
+ snapshot = rolloutTokenSnapshot(info) ?? snapshot;
17346
+ },
17347
+ onIncomplete: () => {
17348
+ complete = false;
17349
+ }
17350
+ });
17351
+ const sources = await reader.listSources(signal);
17352
+ const source = sources[0];
17353
+ if (!source)
17354
+ return null;
17355
+ let history = cache.get(sessionId);
17356
+ if (history?.fingerprint !== source.fingerprint) {
17357
+ const entries = await reader.readSource(source.id, signal);
17358
+ const requests = entries.map((entry) => parseHostUsageRequest({
17359
+ requestId: entry.id,
17360
+ historical: true,
17361
+ ...entry.model ? { model: entry.model } : {},
17362
+ inputTokens: entry.inputTokens,
17363
+ outputTokens: entry.outputTokens,
17364
+ ...entry.cachedInputTokens !== void 0 ? { cachedInputTokens: entry.cachedInputTokens } : {},
17365
+ // Codex/OpenAI cache has no separately billed cache creation bucket.
17366
+ cacheWriteInputTokens: entry.cacheWriteInputTokens ?? 0,
17367
+ ...entry.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: entry.reasoningOutputTokens } : {}
17368
+ }));
17369
+ const inputTokens = requests.reduce((sum, r) => sum + r.inputTokens, 0);
17370
+ const outputTokens = requests.reduce((sum, r) => sum + r.outputTokens, 0);
17371
+ const cachedInputTokens = requests.every((r) => r.cachedInputTokens !== void 0) ? requests.reduce((sum, r) => sum + (r.cachedInputTokens ?? 0), 0) : void 0;
17372
+ const last = requests.at(-1);
17373
+ const usage2 = requests.length ? parseHostUsage({
17374
+ ...snapshot ?? {},
17375
+ inputTokens,
17376
+ outputTokens,
17377
+ totalTokens: inputTokens + outputTokens,
17378
+ ...cachedInputTokens !== void 0 ? { cachedInputTokens } : {},
17379
+ ...complete && cachedInputTokens !== void 0 ? { sessionCacheUsage: { inputTokens, cachedInputTokens } } : {},
17380
+ ...last?.inputTokens && last.cachedInputTokens !== void 0 ? { cacheHitRatePercent: last.cachedInputTokens / last.inputTokens * 100 } : {}
17381
+ }) : snapshot;
17382
+ history = {
17383
+ fingerprint: source.fingerprint,
17384
+ history: { usage: usage2, requests, complete: complete && requests.length > 0 }
17385
+ };
17386
+ cache.set(sessionId, history);
17387
+ }
17388
+ const result = history.history;
17389
+ const latest = live.get(sessionId);
17390
+ const caughtUp = !latest || (latest.inputTokens ?? 0) <= (result.usage?.inputTokens ?? 0) && (latest.outputTokens ?? 0) <= (result.usage?.outputTokens ?? 0);
17391
+ if (!caughtUp && attempt < 2) {
17392
+ await delay(50 * (attempt + 1), void 0, { signal });
17393
+ continue;
17394
+ }
17395
+ return { ...result, complete: result.complete && caughtUp };
17396
+ }
16729
17397
  }
16730
17398
  };
16731
17399
  }
@@ -16736,6 +17404,7 @@ function createUsageStatisticsAdapter(context) {
16736
17404
  const reader = createCodexUsageStatistics(context.environment);
16737
17405
  return {
16738
17406
  harnessId: harnessIdSchema.parse("codex-usage"),
17407
+ sessionUsage: createCodexSessionUsage(context.environment, abort.signal),
16739
17408
  usageStatistics: {
16740
17409
  listSources: (signal) => reader.listSources(AbortSignal.any([signal, abort.signal])),
16741
17410
  readSource: (id, signal) => reader.readSource(id, AbortSignal.any([signal, abort.signal]))