@bli-cockpit/telemetry-core 0.1.88 → 0.1.90

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.
@@ -17,6 +17,7 @@ import { formatImageMarker, imageMarkerPattern, IMAGE_MIN_BASE64_CHARS } from ".
17
17
  import { SECRET_LIKE_CONTENT_PATTERNS } from "./secret-guards-content-rules.js";
18
18
  import { SECRET_REDACTION_RULES } from "./secret-guards-masking.js";
19
19
  import { SECRET_FILE_SEGMENT_PATTERN } from "./secret-guards-path-rules.js";
20
+ import { PDF_RULES_VERSION, formatPdfMarker, formatPdfReference } from "./pdf-markers.js";
20
21
  import { findEmbeddedImages } from "./transcript-images.js";
21
22
  let cached;
22
23
  /** The probe: a tiny PNG header padded past the detector's minimum, in both shapes the detector knows. */
@@ -39,6 +40,10 @@ export function evidenceRulesFingerprint() {
39
40
  image_min_base64_chars: IMAGE_MIN_BASE64_CHARS,
40
41
  image_marker_pattern: describe(imageMarkerPattern()),
41
42
  image_marker_sample: formatImageMarker({ sha256: "0123456789abcdef".repeat(4), mediaType: "image/png", byteSize: 412 * 1024 }),
43
+ // BLI-23347: PDFs become text. The rules version and both marker shapes decide those bytes.
44
+ pdf_rules_version: PDF_RULES_VERSION,
45
+ pdf_marker_sample: formatPdfMarker({ sha256: "0123456789abcdef".repeat(4), pages: 3, byteSize: 412 * 1024, method: "text-layer", notes: ["sample"] }, "body"),
46
+ pdf_reference_sample: formatPdfReference({ sha256: "0123456789abcdef".repeat(4), byteSize: 412 * 1024 }),
42
47
  image_detector_probe: findEmbeddedImages(probe).map((image) => [image.replaceStart, image.replaceEnd, image.mediaType, image.byteSize]),
43
48
  };
44
49
  cached = createHash("sha256").update(JSON.stringify(parts)).digest("hex");
