@openclaw/tokenjuice 2026.9.5 → 2026.9.7

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.
Files changed (29) hide show
  1. package/assets/icon.png +0 -0
  2. package/dist/index.js +1 -1
  3. package/node_modules/tokenjuice/README.md +4 -0
  4. package/node_modules/tokenjuice/dist/cli/main.d.ts +3 -0
  5. package/node_modules/tokenjuice/dist/cli/main.js +58 -10
  6. package/node_modules/tokenjuice/dist/core/analysis.js +3 -3
  7. package/node_modules/tokenjuice/dist/core/artifacts.d.ts +5 -1
  8. package/node_modules/tokenjuice/dist/core/artifacts.js +93 -45
  9. package/node_modules/tokenjuice/dist/core/bounded-jsonl.d.ts +26 -0
  10. package/node_modules/tokenjuice/dist/core/bounded-jsonl.js +407 -0
  11. package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.d.ts +1 -0
  12. package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.js +2 -1
  13. package/node_modules/tokenjuice/dist/core/reduce.js +5 -0
  14. package/node_modules/tokenjuice/dist/core/wrap.js +1 -1
  15. package/node_modules/tokenjuice/dist/hosts/claude-code/index.js +12 -61
  16. package/node_modules/tokenjuice/dist/hosts/codebuddy/index.js +12 -61
  17. package/node_modules/tokenjuice/dist/hosts/codex/index.d.ts +6 -0
  18. package/node_modules/tokenjuice/dist/hosts/codex/index.js +365 -147
  19. package/node_modules/tokenjuice/dist/hosts/droid/index.js +21 -29
  20. package/node_modules/tokenjuice/dist/hosts/opencode/extension/runtime.js +1489 -1193
  21. package/node_modules/tokenjuice/dist/hosts/pi/extension/runtime.js +1471 -1175
  22. package/node_modules/tokenjuice/dist/hosts/shared/settings-file.d.ts +10 -0
  23. package/node_modules/tokenjuice/dist/hosts/shared/settings-file.js +165 -0
  24. package/node_modules/tokenjuice/dist/index.d.ts +1 -1
  25. package/node_modules/tokenjuice/dist/index.js +1 -1
  26. package/node_modules/tokenjuice/dist/types.d.ts +15 -0
  27. package/node_modules/tokenjuice/package.json +1 -1
  28. package/openclaw.plugin.json +1 -1
  29. package/package.json +5 -5
@@ -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,7 +1,8 @@
1
- import { access, mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { dirname, join } from "node:path";
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
3
  import { homedir } from "node:os";
4
4
  import { extractHookCommandPaths } from "../shared/hook-command.js";
5
+ import { readSettingsFile, writeSettingsFile } from "../shared/settings-file.js";
5
6
  import { buildWrapLauncherHookCommand, buildWrappedCommand, commandAlreadyWrapped, isExecutableFile, isRecord, pathExists, resolveHostShell, } from "../shared/pre-tool-wrap.js";
6
7
  const TOKENJUICE_CLAUDE_CODE_STATUS = "wrapping bash through tokenjuice for compaction";
7
8
  const TOKENJUICE_CLAUDE_CODE_LEGACY_STATUS = "compacting bash output with tokenjuice";
@@ -97,22 +98,6 @@ function sanitizeClaudeCodeSettings(raw) {
97
98
  hooks: sanitizeHooksSubtree(raw.hooks),
98
99
  };
99
100
  }
