@luxass/pi-session-search 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/query.ts ADDED
@@ -0,0 +1,490 @@
1
+ /**
2
+ * Query syntax for /find and /find-all, and the exact matching rules.
3
+ *
4
+ * Both scopes verify every hit with matchesItem(), so the index can return
5
+ * loose candidates and results still follow these rules. The index worker
6
+ * loads this module too, so it has type annotations only and no Pi packages.
7
+ */
8
+
9
+ import type { ItemKind } from "./searchable-text.ts";
10
+
11
+ /** Role filter cycled with Tab in the picker. */
12
+ export type RoleFilter = "all" | "user" | "assistant" | "tools";
13
+
14
+ export const ROLE_FILTERS: readonly RoleFilter[] = ["all", "user", "assistant", "tools"];
15
+
16
+ export interface ParsedQuery {
17
+ /** Literal terms. Every one must appear in the item text. */
18
+ terms: string[];
19
+ /** True when a term has an uppercase letter (smart case). */
20
+ caseSensitive: boolean;
21
+ /** Item kinds allowed by a role prefix. Undefined means any kind. */
22
+ kinds?: ItemKind[];
23
+ /** Tool name from t:NAME, tc:NAME, or tr:NAME. */
24
+ toolName?: string;
25
+ /** Working-directory filter from cwd:TEXT. Only the all-sessions scope uses it. */
26
+ cwd?: string;
27
+ /** Session-name filter from name:TEXT or title:TEXT. Smart case, like terms. */
28
+ name?: string;
29
+ /** Earliest message time from since:VALUE. See resolveTimeRange(). */
30
+ since?: TimeBound;
31
+ /** Message time from until:VALUE; messages must be older. See resolveTimeRange(). */
32
+ until?: TimeBound;
33
+ /**
34
+ * One note per filter whose value could not be read, such as `since:yesterday`.
35
+ * The filter is ignored, and the picker shows the note in its status line.
36
+ */
37
+ invalidFilterNotes?: string[];
38
+ /** The terms joined by spaces, for the fuzzy fallback. */
39
+ fuzzyText: string;
40
+ }
41
+
42
+ /**
43
+ * A point in time written in a query. `ago` counts back from the time of the
44
+ * search, which the caller passes in; `date` is already absolute.
45
+ */
46
+ export type TimeBound =
47
+ | { type: "ago"; milliseconds: number }
48
+ | {
49
+ type: "date";
50
+ /** Milliseconds since the epoch. */
51
+ time: number;
52
+ };
53
+
54
+ /** Absolute bounds of a query's time filters, in milliseconds since the epoch. */
55
+ export interface TimeRange {
56
+ /** Messages at or after this time. */
57
+ since?: number;
58
+ /** Messages before this time. */
59
+ until?: number;
60
+ }
61
+
62
+ const HOUR_MS = 60 * 60 * 1000;
63
+
64
+ const DURATION_UNIT_MS: Record<string, number> = {
65
+ h: HOUR_MS,
66
+ d: 24 * HOUR_MS,
67
+ w: 7 * 24 * HOUR_MS,
68
+ };
69
+
70
+ /**
71
+ * Reads `2d`, `3h`, `1w`, or a date such as `2026-11-01`, which means the
72
+ * start of that day in local time. Undefined when the value is neither.
73
+ */
74
+ export function parseTimeBound(value: string): TimeBound | undefined {
75
+ const duration = /^(\d+)([hdw])$/iu.exec(value);
76
+ if (duration !== null) {
77
+ const unit = DURATION_UNIT_MS[(duration[2] as string).toLowerCase()] as number;
78
+ return { type: "ago", milliseconds: Number(duration[1]) * unit };
79
+ }
80
+ const date = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(value);
81
+ if (date !== null) {
82
+ const year = Number(date[1]);
83
+ const monthIndex = Number(date[2]) - 1;
84
+ const day = Number(date[3]);
85
+ const start = new Date(year, monthIndex, day);
86
+ // Date rolls over out-of-range parts, so 2026-02-30 would become March 2.
87
+ if (
88
+ start.getFullYear() !== year ||
89
+ start.getMonth() !== monthIndex ||
90
+ start.getDate() !== day
91
+ ) {
92
+ return undefined;
93
+ }
94
+ return { type: "date", time: start.getTime() };
95
+ }
96
+ return undefined;
97
+ }
98
+
99
+ function timeBoundAt(bound: TimeBound, now: number): number {
100
+ return bound.type === "ago" ? now - bound.milliseconds : bound.time;
101
+ }
102
+
103
+ /** Turns the query's since: and until: into absolute times, counting back from `now`. */
104
+ export function resolveTimeRange(query: ParsedQuery, now: number): TimeRange {
105
+ const range: TimeRange = {};
106
+ if (query.since !== undefined) {
107
+ range.since = timeBoundAt(query.since, now);
108
+ }
109
+ if (query.until !== undefined) {
110
+ range.until = timeBoundAt(query.until, now);
111
+ }
112
+ return range;
113
+ }
114
+
115
+ /** True when the timestamp is at or after `since` and before `until`. */
116
+ export function inTimeRange(timestamp: number, range: TimeRange): boolean {
117
+ if (range.since !== undefined && timestamp < range.since) {
118
+ return false;
119
+ }
120
+ return range.until === undefined || timestamp < range.until;
121
+ }
122
+
123
+ function invalidTimeNote(prefix: string): string {
124
+ return `${prefix}: needs a duration like 2d or a date like 2026-11-01`;
125
+ }
126
+
127
+ const KINDS_BY_ROLE_FILTER: Record<RoleFilter, ItemKind[] | undefined> = {
128
+ all: undefined,
129
+ user: ["user", "shell"],
130
+ assistant: ["assistant"],
131
+ tools: ["toolCall", "toolResult"],
132
+ };
133
+
134
+ interface RolePrefix {
135
+ kinds: ItemKind[];
136
+ /** True when the value after the colon names a tool instead of adding a term. */
137
+ takesToolName: boolean;
138
+ }
139
+
140
+ const ROLE_PREFIXES: Record<string, RolePrefix> = {
141
+ u: { kinds: ["user", "shell"], takesToolName: false },
142
+ user: { kinds: ["user", "shell"], takesToolName: false },
143
+ a: { kinds: ["assistant"], takesToolName: false },
144
+ assistant: { kinds: ["assistant"], takesToolName: false },
145
+ t: { kinds: ["toolCall", "toolResult"], takesToolName: true },
146
+ tool: { kinds: ["toolCall", "toolResult"], takesToolName: true },
147
+ tc: { kinds: ["toolCall"], takesToolName: true },
148
+ call: { kinds: ["toolCall"], takesToolName: true },
149
+ tr: { kinds: ["toolResult"], takesToolName: true },
150
+ result: { kinds: ["toolResult"], takesToolName: true },
151
+ };
152
+
153
+ interface RawToken {
154
+ text: string;
155
+ /** True when the token began with a quote, which makes it a literal term. */
156
+ literal: boolean;
157
+ }
158
+
159
+ /** Splits on whitespace. Double quotes group words; `u:"two words"` stays one token. */
160
+ function tokenize(input: string): RawToken[] {
161
+ const tokens: RawToken[] = [];
162
+ let current = "";
163
+ let literal = false;
164
+ let inQuotes = false;
165
+ let started = false;
166
+
167
+ const finish = (): void => {
168
+ if (started) {
169
+ tokens.push({ text: current, literal });
170
+ }
171
+ current = "";
172
+ literal = false;
173
+ started = false;
174
+ };
175
+
176
+ for (const char of input) {
177
+ if (char === '"') {
178
+ if (!started) {
179
+ literal = true;
180
+ }
181
+ inQuotes = !inQuotes;
182
+ started = true;
183
+ continue;
184
+ }
185
+ if (!inQuotes && /\s/u.test(char)) {
186
+ finish();
187
+ continue;
188
+ }
189
+ current += char;
190
+ started = true;
191
+ }
192
+ finish();
193
+ return tokens;
194
+ }
195
+
196
+ function hasUppercase(text: string): boolean {
197
+ return text !== text.toLowerCase();
198
+ }
199
+
200
+ /** Parses the query text typed in the picker or passed to the command. */
201
+ export function parseQuery(input: string): ParsedQuery {
202
+ const terms: string[] = [];
203
+ let kinds: ItemKind[] | undefined;
204
+ let toolName: string | undefined;
205
+ let cwd: string | undefined;
206
+ let name: string | undefined;
207
+ let since: TimeBound | undefined;
208
+ let until: TimeBound | undefined;
209
+ const invalidFilterNotes: string[] = [];
210
+
211
+ for (const token of tokenize(input)) {
212
+ const colon = token.text.indexOf(":");
213
+ if (colon > 0 && !token.literal) {
214
+ const prefix = token.text.slice(0, colon).toLowerCase();
215
+ const value = token.text.slice(colon + 1);
216
+ const role = ROLE_PREFIXES[prefix];
217
+ if (role !== undefined) {
218
+ kinds = role.kinds;
219
+ if (value !== "") {
220
+ if (role.takesToolName) {
221
+ toolName = value;
222
+ } else {
223
+ terms.push(value);
224
+ }
225
+ }
226
+ continue;
227
+ }
228
+ if (prefix === "cwd") {
229
+ if (value !== "") {
230
+ cwd = value;
231
+ }
232
+ continue;
233
+ }
234
+ if (prefix === "name" || prefix === "title") {
235
+ if (value !== "") {
236
+ name = value;
237
+ }
238
+ continue;
239
+ }
240
+ if (prefix === "since" || prefix === "until") {
241
+ const bound = parseTimeBound(value);
242
+ if (bound === undefined) {
243
+ invalidFilterNotes.push(invalidTimeNote(prefix));
244
+ } else if (prefix === "since") {
245
+ since = bound;
246
+ } else {
247
+ until = bound;
248
+ }
249
+ continue;
250
+ }
251
+ }
252
+ if (token.text !== "") {
253
+ terms.push(token.text);
254
+ }
255
+ }
256
+
257
+ const parsed: ParsedQuery = {
258
+ terms,
259
+ caseSensitive: terms.some(hasUppercase),
260
+ fuzzyText: terms.join(" "),
261
+ };
262
+ if (kinds !== undefined) {
263
+ parsed.kinds = kinds;
264
+ }
265
+ if (toolName !== undefined) {
266
+ parsed.toolName = toolName;
267
+ }
268
+ if (cwd !== undefined) {
269
+ parsed.cwd = cwd;
270
+ }
271
+ if (name !== undefined) {
272
+ parsed.name = name;
273
+ }
274
+ if (since !== undefined) {
275
+ parsed.since = since;
276
+ }
277
+ if (until !== undefined) {
278
+ parsed.until = until;
279
+ }
280
+ if (invalidFilterNotes.length > 0) {
281
+ parsed.invalidFilterNotes = invalidFilterNotes;
282
+ }
283
+ return parsed;
284
+ }
285
+
286
+ /** True when the query has no terms and no filters, so it matches everything. */
287
+ export function isEmptyQuery(query: ParsedQuery): boolean {
288
+ return (
289
+ query.terms.length === 0 &&
290
+ query.kinds === undefined &&
291
+ query.toolName === undefined &&
292
+ query.cwd === undefined &&
293
+ query.name === undefined &&
294
+ query.since === undefined &&
295
+ query.until === undefined
296
+ );
297
+ }
298
+
299
+ function escapeRegExp(text: string): string {
300
+ return text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
301
+ }
302
+
303
+ /**
304
+ * Folds text for the /find-all substring index, so the index can find
305
+ * candidates for the case-insensitive matching done by termPatterns().
306
+ *
307
+ * termPatterns() uses the `iu` flags, which compare characters by Unicode
308
+ * simple case folding. Lowercasing and then uppercasing maps every character
309
+ * of one such folding class to the same text: `k`, `K`, and the Kelvin sign
310
+ * all become `K`, and `s`, `S`, and the long s all become `S`. Whenever a term
311
+ * matches a text under `iu`, the folded term is therefore a substring of the
312
+ * folded text. The reverse need not hold, because the folding can be looser
313
+ * (`ß` becomes `SS`), so the index only finds candidates and matchesItem()
314
+ * decides. The fold is used only for index lookups, never for display.
315
+ */
316
+ export function foldForIndex(text: string): string {
317
+ return text.toLowerCase().toUpperCase();
318
+ }
319
+
320
+ /** Builds one global regular expression per term, honoring smart case. */
321
+ export function termPatterns(query: ParsedQuery): RegExp[] {
322
+ const flags = query.caseSensitive ? "gu" : "giu";
323
+ return query.terms.map((term) => new RegExp(escapeRegExp(term), flags));
324
+ }
325
+
326
+ /** True when the kind passes both the query's role prefix and the picker's role filter. */
327
+ export function kindAllowed(kind: ItemKind, query: ParsedQuery, roleFilter: RoleFilter): boolean {
328
+ const filterKinds = KINDS_BY_ROLE_FILTER[roleFilter];
329
+ if (filterKinds !== undefined && !filterKinds.includes(kind)) {
330
+ return false;
331
+ }
332
+ return query.kinds === undefined || query.kinds.includes(kind);
333
+ }
334
+
335
+ /** Matches a tool name exactly, ignoring case, or the last `__`-separated part of it. */
336
+ export function toolNameMatches(actual: string | undefined, wanted: string): boolean {
337
+ if (actual === undefined) {
338
+ return false;
339
+ }
340
+ const actualLower = actual.toLowerCase();
341
+ const wantedLower = wanted.toLowerCase();
342
+ if (actualLower === wantedLower) {
343
+ return true;
344
+ }
345
+ const separator = actualLower.lastIndexOf("__");
346
+ return separator >= 0 && actualLower.slice(separator + 2) === wantedLower;
347
+ }
348
+
349
+ /** Smart-case substring test for the cwd: filter. */
350
+ export function cwdMatches(cwd: string, wanted: string): boolean {
351
+ if (hasUppercase(wanted)) {
352
+ return cwd.includes(wanted);
353
+ }
354
+ return cwd.toLowerCase().includes(wanted.toLowerCase());
355
+ }
356
+
357
+ /**
358
+ * Smart-case substring test for the name: filter, with the same case rules as
359
+ * terms. A session without a name never matches.
360
+ */
361
+ export function sessionNameMatches(sessionName: string | undefined, wanted: string): boolean {
362
+ if (sessionName === undefined) {
363
+ return false;
364
+ }
365
+ const flags = hasUppercase(wanted) ? "u" : "iu";
366
+ return new RegExp(escapeRegExp(wanted), flags).test(sessionName);
367
+ }
368
+
369
+ /** The fields of an item that the matching rules look at. */
370
+ export interface MatchableItem {
371
+ kind: ItemKind;
372
+ toolName?: string;
373
+ text: string;
374
+ }
375
+
376
+ /**
377
+ * Applies every query rule except cwd:, name:, since:, and until:. The first
378
+ * two belong to the session, and the time filters need the time of the search.
379
+ */
380
+ export function matchesItem(
381
+ item: MatchableItem,
382
+ query: ParsedQuery,
383
+ roleFilter: RoleFilter,
384
+ patterns: RegExp[] = termPatterns(query),
385
+ ): boolean {
386
+ if (!kindAllowed(item.kind, query, roleFilter)) {
387
+ return false;
388
+ }
389
+ if (query.toolName !== undefined && !toolNameMatches(item.toolName, query.toolName)) {
390
+ return false;
391
+ }
392
+ for (const pattern of patterns) {
393
+ pattern.lastIndex = 0;
394
+ if (!pattern.test(item.text)) {
395
+ return false;
396
+ }
397
+ }
398
+ return true;
399
+ }
400
+
401
+ /** A half-open character range [start, end) in a text. */
402
+ export interface TextRange {
403
+ start: number;
404
+ end: number;
405
+ }
406
+
407
+ /**
408
+ * Finds every occurrence of every term, sorted and merged, for highlighting.
409
+ * Stops after `limit` ranges so huge texts stay cheap.
410
+ */
411
+ export function findTermRanges(text: string, patterns: RegExp[], limit = 2000): TextRange[] {
412
+ const ranges: TextRange[] = [];
413
+ for (const pattern of patterns) {
414
+ pattern.lastIndex = 0;
415
+ let match = pattern.exec(text);
416
+ while (match !== null && ranges.length < limit) {
417
+ if (match[0].length === 0) {
418
+ pattern.lastIndex += 1;
419
+ } else {
420
+ ranges.push({ start: match.index, end: match.index + match[0].length });
421
+ }
422
+ match = pattern.exec(text);
423
+ }
424
+ }
425
+ ranges.sort((left, right) => left.start - right.start || left.end - right.end);
426
+
427
+ const merged: TextRange[] = [];
428
+ for (const range of ranges) {
429
+ const last = merged[merged.length - 1];
430
+ if (last !== undefined && range.start <= last.end) {
431
+ last.end = Math.max(last.end, range.end);
432
+ } else {
433
+ merged.push({ ...range });
434
+ }
435
+ }
436
+ return merged;
437
+ }
438
+
439
+ /** Index of the first term occurrence, or 0 when there are no terms. */
440
+ export function firstMatchIndex(text: string, patterns: RegExp[]): number {
441
+ let first = -1;
442
+ for (const pattern of patterns) {
443
+ pattern.lastIndex = 0;
444
+ const match = pattern.exec(text);
445
+ if (match !== null && (first < 0 || match.index < first)) {
446
+ first = match.index;
447
+ }
448
+ }
449
+ return first < 0 ? 0 : first;
450
+ }
451
+
452
+ /**
453
+ * Where the match is in a multi-term query's text: the line where the terms
454
+ * match best, scored by the total length of the distinct terms found on it,
455
+ * so a short term such as "a", which matches almost anywhere, does not pull
456
+ * the needle to the top. Ties go to the earlier line. Within the line, the
457
+ * earliest match. Falls back to the first match of any term when no line has
458
+ * one, which happens only when the patterns do not match the text.
459
+ */
460
+ export function bestMatchIndex(text: string, patterns: RegExp[]): number {
461
+ let bestIndex = -1;
462
+ let bestScore = 0;
463
+ let lineStart = 0;
464
+ while (lineStart <= text.length) {
465
+ const newline = text.indexOf("\n", lineStart);
466
+ const lineEnd = newline < 0 ? text.length : newline;
467
+ const line = text.slice(lineStart, lineEnd);
468
+ let score = 0;
469
+ let firstInLine = -1;
470
+ for (const pattern of patterns) {
471
+ pattern.lastIndex = 0;
472
+ const match = pattern.exec(line);
473
+ if (match !== null) {
474
+ score += Math.max(1, match[0].length);
475
+ if (firstInLine < 0 || match.index < firstInLine) {
476
+ firstInLine = match.index;
477
+ }
478
+ }
479
+ }
480
+ if (score > bestScore) {
481
+ bestScore = score;
482
+ bestIndex = lineStart + firstInLine;
483
+ }
484
+ if (newline < 0) {
485
+ break;
486
+ }
487
+ lineStart = newline + 1;
488
+ }
489
+ return bestIndex < 0 ? firstMatchIndex(text, patterns) : bestIndex;
490
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Turns raw session entries into the text that /find and /find-all search.
3
+ *
4
+ * Both pi's main thread and the index worker use this module, so it holds type
5
+ * annotations only and imports no Pi packages. Entries are plain JSON here,
6
+ * because the worker parses session files itself.
7
+ */
8
+
9
+ /** What kind of conversation content a searchable item holds. */
10
+ export type ItemKind = "user" | "assistant" | "toolCall" | "toolResult" | "shell";
11
+
12
+ /** One searchable piece of a session entry. An assistant entry can yield several. */
13
+ export interface SearchableItem {
14
+ entryId: string;
15
+ parentId: string | null;
16
+ /** Position among the items of the same entry. Stable for a given entry. */
17
+ part: number;
18
+ kind: ItemKind;
19
+ /** Tool name for toolCall and toolResult items. */
20
+ toolName?: string;
21
+ text: string;
22
+ /** Milliseconds since the epoch. 0 when the entry has no usable timestamp. */
23
+ timestamp: number;
24
+ }
25
+
26
+ /** Tool arguments that best describe a call, in priority order. Shown first. */
27
+ const PRIMARY_ARGUMENT_KEYS = [
28
+ "command",
29
+ "path",
30
+ "file_path",
31
+ "filePath",
32
+ "pattern",
33
+ "query",
34
+ "url",
35
+ "code",
36
+ "prompt",
37
+ "task",
38
+ "description",
39
+ "action",
40
+ "name",
41
+ ];
42
+
43
+ type JsonObject = Record<string, unknown>;
44
+
45
+ function isObject(value: unknown): value is JsonObject {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+
49
+ function readTimestamp(entry: JsonObject, message: JsonObject | undefined): number {
50
+ if (typeof entry.timestamp === "string") {
51
+ const parsed = Date.parse(entry.timestamp);
52
+ if (Number.isFinite(parsed)) {
53
+ return parsed;
54
+ }
55
+ }
56
+ if (message && typeof message.timestamp === "number" && Number.isFinite(message.timestamp)) {
57
+ return message.timestamp;
58
+ }
59
+ return 0;
60
+ }
61
+
62
+ /** Joins the text blocks of message content. Images and thinking are skipped. */
63
+ function textBlocks(content: unknown): string {
64
+ if (typeof content === "string") {
65
+ return content;
66
+ }
67
+ if (!Array.isArray(content)) {
68
+ return "";
69
+ }
70
+ const parts: string[] = [];
71
+ for (const block of content) {
72
+ if (isObject(block) && block.type === "text" && typeof block.text === "string") {
73
+ parts.push(block.text);
74
+ }
75
+ }
76
+ return parts.join("\n\n");
77
+ }
78
+
79
+ function formatArgumentValue(value: unknown): string {
80
+ if (typeof value === "string") {
81
+ return value;
82
+ }
83
+ try {
84
+ return JSON.stringify(value) ?? "";
85
+ } catch {
86
+ return String(value);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Formats a tool call as "name primary-argument" followed by the other
92
+ * arguments as "key: value" lines, so the most telling argument leads.
93
+ */
94
+ export function formatToolCall(name: string, args: unknown): string {
95
+ if (!isObject(args)) {
96
+ return name;
97
+ }
98
+ const keys = Object.keys(args);
99
+ let primaryKey = PRIMARY_ARGUMENT_KEYS.find((key) => typeof args[key] === "string");
100
+ if (primaryKey === undefined) {
101
+ primaryKey = keys.find((key) => typeof args[key] === "string");
102
+ }
103
+
104
+ const lines: string[] = [];
105
+ lines.push(primaryKey === undefined ? name : `${name} ${args[primaryKey] as string}`);
106
+ for (const key of keys) {
107
+ if (key === primaryKey || args[key] === undefined) {
108
+ continue;
109
+ }
110
+ lines.push(`${key}: ${formatArgumentValue(args[key])}`);
111
+ }
112
+ return lines.join("\n");
113
+ }
114
+
115
+ /**
116
+ * Extracts the searchable items of one session entry.
117
+ * Returns an empty list for entries without searchable text, such as model
118
+ * changes, labels, compactions, and malformed lines.
119
+ */
120
+ export function extractSearchableItems(entry: unknown): SearchableItem[] {
121
+ if (!isObject(entry) || entry.type !== "message" || typeof entry.id !== "string") {
122
+ return [];
123
+ }
124
+ const message = entry.message;
125
+ if (!isObject(message)) {
126
+ return [];
127
+ }
128
+
129
+ const entryId = entry.id;
130
+ const parentId = typeof entry.parentId === "string" ? entry.parentId : null;
131
+ const timestamp = readTimestamp(entry, message);
132
+ const items: SearchableItem[] = [];
133
+ const add = (kind: ItemKind, text: string, toolName?: string): void => {
134
+ if (text.trim() === "") {
135
+ return;
136
+ }
137
+ const item: SearchableItem = { entryId, parentId, part: items.length, kind, text, timestamp };
138
+ if (toolName !== undefined) {
139
+ item.toolName = toolName;
140
+ }
141
+ items.push(item);
142
+ };
143
+
144
+ switch (message.role) {
145
+ case "user": {
146
+ add("user", textBlocks(message.content));
147
+ break;
148
+ }
149
+ case "assistant": {
150
+ add("assistant", textBlocks(message.content));
151
+ if (Array.isArray(message.content)) {
152
+ for (const block of message.content) {
153
+ if (isObject(block) && block.type === "toolCall" && typeof block.name === "string") {
154
+ add("toolCall", formatToolCall(block.name, block.arguments), block.name);
155
+ }
156
+ }
157
+ }
158
+ break;
159
+ }
160
+ case "toolResult": {
161
+ const toolName = typeof message.toolName === "string" ? message.toolName : undefined;
162
+ add("toolResult", textBlocks(message.content), toolName);
163
+ break;
164
+ }
165
+ case "bashExecution": {
166
+ if (typeof message.command === "string") {
167
+ const output = typeof message.output === "string" ? message.output : "";
168
+ add("shell", output === "" ? `!${message.command}` : `!${message.command}\n${output}`);
169
+ }
170
+ break;
171
+ }
172
+ default:
173
+ break;
174
+ }
175
+ return items;
176
+ }