@@ -0,0 +1,22 @@
1
+ import { type ImageMediaType } from "./image-descriptions.js";
2
+ import type { EmbeddedImage } from "./transcript-images.js";
3
+ /** Is there any chance this line holds an image? Same anchors as the string check, on bytes. */
4
+ export declare function bytesMayHoldImage(line: Buffer): boolean;
5
+ interface Digest {
6
+ sha256: string;
7
+ mediaType: ImageMediaType;
8
+ byteSize: number;
9
+ }
10
+ /**
11
+ * sha256, size and type of the image `line[from, to)` encodes, or null when it is not a PNG, JPEG, GIF
12
+ * or WebP. Blocks of the run are decoded one at a time.
13
+ */
14
+ export declare function digestBase64Run(line: Buffer, from: number, to: number): Digest | null;
15
+ /** The sha256 of an image's decoded bytes, or null when `line[from, to)` does not decode to an image (used to re-check a payload before it is sent). */
16
+ export declare function sha256OfBase64Run(line: Buffer, from: number, to: number): string | null;
17
+ /**
18
+ * Every embedded image in `line` (one physical line, no `\n` inside), in order, with byte offsets inside
19
+ * the line. Equal to `findEmbeddedImages` on the decoded text in everything but the unit of the offsets.
20
+ */
21
+ export declare function scanImagesInLine(line: Buffer): EmbeddedImage[];
22
+ export {};
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Lives in telemetry-core so the collector and the turn-end hook share one scanner (BLI-23349).
3
+ *
4
+ * Find the embedded images of one transcript line without ever building the base64 as a JS string
5
+ * (BLI-23317, stage D).
6
+ *
7
+ * `findEmbeddedImages` (telemetry-core/transcript-images.ts) is the RULE and stays the test oracle: it
8
+ * feeds `evidenceRulesFingerprint`, so its regex and its results do not change. This module is the same
9
+ * rule run on the line's BYTES, which is what the streamed prepare path calls:
10
+ *
11
+ * - a whole-string payload: a base64 run that starts right after a `"`, starts with one of the four
12
+ * image starts (`iVBOR`, `/9j/`, `R0lGO`, `UklGR`), is at least 495 characters past that start
13
+ * (so 499 for a JPEG, 500 for the others, exactly as the regex counts) and is closed by `"` or `\"`;
14
+ * - a data URL: `data:image/<[a-z0-9.+-]+>;base64,` and then a run of at least 500 characters, no closing
15
+ * quote needed. The whole URL is the replaced range.
16
+ *
17
+ * A match is accepted only when the decoded bytes sniff as PNG, JPEG, GIF or WebP; either way the scan
18
+ * resumes after the run, as `matchAll` does. All matched characters are ASCII, so a byte offset here is
19
+ * the character offset there on ASCII text, and the replaced ranges are the same everywhere else.
20
+ *
21
+ * Decoding is incremental: the run is decoded in blocks of 48 Ki characters (a multiple of 4, so each
22
+ * block decodes on its own) straight into a sha256, with the first block sniffed. At no point does a
23
+ * string of the run, or a Buffer of the whole decoded image, exist. The one exception is a run whose
24
+ * `=` characters are not plain trailing padding: Node's decoder rules for those are version specific,
25
+ * so such a run takes the whole-run decode the oracle takes (never seen in real transcripts).
26
+ *
27
+ * `byteSize` is the length Node's `Buffer.from(run, "base64")` gives, because every block, including a
28
+ * short last one, is decoded by that very function.
29
+ */
30
+ import { createHash } from "node:crypto";
31
+ import { IMAGE_MIN_BASE64_CHARS, sniffImageMediaType } from "./image-descriptions.js";
32
+ const QUOTE = 0x22;
33
+ const BACKSLASH = 0x5c;
34
+ const EQUALS = 0x3d;
35
+ /** Characters per decoded block. A multiple of 4: each block is a whole number of base64 quanta. */
36
+ const BLOCK_CHARS = 48 * 1024;
37
+ const BASE64 = new Uint8Array(256);
38
+ for (const range of ["AZ", "az", "09"]) {
39
+ for (let code = range.charCodeAt(0); code <= range.charCodeAt(1); code += 1)
40
+ BASE64[code] = 1;
41
+ }
42
+ for (const char of "+/=")
43
+ BASE64[char.charCodeAt(0)] = 1;
44
+ const DATA_URL_LOWER = new Uint8Array(256);
45
+ for (const range of ["az", "09"]) {
46
+ for (let code = range.charCodeAt(0); code <= range.charCodeAt(1); code += 1)
47
+ DATA_URL_LOWER[code] = 1;
48
+ }
49
+ for (const char of ".+-")
50
+ DATA_URL_LOWER[char.charCodeAt(0)] = 1;
51
+ /** The four image starts of a whole-string payload, and the data URL anchor. */
52
+ const STARTS = ["iVBOR", "/9j/", "R0lGO", "UklGR"].map((text) => Buffer.from(text, "latin1"));
53
+ const DATA_URL = Buffer.from("data:image/", "latin1");
54
+ const BASE64_TAG = Buffer.from(";base64,", "latin1");
55
+ /** Is there any chance this line holds an image? Same anchors as the string check, on bytes. */
56
+ export function bytesMayHoldImage(line) {
57
+ return line.includes(DATA_URL) || STARTS.some((start) => line.includes(start));
58
+ }
59
+ /** The end (exclusive) of the base64-alphabet run that starts at `from`. */
60
+ function runEnd(line, from) {
61
+ let at = from;
62
+ while (at < line.length && BASE64[line[at]] === 1)
63
+ at += 1;
64
+ return at;
65
+ }
66
+ /**
67
+ * sha256, size and type of the image `line[from, to)` encodes, or null when it is not a PNG, JPEG, GIF
68
+ * or WebP. Blocks of the run are decoded one at a time.
69
+ */
70
+ export function digestBase64Run(line, from, to) {
71
+ const length = to - from;
72
+ const inRun = line.subarray(from, to).indexOf(EQUALS);
73
+ const firstPad = inRun === -1 ? -1 : from + inRun;
74
+ const padCount = firstPad === -1 ? 0 : to - firstPad;
75
+ const plainPadding = padCount === 0
76
+ || (padCount <= 2 && length % 4 === 0 && onlyPaddingFrom(line, firstPad, to));
77
+ if (!plainPadding) {
78
+ const bytes = Buffer.from(line.toString("latin1", from, to), "base64");
79
+ const mediaType = sniffImageMediaType(bytes);
80
+ return mediaType ? { sha256: createHash("sha256").update(bytes).digest("hex"), mediaType, byteSize: bytes.byteLength } : null;
81
+ }
82
+ const hash = createHash("sha256");
83
+ let byteSize = 0;
84
+ let mediaType = null;
85
+ for (let at = from; at < to; at += BLOCK_CHARS) {
86
+ const block = Buffer.from(line.toString("latin1", at, Math.min(to, at + BLOCK_CHARS)), "base64");
87
+ if (at === from) {
88
+ mediaType = sniffImageMediaType(block);
89
+ if (!mediaType)
90
+ return null;
91
+ }
92
+ hash.update(block);
93
+ byteSize += block.byteLength;
94
+ }
95
+ return mediaType ? { sha256: hash.digest("hex"), mediaType, byteSize } : null;
96
+ }
97
+ /** True when everything from `firstPad` to `to` is `=` (padding at the very end of the run, nothing after it). */
98
+ function onlyPaddingFrom(line, firstPad, to) {
99
+ for (let at = firstPad; at < to; at += 1)
100
+ if (line[at] !== EQUALS)
101
+ return false;
102
+ return true;
103
+ }
104
+ /** The sha256 of an image's decoded bytes, or null when `line[from, to)` does not decode to an image (used to re-check a payload before it is sent). */
105
+ export function sha256OfBase64Run(line, from, to) {
106
+ return digestBase64Run(line, from, to)?.sha256 ?? null;
107
+ }
108
+ /**
109
+ * The next index at or after `from` where `anchor` sits right after a `"`, or -1. `current` is the answer
110
+ * of the last call: -2 not looked for yet, -1 none left, else still good while it is at or after `from`.
111
+ */
112
+ function nextQuotedStart(line, anchor, from, current) {
113
+ if (current === -1 || current >= from)
114
+ return current;
115
+ let at = line.indexOf(anchor, from);
116
+ while (at !== -1 && !(at > 0 && line[at - 1] === QUOTE))
117
+ at = line.indexOf(anchor, at + 1);
118
+ return at;
119
+ }
120
+ /**
121
+ * Every embedded image in `line` (one physical line, no `\n` inside), in order, with byte offsets inside
122
+ * the line. Equal to `findEmbeddedImages` on the decoded text in everything but the unit of the offsets.
123
+ */
124
+ export function scanImagesInLine(line) {
125
+ const found = [];
126
+ if (line.length < IMAGE_MIN_BASE64_CHARS - 1)
127
+ return found;
128
+ // For each whole-string start, the next quoted occurrence (-2: not looked for yet, -1: none left).
129
+ const nextStart = STARTS.map(() => -2);
130
+ let nextData = -2;
131
+ let position = 0;
132
+ while (position < line.length) {
133
+ let candidate = -1;
134
+ let kind = -1;
135
+ for (let index = 0; index < STARTS.length; index += 1) {
136
+ nextStart[index] = nextQuotedStart(line, STARTS[index], position, nextStart[index]);
137
+ const at = nextStart[index];
138
+ if (at !== -1 && (candidate === -1 || at < candidate)) {
139
+ candidate = at;
140
+ kind = index;
141
+ }
142
+ }
143
+ if (nextData !== -1) {
144
+ nextData = nextData >= position ? nextData : line.indexOf(DATA_URL, position);
145
+ if (nextData !== -1 && (candidate === -1 || nextData < candidate)) {
146
+ candidate = nextData;
147
+ kind = STARTS.length;
148
+ }
149
+ }
150
+ if (candidate === -1)
151
+ break;
152
+ if (kind < STARTS.length) {
153
+ const startLength = STARTS[kind].length;
154
+ const end = runEnd(line, candidate);
155
+ const closed = end < line.length && (line[end] === QUOTE || (line[end] === BACKSLASH && line[end + 1] === QUOTE));
156
+ if (!closed || end - candidate < startLength + (IMAGE_MIN_BASE64_CHARS - 5)) {
157
+ position = candidate + 1;
158
+ continue;
159
+ }
160
+ position = end;
161
+ const digest = digestBase64Run(line, candidate, end);
162
+ if (digest)
163
+ found.push({ replaceStart: candidate, replaceEnd: end, base64Start: candidate, base64End: end, ...digest });
164
+ continue;
165
+ }
166
+ // data:image/<type>;base64,<run of at least 500>
167
+ let cursor = candidate + DATA_URL.length;
168
+ const typeStart = cursor;
169
+ while (cursor < line.length && DATA_URL_LOWER[line[cursor]] === 1)
170
+ cursor += 1;
171
+ if (cursor === typeStart || line.compare(BASE64_TAG, 0, BASE64_TAG.length, cursor, cursor + BASE64_TAG.length) !== 0) {
172
+ position = candidate + 1;
173
+ continue;
174
+ }
175
+ const base64Start = cursor + BASE64_TAG.length;
176
+ const end = runEnd(line, base64Start);
177
+ if (end - base64Start < IMAGE_MIN_BASE64_CHARS) {
178
+ position = candidate + 1;
179
+ continue;
180
+ }
181
+ position = end;
182
+ const digest = digestBase64Run(line, base64Start, end);
183
+ if (digest)
184
+ found.push({ replaceStart: candidate, replaceEnd: end, base64Start, base64End: end, ...digest });
185
+ }
186
+ return found;
187
+ }
package/dist/index.d.ts CHANGED
@@ -14,7 +14,9 @@ export * from "./evidence-upload.js";
14
14
  export * from "./image-description-store.js";
