@openclaw/tokenjuice 2026.9.4 → 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.
- package/assets/activity.svg +3 -0
- package/assets/icon.png +0 -0
- package/node_modules/tokenjuice/README.md +10 -1
- package/node_modules/tokenjuice/dist/cli/install-output.d.ts +7 -0
- package/node_modules/tokenjuice/dist/cli/install-output.js +19 -0
- package/node_modules/tokenjuice/dist/cli/main.d.ts +7 -0
- package/node_modules/tokenjuice/dist/cli/main.js +201 -36
- package/node_modules/tokenjuice/dist/core/analysis.js +3 -3
- package/node_modules/tokenjuice/dist/core/artifacts.d.ts +6 -1
- package/node_modules/tokenjuice/dist/core/artifacts.js +122 -45
- package/node_modules/tokenjuice/dist/core/bounded-jsonl.d.ts +26 -0
- package/node_modules/tokenjuice/dist/core/bounded-jsonl.js +407 -0
- package/node_modules/tokenjuice/dist/core/compaction-metadata.d.ts +1 -1
- package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.d.ts +2 -0
- package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.js +3 -2
- package/node_modules/tokenjuice/dist/core/reduce.js +23 -10
- package/node_modules/tokenjuice/dist/core/text.d.ts +4 -0
- package/node_modules/tokenjuice/dist/core/text.js +32 -0
- package/node_modules/tokenjuice/dist/core/wrap.js +1 -1
- package/node_modules/tokenjuice/dist/hosts/codex/index.d.ts +31 -1
- package/node_modules/tokenjuice/dist/hosts/codex/index.js +554 -288
- package/node_modules/tokenjuice/dist/hosts/droid/index.js +12 -3
- package/node_modules/tokenjuice/dist/hosts/grok-bot/index.d.ts +25 -0
- package/node_modules/tokenjuice/dist/hosts/grok-bot/index.js +644 -0
- package/node_modules/tokenjuice/dist/hosts/opencode/extension/runtime.js +644 -279
- package/node_modules/tokenjuice/dist/hosts/pi/extension/runtime.js +647 -282
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.d.ts +24 -0
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.js +80 -1
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command.d.ts +19 -0
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command.js +61 -6
- package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.d.ts +3 -1
- package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.js +2 -0
- package/node_modules/tokenjuice/dist/hosts/shared/host-command.d.ts +10 -1
- package/node_modules/tokenjuice/dist/hosts/shared/host-command.js +43 -4
- package/node_modules/tokenjuice/dist/hosts/shared/pre-tool-wrap.js +9 -7
- package/node_modules/tokenjuice/dist/index.d.ts +3 -1
- package/node_modules/tokenjuice/dist/index.js +2 -1
- package/node_modules/tokenjuice/dist/types.d.ts +15 -0
- package/node_modules/tokenjuice/package.json +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +8 -6
|
@@ -1,9 +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>;
|
|
10
|
+
export declare function tryStoreArtifactMetadata(input: StoredArtifactInput, storeDir?: string): Promise<ArtifactMetadataRef | undefined>;
|
|
7
11
|
export declare function getArtifact(id: string, storeDir?: string): Promise<StoredArtifact | null>;
|
|
8
12
|
export declare function listArtifacts(storeDir?: string): Promise<StoredArtifactRef[]>;
|
|
9
13
|
export declare function listArtifactMetadata(storeDir?: string): Promise<ArtifactMetadataRef[]>;
|
|
14
|
+
export declare function listArtifactMetadataPage(storeDir?: string, options?: ArtifactMetadataPageOptions): Promise<ArtifactMetadataPage>;
|
|
@@ -1,11 +1,34 @@
|
|
|
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 {
|
|
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;
|
|
15
|
+
const OPTIONAL_METADATA_STORAGE_ERROR_CODES = new Set([
|
|
16
|
+
"EACCES",
|
|
17
|
+
"EDQUOT",
|
|
18
|
+
"EEXIST",
|
|
19
|
+
"EFBIG",
|
|
20
|
+
"EIO",
|
|
21
|
+
"EISDIR",
|
|
22
|
+
"ELOOP",
|
|
23
|
+
"EMFILE",
|
|
24
|
+
"ENAMETOOLONG",
|
|
25
|
+
"ENFILE",
|
|
26
|
+
"ENOENT",
|
|
27
|
+
"ENOSPC",
|
|
28
|
+
"ENOTDIR",
|
|
29
|
+
"EPERM",
|
|
30
|
+
"EROFS",
|
|
31
|
+
]);
|
|
9
32
|
function isRecord(value) {
|
|
10
33
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11
34
|
}
|
|
@@ -28,6 +51,12 @@ function isStoredArtifactMetadata(value) {
|
|
|
28
51
|
if ("command" in value && value.command !== undefined && typeof value.command !== "string") {
|
|
29
52
|
return false;
|
|
30
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
|
+
}
|
|
31
60
|
if ("exitCode" in value && value.exitCode !== undefined && typeof value.exitCode !== "number") {
|
|
32
61
|
return false;
|
|
33
62
|
}
|
|
@@ -71,11 +100,45 @@ function buildArtifactPaths(id, storeDir) {
|
|
|
71
100
|
metadataPath: join(base, `${id}.json`),
|
|
72
101
|
};
|
|
73
102
|
}
|
|
74
|
-
function
|
|
75
|
-
|
|
76
|
-
|
|
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;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return undefined;
|
|
77
121
|
}
|
|
78
|
-
|
|
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";
|
|
79
142
|
}
|
|
80
143
|
export async function storeArtifact(input, storeDir) {
|
|
81
144
|
const id = `tj_${randomUUID().slice(0, 12)}`;
|
|
@@ -101,11 +164,13 @@ export async function storeArtifact(input, storeDir) {
|
|
|
101
164
|
writeFile(ref.path, input.rawText, { encoding: "utf8", mode: 0o600 }),
|
|
102
165
|
writeFile(ref.metadataPath, JSON.stringify(artifact.metadata, null, 2), { encoding: "utf8", mode: 0o600 }),
|
|
103
166
|
]);
|
|
167
|
+
if (input.recordStats ?? shouldRecordStats()) {
|
|
168
|
+
await appendMetadataEvent(id, artifact.metadata, input.input, true, storeDir).catch(() => undefined);
|
|
169
|
+
}
|
|
104
170
|
return ref;
|
|
105
171
|
}
|
|
106
172
|
export async function storeArtifactMetadata(input, storeDir) {
|
|
107
173
|
const id = `tj_${randomUUID().slice(0, 12)}`;
|
|
108
|
-
const metadataPath = buildMetadataOnlyPath(id, storeDir);
|
|
109
174
|
const captureTruncated = extractCaptureTruncatedFlag(input.input);
|
|
110
175
|
const metadata = {
|
|
111
176
|
createdAt: new Date().toISOString(),
|
|
@@ -118,15 +183,32 @@ export async function storeArtifactMetadata(input, storeDir) {
|
|
|
118
183
|
...(captureTruncated !== undefined ? { captureTruncated } : {}),
|
|
119
184
|
...(input.stats ? { reducedChars: input.stats.reducedChars, ratio: input.stats.ratio } : {}),
|
|
120
185
|
};
|
|
121
|
-
|
|
122
|
-
|
|
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
|
+
}
|
|
123
191
|
return {
|
|
124
192
|
id,
|
|
125
193
|
storage: "file",
|
|
126
194
|
metadataPath,
|
|
127
|
-
|
|
195
|
+
metadataFormat: "jsonl-segment",
|
|
196
|
+
metadataRecordId: id,
|
|
197
|
+
metadata: telemetryMetadata,
|
|
128
198
|
};
|
|
129
199
|
}
|
|
200
|
+
export async function tryStoreArtifactMetadata(input, storeDir) {
|
|
201
|
+
try {
|
|
202
|
+
return await storeArtifactMetadata(input, storeDir);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
const code = error.code;
|
|
206
|
+
if (typeof code !== "string" || !OPTIONAL_METADATA_STORAGE_ERROR_CODES.has(code)) {
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
130
212
|
export async function getArtifact(id, storeDir) {
|
|
131
213
|
if (!isValidArtifactId(id)) {
|
|
132
214
|
return null;
|
|
@@ -170,41 +252,36 @@ export async function listArtifacts(storeDir) {
|
|
|
170
252
|
}
|
|
171
253
|
}
|
|
172
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);
|
|
173
269
|
const base = resolveArtifactBaseDir(storeDir);
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
return {
|
|
192
|
-
id: rawId,
|
|
193
|
-
storage: "file",
|
|
194
|
-
...(path ? { path } : {}),
|
|
195
|
-
metadataPath,
|
|
196
|
-
metadata: parsed,
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
catch {
|
|
200
|
-
return null;
|
|
201
|
-
}
|
|
202
|
-
}));
|
|
203
|
-
return metadata
|
|
204
|
-
.filter((entry) => entry !== null)
|
|
205
|
-
.sort((left, right) => right.metadata.createdAt.localeCompare(left.metadata.createdAt));
|
|
206
|
-
}
|
|
207
|
-
catch {
|
|
208
|
-
return [];
|
|
209
|
-
}
|
|
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
|
+
};
|
|
210
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
|
+
};
|
|
@@ -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
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type CompactionKind = "head-tail-omission" | "middle-truncation" | "tail-truncation" | "hashed-middle-clip" | "git-diff-hunk-clip" | "inspection-package-lock-summary" | "inspection-large-document-summary" | "github-actions-command-list-omission" | "github-actions-log-signal-filter" | "github-status-check-rollup-omission" | "no-omit-head-tail-passthrough" | "no-omit-char-clip-passthrough" | "no-omit-domain-passthrough";
|
|
1
|
+
export type CompactionKind = "head-tail-omission" | "middle-truncation" | "tail-truncation" | "hashed-middle-clip" | "git-diff-hunk-clip" | "inspection-package-lock-summary" | "inspection-large-document-summary" | "repeated-emoji-banner-omission" | "github-actions-command-list-omission" | "github-actions-log-signal-filter" | "github-status-check-rollup-omission" | "no-omit-head-tail-passthrough" | "no-omit-char-clip-passthrough" | "no-omit-domain-passthrough";
|
|
2
2
|
export type CompactionMetadata = {
|
|
3
3
|
authoritative: boolean;
|
|
4
4
|
kinds: CompactionKind[];
|
|
@@ -10,7 +10,9 @@ export type CompactBashResultInput = {
|
|
|
10
10
|
exitCode?: number;
|
|
11
11
|
maxInlineChars?: number;
|
|
12
12
|
noOmit?: boolean;
|
|
13
|
+
allowOmit?: boolean;
|
|
13
14
|
storeRaw?: boolean;
|
|
15
|
+
recordStats?: boolean;
|
|
14
16
|
metadata?: Record<string, unknown>;
|
|
15
17
|
inspectionPolicy?: InspectionCommandPolicy;
|
|
16
18
|
/** @deprecated use inspectionPolicy instead. */
|