@liberseek/boft-cli-linux-x64 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.
@@ -14676,6 +14676,8 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
14676
14676
  harness,
14677
14677
  sessionId: external_exports.string().min(1).max(512),
14678
14678
  project: project.nullable(),
14679
+ /** Persisted Desktop title for a mapped Session, otherwise its native name; may be absent. */
14680
+ title: external_exports.string().min(1).max(200).optional(),
14679
14681
  /** Models the session used, most requests first. */
14680
14682
  models: external_exports.array(model).max(16),
14681
14683
  firstAtMs: count,
@@ -14742,7 +14744,12 @@ var usageStatisticsResultSchema = external_exports.strictObject({
14742
14744
  * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
14743
14745
  * requests without a native session are not listed here but count everywhere else.
14744
14746
  */
14745
- sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
14747
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100),
14748
+ /**
14749
+ * The sessions last active in the range, newest first, all filters applied. Optional for older
14750
+ * Hosts; missing is treated as no list rather than no sessions.
14751
+ */
14752
+ recentSessions: external_exports.array(usageStatisticsSessionSchema).max(100).optional()
14746
14753
  });
14747
14754
 
14748
14755
  // ../../shared-contracts/dist/ids.js
@@ -15909,8 +15916,24 @@ import path from "node:path";
15909
15916
  import { setImmediate as yieldToEventLoop } from "node:timers/promises";
15910
15917
 
15911
15918
  // ../../harness-adapter/dist/usage-statistics.js
15919
+ import { createReadStream } from "node:fs";
15920
+ import { createInterface } from "node:readline";
15912
15921
  var MAX_SESSION_ID_LENGTH = 512;
15913
15922
  var MAX_CWD_LENGTH = 4096;
15923
+ var MAX_SESSION_TITLE_LENGTH = 200;
15924
+ function usageSessionTitle(value) {
15925
+ if (typeof value !== "string")
15926
+ return void 0;
15927
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
15928
+ if (!normalized)
15929
+ return void 0;
15930
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
15931
+ return normalized;
15932
+ const characters = [...normalized];
15933
+ if (characters.length <= MAX_SESSION_TITLE_LENGTH)
15934
+ return normalized;
15935
+ return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
15936
+ }
15914
15937
  function sessionIdOk(value) {
15915
15938
  return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
15916
15939
  }
