@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.
@@ -0,0 +1,407 @@
1
+ import { appendFile, lstat, mkdir, open, opendir, readFile, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ const DAY_MS = 24 * 60 * 60 * 1_000;
5
+ const LOCK_RETRIES = 8;
6
+ const LOCK_RETRY_MS = 10;
7
+ const MAX_RETENTION_DAYS = 365;
8
+ const MAX_SHARD_COUNT = 100;
9
+ const MAX_STORE_FILES = 10_000;
10
+ const MAX_SEGMENT_BYTES = 64 * 1024 * 1024;
11
+ const DIRECTORY_ENTRY_SLACK = 256;
12
+ const DEFAULT_RETENTION_DAYS = 14;
13
+ const DEFAULT_SHARD_COUNT = 8;
14
+ const DEFAULT_MAX_SEGMENT_BYTES = 1024 * 1024;
15
+ const DEFAULT_PAGE_LIMIT = 1_000;
16
+ const MAX_PAGE_LIMIT = 10_000;
17
+ function wait(ms) {
18
+ return new Promise((resolvePromise) => {
19
+ setTimeout(resolvePromise, ms);
20
+ });
21
+ }
22
+ function positiveInteger(value, fallback, name, maximum) {
23
+ const resolved = value ?? fallback;
24
+ if (!Number.isSafeInteger(resolved) || resolved <= 0 || resolved > maximum) {
25
+ throw new RangeError(`${name} must be a positive integer no greater than ${maximum}`);
26
+ }
27
+ return resolved;
28
+ }
29
+ function resolveStoreOptions(options) {
30
+ const retentionDays = positiveInteger(options.retentionDays, DEFAULT_RETENTION_DAYS, "retentionDays", MAX_RETENTION_DAYS);
31
+ const shardCount = positiveInteger(options.shardCount, DEFAULT_SHARD_COUNT, "shardCount", MAX_SHARD_COUNT);
32
+ if (retentionDays * shardCount > MAX_STORE_FILES) {
33
+ throw new RangeError(`retentionDays * shardCount must not exceed ${MAX_STORE_FILES}`);
34
+ }
35
+ return {
36
+ retentionDays,
37
+ shardCount,
38
+ maxSegmentBytes: positiveInteger(options.maxSegmentBytes, DEFAULT_MAX_SEGMENT_BYTES, "maxSegmentBytes", MAX_SEGMENT_BYTES),
39
+ };
40
+ }
41
+ function formatDay(date) {
42
+ return date.toISOString().slice(0, 10);
43
+ }
44
+ function shardFor(id, shardCount) {
45
+ const digest = createHash("sha256").update(id).digest();
46
+ return digest[0] % shardCount;
47
+ }
48
+ function segmentName(prefix, day, shard) {
49
+ return `${prefix}-${day}-${String(shard).padStart(2, "0")}.jsonl`;
50
+ }
51
+ function parseSegmentDay(name, prefix) {
52
+ const escapedPrefix = prefix.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
53
+ return new RegExp(`^${escapedPrefix}-(\\d{4}-\\d{2}-\\d{2})-\\d{2}\\.jsonl$`, "u")
54
+ .exec(name)?.[1];
55
+ }
56
+ async function tryCreateLock(lockPath) {
57
+ try {
58
+ await mkdir(lockPath, { mode: 0o700 });
59
+ }
60
+ catch (error) {
61
+ if (error.code === "EEXIST") {
62
+ // Age alone cannot prove ownership; reclaiming here can displace a live or replacement writer.
63
+ return undefined;
64
+ }
65
+ throw error;
66
+ }
67
+ const owner = `${process.pid}:${randomUUID()}`;
68
+ try {
69
+ await writeFile(join(lockPath, "owner"), owner, { encoding: "utf8", flag: "wx", mode: 0o600 });
70
+ return owner;
71
+ }
72
+ catch {
73
+ // Leave an unowned lock in place rather than risk deleting a replacement.
74
+ return undefined;
75
+ }
76
+ }
77
+ async function releaseLock(lockPath, owner) {
78
+ try {
79
+ const ownerPath = join(lockPath, "owner");
80
+ if (await readFile(ownerPath, "utf8") === owner) {
81
+ await unlink(ownerPath);
82
+ await rmdir(lockPath);
83
+ }
84
+ }
85
+ catch {
86
+ // A missing or replaced lock no longer belongs to this writer.
87
+ }
88
+ }
89
+ async function acquireLock(lockPath) {
90
+ for (let attempt = 0; attempt <= LOCK_RETRIES; attempt += 1) {
91
+ const owner = await tryCreateLock(lockPath);
92
+ if (owner) {
93
+ return owner;
94
+ }
95
+ if (attempt < LOCK_RETRIES) {
96
+ await wait(LOCK_RETRY_MS);
97
+ }
98
+ }
99
+ return undefined;
100
+ }
101
+ async function pruneExpiredSegments(directory, prefix, retentionDays, maxFiles, now) {
102
+ const oldestDay = formatDay(new Date(now.getTime() - (retentionDays - 1) * DAY_MS));
103
+ const directoryHandle = await opendir(directory);
104
+ let inspected = 0;
105
+ try {
106
+ for await (const entry of directoryHandle) {
107
+ inspected += 1;
108
+ if (inspected > maxFiles * 2 + DIRECTORY_ENTRY_SLACK) {
109
+ break;
110
+ }
111
+ if (!entry.isFile()) {
112
+ continue;
113
+ }
114
+ const day = parseSegmentDay(entry.name, prefix);
115
+ if (day && day < oldestDay) {
116
+ const path = join(directory, entry.name);
117
+ const lockPath = `${path}.lock`;
118
+ const owner = await tryCreateLock(lockPath);
119
+ if (!owner) {
120
+ continue;
121
+ }
122
+ try {
123
+ await rm(path, { force: true });
124
+ }
125
+ finally {
126
+ await releaseLock(lockPath, owner);
127
+ }
128
+ }
129
+ }
130
+ }
131
+ finally {
132
+ await directoryHandle.close().catch(() => { });
133
+ }
134
+ }
135
+ async function countOwnedSegments(directory, prefix, maxFiles) {
136
+ const directoryHandle = await opendir(directory);
137
+ let count = 0;
138
+ let inspected = 0;
139
+ try {
140
+ for await (const entry of directoryHandle) {
141
+ inspected += 1;
142
+ if (inspected > maxFiles * 2 + DIRECTORY_ENTRY_SLACK) {
143
+ return { count, complete: false };
144
+ }
145
+ if (entry.isFile() && parseSegmentDay(entry.name, prefix)) {
146
+ count += 1;
147
+ if (count >= maxFiles) {
148
+ return { count, complete: true };
149
+ }
150
+ }
151
+ }
152
+ }
153
+ finally {
154
+ await directoryHandle.close().catch(() => { });
155
+ }
156
+ return { count, complete: true };
157
+ }
158
+ export async function appendBoundedJsonl(directory, prefix, id, value, options = {}) {
159
+ const { retentionDays, shardCount, maxSegmentBytes } = resolveStoreOptions(options);
160
+ const now = options.now ?? new Date();
161
+ if (!Number.isFinite(now.getTime())) {
162
+ throw new RangeError("now must be a valid Date");
163
+ }
164
+ const line = `${JSON.stringify(value)}\n`;
165
+ const lineBytes = Buffer.byteLength(line, "utf8");
166
+ if (lineBytes > maxSegmentBytes) {
167
+ return undefined;
168
+ }
169
+ await mkdir(directory, { recursive: true, mode: 0o700 });
170
+ const maxFiles = retentionDays * shardCount;
171
+ const path = join(directory, segmentName(prefix, formatDay(now), shardFor(id, shardCount)));
172
+ const lockPath = `${path}.lock`;
173
+ const admissionLockPath = join(directory, `.${prefix}.admission.lock`);
174
+ const admissionOwner = await acquireLock(admissionLockPath);
175
+ if (!admissionOwner) {
176
+ return undefined;
177
+ }
178
+ let owner;
179
+ try {
180
+ await pruneExpiredSegments(directory, prefix, retentionDays, maxFiles, now);
181
+ let targetExists = false;
182
+ try {
183
+ targetExists = (await lstat(path)).isFile();
184
+ if (!targetExists) {
185
+ return undefined;
186
+ }
187
+ }
188
+ catch (error) {
189
+ if (error.code !== "ENOENT") {
190
+ throw error;
191
+ }
192
+ }
193
+ if (!targetExists) {
194
+ const segmentCount = await countOwnedSegments(directory, prefix, maxFiles);
195
+ if (!segmentCount.complete || segmentCount.count >= maxFiles) {
196
+ return undefined;
197
+ }
198
+ }
199
+ owner = await acquireLock(lockPath);
200
+ if (!owner) {
201
+ return undefined;
202
+ }
203
+ if (!targetExists) {
204
+ try {
205
+ const file = await open(path, "wx", 0o600);
206
+ await file.close();
207
+ }
208
+ catch (error) {
209
+ await releaseLock(lockPath, owner);
210
+ owner = undefined;
211
+ if (error.code === "EEXIST") {
212
+ return undefined;
213
+ }
214
+ throw error;
215
+ }
216
+ }
217
+ }
218
+ catch (error) {
219
+ if (owner) {
220
+ await releaseLock(lockPath, owner);
221
+ owner = undefined;
222
+ }
223
+ throw error;
224
+ }
225
+ finally {
226
+ await releaseLock(admissionLockPath, admissionOwner);
227
+ }
228
+ if (!owner) {
229
+ return undefined;
230
+ }
231
+ try {
232
+ let currentBytes = 0;
233
+ try {
234
+ currentBytes = (await stat(path)).size;
235
+ }
236
+ catch (error) {
237
+ if (error.code !== "ENOENT") {
238
+ throw error;
239
+ }
240
+ }
241
+ if (currentBytes + lineBytes > maxSegmentBytes) {
242
+ return undefined;
243
+ }
244
+ await appendFile(path, line, { encoding: "utf8", mode: 0o600 });
245
+ return path;
246
+ }
247
+ finally {
248
+ await releaseLock(lockPath, owner);
249
+ }
250
+ }
251
+ function encodeCursor(file, line) {
252
+ return Buffer.from(JSON.stringify({ file, line }), "utf8").toString("base64url");
253
+ }
254
+ function decodeCursor(cursor, prefix) {
255
+ try {
256
+ const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
257
+ if (typeof parsed === "object"
258
+ && parsed !== null
259
+ && !Array.isArray(parsed)
260
+ && typeof parsed.file === "string"
261
+ && parsed.file.length <= 255
262
+ && parseSegmentDay(parsed.file, prefix) !== undefined
263
+ && Number.isSafeInteger(parsed.line)
264
+ && Number(parsed.line) >= 0) {
265
+ return {
266
+ file: parsed.file,
267
+ line: Number(parsed.line),
268
+ };
269
+ }
270
+ }
271
+ catch {
272
+ // Fall through to the same public error for every malformed cursor.
273
+ }
274
+ throw new RangeError("cursor must identify a valid retained segment position");
275
+ }
276
+ export async function readBoundedJsonlPage(directory, prefix, validate, options = {}) {
277
+ const limit = positiveInteger(options.limit, DEFAULT_PAGE_LIMIT, "limit", MAX_PAGE_LIMIT);
278
+ const maxFiles = positiveInteger(options.maxFiles, DEFAULT_RETENTION_DAYS * DEFAULT_SHARD_COUNT, "maxFiles", MAX_STORE_FILES);
279
+ const maxSegmentBytes = positiveInteger(options.maxSegmentBytes, DEFAULT_MAX_SEGMENT_BYTES, "maxSegmentBytes", MAX_SEGMENT_BYTES);
280
+ const names = [];
281
+ let directoryTruncated = false;
282
+ try {
283
+ const directoryHandle = await opendir(directory);
284
+ let inspected = 0;
285
+ try {
286
+ for await (const entry of directoryHandle) {
287
+ inspected += 1;
288
+ if (inspected > maxFiles * 2 + DIRECTORY_ENTRY_SLACK) {
289
+ directoryTruncated = true;
290
+ break;
291
+ }
292
+ if (entry.isFile() && parseSegmentDay(entry.name, prefix)) {
293
+ if (names.length >= maxFiles) {
294
+ directoryTruncated = true;
295
+ break;
296
+ }
297
+ names.push(entry.name);
298
+ }
299
+ }
300
+ }
301
+ finally {
302
+ await directoryHandle.close().catch(() => { });
303
+ }
304
+ names.sort().reverse();
305
+ }
306
+ catch (error) {
307
+ if (error.code === "ENOENT") {
308
+ return { records: [], partial: false };
309
+ }
310
+ throw error;
311
+ }
312
+ const cursor = options.cursor === undefined ? undefined : decodeCursor(options.cursor, prefix);
313
+ let startFileIndex = 0;
314
+ if (cursor) {
315
+ const exactFileIndex = names.indexOf(cursor.file);
316
+ if (exactFileIndex >= 0) {
317
+ startFileIndex = exactFileIndex;
318
+ }
319
+ else {
320
+ directoryTruncated = true;
321
+ startFileIndex = names.findIndex((name) => name < cursor.file);
322
+ if (startFileIndex < 0) {
323
+ return { records: [], partial: true };
324
+ }
325
+ }
326
+ }
327
+ const records = [];
328
+ let rejectedRecords = false;
329
+ for (let fileIndex = startFileIndex; fileIndex < names.length; fileIndex += 1) {
330
+ const name = names[fileIndex];
331
+ const path = join(directory, name);
332
+ let details;
333
+ try {
334
+ details = await stat(path);
335
+ }
336
+ catch (error) {
337
+ if (error.code === "ENOENT") {
338
+ continue;
339
+ }
340
+ throw error;
341
+ }
342
+ if (!details.isFile() || details.size > maxSegmentBytes) {
343
+ directoryTruncated = true;
344
+ continue;
345
+ }
346
+ let file;
347
+ try {
348
+ file = await open(path, "r");
349
+ }
350
+ catch (error) {
351
+ if (error.code === "ENOENT") {
352
+ directoryTruncated = true;
353
+ continue;
354
+ }
355
+ throw error;
356
+ }
357
+ let raw;
358
+ try {
359
+ const buffer = Buffer.allocUnsafe(maxSegmentBytes + 1);
360
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
361
+ if (bytesRead > maxSegmentBytes) {
362
+ directoryTruncated = true;
363
+ continue;
364
+ }
365
+ raw = buffer.toString("utf8", 0, bytesRead);
366
+ }
367
+ finally {
368
+ await file.close();
369
+ }
370
+ const lines = raw.split("\n");
371
+ const startLine = cursor && name === cursor.file ? cursor.line : 0;
372
+ for (let lineIndex = startLine; lineIndex < lines.length; lineIndex += 1) {
373
+ const line = lines[lineIndex].trim();
374
+ if (!line) {
375
+ continue;
376
+ }
377
+ try {
378
+ const parsed = JSON.parse(line);
379
+ if (validate(parsed)) {
380
+ if (records.length >= limit) {
381
+ return {
382
+ records,
383
+ nextCursor: encodeCursor(name, lineIndex),
384
+ partial: true,
385
+ };
386
+ }
387
+ records.push({ path, value: parsed });
388
+ }
389
+ else {
390
+ rejectedRecords = true;
391
+ }
392
+ }
393
+ catch {
394
+ rejectedRecords = true;
395
+ // One interrupted or malformed record must not hide the rest of the page.
396
+ }
397
+ }
398
+ }
399
+ return { records, partial: directoryTruncated || rejectedRecords };
400
+ }
401
+ export function boundedJsonlCapacity(options = {}) {
402
+ const { retentionDays, shardCount, maxSegmentBytes } = resolveStoreOptions(options);
403
+ return {
404
+ maxFiles: retentionDays * shardCount,
405
+ maxBytes: retentionDays * shardCount * maxSegmentBytes,
406
+ };
407
+ }
@@ -12,6 +12,7 @@ export type CompactBashResultInput = {
12
12
  noOmit?: boolean;
13
13
  allowOmit?: boolean;
14
14
  storeRaw?: boolean;
15
+ recordStats?: boolean;
15
16
  metadata?: Record<string, unknown>;
16
17
  inspectionPolicy?: InspectionCommandPolicy;
17
18
  /** @deprecated use inspectionPolicy instead. */
@@ -1,5 +1,6 @@
1
1
  import { getInspectionCommandSkipReason, getSafeRepositoryInventorySourceArgv } from "../inventory-safety.js";
2
2
  import { readNoOmissionFromEnv } from "../env.js";
3
+ import { shouldRecordStats } from "../artifacts.js";
3
4
  import { buildInspectionSummary } from "../reduce-inspection-summary.js";
4
5
  import { reduceExecution } from "../reduce.js";
5
6
  import { getCompactionSkipReason } from "./rewrite-policy.js";
@@ -62,7 +63,7 @@ export async function compactBashResult(input) {
62
63
  ...(typeof input.cwd === "string" && input.cwd.trim() ? { cwd: input.cwd } : {}),
63
64
  ...(typeof input.maxInlineChars === "number" ? { maxInlineChars: input.maxInlineChars } : {}),
64
65
  ...(input.noOmit || (!input.allowOmit && readNoOmissionFromEnv()) ? { noOmit: true } : {}),
65
- recordStats: true,
66
+ recordStats: input.recordStats ?? shouldRecordStats(),
66
67
  ...(input.storeRaw ? { store: true } : {}),
67
68
  };
68
69
  const result = await reduceExecution(executionInput, options);
@@ -302,6 +302,7 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
302
302
  input: normalizedInput,
303
303
  rawText,
304
304
  classification,
305
+ ...(opts.recordStats !== undefined ? { recordStats: opts.recordStats } : {}),
305
306
  stats: {
306
307
  rawChars: measuredRawChars,
307
308
  reducedChars: measuredRawChars,
@@ -356,6 +357,7 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
356
357
  input: normalizedInput,
357
358
  rawText,
358
359
  classification: summaryClassification,
360
+ ...(opts.recordStats !== undefined ? { recordStats: opts.recordStats } : {}),
359
361
  stats,
360
362
  }, opts.storeDir)
361
363
  : undefined;
@@ -423,6 +425,7 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
423
425
  input: normalizedInput,
424
426
  rawText,
425
427
  classification,
428
+ ...(opts.recordStats !== undefined ? { recordStats: opts.recordStats } : {}),
426
429
  stats,
427
430
  }, opts.storeDir)
