ltms-reader 0.0.0-stage → 0.1.0

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/src/view.mjs ADDED
@@ -0,0 +1,337 @@
1
+ // src/view.mjs — what the page shows of one transcript, built on ltms's library (long-term-memory-structure, written
2
+ // against 0.2.0; #ltms, which the host package maps: ltms-reader to its dependency, the extension to its vendor/ltms): its
3
+ // turns with their tool calls, replies and compactions, the record at any line, and the text around a search match.
4
+ // Pure functions over a transcript's text or its parse: no I/O, no Node imports.
5
+ //
6
+ // The turns and calls are the ones `ltms skeleton` prints, by the same recipe (cli.ts skeletonOf): turnsOf over the
7
+ // repaired live path, addresses <prefix>:L<line>, turn ids <prefix>:T<nnn>. What ltms never prints, the text, is shown
8
+ // here, because the person reading is the one whose transcripts these are, on their own machine.
9
+ import { blocksOf, indexTranscript, inputChannel, parseTranscript, repairedLivePath, turnsOf } from '#ltms';
10
+
11
+ /** How much text each item carries to the page before the reader asks for the whole record. */
12
+ export const LIMITS = Object.freeze({ prompt: 1200, reply: 600, input: 400, result: 400, note: 300 });
13
+ /** At most this many items of one turn, and of a whole session, go to the page at once (a session of 20,000 tool calls
14
+ * was a 12.4 MB reply and 220,000 elements); the rest of a turn comes when the reader asks for it (turnItems). */
15
+ export const CAPS = Object.freeze({ turnItems: 200, sessionItems: 5000, oneTurn: 2000 });
16
+
17
+ /** ltms's address prefix (cli.ts prefixOf): the file name's first 8 characters; agent-<id>.jsonl gives agent- and the
18
+ * id's first 8, since those names all start alike. */
19
+ export const prefixOf = (name) => (name.startsWith('agent-') ? `agent-${name.slice(6, 14)}` : name.slice(0, 8));
20
+
21
+ /** Content as one string, as ltms reads it (cli.ts flat): a string as it is; an array as its text blocks and bare
22
+ * strings, joined by new lines; anything else as ''. */
23
+ export const flat = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => (typeof x === 'string' ? x : typeof x?.text === 'string' ? x.text : '')).join('\n') : '');
24
+
25
+ const GRAPHEMES = typeof Intl?.Segmenter === 'function' ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null;
26
+
27
+ /** At most n UTF-16 units of s, cut at the last grapheme cluster boundary at or before n (R.F4: a cut by units alone
28
+ * left a pointed letter without some of its marks, and the page and the screen drew it so), and how many units were
29
+ * left out. The boundaries are those of the whole text, by ICU: the cut is where the cluster that holds the unit at n
30
+ * begins (Intl.Segmenter's containing(), which ICU answers from the characters around n: its break iterator backs up
31
+ * to a place its rules call safe, then goes forward, so that the cost is that of the clusters there, not of the text
32
+ * before them). A boundary at or before n depends on the text before it and the code point at it, so the text is given
33
+ * to ICU up to the code point at n. History: segmenting the 512 units before n as if they began a text cut inside a
34
+ * cluster longer than that (N4); then a look-back to a boundary the characters around it guaranteed asked ICU once per
35
+ * printable ASCII character it passed, back to the text's start when a Prepend character stood before each one: 9.4 s
36
+ * at 4,000,000 units (R2); and segmenting every text from its start made opening R's 14 MB record 1.6 s, from 60 ms.
37
+ * Without Intl.Segmenter, never inside a surrogate pair. */
38
+ export function clip(s, n) {
39
+ if (typeof s !== 'string') return { text: '', more: 0 };
40
+ if (s.length <= n) return { text: s, more: 0 };
41
+ let k = Math.max(0, n);
42
+ if (GRAPHEMES) {
43
+ if (k > 0) k = GRAPHEMES.segment(s.slice(0, k + 2)).containing(k).index;
44
+ } else {
45
+ const c = s.charCodeAt(k - 1);
46
+ if (c >= 0xd800 && c <= 0xdbff) k--;
47
+ }
48
+ return { text: s.slice(0, k), more: s.length - k };
49
+ }
50
+
51
+ const str = (v) => (typeof v === 'string' ? v : undefined);
52
+ /** The least and the most of a list of numbers, by a loop: a turn's lines can be more than a call takes arguments. */
53
+ const least = (xs) => xs.reduce((m, x) => (x < m ? x : m), Infinity);
54
+ const most = (xs) => xs.reduce((m, x) => (x > m ? x : m), -Infinity);
55
+
56
+ /** A command typed in Claude Code (A.F18): the harness writes it into the prompt's text as markup,
57
+ * <command-name>/compact</command-name> with <command-args>; its name and arguments, or null for any other text. */
58
+ export function commandOf(text) {
59
+ const m = /<command-name>([^<]{1,200})<\/command-name>/.exec(typeof text === 'string' ? text : '');
60
+ if (!m) return null;
61
+ const a = /<command-args>([^<]*)<\/command-args>/.exec(text);
62
+ return { name: m[1].trim(), args: clip((a?.[1] ?? '').trim(), 400).text };
63
+ }
64
+ /** v as JSON ('' for undefined), indented by `space`; "(too large to write out)" when it cannot be written. A value whose
65
+ * indented JSON would pass JavaScript's limit on a string's length is measured first (jsonSize) and never handed to
66
+ * JSON.stringify, which on Node 20 held some 800 MB before the heap ran out (N3; Node 26 threw at once). Without an
67
+ * indent, JSON is no longer than the line the value was read from. */
68
+ const json = (v, space) => {
69
+ if (space && jsonSize(v, space).units > STRING_MAX_UNITS) return '(too large to write out)';
70
+ try { return JSON.stringify(v, null, space) ?? ''; } catch { return '(too large to write out)'; }
71
+ };
72
+
73
+ /** The input field a person looks at first, by tool: the command, the file, the pattern, the address, the task. */
74
+ const INPUT_KEYS = ['command', 'file_path', 'notebook_path', 'path', 'pattern', 'url', 'query', 'skill', 'description', 'prompt', 'subagent_type'];
75
+ export function inputShown(input) {
76
+ if (input !== null && typeof input === 'object' && !Array.isArray(input)) {
77
+ for (const k of INPUT_KEYS) if (typeof input[k] === 'string' && input[k] !== '') return { key: k, ...clip(input[k], LIMITS.input) };
78
+ }
79
+ return { key: null, ...clip(input === undefined ? '' : json(input), LIMITS.input) };
80
+ }
81
+
82
+ const isBoundary = (r) => r?.type === 'system' && r.subtype === 'compact_boundary';
83
+ /** A record's text blocks, joined: what a person reads as the assistant's reply. */
84
+ const replyText = (r) => blocksOf(r?.message).filter((b) => b.type === 'text' && typeof b.text === 'string' && b.text !== '').map((b) => b.text).join('\n');
85
+
86
+ // One map per parse: a line number → the index of the first record written on it.
87
+ const lineMaps = new WeakMap();
88
+ export function recordIndexAt(t, line) {
89
+ let m = lineMaps.get(t);
90
+ if (!m) { m = new Map(); t.positions.forEach((p, i) => { if (!m.has(p.line)) m.set(p.line, i); }); lineMaps.set(t, m); }
91
+ return m.get(line);
92
+ }
93
+
94
+ /**
95
+ * One session as the page shows it. `name` is the file's name (its prefix is ltms's).
96
+ * Each turn: its id and address, its channel, its time, its prompt (clipped), and its items in the order they were
97
+ * written in the file (by line): the tool calls (each with its input, whether it succeeded, its result's address and
98
+ * the start of its result), the replies, the compactions with their summaries, and the harness's own records (notes).
99
+ */
100
+ export function sessionView(input, { name, caps = true }) {
101
+ const t = typeof input === 'string' ? parseTranscript(input) : input;
102
+ const pre = prefixOf(name);
103
+ const lineOf = (n) => t.positions[n.index].line;
104
+ const at = (n) => `${pre}:L${lineOf(n)}`;
105
+ const rp = repairedLivePath(t);
106
+ const turns = turnsOf(t, rp.path);
107
+ const index = indexTranscript(t, { prefix: pre });
108
+ // A path record as the page shows it: a compaction (with what its record says of it), its summary, a reply, an API
109
+ // error, or one of the harness's own notes; null for the records shown with their calls (tool results) and the rest.
110
+ const itemOf = (node) => {
111
+ const r = node.record;
112
+ if (isBoundary(r)) {
113
+ const m = r.compactMetadata ?? {}, kept = Array.isArray(m.preservedMessages?.uuids) ? m.preservedMessages.uuids : [];
114
+ return { kind: 'compaction', a: at(node), line: lineOf(node), time: str(r.timestamp) ?? null, trigger: str(m.trigger) ?? null,
115
+ pre: Number.isFinite(m.preTokens) ? m.preTokens : null, post: Number.isFinite(m.postTokens) ? m.postTokens : null,
116
+ kept: kept.map((u) => (typeof u === 'string' ? t.nodes.get(u) : undefined)).filter(Boolean).map((n) => ({ a: at(n), line: lineOf(n) })) };
117
+ }
118
+ if (r?.type === 'assistant') {
119
+ if (r.isApiErrorMessage === true) return { kind: 'note', sub: 'api-error', a: at(node), line: lineOf(node), ...clip(replyText(r), LIMITS.note), time: str(r.timestamp) ?? null };
120
+ const rt = replyText(r);
121
+ return rt !== '' ? { kind: 'reply', a: at(node), line: lineOf(node), ...clip(rt, LIMITS.reply), time: str(r.timestamp) ?? null } : null;
122
+ }
123
+ if (r?.type === 'user') {
124
+ const ch = inputChannel(r);
125
+ if (ch === 'harness:compact-summary') return { kind: 'summary', a: at(node), line: lineOf(node), ...clip(flat(r.message?.content), LIMITS.note), time: str(r.timestamp) ?? null };
126
+ if (ch !== undefined && ch.startsWith('harness:')) { const nt = flat(r.message?.content); return { kind: 'note', sub: ch.slice(8), a: at(node), line: lineOf(node), ...clip(nt, LIMITS.note), command: commandOf(nt), time: str(r.timestamp) ?? null }; }
127
+ }
128
+ return null;
129
+ };
130
+ // the path's records before the first prompt (a session that begins with a compaction, say): shown as a lead-in, as
131
+ // ltms search gives them to the first turn
132
+ const first = turns.length ? rp.path.indexOf(turns[0].prompt) : -1;
133
+ const lead = first > 0 ? rp.path.slice(0, first).map(itemOf).filter(Boolean).slice(0, CAPS.turnItems) : [];
134
+ const out = [];
135
+ for (let i = 0; i < turns.length; i++) {
136
+ const turn = turns[i], p = turn.prompt, pr = p.record;
137
+ const ta = `${pre}:T${String(i + 1).padStart(3, '0')}`;
138
+ const text = flat(pr?.message?.content);
139
+ const items = [];
140
+ for (const c of turn.toolCalls) {
141
+ const answered = c.resultBlock !== undefined, rt = answered ? flat(c.resultBlock?.content) : null;
142
+ items.push({
143
+ kind: 'call', a: at(c.callNode), line: lineOf(c.callNode), tool: str(c.name) ?? '(no name)', input: inputShown(c.input),
144
+ ok: answered ? !c.isError : null, r: c.resultNode ? at(c.resultNode) : null, rline: c.resultNode ? lineOf(c.resultNode) : null,
145
+ n: answered ? rt.length : null, result: answered ? clip(rt, LIMITS.result) : null, time: str(c.callNode.record?.timestamp) ?? null,
146
+ });
147
+ }
148
+ for (const node of turn.records) { const x = itemOf(node); if (x) items.push(x); }
149
+ items.sort((x, y) => x.line - y.line);
150
+ // counted before any cap, so the page's counts and its failed-only filter see every call; and the turn's lines, so an
151
+ // address can be found in a turn whose items were cut, or which is not drawn yet
152
+ const calls = items.filter((x) => x.kind === 'call'), lines = [lineOf(p), ...items.flatMap((x) => (x.rline ? [x.line, x.rline] : [x.line])), ...turn.records.map(lineOf)];
153
+ out.push({ ta, a: at(p), line: lineOf(p), ch: inputChannel(pr) || 'none', time: str(pr?.timestamp) ?? null, n: text.length, prompt: clip(text, LIMITS.prompt), command: commandOf(text), records: 1 + turn.records.length,
154
+ calls: calls.length, failed: calls.filter((x) => x.ok === false).length, from: least(lines), to: most(lines), items });
155
+ }
156
+ // A compaction made by /compact (S365, A.F5): Claude Code writes the boundary and its summary first, then the
157
+ // command's own records with the command's earlier time, so the /compact opens the turn after the one that holds its
158
+ // compaction (measured: the demo's dc532898, L128 at 00:57:02, its /compact at L131, 00:56:23). Where ltms's turns put
159
+ // the compaction inside the /compact's own turn (its fixtures library-detached*.jsonl), no note is made. Nothing is
160
+ // moved; each says which made which. An automatic compaction has no command.
161
+ const COMPACT = /<command-name>\/compact<\/command-name>/;
162
+ const held = [...lead.map((x) => [x, -1]), ...out.flatMap((tu, i) => tu.items.filter((x) => x.kind === 'compaction').map((x) => [x, i]))];
163
+ for (const [x, i] of held) {
164
+ const next = out[i + 1];
165
+ if (x.trigger === 'auto' || !next || !COMPACT.test(next.prompt?.text ?? '')) continue;
166
+ if (x.time && next.time && next.time > x.time) continue; // a /compact typed after the compaction did not make it
167
+ x.by = { ta: next.ta, a: next.a, line: next.line, time: next.time };
168
+ (next.made ??= []).push({ a: x.a, line: x.line, time: x.time, lead: i === -1 });
169
+ }
170
+ const s = t.stats;
171
+ return {
172
+ name, prefix: pre, fileKind: t.fileKind,
173
+ stats: { lines: s.lines, parsed: s.parsed, unparseable: s.unparseable, first: s.firstTimestamp, last: s.lastTimestamp, versions: Object.keys(s.versions).slice(-3), outputTokens: s.totalOutputTokens },
174
+ problems: { count: t.problems.length, first: t.problems.slice(0, 20).map((q) => ({ line: q.line, reason: q.reason })) },
175
+ path: { from: rp.from, nodes: rp.path.length, bridges: rp.bridges.length, splices: rp.splices.length, compactions: rp.compactions.length },
176
+ index: { turns: index.turns, calls: index.calls, failures: index.failures, compactions: index.compactions, firstPrompt: index.firstPrompt, lastPrompt: index.lastPrompt, lastReply: index.lastReply },
177
+ lead, turns: caps ? capped(out) : out,
178
+ };
179
+ }
180
+
181
+ /** The turns with their items cut to CAPS: each turn keeps its first items, and says how many it left out. */
182
+ function capped(turns) {
183
+ let budget = CAPS.sessionItems;
184
+ for (const t of turns) {
185
+ const keep = Math.max(0, Math.min(t.items.length, CAPS.turnItems, budget));
186
+ t.itemsMore = t.items.length - keep;
187
+ if (t.itemsMore) t.items = t.items.slice(0, keep);
188
+ budget -= keep;
189
+ }
190
+ return turns;
191
+ }
192
+
193
+ /** Every item of one turn (up to CAPS.oneTurn), for a turn whose items the session view cut; null when there is no
194
+ * such turn. */
195
+ export function turnItems(input, { name, ta }) {
196
+ const turn = sessionView(input, { name, caps: false }).turns.find((t) => t.ta === ta);
197
+ return turn ? { items: turn.items.slice(0, CAPS.oneTurn), total: turn.items.length } : null;
198
+ }
199
+
200
+ /** The parts of a record a person reads, before any is written out: its text blocks, thinking, tool calls (their input
201
+ * as JSON), tool results, a system record's content, an attachment. Each is { kind, label, text }, or, for a part shown
202
+ * as JSON, { kind, label, json: the value, indent }: readingOf writes it, recordViewBytes measures it. */
203
+ export function partsOf(r) {
204
+ const parts = [];
205
+ const add = (kind, label, text) => parts.push({ kind, label, text });
206
+ const asJson = (kind, label, value) => parts.push({ kind, label, json: value, indent: 2 });
207
+ if (r?.type === 'user' || r?.type === 'assistant') {
208
+ for (const b of blocksOf(r.message)) {
209
+ if (b.type === 'text') add('text', 'text', str(b.text) ?? '');
210
+ else if (b.type === 'thinking') add('thinking', 'thinking', str(b.thinking) ?? '');
211
+ else if (b.type === 'redacted_thinking') add('thinking', 'thinking (redacted)', '');
212
+ else if (b.type === 'tool_use') asJson('tool_use', `tool call: ${str(b.name) ?? '(no name)'}`, b.input ?? {});
213
+ else if (b.type === 'tool_result') add('tool_result', b.is_error === true ? 'tool result (error)' : 'tool result', Array.isArray(b.content) ? b.content.map((x) => (typeof x?.text === 'string' ? x.text : x?.type === 'image' ? '[image]' : '')).join('\n') : flat(b.content));
214
+ else if (b.type === 'image') add('image', `image (${str(b.source?.media_type) ?? 'unknown type'})`, '');
215
+ else asJson('other', `block: ${str(b.type) ?? '(no type)'}`, b);
216
+ }
217
+ if (r.type === 'user' && r.toolUseResult !== undefined) {
218
+ if (typeof r.toolUseResult === 'string') add('structured', 'tool result, structured', r.toolUseResult);
219
+ else asJson('structured', 'tool result, structured', r.toolUseResult);
220
+ }
221
+ } else if (r?.type === 'system') {
222
+ if (typeof r.content === 'string') add('system', `system: ${str(r.subtype) ?? '(no subtype)'}`, r.content);
223
+ else asJson('system', `system: ${str(r.subtype) ?? '(no subtype)'}`, r);
224
+ } else if (r?.type === 'attachment') {
225
+ asJson('attachment', `attachment: ${str(r.attachment?.type) ?? '(no type)'}`, r.attachment);
226
+ } else {
227
+ asJson('other', `record: ${str(r?.type) ?? '(no type)'}`, r);
228
+ }
229
+ return parts;
230
+ }
231
+
232
+ /** The parts of a record a person reads (partsOf), each written out and clipped at `perPart` units. */
233
+ export function readingOf(r, perPart) {
234
+ return partsOf(r).map((p) => ({ kind: p.kind, label: p.label, ...clip(p.json !== undefined ? json(p.json, p.indent) : p.text, perPart) }));
235
+ }
236
+
237
+ /** JavaScript's limit on a string's length (V8 on 64 bits, Node 20 to 26: 2^29 - 24 units): JSON.stringify of a value
238
+ * longer than that throws, and view.mjs's json() writes "(too large to write out)" in its place. */
239
+ export const STRING_MAX_UNITS = 2 ** 29 - 24;
240
+
241
+ /**
242
+ * The length of JSON.stringify(v, null, indent), in UTF-16 units, and whether it holds a character past U+00FF (V8 then
243
+ * keeps the string at two bytes a unit), found by walking v: no string is built. For values JSON.parse gives (undefined
244
+ * as json() writes it, ''). A string is measured as JSON.stringify escapes it: " and \ and the controls \b \f \n \r
245
+ * \t as two units, the other controls and a lone surrogate as six. Checked against JSON.stringify over every record of
246
+ * the fixtures (test/record-view.test.mjs).
247
+ */
248
+ export function jsonSize(v, indent) {
249
+ let units = 0, wide = false;
250
+ const text = (s) => {
251
+ let n = 2;
252
+ for (let i = 0; i < s.length; i++) {
253
+ const c = s.charCodeAt(i);
254
+ if (c === 0x22 || c === 0x5c) n += 2;
255
+ else if (c < 0x20) n += c === 8 || c === 9 || c === 10 || c === 12 || c === 13 ? 2 : 6;
256
+ else if (c >= 0xd800 && c <= 0xdfff) {
257
+ const next = s.charCodeAt(i + 1);
258
+ if (c <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) { n += 2; i++; wide = true; } else n += 6;
259
+ } else { n += 1; if (c > 0xff) wide = true; }
260
+ }
261
+ return n;
262
+ };
263
+ const leaf = (x) => (x === null ? 4 : typeof x === 'string' ? text(x) : typeof x === 'number' ? (Number.isFinite(x) ? String(x).length : 4) : typeof x === 'boolean' ? (x ? 4 : 5) : -1);
264
+ // the arrays and objects still to measure, and their depths: a stack, not recursion, and only containers on it
265
+ const values = [v], depths = [0];
266
+ if (v === undefined) return { units: 0, wide: false };
267
+ while (values.length) {
268
+ const x = values.pop(), d = depths.pop();
269
+ const l = leaf(x);
270
+ if (l >= 0) { units += l; continue; }
271
+ const keys = Array.isArray(x) ? null : Object.keys(x), n = keys ? keys.length : x.length;
272
+ if (n === 0) { units += 2; continue; }
273
+ // the brackets; each member after a new line and indent * (d + 1) spaces, an object's after its key and ": "; commas
274
+ // between; a new line and indent * d spaces before the closing bracket
275
+ units += n * (1 + indent * (d + 1) + (keys ? 2 : 0)) + (n - 1) + 3 + indent * d;
276
+ for (let i = 0; i < n; i++) {
277
+ const y = keys ? x[keys[i]] : x[i];
278
+ if (keys) units += text(keys[i]);
279
+ const m = leaf(y);
280
+ if (m >= 0) units += m;
281
+ else { values.push(y); depths.push(d + 1); }
282
+ }
283
+ }
284
+ return { units, wide };
285
+ }
286
+
287
+ /**
288
+ * What recordView writes of the record on `line` (null when no record was parsed on it), in bytes, measured by walking
289
+ * it (jsonSize): the record as JSON (indent 1) and each part shown as JSON (indent 2), whole, before they are clipped;
290
+ * each at one byte a unit, two when it holds a character past U+00FF, as V8 keeps a string; one longer than
291
+ * STRING_MAX_UNITS is never written (json() measures it first, and does not hand it to JSON.stringify) and counts
292
+ * nothing. N3: JSON is
293
+ * indented once more at each level a value is nested in, so that a list nested 990 deep, on a line of 0.8 MB, is written
294
+ * as 399,389,570 units.
295
+ */
296
+ export function recordViewBytes(t, line) {
297
+ const i = recordIndexAt(t, line);
298
+ if (i === undefined) return null;
299
+ const r = t.records[i];
300
+ const bytes = (v, indent) => { const s = jsonSize(v, indent); return s.units > STRING_MAX_UNITS ? 0 : s.units * (s.wide ? 2 : 1); };
301
+ let n = bytes(r, 1);
302
+ for (const p of partsOf(r)) if (p.json !== undefined) n += bytes(p.json, p.indent);
303
+ return n;
304
+ }
305
+
306
+ /** The record written on `line`: its address, where it sits in the file, what kind of record it is, its reading, and the
307
+ * record itself as JSON. `whole` lifts the clipping (still bounded). null when no record was parsed on that line. */
308
+ export function recordView(t, line, { name, whole = false }) {
309
+ const i = recordIndexAt(t, line);
310
+ if (i === undefined) return null;
311
+ const r = t.records[i], pos = t.positions[i];
312
+ const perPart = whole ? 4_000_000 : 20_000, rawMax = whole ? 8_000_000 : 200_000;
313
+ return {
314
+ a: `${prefixOf(name)}:L${line}`, line, offset: pos.offset, bytes: pos.bytes,
315
+ type: str(r?.type) ?? null, subtype: str(r?.subtype) ?? null, time: str(r?.timestamp) ?? null, uuid: str(r?.uuid) ?? null,
316
+ channel: r?.type === 'user' ? inputChannel(r) ?? null : null, whole,
317
+ reading: readingOf(r, perPart), raw: clip(json(r, 1), rawMax),
318
+ };
319
+ }
320
+
321
+ /** The text around a search match, by ltms's recipe (README, "Reading a hit"): follow `field` from the record, and take
322
+ * `width` units around offset `at`. Where `field` holds "(withheld)", the keys at that place whose value leads, along
323
+ * the rest of `field`, to a string longer than `at`. */
324
+ export function fieldWindow(r, field, at, width = 600) {
325
+ if (!Array.isArray(field) || !Number.isSafeInteger(at) || at < 0) return { error: 'not a hit field' };
326
+ const keys = (v) => (v !== null && typeof v === 'object' ? Object.keys(v) : []);
327
+ const leads = (v, i) => (i < field.length ? (field[i] === '(withheld)' ? keys(v).some((x) => leads(v[x], i + 1)) : leads(v?.[field[i]], i + 1)) : typeof v === 'string' && v.length > at);
328
+ let v = r;
329
+ for (let i = 0; i < field.length; i++) {
330
+ if (field[i] === '(withheld)') return { keys: keys(v).filter((x) => leads(v[x], i + 1)) };
331
+ v = v?.[field[i]];
332
+ }
333
+ if (typeof v !== 'string') return { error: 'not a string here' };
334
+ if (at >= v.length) return { error: 'at is past the end of this field' };
335
+ const half = Math.floor(width / 2), start = Math.max(0, at - half), end = Math.min(v.length, at + half);
336
+ return { text: v.slice(start, end), start, at, length: v.length };
337
+ }