@bli-cockpit/telemetry-core 0.1.71 → 0.1.74
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/dist/image-descriptions.d.ts +23 -8
- package/dist/image-descriptions.js +16 -4
- package/dist/image-marker-resolver.d.ts +88 -0
- package/dist/image-marker-resolver.js +195 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/transcript-images.d.ts +4 -1
- package/dist/transcript-images.js +40 -17
- package/package.json +1 -1
|
@@ -6,23 +6,34 @@
|
|
|
6
6
|
* line. Measured on one laptop on 2026-10-09 that was 17% of Claude bytes and 59% of Codex bytes.
|
|
7
7
|
* The collector finds every such image, sends each distinct one ONCE to the describe door (a
|
|
8
8
|
* short text description, kept against the image's sha256), and, only when the switch below says
|
|
9
|
-
* so, replaces the base64 in the uploaded transcript with the short marker built here
|
|
9
|
+
* so, replaces the base64 in the uploaded transcript with the short marker built here and strips
|
|
10
|
+
* the transcript's duplicate copies and bookkeeping (the slim transcript).
|
|
10
11
|
*
|
|
11
12
|
* This file is shared by the collector (builds the marker, builds the request), the dashboard
|
|
12
13
|
* (validates the request, answers) and anything that reads a marker back. Pure: no I/O, no env.
|
|
13
14
|
*/
|
|
14
15
|
import { z } from "zod";
|
|
15
16
|
/**
|
|
16
|
-
* `describe_and_keep` every distinct image is described, the transcript still carries the image
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* `describe_and_keep` every distinct image is described, the transcript still carries the image and
|
|
18
|
+
* is uploaded exactly as it is on disk. The slim transcript is NOT computed
|
|
19
|
+
* and NOT uploaded in this mode.
|
|
20
|
+
* `describe_and_drop` every image that has a stored description is replaced by its marker (an image
|
|
21
|
+
* that could not be described is KEPT, never dropped without a description),
|
|
22
|
+
* and the uploaded transcript is the SLIM transcript: the duplicate copies and
|
|
23
|
+
* the bookkeeping are stripped too, every line stays. What is stripped and
|
|
24
|
+
* kept: docs/architecture/image-descriptions.md, code in
|
|
25
|
+
* packages/cockpit-local-collector/src/slim/.
|
|
20
26
|
*/
|
|
21
27
|
export type ImageHandlingMode = "describe_and_keep" | "describe_and_drop";
|
|
22
28
|
/**
|
|
23
|
-
* The
|
|
24
|
-
*
|
|
25
|
-
*
|
|
29
|
+
* The FLEET DEFAULT and the fallback: the mode a machine uses when Tower has no setting for it and it
|
|
30
|
+
* has never heard from Tower. Default is keep (images stay in the transcript, uploaded as on disk).
|
|
31
|
+
*
|
|
32
|
+
* Since BLI-17273 the mode is decided PER MACHINE. The `collector_image_mode:<device_id>` row in
|
|
33
|
+
* `public.system_settings` (`cockpit settings switches set collector_image_mode:<device_id> describe_and_drop`)
|
|
34
|
+
* rides the reply to the sync-start receipt, the collector caches the last value it saw, and that
|
|
35
|
+
* value overrides this constant for that machine only. Flipping one machine needs a CLI release that
|
|
36
|
+
* carries the per-machine path (`gh workflow run release.yml -f tag=latest`); no other file changes.
|
|
26
37
|
*/
|
|
27
38
|
export declare const IMAGE_HANDLING_MODE: ImageHandlingMode;
|
|
28
39
|
/**
|
|
@@ -42,12 +53,16 @@ export declare function sniffImageMediaType(bytes: Uint8Array): ImageMediaType |
|
|
|
42
53
|
/** Hex characters of the sha256 a marker carries. 64 bits is far past any one person's image count. */
|
|
43
54
|
export declare const IMAGE_MARKER_HASH_CHARS = 16;
|
|
44
55
|
export declare function imageSizeLabel(byteSize: number): string;
|
|
56
|
+
/** What every marker starts with: a cheap `includes` check before anyone runs the marker regex. */
|
|
57
|
+
export declare const IMAGE_MARKER_START = "[image sha256:";
|
|
45
58
|
/** `[image sha256:ab12cd34ef567890… png 412KB]`: what replaces the base64 in an uploaded transcript. */
|
|
46
59
|
export declare function formatImageMarker(image: {
|
|
47
60
|
sha256: string;
|
|
48
61
|
mediaType: ImageMediaType;
|
|
49
62
|
byteSize: number;
|
|
50
63
|
}): string;
|
|
64
|
+
/** A fresh global regex for one marker: group 1 the 16-hex prefix, 2 the type extension, 3 the size label. */
|
|
65
|
+
export declare function imageMarkerPattern(): RegExp;
|
|
51
66
|
export interface ParsedImageMarker {
|
|
52
67
|
sha256Prefix: string;
|
|
53
68
|
mediaType: ImageMediaType;
|
|
@@ -6,16 +6,22 @@
|
|
|
6
6
|
* line. Measured on one laptop on 2026-10-09 that was 17% of Claude bytes and 59% of Codex bytes.
|
|
7
7
|
* The collector finds every such image, sends each distinct one ONCE to the describe door (a
|
|
8
8
|
* short text description, kept against the image's sha256), and, only when the switch below says
|
|
9
|
-
* so, replaces the base64 in the uploaded transcript with the short marker built here
|
|
9
|
+
* so, replaces the base64 in the uploaded transcript with the short marker built here and strips
|
|
10
|
+
* the transcript's duplicate copies and bookkeeping (the slim transcript).
|
|
10
11
|
*
|
|
11
12
|
* This file is shared by the collector (builds the marker, builds the request), the dashboard
|
|
12
13
|
* (validates the request, answers) and anything that reads a marker back. Pure: no I/O, no env.
|
|
13
14
|
*/
|
|
14
15
|
import { z } from "zod";
|
|
15
16
|
/**
|
|
16
|
-
* The
|
|
17
|
-
*
|
|
18
|
-
*
|
|
17
|
+
* The FLEET DEFAULT and the fallback: the mode a machine uses when Tower has no setting for it and it
|
|
18
|
+
* has never heard from Tower. Default is keep (images stay in the transcript, uploaded as on disk).
|
|
19
|
+
*
|
|
20
|
+
* Since BLI-17273 the mode is decided PER MACHINE. The `collector_image_mode:<device_id>` row in
|
|
21
|
+
* `public.system_settings` (`cockpit settings switches set collector_image_mode:<device_id> describe_and_drop`)
|
|
22
|
+
* rides the reply to the sync-start receipt, the collector caches the last value it saw, and that
|
|
23
|
+
* value overrides this constant for that machine only. Flipping one machine needs a CLI release that
|
|
24
|
+
* carries the per-machine path (`gh workflow run release.yml -f tag=latest`); no other file changes.
|
|
19
25
|
*/
|
|
20
26
|
export const IMAGE_HANDLING_MODE = "describe_and_keep";
|
|
21
27
|
// ---------------------------------------------------------------------------
|
|
@@ -69,12 +75,18 @@ export function imageSizeLabel(byteSize) {
|
|
|
69
75
|
return `${Math.round(byteSize / 1_000)}KB`;
|
|
70
76
|
return `${byteSize}B`;
|
|
71
77
|
}
|
|
78
|
+
/** What every marker starts with: a cheap `includes` check before anyone runs the marker regex. */
|
|
79
|
+
export const IMAGE_MARKER_START = "[image sha256:";
|
|
72
80
|
/** `[image sha256:ab12cd34ef567890… png 412KB]`: what replaces the base64 in an uploaded transcript. */
|
|
73
81
|
export function formatImageMarker(image) {
|
|
74
82
|
const hash = image.sha256.slice(0, IMAGE_MARKER_HASH_CHARS);
|
|
75
83
|
return `[image sha256:${hash}… ${EXTENSION_BY_TYPE[image.mediaType]} ${imageSizeLabel(image.byteSize)}]`;
|
|
76
84
|
}
|
|
77
85
|
const MARKER_SOURCE = String.raw `\[image sha256:([0-9a-f]{${IMAGE_MARKER_HASH_CHARS}})… (png|jpg|gif|webp) (\d+(?:\.\d)?(?:B|KB|MB))\]`;
|
|
86
|
+
/** A fresh global regex for one marker: group 1 the 16-hex prefix, 2 the type extension, 3 the size label. */
|
|
87
|
+
export function imageMarkerPattern() {
|
|
88
|
+
return new RegExp(MARKER_SOURCE, "g");
|
|
89
|
+
}
|
|
78
90
|
/** Every marker in a piece of text, in order. A fresh regex per call, so no shared `lastIndex`. */
|
|
79
91
|
export function parseImageMarkers(text) {
|
|
80
92
|
const found = [];
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** Hash prefix (16 hex) to the description of that image. A prefix with no row is simply absent. */
|
|
2
|
+
export type ImageDescriptionLookup = (hashPrefixes: string[]) => Promise<ReadonlyMap<string, string>>;
|
|
3
|
+
export interface InlineImageDescriptionsResult {
|
|
4
|
+
text: string;
|
|
5
|
+
/** Markers in the text (a marker repeated three times counts three). */
|
|
6
|
+
found: number;
|
|
7
|
+
/** Markers swapped for their description. */
|
|
8
|
+
resolved: number;
|
|
9
|
+
/** Markers left as they were: `found - resolved`. */
|
|
10
|
+
missing: number;
|
|
11
|
+
/** Why markers stayed, by reason label. */
|
|
12
|
+
missing_reasons: Record<string, number>;
|
|
13
|
+
/** Database calls this one call made (0 when everything was already remembered). */
|
|
14
|
+
lookups: number;
|
|
15
|
+
}
|
|
16
|
+
/** One described image found in a text: the marker as written, and its words. */
|
|
17
|
+
export interface ImageNote {
|
|
18
|
+
/** `sha256:ab12cd34ef567890` */
|
|
19
|
+
image: string;
|
|
20
|
+
description: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ImageNotesResult {
|
|
23
|
+
notes: ImageNote[];
|
|
24
|
+
found: number;
|
|
25
|
+
resolved: number;
|
|
26
|
+
missing: number;
|
|
27
|
+
missing_reasons: Record<string, number>;
|
|
28
|
+
lookups: number;
|
|
29
|
+
}
|
|
30
|
+
export interface ImageDescriptionResolver {
|
|
31
|
+
/**
|
|
32
|
+
* `escape: "json"` (default) writes the description so it is safe INSIDE a JSON string, because
|
|
33
|
+
* the marker sits inside one in a JSONL transcript: quotes, backslashes and line breaks are
|
|
34
|
+
* escaped and every line stays one valid JSON line. `"plain"` is for text that is not JSON.
|
|
35
|
+
*/
|
|
36
|
+
inline(text: string, options?: {
|
|
37
|
+
escape?: "json" | "plain";
|
|
38
|
+
}): Promise<InlineImageDescriptionsResult>;
|
|
39
|
+
/**
|
|
40
|
+
* The same lookup without touching the text, for a reader that must keep the bytes it was handed
|
|
41
|
+
* exactly (a quote whose hash is bound to its bytes). Distinct images only, in order of first sight.
|
|
42
|
+
*/
|
|
43
|
+
notes(text: string): Promise<ImageNotesResult>;
|
|
44
|
+
}
|
|
45
|
+
export interface ImageDescriptionResolverOptions {
|
|
46
|
+
/** Who is asking, for the log line: `harvest_extract`, `judge_quotes`, `digest`, ... */
|
|
47
|
+
reader: string;
|
|
48
|
+
/** Prefixes asked per database call. */
|
|
49
|
+
batchSize?: number;
|
|
50
|
+
/** Descriptions remembered for the run before the oldest are forgotten. */
|
|
51
|
+
maxRemembered?: number;
|
|
52
|
+
/** Tests only. */
|
|
53
|
+
log?: (message: string, fields: Record<string, unknown>) => void;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Swap each marker in `text` for `[image sha256:... png 412KB: <words>]` using notes a resolver
|
|
57
|
+
* already fetched. Pure and synchronous, so a prompt builder can apply it to a quote it must keep
|
|
58
|
+
* byte-exact elsewhere. A marker with no note stays as it is.
|
|
59
|
+
*/
|
|
60
|
+
export declare function applyImageNotes(text: string, notes: readonly ImageNote[], escape?: "json" | "plain"): string;
|
|
61
|
+
export declare function createImageDescriptionResolver(lookup: ImageDescriptionLookup, options: ImageDescriptionResolverOptions): ImageDescriptionResolver;
|
|
62
|
+
/**
|
|
63
|
+
* The smallest slice of a Supabase client the lookup needs. A reader passes the client it already
|
|
64
|
+
* uses: the caller's RLS client (the database decides which rows that person sees) or, for a cron
|
|
65
|
+
* that reads every person's sessions, the service role. This file never builds a client.
|
|
66
|
+
*/
|
|
67
|
+
export interface ImageDescriptionRowsClient {
|
|
68
|
+
from(table: "ambient_image_descriptions"): {
|
|
69
|
+
select(columns: string): {
|
|
70
|
+
or(filter: string): {
|
|
71
|
+
limit(count: number): PromiseLike<{
|
|
72
|
+
data: Array<{
|
|
73
|
+
sha256: string;
|
|
74
|
+
description: string;
|
|
75
|
+
}> | null;
|
|
76
|
+
error: {
|
|
77
|
+
code?: string | null;
|
|
78
|
+
message?: string;
|
|
79
|
+
} | null;
|
|
80
|
+
}>;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
export declare function imageDescriptionLookupFor(client: ImageDescriptionRowsClient, options: {
|
|
86
|
+
reader: string;
|
|
87
|
+
log?: (message: string, fields: Record<string, unknown>) => void;
|
|
88
|
+
}): ImageDescriptionLookup;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn an image marker back into the words that describe the image (BLI-16979).
|
|
3
|
+
*
|
|
4
|
+
* In slim mode a stored transcript carries only `[image sha256:ab12cd34ef567890… png 412KB]` where
|
|
5
|
+
* a screenshot used to be. The describe door keeps the words for each image in
|
|
6
|
+
* `ambient_image_descriptions`. A model that is asked about a screenshot and sees only the sticker
|
|
7
|
+
* guesses (blind test on 15 real sessions: originals 12 right, descriptions inlined 10, stickers
|
|
8
|
+
* only 5). So every reader that hands transcript text to a model runs it through this one resolver
|
|
9
|
+
* first.
|
|
10
|
+
*
|
|
11
|
+
* One resolver per run. It looks descriptions up in ONE batch per call (all the markers in the text
|
|
12
|
+
* at once, not one query per marker), remembers every answer for the rest of the run, and leaves a
|
|
13
|
+
* marker with no description exactly as it was. The lookup itself is passed in: a reader hands in
|
|
14
|
+
* the Supabase client it already uses (the caller's RLS client for a person's request, the service
|
|
15
|
+
* role for a cron), so this file never widens who can read what.
|
|
16
|
+
*
|
|
17
|
+
* Logs counts only: markers found, resolved, missing, and one reason label per kind of miss. Never
|
|
18
|
+
* a description, never an image.
|
|
19
|
+
*/
|
|
20
|
+
import { IMAGE_MARKER_HASH_CHARS, IMAGE_MARKER_START, imageMarkerPattern, parseImageMarkers } from "./image-descriptions.js";
|
|
21
|
+
const TAG = "[image-markers]";
|
|
22
|
+
/** Characters of the sha256 a marker carries. */
|
|
23
|
+
const PREFIX_CHARS = IMAGE_MARKER_HASH_CHARS;
|
|
24
|
+
const DEFAULT_BATCH = 25;
|
|
25
|
+
const DEFAULT_MAX_REMEMBERED = 20_000;
|
|
26
|
+
function escapeForJsonString(description) {
|
|
27
|
+
return JSON.stringify(description).slice(1, -1);
|
|
28
|
+
}
|
|
29
|
+
/** `[image sha256:ab12cd34ef567890… png 412KB: the words]`. The id stays so a quote can still point at the image. */
|
|
30
|
+
function describedMarker(marker, description, escape) {
|
|
31
|
+
const safe = escape === "json" ? escapeForJsonString(oneLine(description)) : oneLine(description);
|
|
32
|
+
return `${marker.slice(0, -1)}: ${safe}]`;
|
|
33
|
+
}
|
|
34
|
+
function oneLine(description) {
|
|
35
|
+
return description.replace(/\s+/g, " ").trim();
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Swap each marker in `text` for `[image sha256:... png 412KB: <words>]` using notes a resolver
|
|
39
|
+
* already fetched. Pure and synchronous, so a prompt builder can apply it to a quote it must keep
|
|
40
|
+
* byte-exact elsewhere. A marker with no note stays as it is.
|
|
41
|
+
*/
|
|
42
|
+
export function applyImageNotes(text, notes, escape = "json") {
|
|
43
|
+
if (notes.length === 0 || !text.includes(IMAGE_MARKER_START))
|
|
44
|
+
return text;
|
|
45
|
+
const byImage = new Map(notes.map((note) => [note.image, note.description]));
|
|
46
|
+
return text.replace(imageMarkerPattern(), (whole, prefix) => {
|
|
47
|
+
const description = byImage.get(`sha256:${prefix}`);
|
|
48
|
+
return description ? describedMarker(whole, description, escape) : whole;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
export function createImageDescriptionResolver(lookup, options) {
|
|
52
|
+
const log = options.log ?? ((message, fields) => console.info(message, JSON.stringify(fields)));
|
|
53
|
+
const batchSize = Math.max(1, options.batchSize ?? DEFAULT_BATCH);
|
|
54
|
+
const maxRemembered = Math.max(1, options.maxRemembered ?? DEFAULT_MAX_REMEMBERED);
|
|
55
|
+
/** description, or null for "asked and there is none". A failed lookup is never remembered. */
|
|
56
|
+
const remembered = new Map();
|
|
57
|
+
let totalFound = 0;
|
|
58
|
+
let totalResolved = 0;
|
|
59
|
+
let totalLookups = 0;
|
|
60
|
+
function remember(prefix, description) {
|
|
61
|
+
if (remembered.size >= maxRemembered) {
|
|
62
|
+
const oldest = remembered.keys().next();
|
|
63
|
+
if (!oldest.done)
|
|
64
|
+
remembered.delete(oldest.value);
|
|
65
|
+
}
|
|
66
|
+
remembered.set(prefix, description);
|
|
67
|
+
}
|
|
68
|
+
async function fetchMissing(prefixes) {
|
|
69
|
+
const failed = new Set();
|
|
70
|
+
let lookups = 0;
|
|
71
|
+
for (let start = 0; start < prefixes.length; start += batchSize) {
|
|
72
|
+
const batch = prefixes.slice(start, start + batchSize);
|
|
73
|
+
lookups += 1;
|
|
74
|
+
try {
|
|
75
|
+
const answers = await lookup(batch);
|
|
76
|
+
for (const prefix of batch)
|
|
77
|
+
remember(prefix, answers.get(prefix) ?? null);
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
for (const prefix of batch)
|
|
81
|
+
failed.add(prefix);
|
|
82
|
+
log(`${TAG} lookup failed, markers stay as they are`, {
|
|
83
|
+
reader: options.reader,
|
|
84
|
+
reason: "lookup_failed",
|
|
85
|
+
markers: batch.length,
|
|
86
|
+
error_name: error instanceof Error ? error.name : typeof error,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { lookups, failed };
|
|
91
|
+
}
|
|
92
|
+
/** Looks up every distinct marker in `text` that is not already remembered. */
|
|
93
|
+
async function ask(text) {
|
|
94
|
+
const markers = parseImageMarkers(text);
|
|
95
|
+
if (markers.length === 0)
|
|
96
|
+
return null;
|
|
97
|
+
const distinct = [...new Set(markers.map((marker) => marker.sha256Prefix))];
|
|
98
|
+
const toAsk = distinct.filter((prefix) => !remembered.has(prefix));
|
|
99
|
+
const { lookups, failed } = toAsk.length ? await fetchMissing(toAsk) : { lookups: 0, failed: new Set() };
|
|
100
|
+
return { found: markers.length, distinct, failed, lookups, askedFor: toAsk.length };
|
|
101
|
+
}
|
|
102
|
+
function logSummary(summary) {
|
|
103
|
+
totalFound += summary.found;
|
|
104
|
+
totalResolved += summary.resolved;
|
|
105
|
+
totalLookups += summary.lookups;
|
|
106
|
+
log(`${TAG} markers resolved`, {
|
|
107
|
+
reader: options.reader,
|
|
108
|
+
found: summary.found,
|
|
109
|
+
resolved: summary.resolved,
|
|
110
|
+
missing: summary.found - summary.resolved,
|
|
111
|
+
missing_reasons: summary.reasons,
|
|
112
|
+
distinct: summary.distinct,
|
|
113
|
+
looked_up: summary.askedFor,
|
|
114
|
+
lookups: summary.lookups,
|
|
115
|
+
run_found: totalFound,
|
|
116
|
+
run_resolved: totalResolved,
|
|
117
|
+
run_lookups: totalLookups,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const reasonFor = (prefix, failed) => (failed.has(prefix) ? "lookup_failed" : "no_description_row");
|
|
121
|
+
return {
|
|
122
|
+
async inline(text, callOptions) {
|
|
123
|
+
const asked = await ask(text);
|
|
124
|
+
if (!asked)
|
|
125
|
+
return { text, found: 0, resolved: 0, missing: 0, missing_reasons: {}, lookups: 0 };
|
|
126
|
+
const escape = callOptions?.escape ?? "json";
|
|
127
|
+
const reasons = {};
|
|
128
|
+
let resolved = 0;
|
|
129
|
+
const output = text.replace(imageMarkerPattern(), (whole, prefix) => {
|
|
130
|
+
const description = remembered.get(prefix);
|
|
131
|
+
if (description) {
|
|
132
|
+
resolved += 1;
|
|
133
|
+
return describedMarker(whole, description, escape);
|
|
134
|
+
}
|
|
135
|
+
const reason = reasonFor(prefix, asked.failed);
|
|
136
|
+
reasons[reason] = (reasons[reason] ?? 0) + 1;
|
|
137
|
+
return whole;
|
|
138
|
+
});
|
|
139
|
+
logSummary({ found: asked.found, resolved, reasons, distinct: asked.distinct.length, askedFor: asked.askedFor, lookups: asked.lookups });
|
|
140
|
+
return { text: output, found: asked.found, resolved, missing: asked.found - resolved, missing_reasons: reasons, lookups: asked.lookups };
|
|
141
|
+
},
|
|
142
|
+
async notes(text) {
|
|
143
|
+
const asked = await ask(text);
|
|
144
|
+
if (!asked)
|
|
145
|
+
return { notes: [], found: 0, resolved: 0, missing: 0, missing_reasons: {}, lookups: 0 };
|
|
146
|
+
const reasons = {};
|
|
147
|
+
let resolved = 0;
|
|
148
|
+
const notes = [];
|
|
149
|
+
const seen = new Set();
|
|
150
|
+
for (const marker of parseImageMarkers(text)) {
|
|
151
|
+
const description = remembered.get(marker.sha256Prefix);
|
|
152
|
+
if (description) {
|
|
153
|
+
resolved += 1;
|
|
154
|
+
if (!seen.has(marker.sha256Prefix)) {
|
|
155
|
+
seen.add(marker.sha256Prefix);
|
|
156
|
+
notes.push({ image: `sha256:${marker.sha256Prefix}`, description: oneLine(description) });
|
|
157
|
+
}
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const reason = reasonFor(marker.sha256Prefix, asked.failed);
|
|
161
|
+
reasons[reason] = (reasons[reason] ?? 0) + 1;
|
|
162
|
+
}
|
|
163
|
+
logSummary({ found: asked.found, resolved, reasons, distinct: asked.distinct.length, askedFor: asked.askedFor, lookups: asked.lookups });
|
|
164
|
+
return { notes, found: asked.found, resolved, missing: asked.found - resolved, missing_reasons: reasons, lookups: asked.lookups };
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/** PostgREST caps a request at 1,000 rows; a batch cannot reach it (25 prefixes) but a cap is said out loud. */
|
|
169
|
+
const ROW_CAP = 1_000;
|
|
170
|
+
export function imageDescriptionLookupFor(client, options) {
|
|
171
|
+
const log = options.log ?? ((message, fields) => console.warn(message, JSON.stringify(fields)));
|
|
172
|
+
return async (prefixes) => {
|
|
173
|
+
const filter = prefixes.map((prefix) => `sha256.like.${prefix}*`).join(",");
|
|
174
|
+
const { data, error } = await client
|
|
175
|
+
.from("ambient_image_descriptions")
|
|
176
|
+
.select("sha256,description")
|
|
177
|
+
.or(filter)
|
|
178
|
+
.limit(ROW_CAP);
|
|
179
|
+
if (error) {
|
|
180
|
+
log(`${TAG} description read failed`, { reader: options.reader, reason: "description_read_failed", code: error.code ?? null, prefixes: prefixes.length });
|
|
181
|
+
throw new Error("description_read_failed");
|
|
182
|
+
}
|
|
183
|
+
const rows = data ?? [];
|
|
184
|
+
if (rows.length >= ROW_CAP) {
|
|
185
|
+
log(`${TAG} description read hit the row cap`, { reader: options.reader, reason: "description_read_capped", rows: rows.length, prefixes: prefixes.length });
|
|
186
|
+
}
|
|
187
|
+
const byPrefix = new Map();
|
|
188
|
+
for (const row of rows) {
|
|
189
|
+
const prefix = row.sha256.slice(0, PREFIX_CHARS);
|
|
190
|
+
if (row.description && !byPrefix.has(prefix))
|
|
191
|
+
byPrefix.set(prefix, row.description);
|
|
192
|
+
}
|
|
193
|
+
return byPrefix;
|
|
194
|
+
};
|
|
195
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export * from "./evidence-stubs.js";
|
|
|
11
11
|
export * from "./evidence-transcripts.js";
|
|
12
12
|
export * from "./evidence-upload.js";
|
|
13
13
|
export * from "./image-descriptions.js";
|
|
14
|
+
export * from "./image-marker-resolver.js";
|
|
14
15
|
export * from "./transcript-images.js";
|
|
15
16
|
export * from "./ingest-dto.js";
|
|
16
17
|
export * from "./local-config.js";
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,7 @@ export * from "./evidence-stubs.js";
|
|
|
11
11
|
export * from "./evidence-transcripts.js";
|
|
12
12
|
export * from "./evidence-upload.js";
|
|
13
13
|
export * from "./image-descriptions.js";
|
|
14
|
+
export * from "./image-marker-resolver.js";
|
|
14
15
|
export * from "./transcript-images.js";
|
|
15
16
|
export * from "./ingest-dto.js";
|
|
16
17
|
export * from "./local-config.js";
|
|
@@ -11,7 +11,10 @@ export interface EmbeddedImage {
|
|
|
11
11
|
/** Decoded size in bytes. */
|
|
12
12
|
byteSize: number;
|
|
13
13
|
}
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Cheap check on raw bytes before anyone decodes a whole transcript to text: does it hold a data
|
|
16
|
+
* URL, or a string that starts the way a PNG, JPEG, GIF or WebP does in base64?
|
|
17
|
+
*/
|
|
15
18
|
export declare function mightHoldEmbeddedImages(bytes: Buffer): boolean;
|
|
16
19
|
/** Every embedded image in `text`, in order. Runs that are not images are skipped. */
|
|
17
20
|
export declare function findEmbeddedImages(text: string): EmbeddedImage[];
|
|
@@ -1,41 +1,64 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Find the base64 images inside a transcript's text, and swap them for short markers (BLI-16977).
|
|
3
3
|
*
|
|
4
|
-
* A
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* A transcript stores a picture as one long run of base64 characters, in one of two shapes:
|
|
5
|
+
*
|
|
6
|
+
* - a JSON string that is NOTHING BUT the run (`"data":"<base64>"` in a Claude image block, a
|
|
7
|
+
* Codex `image_gen` result, an MCP image, a Codex `toolSurface.screenshot` value, ...). Any key
|
|
8
|
+
* name, any depth: the finder looks at the string, not at what it is called.
|
|
9
|
+
* - a data URL (`data:image/png;base64,<base64>`) anywhere inside a string (a Codex `image_url`).
|
|
10
|
+
*
|
|
11
|
+
* Either way this file decodes each run far enough to know it IS an image (magic bytes, never the
|
|
12
|
+
* transcript's own claim) and what its sha256 is, and can rewrite the text with a marker in place
|
|
13
|
+
* of chosen images.
|
|
9
14
|
*
|
|
10
15
|
* Pure: text in, text out. No network, no disk, no environment. A run that does not decode to a
|
|
11
16
|
* PNG, JPEG, GIF or WebP is left exactly as it is (a PDF, a long token, a hex dump).
|
|
12
17
|
*
|
|
13
|
-
* The rewrite keeps the JSON line valid: in the
|
|
14
|
-
* inside its quotes; in the
|
|
15
|
-
*
|
|
18
|
+
* The rewrite keeps the JSON line valid: in the whole-string form only the base64 is replaced,
|
|
19
|
+
* inside its quotes; in the data-URL form the whole data URL is replaced, inside the string it sat
|
|
20
|
+
* in. So every parser that read the line before still reads it.
|
|
16
21
|
*/
|
|
17
22
|
import { createHash } from "node:crypto";
|
|
18
23
|
import { IMAGE_MIN_BASE64_CHARS, formatImageMarker, sniffImageMediaType, } from "./image-descriptions.js";
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
24
|
+
const BASE64_RUN = `[A-Za-z0-9+/=]{${IMAGE_MIN_BASE64_CHARS},}`;
|
|
25
|
+
/**
|
|
26
|
+
* What the first characters of a base64 run look like for each type we accept: PNG `iVBOR`, JPEG
|
|
27
|
+
* `/9j/`, GIF `R0lGO`, WebP (RIFF) `UklGR`. Anchoring the whole-string form on these keeps the scan
|
|
28
|
+
* fast (no 500-character attempt after every quote); the decoded bytes are still sniffed after.
|
|
29
|
+
*/
|
|
30
|
+
const IMAGE_BASE64_STARTS = String.raw `(?:iVBOR|\/9j\/|R0lGO|UklGR)`;
|
|
31
|
+
/**
|
|
32
|
+
* 1: a run that starts like an image and sits between two quotes (plain `"` or the `\"` of a JSON
|
|
33
|
+
* string that was itself stored inside a string), so it is the whole string.
|
|
34
|
+
* 2: a data URL prefix, then the run.
|
|
35
|
+
*/
|
|
36
|
+
const IMAGE_STRING = new RegExp(`(?<=")(${IMAGE_BASE64_STARTS}[A-Za-z0-9+/=]{${IMAGE_MIN_BASE64_CHARS - 5},})(?=\\\\?")|(data:image/[a-z0-9.+-]+;base64,)(${BASE64_RUN})`, "g");
|
|
37
|
+
/**
|
|
38
|
+
* Cheap check on raw bytes before anyone decodes a whole transcript to text: does it hold a data
|
|
39
|
+
* URL, or a string that starts the way a PNG, JPEG, GIF or WebP does in base64?
|
|
40
|
+
*/
|
|
22
41
|
export function mightHoldEmbeddedImages(bytes) {
|
|
23
|
-
return bytes.includes("base64") ||
|
|
42
|
+
return (bytes.includes("base64") ||
|
|
43
|
+
bytes.includes("iVBOR") ||
|
|
44
|
+
bytes.includes("/9j/") ||
|
|
45
|
+
bytes.includes("R0lGO") ||
|
|
46
|
+
bytes.includes("UklGR"));
|
|
24
47
|
}
|
|
25
48
|
/** Every embedded image in `text`, in order. Runs that are not images are skipped. */
|
|
26
49
|
export function findEmbeddedImages(text) {
|
|
27
50
|
const found = [];
|
|
28
|
-
for (const match of text.matchAll(
|
|
29
|
-
const
|
|
30
|
-
const run = (
|
|
51
|
+
for (const match of text.matchAll(IMAGE_STRING)) {
|
|
52
|
+
const isWholeString = match[1] !== undefined;
|
|
53
|
+
const run = (isWholeString ? match[1] : match[3]) ?? "";
|
|
31
54
|
const matchStart = match.index ?? 0;
|
|
32
|
-
const base64Start = matchStart + (
|
|
55
|
+
const base64Start = matchStart + (isWholeString ? 0 : match[2].length);
|
|
33
56
|
const bytes = Buffer.from(run, "base64");
|
|
34
57
|
const mediaType = sniffImageMediaType(bytes);
|
|
35
58
|
if (!mediaType)
|
|
36
59
|
continue;
|
|
37
60
|
found.push({
|
|
38
|
-
replaceStart:
|
|
61
|
+
replaceStart: isWholeString ? base64Start : matchStart,
|
|
39
62
|
replaceEnd: base64Start + run.length,
|
|
40
63
|
base64Start,
|
|
41
64
|
base64End: base64Start + run.length,
|