@openclaw/tokenjuice 2026.9.5 → 2026.9.6

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.
@@ -166,6 +166,7 @@ tokenjuice --version
166
166
  tokenjuice reduce [file]
167
167
  tokenjuice reduce-json [file]
168
168
  tokenjuice wrap -- <command> [args...]
169
+ tokenjuice wrap --no-stats -- <command> [args...]
169
170
  tokenjuice wrap --raw -- <command> [args...]
170
171
  tokenjuice wrap --store -- <command> [args...]
171
172
  tokenjuice install [adal|aether|aictl|ai-memory-protocol|aider|agent-layer|agentinit|agentlink|agentloom|agents-cli|agents-md|agentsge|agentsmesh|amazon-q|amp|antigravity|anywhere-agents|augment|avante|baz|bito|blackbox|blocks|clawdbot|bob|builder|charlie|codex|claude-code|cline|codeant|codebuff|codegen|coder-agents|coderabbit|codebuddy|command-code|continue|copilot-agent|crush|cursor|deepagents|devin|dot-agents|docker-agent|droid|eca|elyra|firebase-studio|forgecode|gemini-cli|gitlab-duo|goose|greptile|grok-build|grok-cli|gptme|jean2|jetbrains-ai|junie|jules|leanctl|kimi|kiro|kilo|localcode|mcp-agent|mini-swe-agent|swe-agent|stagewise|mistral-vibe|mux|novakit|knowns|ona|openhands|open-interpreter|openwebui|pi|pi-go|opencode|plandex|qodo|qoder|qwen-code|replit|roo|rovo|ruler|tabby|tabnine|trae|uipath|vscode-copilot|warp|windsurf|copilot-cli|zed|zencoder]
@@ -181,6 +182,7 @@ tokenjuice doctor pi
181
182
  tokenjuice doctor opencode
182
183
  tokenjuice stats
183
184
  tokenjuice stats --timezone utc
185
+ tokenjuice stats --limit 1000
184
186
  ```
185
187
 
186
188
  ## overview
@@ -196,6 +198,8 @@ tokenjuice wrap --raw -- pnpm --help
196
198
  tokenjuice wrap --full -- git status
197
199
  ```
198
200
 
201
+ statistics use bounded metadata segments and exclude pre-existing JSON sidecars. page with `--limit` and the returned `--cursor`; output reports when coverage is partial. set `TOKENJUICE_STATS=off` or pass `--no-stats` to stop metadata and hook-debug telemetry writes. `--raw` and `--full` return untouched bytes; artifact retention remains opt-in through `--store`.
202
+
199
203
  useful maintenance commands:
200
204
 