@@ -15920,12 +15943,14 @@ function cwdOk(value) {
15920
15943
  function withUsageSession(entry, session) {
15921
15944
  const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
15922
15945
  const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
15946
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
15923
15947
  if (sessionId === void 0 && cwd === void 0)
15924
15948
  return entry;
15925
15949
  return {
15926
15950
  ...entry,
15927
15951
  ...sessionId !== void 0 ? { sessionId } : {},
15928
- ...cwd !== void 0 ? { cwd } : {}
15952
+ ...cwd !== void 0 ? { cwd } : {},
15953
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
15929
15954
  };
15930
15955
  }
15931
15956
  function tokenCount(value) {
@@ -15965,6 +15990,12 @@ function parseHarnessUsageEntry(value) {
15965
15990
  return null;
15966
15991
  if (entry.cwd !== void 0 && !cwdOk(entry.cwd))
15967
15992
  return null;
15993
+ if (entry.sessionTitle !== void 0) {
15994
+ const sessionTitle = usageSessionTitle(entry.sessionTitle);
15995
+ if (sessionTitle === void 0)
15996
+ return null;
15997
+ entry.sessionTitle = sessionTitle;
15998
+ }
15968
15999
  if (entry.tokensUnknown !== void 0 && entry.tokensUnknown !== true)
15969
16000
  return null;
15970
16001
  if (entry.costUsd !== void 0 && (typeof entry.costUsd !== "number" || !Number.isFinite(entry.costUsd) || entry.costUsd < 0)) {
@@ -15975,6 +16006,25 @@ function parseHarnessUsageEntry(value) {
15975
16006
  }
15976
16007
  return entry;
15977
16008
  }
16009
+ async function* jsonlRecords(file2, marker, signal) {
16010
+ const lines = createInterface({
16011
+ input: createReadStream(file2, { encoding: "utf8", signal }),
16012
+ crlfDelay: Infinity
16013
+ });
16014
+ for await (const line of lines) {
16015
+ if (!line.includes(marker))
16016
+ continue;
16017
+ let value;
16018
+ try {
16019
+ value = JSON.parse(line);
16020
+ } catch {
16021
+ continue;
16022
+ }
16023
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
16024
+ yield value;
16025
+ }
16026
+ }
16027
+ }
15978
16028
  function nativeTimeMs(value) {
15979
16029
  const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
15980
16030
  return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
@@ -16383,7 +16433,7 @@ var CodexCounters = class {
16383
16433
  };
16384
16434
 
16385
16435
  // dist/rollout-io.js
16386
- import { createReadStream } from "node:fs";
16436
+ import { createReadStream as createReadStream2 } from "node:fs";
16387
16437
  import { StringDecoder } from "node:string_decoder";
16388
16438
  import { promisify } from "node:util";
16389
16439
  import { zstdDecompress } from "node:zlib";
@@ -16448,7 +16498,7 @@ function frameSize(data) {
16448
16498
  }
16449
16499
  async function* rolloutBytes(file2, signal) {
16450
16500
  signal.throwIfAborted();
16451
- const stream = createReadStream(file2, { signal });
16501
+ const stream = createReadStream2(file2, { signal });
16452
16502
  let pending = Buffer.alloc(0);
16453
16503
  try {
16454
16504
  for await (const value of stream) {
@@ -16540,32 +16590,84 @@ async function copyRelation(a, b, signal) {
16540
16590
  // dist/usage-statistics.js
16541
16591
  var ROLLOUT = /^rollout-.*?([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})(?:[_-][0-9a-f-]+)?\.jsonl(?:\.zst)?$/iu;
16542
16592
  var text = (value) => typeof value === "string" ? value : "";
16593
+ var ROW_KINDS = /* @__PURE__ */ new Set([
16594
+ "session_meta",
16595
+ "turn_context",
16596
+ "token_usage_record",
16597
+ "compacted",
16598
+ "event_msg",
16599
+ "response_item"
16600
+ ]);
16601
+ var HEAD_TYPE = /"type"\s*:\s*"([^"]+)"/u;
16602
+ var TAIL_TYPE = /"type"\s*:\s*"([^"]+)"\s*\}\s*$/u;
16603
+ function rowKind(line) {
16604
+ const head = HEAD_TYPE.exec(line.slice(0, 1024))?.[1];
16605
+ if (head && ROW_KINDS.has(head))
16606
+ return head;
16607
+ return TAIL_TYPE.exec(line.slice(-1024))?.[1] ?? head;
16608
+ }
16543
16609
  async function stamp(file2) {
16544
16610
  const s = await lstat(file2, { bigint: true });
16545
16611
  if (!s.isFile())
16546
16612
  throw new Error("Codex rollout is not a regular file");
16547
16613
  return `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
16548
16614
  }
16549
- function fingerprint(files) {
16550
- return createHash("sha256").update(JSON.stringify(files)).digest("hex");
16615
+ function fingerprint(files, extra = "") {
16616
+ return createHash("sha256").update(JSON.stringify(files)).update(extra).digest("hex");
16551
16617
  }
16552
- async function readCodexRollouts(files, thread, signal) {
16618
+ function typedPrompt(value) {
16619
+ if (typeof value !== "string")
16620
+ return void 0;
16621
+ const text2 = value.trim();
16622
+ if (!text2 || text2.startsWith("<") || text2.startsWith("# AGENTS.md") || text2.startsWith("<!--")) {
16623
+ return void 0;
16624
+ }
16625
+ return usageSessionTitle(text2);
16626
+ }
16627
+ function userItemPrompt(payload) {
16628
+ if (!payload || payload.type !== "message" || payload.role !== "user")
16629
+ return void 0;
16630
+ if (!Array.isArray(payload.content))
16631
+ return typedPrompt(payload.content);
16632
+ for (const part of payload.content) {
16633
+ if (typeof part !== "object" || part === null)
16634
+ continue;
16635
+ const block = part;
16636
+ if (block.type === "input_text" || block.type === "text") {
16637
+ const prompt = typedPrompt(block.text);
16638
+ if (prompt)
16639
+ return prompt;
16640
+ }
16641
+ }
16642
+ return void 0;
16643
+ }
16644
+ async function readThreadNames(home, signal) {
16645
+ const names = /* @__PURE__ */ new Map();
16646
+ try {
16647
+ for await (const line of jsonlRecords(path.join(home, "session_index.jsonl"), '"thread_name"', signal)) {
16648
+ const id = text(line.id);
16649
+ const name = usageSessionTitle(line.thread_name);
16650
+ if (id && name)
16651
+ names.set(id, name);
16652
+ }
16653
+ } catch (error51) {
16654
+ if (error51.code !== "ENOENT")
16655
+ throw error51;
16656
+ }
16657
+ return names;
16658
+ }
16659
+ async function readCodexRollouts(files, thread, signal, options = {}) {
16553
16660
  const counters = new CodexCounters();
16554
- let model2 = "", cwd = "", ownFrom = null, firstMeta = false, forkAt = 0, seen = 0;
16661
+ let model2 = "", cwd = "", ownFrom = null, firstMeta = false, forkAt = 0, seen = 0, firstPrompt;
16555
16662
  for (const file2 of files) {
16556
16663
  for await (const line of rolloutLines(file2, signal)) {
16557
16664
  signal.throwIfAborted();
16558
16665
  if (++seen % 128 === 0)
16559
16666
  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))
16667
+ const kind = rowKind(line);
16668
+ if (!kind && line.trim())
16669
+ options.onIncomplete?.();
16670
+ if (!kind || !ROW_KINDS.has(kind))
16569
16671
  continue;
16570
16672
  if (kind === "response_item" && !/"role"\s*:\s*"user"/u.test(line.slice(0, 1024)))
16571
16673
  continue;
@@ -16575,19 +16677,24 @@ async function readCodexRollouts(files, thread, signal) {
16575
16677
  try {
16576
16678
  row = object2(JSON.parse(line));
16577
16679
  } catch {
16680
+ options.onIncomplete?.();
16578
16681
  continue;
16579
16682
  }
16580
16683
  const p = object2(row?.payload);
16581
16684
  const at = nativeTimeMs(row?.timestamp);
16582
- if (!row || !p || at === null)
16685
+ if (!row || !p || at === null) {
16686
+ options.onIncomplete?.();
16583
16687
  continue;
16688
+ }
16584
16689
  switch (row.type) {
16585
16690
  case "session_meta": {
16586
16691
  if (!firstMeta) {
16587
16692
  if (text(p.id) !== thread)
16588
16693
  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)
16694
+ if (p.forked_from_id || p.parent_thread_id || p.subagent_history_start_ordinal) {
16590
16695
  forkAt = nativeTimeMs(p.timestamp) ?? at;
16696
+ options.onIncomplete?.();
16697
+ }
16591
16698
  cwd = text(p.cwd);
16592
16699
  firstMeta = true;
16593
16700
  }
@@ -16601,30 +16708,41 @@ async function readCodexRollouts(files, thread, signal) {
16601
16708
  counters.context("", text(p.turn_id), model2);
16602
16709
  break;
16603
16710
  case "token_usage_record":
16711
+ if (!usage(p.usage) || !text(p.response_id))
16712
+ options.onIncomplete?.();
16604
16713
  counters.record(at, model2, p);
16605
16714
  break;
16606
16715
  case "compacted": {
16607
16716
  const record2 = object2(p.latest_token_usage_record);
16608
- if (record2 && p.compaction_response_id && record2.response_id === p.compaction_response_id)
16717
+ if (record2 && p.compaction_response_id && record2.response_id === p.compaction_response_id) {
16718
+ if (!usage(record2.usage))
16719
+ options.onIncomplete?.();
16609
16720
  counters.record(at, model2, record2, true);
16721
+ }
16610
16722
  break;
16611
16723
  }
16612
16724
  case "response_item":
16613
16725
  counters.boundary();
16726
+ firstPrompt ??= userItemPrompt(p);
16614
16727
  break;
16615
16728
  case "event_msg":
16616
16729
  if (p.type === "task_started") {
16617
16730
  counters.context("", text(p.turn_id), "");
16618
16731
  counters.boundary();
16619
16732
  }
16620
- if (p.type === "user_message")
16733
+ if (p.type === "user_message") {
16621
16734
  counters.boundary();
16735
+ firstPrompt ??= typedPrompt(p.message);
16736
+ }
16622
16737
  if (p.type === "thread_settings_applied") {
16623
16738
  model2 = text(object2(p.thread_settings)?.model) || model2;
16624
16739
  counters.context("", "", model2);
16625
16740
  }
16626
16741
  if (p.type === "token_count") {
16627
16742
  const info = object2(p.info);
16743
+ options.onTokenCount?.(info);
16744
+ if (info && !usage(info.total_token_usage))
16745
+ options.onIncomplete?.();
16628
16746
  if (info)
16629
16747
  counters.count(at, model2, usage(info.total_token_usage), usage(info.last_token_usage));
16630
16748
  }
@@ -16651,12 +16769,22 @@ async function readCodexRollouts(files, thread, signal) {
16651
16769
  ...v.usage.known & 8 ? { cacheWriteInputTokens: written } : {},
16652
16770
  ...v.usage.known & 16 ? { reasoningOutputTokens: reasoning } : {}
16653
16771
  });
16654
- return entry ? [withUsageSession(entry, { sessionId: thread, cwd })] : [];
16772
+ return entry ? [withUsageSession(entry, { sessionId: thread, cwd, title: firstPrompt })] : [];
16655
16773
  });
16656
16774
  }
16657
- function createCodexUsageStatistics(environment) {
16775
+ function createCodexUsageStatistics(environment, options = {}) {
16658
16776
  const home = path.resolve(environment.CODEX_HOME || path.join(environment.HOME || environment.USERPROFILE || os.homedir(), ".codex"));
16659
16777
  const groups = /* @__PURE__ */ new Map();
16778
+ let names = /* @__PURE__ */ new Map();
16779
+ let namesStamp = "";
16780
+ async function threadNames(signal) {
16781
+ const current = await stamp(path.join(home, "session_index.jsonl")).catch(() => "-");
16782
+ if (namesStamp === current)
16783
+ return names;
16784
+ names = await readThreadNames(home, signal);
16785
+ namesStamp = current;
16786
+ return names;
16787
+ }
16660
16788
  return {
16661
16789
  async listSources(signal) {
16662
16790
  const found = /* @__PURE__ */ new Map();
@@ -16675,7 +16803,7 @@ function createCodexUsageStatistics(environment) {
16675
16803
  if (!entry.isFile())
16676
16804
  continue;
16677
16805
  const thread = ROLLOUT.exec(entry.name)?.[1];
16678
- if (!thread)
16806
+ if (!thread || options.sessionId && thread !== options.sessionId)
16679
16807
  continue;
16680
16808
  const list = found.get(thread) ?? [];
16681
16809
  list.push({ file: file2, fingerprint: await stamp(file2) });
@@ -16684,13 +16812,14 @@ function createCodexUsageStatistics(environment) {
16684
16812
  }
16685
16813
  await visit(path.join(home, "sessions"), 0);
16686
16814
  await visit(path.join(home, "archived_sessions"), 0);
16815
+ const indexStamp = options.sessionId ? "" : await stamp(path.join(home, "session_index.jsonl")).catch(() => "-");
16687
16816
  const result = [];
16688
16817
  groups.clear();
16689
16818
  for (const [thread, files] of found) {
16690
16819
  files.sort((a, b) => path.basename(a.file).localeCompare(path.basename(b.file)) || a.file.localeCompare(b.file));
16691
16820
  const id = path.join(home, `usage-thread-${thread}`);
16692
16821
  groups.set(id, { thread, files });
16693
- result.push({ id, fingerprint: fingerprint(files) });
16822
+ result.push({ id, fingerprint: fingerprint(files, indexStamp) });
16694
16823
  }
16695
16824
  return result;
16696
16825
  },
@@ -16721,11 +16850,517 @@ function createCodexUsageStatistics(environment) {
16721
16850
  if (!duplicate)
16722
16851
  kept.push(candidate);
16723
16852
  }
16724
- const entries = await readCodexRollouts(kept.map(({ file: file2 }) => file2), group.thread, signal);
16853
+ const entries = await readCodexRollouts(kept.map(({ file: file2 }) => file2), group.thread, signal, options);
16725
16854
  for (const file2 of group.files)
16726
16855
  if (await stamp(file2.file) !== file2.fingerprint)
16727
16856
  throw new Error("Codex rollout changed while reading; refresh to retry");
16728
- return entries;
16857
+ const named = options.sessionId ? void 0 : (await threadNames(signal)).get(group.thread);
16858
+ return named ? entries.map((entry) => withUsageSession(entry, {
16859
+ sessionId: entry.sessionId,
16860
+ cwd: entry.cwd,
16861
+ title: named
16862
+ })) : entries;
16863
+ }
16864
+ };
16865
+ }
16866
+
16867
+ // dist/session-usage.js
16868
+ import { setTimeout as delay } from "node:timers/promises";
16869
+
16870
+ // ../../harness-adapter/dist/usage.js
16871
+ var tokenFields = [
16872
+ "inputTokens",
16873
+ "cachedInputTokens",
16874
+ "cacheWriteInputTokens",
16875
+ "outputTokens",
16876
+ "reasoningOutputTokens",
16877
+ "totalTokens",
16878
+ "contextWindowTokens",
16879
+ "contextUsedTokens"
16880
+ ];
16881
+ var safeIntegerFields = [
16882
+ "planFiveHourResetsAtUnix",
16883
+ "planSevenDayResetsAtUnix",
16884
+ "timeToFirstOutputMs"
16885
+ ];
16886
+ var percentFields = [
16887
+ "cacheHitRatePercent",
16888
+ "sessionCacheHitRatePercent",
16889
+ "planFiveHourUsedPercent",
16890
+ "planSevenDayUsedPercent"
16891
+ ];
16892
+ var usageFields = /* @__PURE__ */ new Set([
16893
+ ...tokenFields,
16894
+ ...safeIntegerFields,
16895
+ ...percentFields,
16896
+ "sessionCacheUsage",
16897
+ "totalCostUsd",
16898
+ "totalCredits",
16899
+ "contextUsagePercent",
16900
+ "outputTokensPerSecond",
16901
+ "apiOutputTokensPerSecond",
16902
+ "costSource",
16903
+ "unpricedModels"
16904
+ ]);
16905
+ function isRecord(value) {
16906
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16907
+ }
16908
+ function parseHostUsage(value) {
16909
+ if (!isRecord(value))
16910
+ throw new Error("Harness Usage must be an object");
16911
+ const keys = Object.keys(value);
16912
+ if (keys.length === 0)
16913
+ throw new Error("Harness Usage must contain a reliable field");
16914
+ for (const key2 of keys) {
16915
+ if (!usageFields.has(key2)) {
16916
+ throw new Error(`Harness Usage contains unknown field '${key2}'`);
16917
+ }
16918
+ }
16919
+ for (const field of [
16920
+ "totalCredits",
16921
+ "contextUsagePercent",
16922
+ "apiOutputTokensPerSecond"
16923
+ ]) {
16924
+ const candidate = value[field];
16925
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16926
+ throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16927
+ }
16928
+ }
16929
+ for (const field of tokenFields) {
16930
+ const candidate = value[field];
16931
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16932
+ throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16933
+ }
16934
+ }
16935
+ for (const field of safeIntegerFields) {
16936
+ const candidate = value[field];
16937
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16938
+ throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16939
+ }
16940
+ }
16941
+ if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
16942
+ throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
16943
+ }
16944
+ if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
16945
+ throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
16946
+ }
16947
+ for (const field of ["totalCredits", "contextUsagePercent"]) {
16948
+ const candidate = value[field];
16949
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16950
+ throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16951
+ }
16952
+ }
16953
+ for (const field of percentFields) {
16954
+ const candidate = value[field];
16955
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
16956
+ throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16957
+ }
16958
+ }
16959
+ if (value.sessionCacheUsage !== void 0) {
16960
+ const totals2 = value.sessionCacheUsage;
16961
+ 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) {
16962
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
16963
+ }
16964
+ }
16965
+ const hasContextUsed = value.contextUsedTokens !== void 0;
16966
+ const hasContextWindow = value.contextWindowTokens !== void 0;
16967
+ if (hasContextUsed !== hasContextWindow) {
16968
+ throw new Error("Harness Usage context fields must be provided together");
16969
+ }
16970
+ if (hasContextWindow && value.contextWindowTokens === 0) {
16971
+ throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
16972
+ }
16973
+ if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
16974
+ throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
16975
+ }
16976
+ if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
16977
+ throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
16978
+ }
16979
+ if (value.costSource !== void 0) {
16980
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
16981
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
16982
+ }
16983
+ if (value.totalCostUsd === void 0) {
16984
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
16985
+ }
16986
+ }
16987
+ if (value.unpricedModels !== void 0) {
16988
+ const models = value.unpricedModels;
16989
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
16990
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
16991
+ }
16992
+ if (value.costSource !== "publicPrice") {
16993
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
16994
+ }
16995
+ return { ...value, unpricedModels: [...models] };
16996
+ }
16997
+ return { ...value };
16998
+ }
16999
+ var requestTokenFields = [
17000
+ "inputTokens",
17001
+ "cachedInputTokens",
17002
+ "cacheWriteInputTokens",
17003
+ "cacheWrite1hInputTokens",
17004
+ "outputTokens",
17005
+ "reasoningOutputTokens",
17006
+ "startedAtMs",
17007
+ "completedAtMs"
17008
+ ];
17009
+ var requestFields = /* @__PURE__ */ new Set([
17010
+ ...requestTokenFields,
17011
+ "requestId",
17012
+ "historical",
17013
+ "model",
17014
+ "provider"
17015
+ ]);
17016
+ function parseHostUsageRequest(value) {
17017
+ if (!isRecord(value))
17018
+ throw new Error("Harness Usage request must be an object");
17019
+ for (const key2 of Object.keys(value)) {
17020
+ if (!requestFields.has(key2)) {
17021
+ throw new Error(`Harness Usage request contains unknown field '${key2}'`);
17022
+ }
17023
+ }
17024
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17025
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17026
+ }
17027
+ for (const field of ["model", "provider"]) {
17028
+ const candidate = value[field];
17029
+ if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17030
+ throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
17031
+ }
17032
+ }
17033
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17034
+ throw new Error("Harness Usage request 'historical' must be a boolean");
17035
+ }
17036
+ for (const field of requestTokenFields) {
17037
+ const candidate = value[field];
17038
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17039
+ throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
17040
+ }
17041
+ }
17042
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17043
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
17044
+ }
17045
+ const request = value;
17046
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17047
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17048
+ }
17049
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17050
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17051
+ }
17052
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17053
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17054
+ }
17055
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17056
+ throw new Error("Harness Usage request timing fields must be provided together");
17057
+ }
17058
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17059
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17060
+ }
17061
+ return { ...request };
17062
+ }
17063
+
17064
+ // dist/session-observation.js
17065
+ var integer2 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
17066
+ function tokenSnapshot(value) {
17067
+ const token = object2(value);
17068
+ if (!token)
17069
+ return null;
17070
+ const total = object2(token.total);
17071
+ const last = object2(token.last);
17072
+ const result = {};
17073
+ for (const field of [
17074
+ "totalTokens",
17075
+ "inputTokens",
17076
+ "cachedInputTokens",
17077
+ "cacheWriteInputTokens",
17078
+ "outputTokens",
17079
+ "reasoningOutputTokens"
17080
+ ]) {
17081
+ const n = integer2(total?.[field]);
17082
+ if (n !== void 0)
17083
+ result[field] = n;
17084
+ }
17085
+ const used = integer2(last?.totalTokens);
17086
+ const window = integer2(token.modelContextWindow);
17087
+ if (used !== void 0 && window !== void 0 && window > 0) {
17088
+ result.contextUsedTokens = used;
17089
+ result.contextWindowTokens = window;
17090
+ }
17091
+ const input = integer2(last?.inputTokens);
17092
+ const cached2 = integer2(last?.cachedInputTokens);
17093
+ if (input && cached2 !== void 0 && cached2 <= input)
17094
+ result.cacheHitRatePercent = cached2 / input * 100;
17095
+ if (result.inputTokens && result.cachedInputTokens !== void 0) {
17096
+ result.sessionCacheUsage = {
17097
+ inputTokens: result.inputTokens,
17098
+ cachedInputTokens: result.cachedInputTokens
17099
+ };
17100
+ }
17101
+ try {
17102
+ return Object.keys(result).length ? parseHostUsage(result) : null;
17103
+ } catch {
17104
+ return null;
17105
+ }
17106
+ }
17107
+ function observeSessionUsage(message) {
17108
+ const frame = object2(message);
17109
+ const params = object2(frame?.params);
17110
+ if (!params || typeof params.threadId !== "string" || !params.threadId)
17111
+ return null;
17112
+ const sessionId = params.threadId;
17113
+ if (frame?.method === "thread/tokenUsage/updated") {
17114
+ const usage2 = tokenSnapshot(params.tokenUsage);
17115
+ return usage2 ? { sessionId, usage: usage2 } : null;
17116
+ }
17117
+ if (frame?.method === "turn/started" || frame?.method === "turn/completed") {
17118
+ const turn = object2(params.turn);
17119
+ return typeof turn?.id === "string" && turn.id ? {
17120
+ sessionId,
17121
+ turn: { id: turn.id, phase: frame.method === "turn/started" ? "started" : "completed" }
17122
+ } : null;
17123
+ }
17124
+ if (typeof params.turnId !== "string" || !params.turnId)
17125
+ return null;
17126
+ if ([
17127
+ "item/agentMessage/delta",
17128
+ "item/reasoning/textDelta",
17129
+ "item/reasoning/summaryTextDelta"
17130
+ ].includes(String(frame?.method)) && typeof params.delta === "string" && params.delta.length > 0) {
17131
+ return { sessionId, turn: { id: params.turnId, phase: "output" } };
17132
+ }
17133
+ return null;
17134
+ }
17135
+ function rolloutTokenSnapshot(info) {
17136
+ const record2 = object2(info);
17137
+ if (!record2)
17138
+ return null;
17139
+ const convert = (value) => {
17140
+ const u = object2(value);
17141
+ return u && {
17142
+ totalTokens: u.total_tokens,
17143
+ inputTokens: u.input_tokens,
17144
+ cachedInputTokens: u.cached_input_tokens,
17145
+ cacheWriteInputTokens: u.cache_write_input_tokens,
17146
+ outputTokens: u.output_tokens,
17147
+ reasoningOutputTokens: u.reasoning_output_tokens
17148
+ };
17149
+ };
17150
+ return tokenSnapshot({
17151
+ total: convert(record2.total_token_usage),
17152
+ last: convert(record2.last_token_usage),
17153
+ modelContextWindow: record2.model_context_window
17154
+ });
17155
+ }
17156
+
17157
+ // dist/response-timing.js
17158
+ var nonNegativeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
17159
+ var CodexResponseTiming = class {
17160
+ #turns = /* @__PURE__ */ new Map();
17161
+ reset() {
17162
+ this.#turns.clear();
17163
+ }
17164
+ observe(message, now) {
17165
+ const frame = object2(message);
17166
+ const params = object2(frame?.params);
17167
+ if (!params || typeof params.threadId !== "string")
17168
+ return null;
17169
+ const sessionId = params.threadId;
17170
+ const turn = object2(params.turn);
17171
+ if (frame?.method === "turn/started" && typeof turn?.id === "string") {
17172
+ if (this.#turns.get(sessionId)?.id !== turn.id) {
17173
+ this.#turns.set(sessionId, {
17174
+ id: turn.id,
17175
+ pending: false,
17176
+ unavailable: false,
17177
+ seen: /* @__PURE__ */ new Set()
17178
+ });
17179
+ }
17180
+ return null;
17181
+ }
17182
+ const state = this.#turns.get(sessionId);
17183
+ if (!state)
17184
+ return null;
17185
+ const unavailable = () => {
17186
+ state.unavailable = true;
17187
+ return { sessionId, timingUnavailable: { turnId: state.id } };
17188
+ };
17189
+ if (frame?.method === "thread/closed") {
17190
+ this.#turns.delete(sessionId);
17191
+ return unavailable();
17192
+ }
17193
+ if (frame?.method === "turn/completed" && turn?.id === state.id) {
17194
+ this.#turns.delete(sessionId);
17195
+ return state.pending || state.unavailable ? unavailable() : null;
17196
+ }
17197
+ if (params.turnId !== state.id)
17198
+ return null;
17199
+ if (frame?.method === "error")
17200
+ return unavailable();
17201
+ if (frame?.method === "rawResponse/completed") {
17202
+ const id = params.responseId;
17203
+ if (typeof id !== "string" || !id)
17204
+ return unavailable();
17205
+ if (state.seen.has(id))
17206
+ return null;
17207
+ state.seen.add(id);
17208
+ const usage2 = object2(params.usage);
17209
+ const startedAtMs = state.firstOutputAtMs;
17210
+ state.firstOutputAtMs = void 0;
17211
+ state.pending = false;
17212
+ if (state.unavailable || startedAtMs === void 0 || !nonNegativeInteger(now) || now <= startedAtMs || !nonNegativeInteger(usage2?.outputTokens) || usage2.reasoningOutputTokens != null && (!nonNegativeInteger(usage2.reasoningOutputTokens) || usage2.reasoningOutputTokens > usage2.outputTokens)) {
17213
+ return unavailable();
17214
+ }
17215
+ return {
17216
+ sessionId,
17217
+ requestTiming: {
17218
+ requestId: id,
17219
+ turnId: state.id,
17220
+ outputTokens: usage2.outputTokens,
17221
+ startedAtMs,
17222
+ completedAtMs: now
17223
+ }
17224
+ };
17225
+ }
17226
+ if (frame?.method === "rawResponseItem/completed") {
17227
+ const item = object2(params.item);
17228
+ if (item?.type === "message" && item.role === "assistant" || [
17229
+ "reasoning",
17230
+ "function_call",
17231
+ "custom_tool_call",
17232
+ "local_shell_call",
17233
+ "web_search_call",
17234
+ "image_generation_call",
17235
+ "tool_search_call"
17236
+ ].includes(String(item?.type)))
17237
+ state.pending = true;
17238
+ return null;
17239
+ }
17240
+ if (frame?.method === "item/started") {
17241
+ const item = object2(params.item);
17242
+ if (item?.type === "agentMessage" || item?.type === "reasoning" || item?.type === "plan") {
17243
+ state.pending = true;
17244
+ state.firstOutputAtMs ??= now;
17245
+ }
17246
+ return null;
17247
+ }
17248
+ const reasoning = frame?.method === "item/reasoning/textDelta" || frame?.method === "item/reasoning/summaryTextDelta";
17249
+ if ((reasoning || frame?.method === "item/agentMessage/delta" || frame?.method === "item/plan/delta") && typeof params.delta === "string" && params.delta.length > 0) {
17250
+ state.pending = true;
17251
+ state.firstOutputAtMs ??= now;
17252
+ }
17253
+ return null;
17254
+ }
17255
+ };
17256
+
17257
+ // dist/session-usage.js
17258
+ function createCodexSessionUsage(environment, closed) {
17259
+ const timing = new CodexResponseTiming();
17260
+ const rawCompleted = "rawResponse/completed";
17261
+ let hideRawCompleted = false;
17262
+ const live = /* @__PURE__ */ new Map();
17263
+ const cache = /* @__PURE__ */ new Map();
17264
+ return {
17265
+ requestOptions({ method, params, initializeParams }) {
17266
+ if (closed.aborted)
17267
+ return null;
17268
+ if (method === "initialize") {
17269
+ const capabilities2 = object2(params.capabilities);
17270
+ const excluded2 = capabilities2?.optOutNotificationMethods;
17271
+ hideRawCompleted = false;
17272
+ if (capabilities2?.experimentalApi !== true || !Array.isArray(excluded2))
17273
+ return null;
17274
+ if (!excluded2.includes(rawCompleted))
17275
+ return null;
17276
+ hideRawCompleted = true;
17277
+ return {
17278
+ capabilities: {
17279
+ ...capabilities2,
17280
+ optOutNotificationMethods: excluded2.filter((method2) => method2 !== rawCompleted)
17281
+ }
17282
+ };
17283
+ }
17284
+ const capabilities = object2(initializeParams?.capabilities);
17285
+ const excluded = capabilities?.optOutNotificationMethods;
17286
+ return method === "thread/start" && capabilities?.experimentalApi === true && !(Array.isArray(excluded) && excluded.includes(rawCompleted)) && (params.experimentalRawEvents === void 0 || params.experimentalRawEvents === false) ? { experimentalRawEvents: true } : null;
17287
+ },
17288
+ shouldForwardNotification(message) {
17289
+ return closed.aborted || !hideRawCompleted || object2(message)?.method !== rawCompleted;
17290
+ },
17291
+ reset() {
17292
+ timing.reset();
17293
+ },
17294
+ observe(message, observedAtMs = Date.now()) {
17295
+ if (closed.aborted)
17296
+ return null;
17297
+ const observation = observeSessionUsage(message);
17298
+ const measured = timing.observe(message, observedAtMs);
17299
+ if (observation?.usage)
17300
+ live.set(observation.sessionId, observation.usage);
17301
+ return measured ? { ...observation, ...measured } : observation;
17302
+ },
17303
+ async read(sessionId, signal) {
17304
+ signal = AbortSignal.any([signal, closed]);
17305
+ signal.throwIfAborted();
17306
+ for (let attempt = 0; ; attempt++) {
17307
+ let snapshot = null;
17308
+ let complete = true;
17309
+ const reader = createCodexUsageStatistics(environment, {
17310
+ sessionId,
17311
+ onTokenCount: (info) => {
17312
+ snapshot = rolloutTokenSnapshot(info) ?? snapshot;
17313
+ },
17314
+ onIncomplete: () => {
17315
+ complete = false;
17316
+ }
17317
+ });
17318
+ const sources = await reader.listSources(signal);
17319
+ const source = sources[0];
17320
+ if (!source)
17321
+ return null;
17322
+ let history = cache.get(sessionId);
17323
+ if (history?.fingerprint !== source.fingerprint) {
17324
+ const entries = await reader.readSource(source.id, signal);
17325
+ const requests = entries.map((entry) => parseHostUsageRequest({
17326
+ requestId: entry.id,
17327
+ historical: true,
17328
+ ...entry.model ? { model: entry.model } : {},
17329
+ inputTokens: entry.inputTokens,
17330
+ outputTokens: entry.outputTokens,
17331
+ ...entry.cachedInputTokens !== void 0 ? { cachedInputTokens: entry.cachedInputTokens } : {},
17332
+ // Codex/OpenAI cache has no separately billed cache creation bucket.
17333
+ cacheWriteInputTokens: entry.cacheWriteInputTokens ?? 0,
17334
+ ...entry.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: entry.reasoningOutputTokens } : {}
17335
+ }));
17336
+ const inputTokens = requests.reduce((sum, r) => sum + r.inputTokens, 0);
17337
+ const outputTokens = requests.reduce((sum, r) => sum + r.outputTokens, 0);
17338
+ const cachedInputTokens = requests.every((r) => r.cachedInputTokens !== void 0) ? requests.reduce((sum, r) => sum + (r.cachedInputTokens ?? 0), 0) : void 0;
17339
+ const last = requests.at(-1);
17340
+ const usage2 = requests.length ? parseHostUsage({
17341
+ ...snapshot ?? {},
17342
+ inputTokens,
17343
+ outputTokens,
17344
+ totalTokens: inputTokens + outputTokens,
17345
+ ...cachedInputTokens !== void 0 ? { cachedInputTokens } : {},
17346
+ ...complete && cachedInputTokens !== void 0 ? { sessionCacheUsage: { inputTokens, cachedInputTokens } } : {},
17347
+ ...last?.inputTokens && last.cachedInputTokens !== void 0 ? { cacheHitRatePercent: last.cachedInputTokens / last.inputTokens * 100 } : {}
17348
+ }) : snapshot;
17349
+ history = {
17350
+ fingerprint: source.fingerprint,
17351
+ history: { usage: usage2, requests, complete: complete && requests.length > 0 }
17352
+ };
17353
+ cache.set(sessionId, history);
17354
+ }
17355
+ const result = history.history;
17356
+ const latest = live.get(sessionId);
17357
+ const caughtUp = !latest || (latest.inputTokens ?? 0) <= (result.usage?.inputTokens ?? 0) && (latest.outputTokens ?? 0) <= (result.usage?.outputTokens ?? 0);
17358
+ if (!caughtUp && attempt < 2) {
17359
+ await delay(50 * (attempt + 1), void 0, { signal });
17360
+ continue;
17361
+ }
17362
+ return { ...result, complete: result.complete && caughtUp };
17363
+ }
16729
17364
  }
16730
17365
  };
16731
17366
  }
@@ -16736,6 +17371,7 @@ function createUsageStatisticsAdapter(context) {
16736
17371
  const reader = createCodexUsageStatistics(context.environment);
16737
17372
  return {
16738
17373
  harnessId: harnessIdSchema.parse("codex-usage"),
17374
+ sessionUsage: createCodexSessionUsage(context.environment, abort.signal),
16739
17375
  usageStatistics: {
16740
17376
  listSources: (signal) => reader.listSources(AbortSignal.any([signal, abort.signal])),
16741
17377
  readSource: (id, signal) => reader.readSource(id, AbortSignal.any([signal, abort.signal]))