100
- async function loadClaudeCodeSettings(settingsPath) {
101
- try {
102
- const rawText = await readFile(settingsPath, "utf8");
103
- const parsed = JSON.parse(rawText);
104
- const config = sanitizeClaudeCodeSettings(parsed);
105
- const backupPath = `${settingsPath}.bak`;
106
- await writeFile(backupPath, rawText, "utf8");
107
- return { config, backupPath };
108
- }
109
- catch (error) {
110
- if (error.code === "ENOENT") {
111
- return { config: { hooks: {} } };
112
- }
113
- throw new Error(`failed to load claude code settings from ${settingsPath}: ${error instanceof Error ? error.message : String(error)}`);
114
- }
115
- }
116
101
  async function readClaudeCodeSettings(settingsPath) {
117
102
  try {
118
103
  const rawText = await readFile(settingsPath, "utf8");
@@ -132,20 +117,6 @@ async function readClaudeCodeSettings(settingsPath) {
132
117
  throw new Error(`failed to read claude code settings from ${settingsPath}: ${error instanceof Error ? error.message : String(error)}`);
133
118
  }
134
119
  }
135
- async function chooseBackupPath(filePath) {
136
- for (let index = 0;; index += 1) {
137
- const candidate = index === 0 ? `${filePath}.bak` : `${filePath}.bak.${index}`;
138
- try {
139
- await access(candidate);
140
- }
141
- catch (error) {
142
- if (error.code === "ENOENT") {
143
- return candidate;
144
- }
145
- throw error;
146
- }
147
- }
148
- }
149
120
  function pruneTokenjuiceHookEntries(groups) {
150
121
  const pruned = [];
151
122
  for (const group of groups) {
@@ -193,7 +164,8 @@ async function resolveClaudeCodeHostShell(toolInput) {
193
164
  ]);
194
165
  }
195
166
  export async function installClaudeCodeHook(settingsPath = getDefaultSettingsPath(), options = {}) {
196
- const { config, backupPath } = await loadClaudeCodeSettings(settingsPath);
167
+ const settings = await readSettingsFile(settingsPath);
168
+ const config = sanitizeClaudeCodeSettings(settings.data ? JSON.parse(settings.data.toString("utf8")) : undefined);
197
169
  const command = await buildClaudeCodeHookCommand(options);
198
170
  if (Array.isArray(config.hooks.PostToolUse)) {
199
171
  const prunedPost = pruneTokenjuiceHookEntries(config.hooks.PostToolUse);
@@ -208,10 +180,7 @@ export async function installClaudeCodeHook(settingsPath = getDefaultSettingsPat
208
180
  const retained = pruneTokenjuiceHookEntries(preToolUse);
209
181
  retained.push(createTokenjuiceClaudeCodeHook(command));
210
182
  config.hooks.PreToolUse = retained;
211
- await mkdir(dirname(settingsPath), { recursive: true });
212
- const tempPath = `${settingsPath}.tmp`;
213
- await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
214
- await rename(tempPath, settingsPath);
183
+ const backupPath = await writeSettingsFile(settings, `${JSON.stringify(config, null, 2)}\n`, "replace");
215
184
  return {
216
185
  settingsPath,
217
186
  ...(backupPath ? { backupPath } : {}),
@@ -219,39 +188,21 @@ export async function installClaudeCodeHook(settingsPath = getDefaultSettingsPat
219
188
  };
220
189
  }
221
190
  export async function uninstallClaudeCodeHook(settingsPath = getDefaultSettingsPath()) {
222
- let rawText;
223
- try {
224
- rawText = await readFile(settingsPath, "utf8");
225
- }
226
- catch (error) {
227
- if (error.code === "ENOENT") {
228
- return { settingsPath, removed: false };
229
- }
230
- throw new Error(`failed to read claude code settings from ${settingsPath}: ${error instanceof Error ? error.message : String(error)}`);
231
- }
232
- let parsed;
233
- try {
234
- parsed = JSON.parse(rawText);
235
- }
236
- catch (error) {
237
- throw new Error(`failed to read claude code settings from ${settingsPath}: ${error instanceof Error ? error.message : String(error)}`);
191
+ const settings = await readSettingsFile(settingsPath);
192
+ if (!settings.data) {
193
+ return { settingsPath, removed: false };
238
194
  }
239
- const config = sanitizeClaudeCodeSettings(parsed);
195
+ const config = sanitizeClaudeCodeSettings(JSON.parse(settings.data.toString("utf8")));
240
196
  const removedPreToolUse = removeTokenjuiceHookEvent(config, "PreToolUse");
241
197
  const removedPostToolUse = removeTokenjuiceHookEvent(config, "PostToolUse");
242
198
  const removed = removedPreToolUse || removedPostToolUse;
243
199
  if (!removed) {
244
200
  return { settingsPath, removed: false };
245
201
  }
246
- const backupPath = await chooseBackupPath(settingsPath);
247
- await writeFile(backupPath, rawText, "utf8");
248
- await mkdir(dirname(settingsPath), { recursive: true });
249
- const tempPath = `${settingsPath}.tmp`;
250
- await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
251
- await rename(tempPath, settingsPath);
202
+ const backupPath = await writeSettingsFile(settings, `${JSON.stringify(config, null, 2)}\n`, "preserve");
252
203
  return {
253
204
  settingsPath,
254
- backupPath,
205
+ ...(backupPath ? { backupPath } : {}),
255
206
  removed: true,
256
207
  };
257
208
  }