201
205
  ```bash
@@ -12,6 +12,7 @@ type ParsedArgs = {
12
12
  toolName: string | undefined;
13
13
  exitCode: number | undefined;
14
14
  store: boolean;
15
+ noStats: boolean;
15
16
  tee: boolean;
16
17
  raw: boolean;
17
18
  noOmit: boolean;
@@ -23,6 +24,8 @@ type ParsedArgs = {
23
24
  timeZone: string | undefined;
24
25
  source: string | undefined;
25
26
  bySource: boolean;
27
+ limit: number | undefined;
28
+ cursor: string | undefined;
26
29
  wrapLauncher: string | undefined;
27
30
  trace: boolean;
28
31
  printInstructions: boolean;
@@ -4,7 +4,8 @@ import { dirname, relative, resolve } from "node:path";
4
4
  import { stdin as inputStdin } from "node:process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import packageJson from "../../package.json" with { type: "json" };
7
- import { getArtifact, listArtifactMetadata, listArtifacts } from "../core/artifacts.js";
7
+ import { getArtifact, listArtifactMetadata, listArtifactMetadataPage, listArtifacts } from "../core/artifacts.js";
8
+ import { shouldRecordStats } from "../core/artifacts.js";
8
9
  import { buildAnalysisEntry, discoverCandidates, doctorArtifacts, statsArtifacts } from "../core/analysis.js";
9
10
  import { verifyBuiltinFixtures } from "../core/fixtures.js";
10
11
  import { readNoOmissionFromEnv } from "../core/env.js";
@@ -133,9 +134,9 @@ function printUsage() {
133
134
  "usage:",
134
135
  " tokenjuice --help",
135
136
  " tokenjuice --version",
136
- " tokenjuice reduce [file] [--format text|json] [--classifier <id>] [--store] [--raw|--full] [--no-omit]",
137
+ " tokenjuice reduce [file] [--format text|json] [--classifier <id>] [--store] [--raw|--full] [--no-omit] [--no-stats]",
137
138
  " tokenjuice reduce-json [file]",
138
- " tokenjuice wrap [--raw|--full] [--no-omit] [--source <name>] -- <command> [args...] [--tee] [--store] [--max-capture-bytes <n>]",
139
+ " tokenjuice wrap [--raw|--full] [--no-omit] [--no-stats] [--source <name>] -- <command> [args...] [--tee] [--store] [--max-capture-bytes <n>]",
139
140
  " tokenjuice <command> ... [--trace]",
140
141
  " tokenjuice install adal",
141
142
  " tokenjuice install aether",
@@ -343,7 +344,7 @@ function printUsage() {
343
344
  " tokenjuice discover [file] [--source-command <cmd>] [--tool-name <name>] [--exit-code <n>] [--source <name>] [--by-source]",
344
345
  " tokenjuice doctor [file|hooks|adal|aether|aictl|ai-memory-protocol|aider|agent-layer|agentinit|agentlink|agentloom|agents-cli|agents-md|agentsge|agentsmesh|amazon-q|amp|antigravity|anywhere-agents|augment|avante|baz|bito|blackbox|blocks|clawdbot|bob|builder|charlie|codex|claude-code|cline|codeant|codebuff|codegen|coder-agents|coderabbit|codebuddy|command-code|continue|copilot-agent|crush|cursor|deepagents|devin|dot-agents|docker-agent|droid|eca|elyra|firebase-studio|forgecode|gemini-cli|gitlab-duo|goose|greptile|grok-build|grok-bot|grok-cli|gptme|jean2|jetbrains-ai|junie|jules|leanctl|kimi|kiro|kilo|localcode|mcp-agent|mini-swe-agent|swe-agent|stagewise|mistral-vibe|mux|novakit|knowns|ona|openhands|open-interpreter|openwebui|pi|pi-go|opencode|plandex|qodo|qoder|qwen-code|replit|roo|rovo|ruler|tabby|tabnine|trae|uipath|vscode-copilot|warp|windsurf|zed|zencoder|copilot-cli] [--local] [--print-instructions] [--source-command <cmd>] [--tool-name <name>] [--exit-code <n>]",
345
346
  " tokenjuice doctor codex [--local] [--no-omit]",
346
- " tokenjuice stats [--timezone local|utc|<iana-timezone>] [--source <name>] [--by-source]",
347
+ " tokenjuice stats [--timezone local|utc|<iana-timezone>] [--source <name>] [--by-source] [--limit <n>] [--cursor <cursor>]",
347
348
  ].join("\n"));
348
349
  process.stderr.write("\n");
349
350
  }
@@ -359,6 +360,7 @@ export function parseArgs(argv) {
359
360
  let toolName;
360
361
  let exitCode;
361
362
  let store = false;
363
+ let noStats = false;
362
364
  let tee = false;
363
365
  let raw = false;
364
366
  let noOmit = false;
@@ -370,6 +372,8 @@ export function parseArgs(argv) {
370
372
  let timeZone;
371
373
  let source;
372
374
  let bySource = false;
375
+ let limit;
376
+ let cursor;
373
377
  let wrapLauncher;
374
378
  let trace = false;
375
379
  let printInstructions = false;
@@ -434,6 +438,10 @@ export function parseArgs(argv) {
434
438
  store = true;
435
439
  index += 1;
436
440
  break;
441
+ case "--no-stats":
442
+ noStats = true;
443
+ index += 1;
444
+ break;
437
445
  case "--raw":
438
446
  case "--full":
439
447
  raw = true;
@@ -497,6 +505,20 @@ export function parseArgs(argv) {
497
505
  bySource = true;
498
506
  index += 1;
499
507
  break;
508
+ case "--limit":
509
+ if (!next || !Number.isInteger(Number(next)) || Number(next) <= 0) {
510
+ throw new Error("--limit requires a positive integer");
511
+ }
512
+ limit = Number(next);
513
+ index += 2;
514
+ break;
515
+ case "--cursor":
516
+ if (!next) {
517
+ throw new Error("--cursor requires a value");
518
+ }
519
+ cursor = next;
520
+ index += 2;
521
+ break;
500
522
  case "--wrap-launcher":
501
523
  if (!next) {
502
524
  throw new Error("--wrap-launcher requires a value");
@@ -532,6 +554,7 @@ export function parseArgs(argv) {
532
554
  toolName,
533
555
  exitCode,
534
556
  store,
557
+ noStats,
535
558
  tee,
536
559
  raw,
537
560
  noOmit,
@@ -543,6 +566,8 @@ export function parseArgs(argv) {
543
566
  timeZone,
544
567
  source,
545
568
  bySource,
569
+ limit,
570
+ cursor,
546
571
  wrapLauncher,
547
572
  trace,
548
573
  printInstructions,
@@ -617,7 +642,7 @@ async function runReduce(args) {
617
642
  ...(args.raw ? { raw: true } : {}),
618
643
  ...(noOmit ? { noOmit: true } : {}),
619
644
  ...(args.trace ? { trace: true } : {}),
620
- recordStats: true,
645
+ recordStats: !args.noStats && shouldRecordStats(),
621
646
  ...(args.store ? { store: true } : {}),
622
647
  ...(args.storeDir ? { storeDir: args.storeDir } : {}),
623
648
  ...(typeof args.maxInlineChars === "number" ? { maxInlineChars: args.maxInlineChars } : {}),
@@ -648,7 +673,7 @@ async function runReduceJson(args) {
648
673
  ...(args.raw ? { raw: true } : {}),
649
674
  ...(noOmit ? { noOmit: true } : {}),
650
675
  ...(args.trace ? { trace: true } : {}),
651
- recordStats: true,
676
+ recordStats: !args.noStats && shouldRecordStats(),
652
677
  ...(args.store ? { store: true } : {}),
653
678
  ...(args.storeDir ? { storeDir: args.storeDir } : {}),
654
679
  ...(typeof args.maxInlineChars === "number" ? { maxInlineChars: args.maxInlineChars } : {}),
@@ -663,7 +688,7 @@ async function runWrap(args) {
663
688
  ...(args.raw ? { raw: true } : {}),
664
689
  ...(noOmit ? { noOmit: true } : {}),
665
690
  ...(args.trace ? { trace: true } : {}),
666
- recordStats: true,
691
+ recordStats: !args.noStats && shouldRecordStats(),
667
692
  ...(args.store ? { store: true } : {}),
668
693
  ...(args.storeDir ? { storeDir: args.storeDir } : {}),
669
694
  ...(typeof args.maxInlineChars === "number" ? { maxInlineChars: args.maxInlineChars } : {}),
@@ -1217,6 +1242,7 @@ async function runInstall(args) {
1217
1242
  const details = [
1218
1243
  { label: "Hook", value: result.hooksPath },
1219
1244
  { label: "Command", value: result.command },
1245
+ { label: "Writer", value: `${result.writer} (${result.fragmentId})` },
1220
1246
  ];
1221
1247
  if (result.featureFlag.enabled) {
1222
1248
  const source = result.featureFlag.key ? `[features].${result.featureFlag.key}` : "default-on";
@@ -2879,6 +2905,7 @@ async function runUninstall(args) {
2879
2905
  }
2880
2906
  process.stdout.write(`removed codex hook: ${result.hooksPath}\n`);
2881
2907
  process.stdout.write(`removed entries: ${result.removed}\n`);
2908
+ process.stdout.write(`writer: ${result.writer} (${result.fragmentId})\n`);
2882
2909
  if (result.backupPath) {
2883
2910
  process.stdout.write(`backup: ${result.backupPath}\n`);
2884
2911
  }
@@ -6579,16 +6606,37 @@ async function runDoctor(args) {
6579
6606
  return 0;
6580
6607
  }
6581
6608
  async function runStats(args) {
6582
- const entries = await listArtifactMetadata(args.storeDir);
6583
- const report = statsArtifacts(entries, {
6609
+ const page = await listArtifactMetadataPage(args.storeDir, {
6610
+ ...(typeof args.limit === "number" ? { limit: args.limit } : {}),
6611
+ ...(args.cursor ? { cursor: args.cursor } : {}),
6612
+ });
6613
+ const report = statsArtifacts(page.entries, {
6584
6614
  timeZone: args.timeZone ?? "local",
6585
6615
  ...(args.source ? { source: args.source } : {}),
6586
6616
  ...(args.bySource ? { bySource: true } : {}),
6587
6617
  });
6588
6618
  if (args.format === "json") {
6589
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
6619
+ process.stdout.write(`${JSON.stringify({
6620
+ ...report,
6621
+ coverage: {
6622
+ source: "bounded-metadata-segments",
6623
+ legacySidecarsIncluded: page.legacySidecarsIncluded,
6624
+ partial: page.partial,
6625
+ nextCursor: page.nextCursor ?? null,
6626
+ },
6627
+ }, null, 2)}\n`);
6590
6628
  return 0;
6591
6629
  }
6630
+ process.stdout.write("coverage: bounded metadata segments; legacy sidecars excluded\n");
6631
+ if (page.partial) {
6632
+ process.stdout.write("partial: yes\n");
6633
+ if (page.nextCursor) {
6634
+ process.stdout.write(`next cursor: ${page.nextCursor}\n`);
6635
+ }
6636
+ }
6637
+ else {
6638
+ process.stdout.write("partial: no\n");
6639
+ }
6592
6640
  process.stdout.write(`entries: ${formatMetric(report.totals.entries)}\n`);
6593
6641
  process.stdout.write(`capture-truncated entries: ${formatMetric(report.totals.captureTruncatedEntries)}\n`);
6594
6642
  process.stdout.write(`observed entries: ${formatMetric(report.totals.observedEntries)}\n`);
@@ -49,7 +49,7 @@ function groupCandidates(entries, options = {}) {
49
49
  const groups = new Map();
50
50
  const includeSource = options.bySource || Boolean(options.source);
51
51
  for (const entry of entries) {
52
- const signature = normalizeCommandSignature(entry.metadata.command);
52
+ const signature = normalizeCommandSignature(entry.metadata.command ?? entry.metadata.commandFamily);
53
53
  if (!signature) {
54
54
  continue;
55
55
  }
@@ -68,7 +68,7 @@ function groupCandidates(entries, options = {}) {
68
68
  totalRawChars: 0,
69
69
  ratioSum: 0,
70
70
  ratioCount: 0,
71
- sampleCommand: entry.metadata.command ?? signature,
71
+ sampleCommand: entry.metadata.command ?? entry.metadata.commandFamily ?? signature,
72
72
  ...(entry.metadata.classification.matchedReducer
73
73
  ? { matchedReducer: entry.metadata.classification.matchedReducer }
74
74
  : {}),
@@ -198,7 +198,7 @@ function buildStatsReport(entries, options, source) {
198
198
  continue;
199
199
  }
200
200
  const reducer = entry.metadata.classification.matchedReducer ?? "generic/fallback";
201
- const signature = normalizeCommandSignature(entry.metadata.command) ?? "(unknown)";
201
+ const signature = normalizeCommandSignature(entry.metadata.command ?? entry.metadata.commandFamily) ?? "(unknown)";
202
202
  const day = formatDay(entry.metadata.createdAt);
203
203
  rawChars += entry.metadata.rawChars;
204
204
  reducedChars += reduced;
@@ -1,10 +1,14 @@
1
- import type { ArtifactMetadataRef, StoredArtifact, StoredArtifactInput, StoredArtifactRef } from "../types.js";
1
+ import type { ArtifactMetadataPage, ArtifactMetadataPageOptions, ArtifactMetadataRef, StoredArtifact, StoredArtifactInput, StoredArtifactRef, ToolExecutionInput } from "../types.js";
2
2
  export declare const ARTIFACT_DIR_ENV = "TOKENJUICE_ARTIFACT_DIR";
3
+ export declare const STATS_ENABLED_ENV = "TOKENJUICE_STATS";
3
4
  export declare function resolveArtifactBaseDir(storeDir?: string): string;
4
5
  export declare function isValidArtifactId(id: string): boolean;
6
+ export declare function getTelemetryCommandFamily(input: Pick<ToolExecutionInput, "argv" | "command">): string | undefined;
7
+ export declare function shouldRecordStats(env?: NodeJS.ProcessEnv): boolean;
5
8
  export declare function storeArtifact(input: StoredArtifactInput, storeDir?: string): Promise<StoredArtifactRef>;
6
9
  export declare function storeArtifactMetadata(input: StoredArtifactInput, storeDir?: string): Promise<ArtifactMetadataRef>;
7
10
  export declare function tryStoreArtifactMetadata(input: StoredArtifactInput, storeDir?: string): Promise<ArtifactMetadataRef | undefined>;
8
11
  export declare function getArtifact(id: string, storeDir?: string): Promise<StoredArtifact | null>;
9
12
  export declare function listArtifacts(storeDir?: string): Promise<StoredArtifactRef[]>;
10
13
  export declare function listArtifactMetadata(storeDir?: string): Promise<ArtifactMetadataRef[]>;
14
+ export declare function listArtifactMetadataPage(storeDir?: string, options?: ArtifactMetadataPageOptions): Promise<ArtifactMetadataPage>;
@@ -1,11 +1,17 @@
1
1
  import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { homedir } from "node:os";
3
4
  import { join } from "node:path";
4
- import { randomUUID } from "node:crypto";
5
+ import { appendBoundedJsonl, readBoundedJsonlPage } from "./bounded-jsonl.js";
6
+ import { getCommandName, getEffectiveCommandArgv } from "./command.js";
5
7
  import { countTextChars, stripAnsi } from "./text.js";
6
8
  import { resolveArtifactSource } from "./source.js";
7
9
  const ARTIFACT_ID_PATTERN = /^tj_[0-9a-f-]{12}$/iu;
8
10
  export const ARTIFACT_DIR_ENV = "TOKENJUICE_ARTIFACT_DIR";
11
+ export const STATS_ENABLED_ENV = "TOKENJUICE_STATS";
12
+ const METADATA_SEGMENT_DIRECTORY = "metadata-v1";
13
+ const METADATA_SEGMENT_PREFIX = "events";
14
+ const DEFAULT_METADATA_LIST_LIMIT = 10_000;
9
15
  const OPTIONAL_METADATA_STORAGE_ERROR_CODES = new Set([
10
16
  "EACCES",
11
17
  "EDQUOT",
@@ -45,6 +51,12 @@ function isStoredArtifactMetadata(value) {
45
51
  if ("command" in value && value.command !== undefined && typeof value.command !== "string") {
46
52
  return false;
47
53
  }
54
+ if ("commandFamily" in value && value.commandFamily !== undefined && typeof value.commandFamily !== "string") {
55
+ return false;
56
+ }
57
+ if ("commandDigest" in value && value.commandDigest !== undefined && typeof value.commandDigest !== "string") {
58
+ return false;
59
+ }
48
60
  if ("exitCode" in value && value.exitCode !== undefined && typeof value.exitCode !== "number") {
49
61
  return false;
50
62
  }
@@ -88,11 +100,45 @@ function buildArtifactPaths(id, storeDir) {
88
100
  metadataPath: join(base, `${id}.json`),
89
101
  };
90
102
  }
91
- function buildMetadataOnlyPath(id, storeDir) {
92
- if (!isValidArtifactId(id)) {
93
- throw new Error(`invalid artifact id: ${id}`);
103
+ function isStoredMetadataEvent(value) {
104
+ return isRecord(value)
105
+ && typeof value.id === "string"
106
+ && isValidArtifactId(value.id)
107
+ && typeof value.hasRaw === "boolean"
108
+ && isStoredArtifactMetadata(value.metadata);
109
+ }
110
+ function metadataSegmentDir(storeDir) {
111
+ return join(resolveArtifactBaseDir(storeDir), METADATA_SEGMENT_DIRECTORY);
112
+ }
113
+ const SAFE_COMMAND_FAMILY = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u;
114
+ export function getTelemetryCommandFamily(input) {
115
+ try {
116
+ const family = getCommandName(getEffectiveCommandArgv(input));
117
+ return family && SAFE_COMMAND_FAMILY.test(family) ? family : undefined;
94
118
  }
95
- return join(resolveArtifactBaseDir(storeDir), `${id}.meta.json`);
119
+ catch {
120
+ return undefined;
121
+ }
122
+ }
123
+ function buildTelemetryMetadata(metadata, input) {
124
+ const retainedMetadata = { ...metadata };
125
+ delete retainedMetadata.command;
126
+ const family = getTelemetryCommandFamily(input);
127
+ return {
128
+ ...retainedMetadata,
129
+ ...(family ? { commandFamily: family } : {}),
130
+ };
131
+ }
132
+ async function appendMetadataEvent(id, metadata, input, hasRaw, storeDir) {
133
+ return await appendBoundedJsonl(metadataSegmentDir(storeDir), METADATA_SEGMENT_PREFIX, id, {
134
+ id,
135
+ hasRaw,
136
+ metadata: buildTelemetryMetadata(metadata, input),
137
+ });
138
+ }
139
+ export function shouldRecordStats(env = process.env) {
140
+ const value = env[STATS_ENABLED_ENV]?.trim().toLowerCase();
141
+ return value !== "0" && value !== "false" && value !== "no" && value !== "off";
96
142
  }
97
143
  export async function storeArtifact(input, storeDir) {
98
144
  const id = `tj_${randomUUID().slice(0, 12)}`;
@@ -118,11 +164,13 @@ export async function storeArtifact(input, storeDir) {
118
164
  writeFile(ref.path, input.rawText, { encoding: "utf8", mode: 0o600 }),
119
165
  writeFile(ref.metadataPath, JSON.stringify(artifact.metadata, null, 2), { encoding: "utf8", mode: 0o600 }),
120
166
  ]);
167
+ if (input.recordStats ?? shouldRecordStats()) {
168
+ await appendMetadataEvent(id, artifact.metadata, input.input, true, storeDir).catch(() => undefined);
169
+ }
121
170
  return ref;
122
171
  }
123
172
  export async function storeArtifactMetadata(input, storeDir) {
124
173
  const id = `tj_${randomUUID().slice(0, 12)}`;
125
- const metadataPath = buildMetadataOnlyPath(id, storeDir);
126
174
  const captureTruncated = extractCaptureTruncatedFlag(input.input);
127
175
  const metadata = {
128
176
  createdAt: new Date().toISOString(),
@@ -135,13 +183,18 @@ export async function storeArtifactMetadata(input, storeDir) {
135
183
  ...(captureTruncated !== undefined ? { captureTruncated } : {}),
136
184
  ...(input.stats ? { reducedChars: input.stats.reducedChars, ratio: input.stats.ratio } : {}),
137
185
  };
138
- await mkdir(resolveArtifactBaseDir(storeDir), { recursive: true, mode: 0o700 });
139
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2), { encoding: "utf8", mode: 0o600 });
186
+ const telemetryMetadata = buildTelemetryMetadata(metadata, input.input);
187
+ const metadataPath = await appendMetadataEvent(id, telemetryMetadata, input.input, false, storeDir);
188
+ if (!metadataPath) {
189
+ throw Object.assign(new Error("metadata segment is full or busy"), { code: "EFBIG" });
190
+ }
140
191
  return {
141
192
  id,
142
193
  storage: "file",
143
194
  metadataPath,
144
- metadata,
195
+ metadataFormat: "jsonl-segment",
196
+ metadataRecordId: id,
197
+ metadata: telemetryMetadata,
145
198
  };
146
199
  }
147
200
  export async function tryStoreArtifactMetadata(input, storeDir) {
@@ -199,41 +252,36 @@ export async function listArtifacts(storeDir) {
199
252
  }
200
253
  }
201
254
  export async function listArtifactMetadata(storeDir) {
255
+ const entries = [];
256
+ let cursor;
257
+ do {
258
+ const page = await listArtifactMetadataPage(storeDir, {
259
+ limit: DEFAULT_METADATA_LIST_LIMIT,
260
+ ...(cursor ? { cursor } : {}),
261
+ });
262
+ entries.push(...page.entries);
263
+ cursor = page.nextCursor;
264
+ } while (cursor);
265
+ return entries.sort((left, right) => right.metadata.createdAt.localeCompare(left.metadata.createdAt));
266
+ }
267
+ export async function listArtifactMetadataPage(storeDir, options = {}) {
268
+ const page = await readBoundedJsonlPage(metadataSegmentDir(storeDir), METADATA_SEGMENT_PREFIX, isStoredMetadataEvent, options);
202
269
  const base = resolveArtifactBaseDir(storeDir);
203
- try {
204
- const files = await readdir(base);
205
- const metadata = await Promise.all(files
206
- .filter((name) => name.endsWith(".json"))
207
- .map(async (name) => {
208
- const rawId = name.endsWith(".meta.json") ? name.replace(/\.meta\.json$/u, "") : name.replace(/\.json$/u, "");
209
- if (!isValidArtifactId(rawId)) {
210
- return null;
211
- }
212
- const metadataPath = join(base, name);
213
- try {
214
- const raw = await readFile(metadataPath, "utf8");
215
- const parsed = JSON.parse(raw);
216
- if (!isStoredArtifactMetadata(parsed)) {
217
- return null;
218
- }
219
- const path = name.endsWith(".meta.json") ? undefined : join(base, `${rawId}.txt`);
220
- return {
221
- id: rawId,
222
- storage: "file",
223
- ...(path ? { path } : {}),
224
- metadataPath,
225
- metadata: parsed,
226
- };
227
- }
228
- catch {
229
- return null;
230
- }
231
- }));
232
- return metadata
233
- .filter((entry) => entry !== null)
234
- .sort((left, right) => right.metadata.createdAt.localeCompare(left.metadata.createdAt));
235
- }
236
- catch {
237
- return [];
238
- }
270
+ const entries = page.records
271
+ .map(({ path: metadataPath, value }) => ({
272
+ id: value.id,
273
+ storage: "file",
274
+ ...(value.hasRaw ? { path: join(base, `${value.id}.txt`) } : {}),
275
+ metadataPath,
276
+ metadataFormat: "jsonl-segment",
277
+ metadataRecordId: value.id,
278
+ metadata: value.metadata,
279
+ }))
280
+ .sort((left, right) => right.metadata.createdAt.localeCompare(left.metadata.createdAt));
281
+ return {
282
+ entries,
283
+ partial: page.partial,
284
+ legacySidecarsIncluded: false,
285
+ ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
286
+ };
239
287
  }
@@ -0,0 +1,26 @@
1
+ export type BoundedJsonlOptions = {
2
+ retentionDays?: number;
3
+ shardCount?: number;
4
+ maxSegmentBytes?: number;
5
+ now?: Date;
6
+ };
7
+ export type BoundedJsonlPageOptions = {
8
+ limit?: number;
9
+ cursor?: string;
10
+ maxFiles?: number;
11
+ maxSegmentBytes?: number;
12
+ };
13
+ export type BoundedJsonlPage<T> = {
14
+ records: Array<{
15
+ path: string;
16
+ value: T;
17
+ }>;
18
+ nextCursor?: string;
19
+ partial: boolean;
20
+ };
21
+ export declare function appendBoundedJsonl(directory: string, prefix: string, id: string, value: unknown, options?: BoundedJsonlOptions): Promise<string | undefined>;
22
+ export declare function readBoundedJsonlPage<T>(directory: string, prefix: string, validate: (value: unknown) => value is T, options?: BoundedJsonlPageOptions): Promise<BoundedJsonlPage<T>>;
23
+ export declare function boundedJsonlCapacity(options?: BoundedJsonlOptions): {
24
+ maxFiles: number;
25
+ maxBytes: number;
26
+ };