codex-copilot-dx 1.4.15 → 1.4.17

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.
@@ -4,7 +4,11 @@ const integer = value => Number.isSafeInteger(value) && value >= 0;
4
4
  const appIds = { codex_app: "codex", codex_cli: "codex", codex: "codex", claude_app: "claude_app", claude_code: "claude_code", gemini_app: "antigravity" };
5
5
  export const TERMINAL_CLIENT_NAMES = Object.freeze({ codex: "Codex", claude_app: "Claude App", claude_code: "Claude Code", gemini: "Antigravity", antigravity: "Antigravity" });
6
6
  export function terminalRequestState(row) {
7
- if (!row.active) return row.state || "unknown";
7
+ if (!row.active) {
8
+ if (row.state === "incomplete" && row.stop_reason === "max_tokens") return "Output limit";
9
+ if (row.state === "incomplete" && row.stop_reason === "content_filter") return "Content filtered";
10
+ return row.state || "unknown";
11
+ }
8
12
  if (row.terminal_outcome) return "Finishing";
9
13
  if (row.first_output_ms != null) return "Responding";
10
14
  if (row.phase === "admission") return "Queued";
@@ -9,8 +9,19 @@ const MAX_ENTRIES = 2;
9
9
  const MAX_BYTES = 2 * 1024 * 1024;
10
10
  const MAX_PENDING_BYTES = 256 * 1024;
11
11
  const cache = new Map(), activeReads = createAbortAwareSingleflight();
12
+ const dateFormatters = new Map();
12
13
  let unsubscribe;
13
14
 
15
+ function dateFormatter(timeZone) {
16
+ let formatter = dateFormatters.get(timeZone);
17
+ if (!formatter) {
18
+ formatter = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
19
+ if (dateFormatters.size >= 8) dateFormatters.delete(dateFormatters.keys().next().value);
20
+ dateFormatters.set(timeZone, formatter);
21
+ }
22
+ return formatter;
23
+ }
24
+
14
25
  async function completeLines(file) {
15
26
  for (const candidate of [file + ".1", file]) {
16
27
  let handle;
@@ -32,7 +43,7 @@ function appendOnly(before, after, bytes) {
32
43
  const a = before.split("\0"), b = after.split("\0");
33
44
  if (a.length !== 2 || b.length !== 2 || a[0] !== b[0]) return false;
34
45
  const oldFiles = a[1].split("|"), nextFiles = b[1].split("|");
35
- if (oldFiles.length !== 2 || nextFiles.length !== 2 || oldFiles[0] !== nextFiles[0]) return false;
46
+ if (oldFiles.length !== 3 || nextFiles.length !== 3 || oldFiles[0] !== nextFiles[0] || oldFiles[2] !== nextFiles[2]) return false;
36
47
  const old = oldFiles[1].split(":"), next = nextFiles[1].split(":");
37
48
  return next.length === 5 && (oldFiles[1] === "missing" ? Number(next[2]) === bytes
38
49
  : old.length === 5 && old[0] === next[0] && old[1] === next[1] && Number(next[2]) === Number(old[2]) + bytes);
@@ -59,7 +70,7 @@ function observe() {
59
70
 
60
71
  export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", model = "", purpose = "", days = "all", from = "", to = "", signal } = {}) {
61
72
  const selection = createUsageQuery({ provider, model, purpose, days, from, to, timeZone, now });
62
- const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
73
+ const zone = dateFormatter(timeZone);
63
74
  const file = path.resolve(filePath), query = `${file}\0${selection.key}\0${zone.format(new Date(now))}`;
64
75
  const version = warn === console.error ? await usageSummaryVersion(file, { settled: false }) : null;
65
76
  const collect = async () => {
@@ -0,0 +1,90 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { Transform, Writable } from "node:stream";
5
+ import { pipeline } from "node:stream/promises";
6
+ import { createGzip, createGunzip } from "node:zlib";
7
+
8
+ export const USAGE_ARCHIVE_MAX_BYTES = 256 * 1024 * 1024;
9
+ export const USAGE_ARCHIVE_DAYS = 365;
10
+ const archivePattern = /^\d{13}-[a-f0-9]{32}\.jsonl\.gz$/;
11
+ const directoryFor = file => path.resolve(file) + ".archive";
12
+ const identity = stat => createHash("sha256").update([stat.dev, stat.ino, stat.size, stat.ctimeNs].join(":")).digest("hex").slice(0, 32);
13
+
14
+ async function segments(file) {
15
+ const directory = directoryFor(file);
16
+ try {
17
+ const entries = await fs.promises.readdir(directory, { withFileTypes: true });
18
+ return entries.filter(entry => entry.isFile() && archivePattern.test(entry.name)).map(entry => entry.name).sort();
19
+ } catch (error) { if (error.code === "ENOENT") return [];throw error; }
20
+ }
21
+
22
+ export async function usageArchiveFiles(file) {
23
+ return (await segments(file)).map(name => path.join(directoryFor(file), name));
24
+ }
25
+
26
+ export async function archivedUsageBackup(file, archive, stat) {
27
+ const key = identity(stat ?? await fs.promises.stat(file + ".1", { bigint: true }));
28
+ return archive.some(name => name.endsWith("-" + key + ".jsonl.gz"));
29
+ }
30
+
31
+ async function verifyCompressedUsage(file, size, expected) {
32
+ const hash = createHash("sha256");
33
+ let bytes = 0;
34
+ await pipeline(fs.createReadStream(file), createGunzip(), new Writable({ write(chunk, _encoding, callback) {
35
+ bytes += chunk.length;
36
+ if (bytes > size) return callback(new Error("Usage archive exceeds its source size"));
37
+ hash.update(chunk);
38
+ callback();
39
+ } }));
40
+ if (bytes !== size || hash.digest("hex") !== expected) throw new Error("Usage archive did not verify");
41
+ }
42
+
43
+ export async function sealUsageBackup(file) {
44
+ const backup = file + ".1";
45
+ let stat;
46
+ try { stat = await fs.promises.stat(backup, { bigint: true }); }
47
+ catch (error) { if (error.code === "ENOENT") return;throw error; }
48
+ if (!stat.isFile()) throw new Error("Usage backup is not a regular file");
49
+ const directory = directoryFor(file);
50
+ await fs.promises.mkdir(directory, { recursive: true, mode: 0o700 });
51
+ const archive = await usageArchiveFiles(file);
52
+ const matching = archive.find(name => name.endsWith("-" + identity(stat) + ".jsonl.gz"));
53
+ const sealed = matching || path.join(directory, `${Date.now()}-${identity(stat)}.jsonl.gz`);
54
+ const temporary = path.join(directory, `.seal-${randomUUID()}.tmp`);
55
+ const hash = createHash("sha256");
56
+ try {
57
+ if (matching) {
58
+ for await (const chunk of fs.createReadStream(backup)) hash.update(chunk);
59
+ await verifyCompressedUsage(matching, Number(stat.size), hash.digest("hex"));
60
+ return;
61
+ }
62
+ await pipeline(fs.createReadStream(backup), new Transform({ transform(chunk, _encoding, callback) {
63
+ hash.update(chunk);
64
+ callback(null, chunk);
65
+ } }), createGzip({ level: 3 }), fs.createWriteStream(temporary, { flags: "wx", mode: 0o600 }));
66
+ await verifyCompressedUsage(temporary, Number(stat.size), hash.digest("hex"));
67
+ const handle = await fs.promises.open(temporary, "r+");
68
+ try { await handle.sync(); } finally { await handle.close(); }
69
+ await fs.promises.rename(temporary, sealed);
70
+ if (process.platform !== "win32") {
71
+ const dir = await fs.promises.open(directory, "r");
72
+ try { await dir.sync(); }
73
+ catch (error) { if (!["EINVAL", "ENOTSUP", "EBADF"].includes(error.code)) throw error; }
74
+ finally { await dir.close(); }
75
+ }
76
+ await pruneUsageArchive([...archive, sealed]);
77
+ } finally { await fs.promises.rm(temporary, { force: true }); }
78
+ }
79
+
80
+ async function pruneUsageArchive(files) {
81
+ const sizes = await Promise.all(files.map(name => fs.promises.stat(name).then(stat => stat.size)));
82
+ let bytes = sizes.reduce((sum, size) => sum + size, 0);
83
+ const before = Date.now() - USAGE_ARCHIVE_DAYS * 86400000;
84
+ // Preserve the newest verified segment even if one custom log exceeds the archive budget.
85
+ for (let i = 0; i < files.length - 1; i++) {
86
+ if (bytes <= USAGE_ARCHIVE_MAX_BYTES && Number(path.basename(files[i]).slice(0, 13)) >= before) break;
87
+ await fs.promises.unlink(files[i]);
88
+ bytes -= sizes[i];
89
+ }
90
+ }
@@ -9,6 +9,8 @@ import { appendRotatingLines, parseByteLimit, rotatedFilePath } from "./file-rot
9
9
  import { withFileLock } from "./lock.mjs";
10
10
  import { terminalCell } from "./terminal-text.mjs";
11
11
  import { currentRequestContext, requestPurpose } from "./request-context.mjs";
12
+ import { archivedUsageBackup, sealUsageBackup, usageArchiveFiles, USAGE_ARCHIVE_DAYS, USAGE_ARCHIVE_MAX_BYTES } from "./usage-archive.mjs";
13
+ import { createGunzip } from "node:zlib";
12
14
 
13
15
  const DEFAULT_USAGE_PATH = path.join(os.homedir(), ".local", "share", "codex-copilot-dx", "usage.jsonl");
14
16
  const DEFAULT_USAGE_MAX_BYTES = 32 * 1024 * 1024;
@@ -25,6 +27,7 @@ let pendingRecords = 0;
25
27
  let pendingBytes = 0;
26
28
  let droppedRecords = 0;
27
29
  let writeFailures = 0;
30
+ let unconfirmedRecords = 0;
28
31
  const appendObservers = new Set();
29
32
  export function subscribeUsageAppends(listener) {
30
33
  appendObservers.add(listener);return () => appendObservers.delete(listener);
@@ -41,7 +44,9 @@ export function runtimeUsageSnapshot() {
41
44
 
42
45
  export function usageLoggingStats() {
43
46
  return { pending_records: pendingRecords, pending_bytes: pendingBytes, dropped_records: droppedRecords,
44
- write_failures: writeFailures, max_records: USAGE_QUEUE_MAX_RECORDS, max_bytes: USAGE_QUEUE_MAX_BYTES };
47
+ write_failures: writeFailures,
48
+ unconfirmed_records: unconfirmedRecords, max_records: USAGE_QUEUE_MAX_RECORDS, max_bytes: USAGE_QUEUE_MAX_BYTES,
49
+ archive_days: USAGE_ARCHIVE_DAYS, archive_max_bytes: USAGE_ARCHIVE_MAX_BYTES };
45
50
  }
46
51
 
47
52
  export function usageLogPath() {
@@ -158,10 +163,13 @@ function takePendingWrites(filePath, maxBytes) {
158
163
  async function writeUsageBatch(batch) {
159
164
  const { filePath, maxBytes } = batch[0];
160
165
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
161
- await withFileLock(`${path.resolve(filePath)}.lock`, async () => {
166
+ let entered = false;
167
+ const write = timeoutMs => withFileLock(`${path.resolve(filePath)}.lock`, async () => {
168
+ entered = true;
162
169
  batch.push(...takePendingWrites(filePath, maxBytes));
170
+ await separateUsageTail(filePath);
163
171
  const before = appendObservers.size ? await usageSummaryVersion(filePath, { settled: false }) : null;
164
- await appendRotatingLines(filePath, batch.map(({ line }) => line), maxBytes);
172
+ await appendRotatingLines(filePath, batch.map(({ line }) => line), maxBytes, { sealBackup: sealUsageBackup });
165
173
  if (before && appendObservers.size) {
166
174
  const after = await usageSummaryVersion(filePath, { settled: false });
167
175
  const change = { filePath: path.resolve(filePath), before, after,
@@ -169,10 +177,32 @@ async function writeUsageBatch(batch) {
169
177
  for (const listener of appendObservers) { try { listener(change); } catch { /* Analytics cannot fail a log write. */ } }
170
178
  }
171
179
  }, {
172
- timeoutMs: USAGE_WRITE_LOCK_TIMEOUT_MS,
180
+ timeoutMs,
173
181
  staleMs: USAGE_WRITE_LOCK_STALE_MS,
174
182
  pollMs: USAGE_WRITE_LOCK_POLL_MS,
175
183
  });
184
+ const deadline = Date.now() + USAGE_WRITE_LOCK_TIMEOUT_MS;
185
+ try { await write(USAGE_WRITE_LOCK_TIMEOUT_MS - 100); }
186
+ catch (error) {
187
+ if (entered || !/^Timed out waiting for lock:/.test(error.message)) throw error;
188
+ const remaining = deadline - Date.now();
189
+ if (remaining <= 0) throw error;
190
+ await write(remaining);
191
+ }
192
+ }
193
+
194
+ async function separateUsageTail(filePath) {
195
+ let file;
196
+ try { file = await fs.promises.open(filePath, "r+"); }
197
+ catch (error) { if (error.code === "ENOENT") return;throw error; }
198
+ try {
199
+ const { size } = await file.stat();
200
+ if (!size) return;
201
+ const last = Buffer.alloc(1);
202
+ await file.read(last, 0, 1, size - 1);
203
+ // A partial line is still reported by the reader. Keep the next record separate.
204
+ if (last[0] !== 10) await file.write("\n", size, "utf8");
205
+ } finally { await file.close(); }
176
206
  }
177
207
 
178
208
  function scheduleUsageWriteDrain() {
@@ -186,6 +216,7 @@ function scheduleUsageWriteDrain() {
186
216
  } catch (error) {
187
217
  writeFailures += 1;
188
218
  batch.push(...takePendingWrites(first.filePath, first.maxBytes));
219
+ unconfirmedRecords += batch.length;
189
220
  console.error(`codex-copilot-dx usage log write failed: ${error.message}`);
190
221
  } finally {
191
222
  for (const entry of batch) {
@@ -266,10 +297,10 @@ export async function flushUsageWrites({
266
297
  }
267
298
  }
268
299
 
269
- async function* iterateUsageRecords(filePath, { warn = console.error } = {}) {
300
+ async function* iterateUsageRecords(filePath, { warn = console.error, compressed = false } = {}) {
270
301
  let input;
271
302
  try {
272
- input = fs.createReadStream(filePath, { encoding: "utf8" });
303
+ input = fs.createReadStream(filePath, compressed ? undefined : { encoding: "utf8" });
273
304
  await new Promise((resolve, reject) => {
274
305
  input.once("open", resolve);
275
306
  input.once("error", reject);
@@ -280,7 +311,9 @@ async function* iterateUsageRecords(filePath, { warn = console.error } = {}) {
280
311
  throw e;
281
312
  }
282
313
 
283
- const lines = readline.createInterface({ input, crlfDelay: Infinity });
314
+ const decoded = compressed ? input.pipe(createGunzip()) : input;
315
+ if (compressed) input.on("error", error => decoded.destroy(error));
316
+ const lines = readline.createInterface({ input: decoded, crlfDelay: Infinity });
284
317
  let invalidRecords = 0;
285
318
  for await (const line of lines) {
286
319
  if (!line) continue;
@@ -361,13 +394,26 @@ export function summarizeUsage(records, { provider = "" } = {}) {
361
394
 
362
395
  async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord, recordFilter, provider = "" } = {}) {
363
396
  const summary = summarizeUsage([], { provider });
364
- for (const candidate of [rotatedFilePath(filePath), filePath]) {
365
- for await (const record of iterateUsageRecords(candidate, { warn })) {
366
- if (provider && provider !== usageProvider(record)) continue;
367
- if (recordFilter && !recordFilter(record)) continue;
368
- const one = summarizeUsage([record]);
369
- onRecord?.(record, one);
370
- mergeUsageSummary(summary, one);
397
+ const archive = await usageArchiveFiles(filePath);
398
+ let archivedBackup = false;
399
+ if (archive.length) {
400
+ try { archivedBackup = await archivedUsageBackup(filePath, archive); }
401
+ catch (error) { if (error.code !== "ENOENT") throw error; }
402
+ }
403
+ for (const candidate of [...archive, ...(archivedBackup ? [] : [rotatedFilePath(filePath)]), filePath]) {
404
+ const compressed = archive.includes(candidate);
405
+ try {
406
+ for await (const record of iterateUsageRecords(candidate, { warn, compressed })) {
407
+ if (provider && provider !== usageProvider(record)) continue;
408
+ if (recordFilter && !recordFilter(record)) continue;
409
+ const one = summarizeUsage([record]);
410
+ onRecord?.(record, one);
411
+ mergeUsageSummary(summary, one);
412
+ }
413
+ } catch (error) {
414
+ if (!compressed) throw error;
415
+ summary.archive_read_failures = (summary.archive_read_failures || 0) + 1;
416
+ warn("A usage archive could not be read. Its totals may be incomplete.");
371
417
  }
372
418
  }
373
419
  return summary;
@@ -389,7 +435,7 @@ const activeSummaries = createAbortAwareSingleflight();
389
435
 
390
436
  export async function usageSummaryVersion(filePath, { settled = true } = {}) {
391
437
  try {
392
- const files = await Promise.all([rotatedFilePath(filePath), filePath].map(async (file) => {
438
+ const [files, archive] = await Promise.all([Promise.all([rotatedFilePath(filePath), filePath].map(async (file) => {
393
439
  try {
394
440
  const stat = await fs.promises.stat(file, { bigint: true });
395
441
  if (!stat.isFile()) return null;
@@ -400,8 +446,12 @@ export async function usageSummaryVersion(filePath, { settled = true } = {}) {
400
446
  if (error?.code === "ENOENT") return "missing";
401
447
  throw error;
402
448
  }
449
+ })), usageArchiveFiles(filePath)]);
450
+ const metadata = await Promise.all(archive.map(async name => {
451
+ const stat = await fs.promises.stat(name, { bigint: true });
452
+ return [path.basename(name), stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
403
453
  }));
404
- return files.some((version) => version === null) ? null : `${path.resolve(filePath)}\0${files.join("|")}`;
454
+ return files.some((version) => version === null) ? null : `${path.resolve(filePath)}\0${[...files, metadata.join(",")].join("|")}`;
405
455
  } catch { return null; } // Uncacheable metadata never replaces the normal read/error path.
406
456
  }
407
457