15
15
  export * from "./image-descriptions.js";
16
16
  export * from "./image-marker-resolver.js";
17
+ export * from "./pdf-markers.js";
17
18
  export * from "./transcript-images.js";
19
+ export * from "./image-byte-scan.js";
18
20
  export * from "./ingest-dto.js";
19
21
  export * from "./local-config.js";
20
22
  export * from "./memory-daemon-endpoint.js";
package/dist/index.js CHANGED
@@ -14,7 +14,9 @@ export * from "./evidence-upload.js";
14
14
  export * from "./image-description-store.js";
15
15
  export * from "./image-descriptions.js";
16
16
  export * from "./image-marker-resolver.js";
17
+ export * from "./pdf-markers.js";
17
18
  export * from "./transcript-images.js";
19
+ export * from "./image-byte-scan.js";
18
20
  export * from "./ingest-dto.js";
19
21
  export * from "./local-config.js";
20
22
  export * from "./memory-daemon-endpoint.js";
@@ -0,0 +1,21 @@
1
+ /** Bump when the extraction rules (layout heuristics, limits, page-image encoding) change what a PDF becomes. */
2
+ export declare const PDF_RULES_VERSION = "pdf-text.v1";
3
+ /** What every PDF marker starts with: a cheap `includes` check before anyone runs a regex. */
4
+ export declare const PDF_MARKER_START = "[pdf sha256:";
5
+ export declare const PDF_MARKER_END = "[/pdf]";
6
+ export type PdfConversionMethod = "text-layer" | "page-images";
7
+ export interface PdfMarkerFacts {
8
+ sha256: string;
9
+ pages: number;
10
+ byteSize: number;
11
+ method: PdfConversionMethod;
12
+ /** Short plain statements about the conversion ("pages 1-200 of 412 shown"), shown after the method. */
13
+ notes?: readonly string[];
14
+ }
15
+ /** The marker block for the first copy of a PDF: header, body, closing line. */
16
+ export declare function formatPdfMarker(facts: PdfMarkerFacts, body: string): string;
17
+ /** The one-line stand-in for a repeat copy of a PDF already converted earlier in the same transcript. */
18
+ export declare function formatPdfReference(facts: {
19
+ sha256: string;
20
+ byteSize: number;
21
+ }): string;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * PDFs inside collected transcripts: what replaces their base64 (BLI-23347).
3
+ *
4
+ * Claude Code stores a PDF it read as base64, twice on one line (the tool result block and the
5
+ * structured `toolUseResult.file.base64`). In `describe_and_drop` mode the collector replaces each copy:
6
+ *
7
+ * - the FIRST copy of a PDF becomes a marker block: a header line with the sha256 prefix, page count,
8
+ * size and how it was converted, then the converted body (the PDF's text with tables as Markdown, or
9
+ * for a scan the markers of the page images the describe door described), then `[/pdf]`;
10
+ * - every further copy of the same PDF in the same transcript becomes a one-line reference to it.
11
+ *
12
+ * Shared by the collector (builds the marker) and anything that reads a marker back. Pure: no I/O.
13
+ * Changing the format, or `PDF_RULES_VERSION`, changes `evidenceRulesFingerprint()`, which rebuilds every
14
+ * collector's prepare memo once. That is intended: the bytes the collector makes from a PDF changed.
15
+ */
16
+ import { imageSizeLabel } from "./image-descriptions.js";
17
+ /** Bump when the extraction rules (layout heuristics, limits, page-image encoding) change what a PDF becomes. */
18
+ export const PDF_RULES_VERSION = "pdf-text.v1";
19
+ /** What every PDF marker starts with: a cheap `includes` check before anyone runs a regex. */
20
+ export const PDF_MARKER_START = "[pdf sha256:";
21
+ export const PDF_MARKER_END = "[/pdf]";
22
+ /** Hex characters of the sha256 a PDF marker carries (same as an image marker). */
23
+ const PDF_MARKER_HASH_CHARS = 16;
24
+ function header(facts) {
25
+ const hash = facts.sha256.slice(0, PDF_MARKER_HASH_CHARS);
26
+ const pages = `${facts.pages} ${facts.pages === 1 ? "page" : "pages"}`;
27
+ const method = facts.method === "text-layer" ? "text" : "scanned, page images described";
28
+ const notes = (facts.notes ?? []).map((note) => `; ${note}`).join("");
29
+ return `${PDF_MARKER_START}${hash}… ${pages} ${imageSizeLabel(facts.byteSize)} ${method}${notes}]`;
30
+ }
31
+ /** The marker block for the first copy of a PDF: header, body, closing line. */
32
+ export function formatPdfMarker(facts, body) {
33
+ return `${header(facts)}\n${body}\n${PDF_MARKER_END}`;
34
+ }
35
+ /** The one-line stand-in for a repeat copy of a PDF already converted earlier in the same transcript. */
36
+ export function formatPdfReference(facts) {
37
+ const hash = facts.sha256.slice(0, PDF_MARKER_HASH_CHARS);
38
+ return `${PDF_MARKER_START}${hash}… ${imageSizeLabel(facts.byteSize)} same PDF as the earlier copy in this transcript]`;
39
+ }
@@ -10,6 +10,11 @@ export interface EmbeddedImage {
10
10
  mediaType: ImageMediaType;
11
11
  /** Decoded size in bytes. */
12
12
  byteSize: number;
13
+ /**
14
+ * BLI-23347: set on a stand-in for something that is not an image (a PDF's base64). When present the
15
+ * range is swapped for exactly this text, whatever `replace` says, and no image marker is built.
16
+ */
17
+ replacement?: string;
13
18
  }
14
19
  /**
15
20
  * Cheap check on raw bytes before anyone decodes a whole transcript to text: does it hold a data
@@ -83,9 +83,9 @@ export function replaceImagesWithMarkers(text, images, replace) {
83
83
  let replacedCount = 0;
84
84
  let charsSaved = 0;
85
85
  for (const image of images) {
86
- if (!replace(image))
86
+ if (image.replacement === undefined && !replace(image))
87
87
  continue;
88
- const marker = formatImageMarker({
88
+ const marker = image.replacement ?? formatImageMarker({
89
89
  sha256: image.sha256,
90
90
  mediaType: image.mediaType,
91
91
  byteSize: image.byteSize,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.88",
3
+ "version": "0.1.90",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",