428
431
  : undefined;
@@ -464,6 +467,7 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
464
467
  input: normalizedInput,
465
468
  rawText,
466
469
  classification: jsonClassification,
470
+ ...(opts.recordStats !== undefined ? { recordStats: opts.recordStats } : {}),
467
471
  stats,
468
472
  }, opts.storeDir)
469
473
  : undefined;
@@ -501,6 +505,7 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
501
505
  input: normalizedInput,
502
506
  rawText,
503
507
  classification,
508
+ ...(opts.recordStats !== undefined ? { recordStats: opts.recordStats } : {}),
504
509
  stats,
505
510
  }, opts.storeDir)
506
511
  : undefined;
@@ -84,7 +84,7 @@ export async function runWrappedCommand(argv, opts = {}) {
84
84
  raw: opts.raw ?? false,
85
85
  noOmit: opts.noOmit ?? false,
86
86
  trace: opts.trace ?? false,
87
- recordStats: opts.recordStats ?? false,
87
+ ...(opts.recordStats !== undefined ? { recordStats: opts.recordStats } : {}),
88
88
  store: opts.store ?? false,
89
89
  ...(opts.storeDir ? { storeDir: opts.storeDir } : {}),
90
90
  ...(typeof opts.maxInlineChars === "number" ? { maxInlineChars: opts.maxInlineChars } : {}),
@@ -1,9 +1,12 @@
1
1
  import type { HookCommandPackageVersionMismatch, HookCommandRuntimeMismatch } from "../shared/hook-command-doctor.js";
2
+ declare const CODEX_HOOK_INTEGRATION_ID = "tokenjuice.post-tool-use";
2
3
  export type InstallCodexHookResult = {
3
4
  hooksPath: string;
4
5
  backupPath?: string;
5
6
  command: string;
6
7
  featureFlag: CodexFeatureFlagStatus;
8
+ writer: "codex-hooks" | "standalone";
9
+ fragmentId: typeof CODEX_HOOK_INTEGRATION_ID;
7
10
  };
8
11
  export type CodexFeatureFlagStatus = {
9
12
  /** Absolute path we looked at (`~/.codex/config.toml` by default). */
@@ -85,6 +88,8 @@ export type UninstallCodexHookResult = {
85
88
  hooksPath: string;
86
89
  backupPath?: string;
87
90
  removed: number;
91
+ writer: "codex-hooks" | "standalone";
92
+ fragmentId: typeof CODEX_HOOK_INTEGRATION_ID;
88
93
  };
89
94
  /**
90
95
  * Read-only scan of ~/.codex/config.toml for the modern `hooks = <bool>`
@@ -115,3 +120,4 @@ export declare function runCodexPostToolUseHook(rawText: string, options?: {
115
120
  noOmit?: boolean;
116
121
  allowOmit?: boolean;
117
122
  }): Promise<number>;
123
+ export {};