Something went wrong. Try again.
small gleam coding and (not yet) persistent agent daemon with a detachable cli forked from okami.mom/albedo
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723import { dropQueued, editInput, getShellCommand, holdInput, readContentBatch, readEntryContent, readHistory, readQueue, readRequests, releaseInput, sendContinue, sendMessage, uuidv7, type CompactionProgress, type ContentPart, type HistoryEntry, type Phase, type QueueCollection, type QueueItem, type SideQuestion, type SkillLoad, type ShellCommand,} from './api';import { oneLine, type Trace } from './burst';import { resolve, type Attached, type AttachedFile } from './chat/attachments';import { draftOf, type Draft, type DraftSnapshot } from './chat/drafts';import type { Usage } from './context';import { follow, type Batch } from './stream';import { formatGap, outcome, type Mood } from './moods';import { isNotWaiting, renewalDelay, waitingSend } from './queueEdit';
// One session's transcript as the chat shows it. Entries arrive as history// pages; blocks are what the chat draws. Content a page only referenced is// fetched when needed: messages and shell receipts at once, tool output on opening.
/** Why a turn failed: the error's own words, and all it said. */type Failure = { text: string; detail: string };
export type Block = | { kind: 'user'; key: string; text: string; images: Picture[]; /** Cards for the generic files sent, from the payload or the entry's metadata. */ files: { name: string; size: number }[]; from: string | null; mail?: { senderId: string | null; /** From a webhook or an extension's channel, not an agent. */ external: boolean; /** A child's answer to its parent. */ answer: boolean; } | null; turnType?: HistoryEntry['turn_type']; gap: string | null; at: number; state: 'sending' | 'sent' | 'seen' | 'failed'; error?: string; skill?: string; } | { kind: 'assistant'; key: string; text: string; plate: boolean; phase: HistoryEntry['phase']; } | { kind: 'thinking'; key: string; text: string; ms: number | null } | { kind: 'tool'; key: string; name: string; entry: HistoryEntry; done: boolean; trace?: Trace; failed: boolean; } | { kind: 'note'; key: string; text: string } | { kind: 'compaction'; key: string; text: string } | ({ kind: 'failure'; key: string } & Failure) | { kind: 'end'; key: string; turnId: string | null; from: number; mood: Mood; seed: number; elapsedMs: number; tools: number; text: string; changed: { files: number; added: number; removed: number }; } | { kind: 'progress'; key: string; name: string; title?: string | null; preview: string; } | { kind: 'shell'; key: string; command: ShellCommand };
/** An artifact a cell made or revised: its id, the version, and its title. */export interface Made { id: string; version: number; title: string;}
/** The artifacts a trace says its cell made or revised. */export function madeIn(trace: Trace | undefined): Made[] { return (trace?.activities ?? []).flatMap((activity) => activity.kind === 'artifact' && activity.artifact ? [ { id: activity.artifact.id, version: activity.artifact.version, title: activity.target, }, ] : [], );}
/** Content a cell showed with `display()`. */export interface Displayed { entryId: string; index: number; title: string; description: string; detail: string;}
/** The `display` activities a cell's trace recorded, in order. */export function displayedIn( entryId: string, trace: Trace | undefined,): Displayed[] { let index = 0; return (trace?.activities ?? []).flatMap((activity) => activity.kind === 'display' ? [ { entryId, index: index++, title: activity.title || oneLine(activity.target) || 'content', description: activity.description ?? '', detail: activity.detail ?? '', }, ] : [], );}
/** Output the session is writing now, before it commits: one message of thinking or reply. */interface Live { id: string; kind: 'text' | 'thinking'; text: string;}
// stream notes stay where they arrived across later turns, and after is null until initial load finishesinterface LiveNote { id: string; text: string; after: number | null;}
/** A tool call running now, as its progress reports it. */interface Progress { id: string; /** The model's id for the call, which its tool_call entry carries too. */ call: string; name: string; title?: string | null; preview: string;}
interface Turn { id: string | null; /** The turn's first history position, where a review starts reading. */ from: number; start: number; last: number; tools: number; answered: boolean; files: Set<string>; added: number; removed: number; /** The turn's last reply, which its copy action copies. */ text: string;}
/** What `#read` hands `#tail`: history's blocks, its still-open turn and speaker, and the calls and shell commands it shows. */interface Read { blocks: Block[]; turn: Turn | null; speaker: string; called: Set<string>; durable: Set<string>; notesFrom: number;}
/** * Whether two blocks hold the same values, two levels down: deeper values * (an entry's content, a trace's steps) count as the same only when they are * the same objects, which they are until the entry is replaced. */function alike(a: unknown, b: unknown, depth = 2): boolean { if (Object.is(a, b)) return true; if ( depth === 0 || !a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) !== Array.isArray(b) ) return false; const keys = Object.keys(a); return ( keys.length === Object.keys(b).length && keys.every((key) => alike( (a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], depth - 1, ), ) );}
/** * A value worked out once per entry: entries are replaced, never changed, so * `#read`, which walks every entry on each change, reads it from here. */function perEntry<K extends object, V>(compute: (key: K) => V): (key: K) => V { const known = new WeakMap<K, V>(); return (key) => { if (known.has(key)) return known.get(key)!; const value = compute(key); known.set(key, value); return value; };}
/** The pause before your message that earns a "later" note, as in the TUI. */const AWAY_MS = 30 * 60_000;
/** A turn's run of thinking and tool use, drawn as one collapsible step list. */export type Group = { kind: 'work'; key: string; steps: Block[] } | Block;
/** An image in a message: where to load it, and its size when known. */export interface Picture { src: string; width?: number; height?: number;}
interface Pending { id: string; text: string; images: Attached[]; files: AttachedFile[]; at: number; continuation?: boolean; /** The daemon has it, waiting for the loop to take it into the conversation. */ accepted?: boolean; error?: string;}
/** The images an entry carries; the daemon serves each under its reference. */export const picturesOf = perEntry((entry: HistoryEntry): Picture[] => entry.content.flatMap((part) => part.kind === 'image' && part.image.reference ? [ { src: `/api${part.image.reference.url}`, width: part.image.width, height: part.image.height, }, ] : [], ),);
const textOf = perEntry((content: ContentPart[]): string => content.map((part) => (part.kind === 'text' ? part.text : '')).join(''),);/** File cards come only from the entry's metadata; text that looks like a label is prose. */const filesOf = perEntry( (entry: HistoryEntry): { name: string; size: number }[] => (entry.files ?? []).map(({ name, size }) => ({ name, size })),);
/** The value of a JSON field of an entry, if the page carried it inline. */export function jsonField(entry: HistoryEntry, field: string): unknown { for (const part of entry.content) if (part.kind === 'json' && part.field === field) return part.value; return undefined;}
function traceOf(entry: HistoryEntry): Trace | undefined { for (const part of entry.content) if (part.kind === 'trace') return part.trace; return undefined;}
/** A python cell that raised, read from its result envelope. */export const failedTool = perEntry((entry: HistoryEntry): boolean => { const result = jsonField(entry, 'result'); if (typeof result !== 'string') return false; try { return JSON.parse(result)?.status === 'error'; } catch { return false; }});
function progressOf(progress: any): Progress { return { id: progress?.call_id ?? '', call: progress?.tool_call_id ?? '', name: progress?.name ?? 'tool', title: progress?.title ?? undefined, preview: progress?.preview?.text ?? '', };}
/** An error as one line: the message inside the provider's JSON body when it carries one. */function failureLine(detail: string): string { const body = detail.slice(detail.indexOf('{'), detail.lastIndexOf('}') + 1); // The stream's error quotes the body inside the transport's own words. for (const candidate of [body, body.replaceAll('\\"', '"')]) { try { const parsed = JSON.parse(candidate); const message = parsed?.error?.message ?? parsed?.message; if (typeof message === 'string' && message.trim()) return message.trim(); } catch {} } return detail.trim().split('\n')[0];}
const failureOf = (detail: string): Failure => ({ text: failureLine(detail), detail: detail.trim(),});
/** Entries whose text the chat shows as soon as it opens, so their references are read with their page. */const TEXT_KINDS = new Set([ 'user', 'assistant', 'thinking', 'note', 'compaction', 'shell_command',]);
const byPosition = (a: HistoryEntry, b: HistoryEntry) => a.position - b.position;
/** * `added`, sorted and new, joined to `entries` in history order. A page is * older or newer than everything loaded; only a read that raced another lands * in between and needs the whole list sorted. */function joined( entries: HistoryEntry[], added: HistoryEntry[],): HistoryEntry[] { if (!entries.length || added[0].position > entries.at(-1)!.position) return [...entries, ...added]; if (added.at(-1)!.position < entries[0].position) return [...added, ...entries]; return [...entries, ...added].sort(byPosition);}
const at = perEntry((entry: HistoryEntry) => entry.created_at ? Date.parse(entry.created_at) : 0,);
function shellCommandOf(value: unknown): ShellCommand | null { if (!value || typeof value !== 'object') return null; const command = value as Record<string, unknown>; if ( typeof command.id !== 'string' || typeof command.command !== 'string' || !['running', 'completed', 'cancelled', 'interrupted', 'failed'].includes( String(command.status), ) || (command.exit_code !== null && typeof command.exit_code !== 'number') || typeof command.output !== 'string' || typeof command.output_bytes !== 'number' || typeof command.truncated !== 'boolean' || (command.error !== null && typeof command.error !== 'string') || (command.history_seq !== null && typeof command.history_seq !== 'number') || (command.delivery !== undefined && !['unknown', 'pending', 'delivered', 'detached'].includes( String(command.delivery), )) ) return null; return { ...(value as ShellCommand), delivery: (command.delivery as ShellCommand['delivery']) ?? 'unknown', };}
/** HTTP admission replies can lag behind completion/ACK events. Neither may undo an acknowledgment. */function mergeShell(previous: ShellCommand, next: ShellCommand): ShellCommand { const stale = next.delivery !== 'detached' && (previous.delivery === 'detached' || (previous.delivery === 'delivered' && next.delivery !== 'delivered') || (previous.status !== 'running' && next.status === 'running') || (previous.history_seq !== null && next.history_seq === null) || previous.output_bytes > next.output_bytes); const latest = stale ? previous : next; // Reset/events carry a smaller head than hydrated history; keep the richer preview. const output = previous.output.length > next.output.length ? previous.output : next.output; return latest.output === output ? latest : { ...latest, output };}
function referenced(entry: HistoryEntry): boolean { return entry.content.some( (part) => part.kind === 'reference' && !part.reference.field.startsWith('image-'), );}
/** What tool results that just arrived made or displayed, reading the traces their page only referenced. */async function surfacedBy( entries: HistoryEntry[],): Promise<{ made: Made[]; displayed: Displayed[] }> { const results = entries.filter((entry) => entry.kind === 'tool_result'); const referencing = results.filter((entry) => entry.content.some( (part) => part.kind === 'reference' && part.reference.field === 'trace', ), ); const traced = new Map( (await hydrateAll(referencing)).map((entry) => [entry.id, entry]), ); return { made: results.flatMap((entry) => madeIn(traceOf(traced.get(entry.id) ?? entry)), ), displayed: results.flatMap((entry) => displayedIn(entry.id, traceOf(traced.get(entry.id) ?? entry)), ), };}
/** The batch content route takes at most this many entries a read. */const BATCH = 200;const named = /^\/sessions\/([^/]+)\/history\/([^/?]+)$/;
/** * A stored JSON field as its part, or as its text when it does not parse (a * reference the batch read left out reads as ''): one bad field must not keep * the rest of the page from showing. */function stored(field: string, raw: string): ContentPart { try { const value = JSON.parse(raw); return field === 'trace' ? { kind: 'trace', trace: value } : { kind: 'json', field, value }; } catch { return { kind: 'text', text: raw }; }}
/** * Replaces the entries' references with the content they name, in order: * every reference is read through the batch content route, one walk per session and 200 entries, rather than one * request per entry. A reference the route cannot name is read on its own. */export async function hydrateAll( entries: HistoryEntry[],): Promise<HistoryEntry[]> { const urls = new Set( entries.flatMap((entry) => referenced(entry) ? entry.content.flatMap((part) => part.kind === 'reference' && !part.reference.field.startsWith('image-') ? [part.reference.url] : [], ) : [], ), ); const bySession = new Map<string, string[]>(); const alone: string[] = []; for (const url of urls) { const match = named.exec(url); if (!match) alone.push(url); else if (bySession.has(match[1])) bySession.get(match[1])!.push(match[2]); else bySession.set(match[1], [match[2]]); } const loaded = new Map<string, Record<string, string>>(); const reads: Promise<void>[] = alone.map( async (url) => void loaded.set(url, await readEntryContent(url)), ); for (const [session, ids] of bySession) { for (let start = 0; start < ids.length; start += BATCH) { const chunk = ids.slice(start, start + BATCH); reads.push( readContentBatch(session, chunk).then((fields) => { for (const id of chunk) loaded.set( `/sessions/${session}/history/${id}`, fields.get(id) ?? {}, ); }), ); } } await Promise.all(reads); return entries.map((entry) => { if (!referenced(entry)) return { ...entry, content_complete: true }; const content = entry.content.map((part): ContentPart => { if ( part.kind !== 'reference' || part.reference.field.startsWith('image-') ) return part; const { url, field } = part.reference; const raw = loaded.get(url)?.[field] ?? ''; return field === 'text' ? { kind: 'text', text: raw } : stored(field, raw); }); return { ...entry, content, content_complete: true }; });}
/** The message an edit is working on, its id, the composer draft it stashed, and that draft. */interface Editing { id: string; stash: DraftSnapshot; draft: Draft;}
function snapshotOf( text: string, images: Attached[], files: AttachedFile[],): DraftSnapshot { return { text, images: new Map(images.map((image, index) => [index + 1, image])), files: new Map(files.map((file, index) => [index + 1, file])), next: 0, };}
function errorText(error: unknown): string { return String((error as Error).message ?? error);}
export class Transcript { entries = $state.raw<HistoryEntry[]>([]); pending = $state.raw<Pending[]>([]); loading = $state(true); /** Whether the session is busy, so its newest turn is not signed off yet. */ running = $state(false); /** The phase the stream last reported, fresher than the session list's. */ phase = $state<Phase | null>(null); /** Live compaction progress the stream last reported, fresher than the session list's. */ compaction = $state<CompactionProgress | null>(null); streaming = $state(false); live = $state.raw<Live[]>([]); #notes = $state.raw<LiveNote[]>([]); progress = $state.raw<Progress[]>([]); shellCommands = $state.raw<ShellCommand[]>([]); /** What waits in the session's inbox, in the order it will be read. */ queue = $state.raw<QueueItem[]>([]); queueTotal = $state(0); queueError = $state<string | null>(null); /** The waiting message being edited: its composer draft waits here until the edit ends. */ editing = $state.raw<Editing | null>(null); #queueRead = 0; #lease: ReturnType<typeof setTimeout> | undefined; #stop: (() => void) | null = null; #settle: ReturnType<typeof setTimeout> | undefined; /** Live output ids history has committed, kept until a read that began after their commit succeeds. */ #replacing = new Set<string>(); more = $state(false); error = $state<string | null>(null); /** * Artifacts made or revised since the chat opened, oldest first, so the * chat can open them as they arrive; history read on opening never adds. */ made = $state.raw<Made[]>([]); /** Blocks shown with `display()` since the chat opened, oldest first; history read on opening never adds. */ displayed = $state.raw<Displayed[]>([]);
/** Why turns failed, by run id: the stream's error, then the failed model call's own record. */ failures = $state.raw<Record<string, Failure>>({}); /** * Whether each run's last model call read so far failed. A later call * clears only a failure a call set: one the stream reported after a call * that succeeded stays. */ #calls = new Map<string, boolean>(); /** The first and last model calls read. */ #requestsFrom = Infinity; #requestsAfter = 0;
/** The newest request's usage, from the stream's snapshot and its usage events; null before the first. */ usage = $state.raw<Usage | null>(null);
#history = $derived(this.#read()); blocks = $derived( this.#keep([...this.#history.blocks, ...this.#tail(this.#history)]), ); /** Whether mid-turn prose folds into the work around it. */ #collapse = () => false; groups = $derived(this.#keepGroups(group(this.blocks, this.#collapse()))); /** Last time's blocks and groups by key, which `#keep` and `#keepGroups` reuse. */ #shown = new Map<string, Block>(); #shownGroups = new Map<string, Group>(); /** Your newest message, until a reply follows it, so the chat can say whether the model has it. */ receipt = $derived(this.#receipt());
#expanding = new Set<string>(); /** Entries asked to expand since the last read began, and the read that will take them. */ #asked = new Map<string, HistoryEntry>(); #expansion: Promise<void> | null = null; /** The ids `entries` holds, so a page is checked against them without a pass over all of it. */ #ids = new Set<string>(); /** The history read in flight, which a poll during it shares, and whether one asked while it ran. */ #reading: Promise<void> | null = null; #again = false; #shellRefresh: AbortController | undefined;
constructor( readonly sessionId: string, collapse: () => boolean = () => false, /** The chat's side-question store, fed from resets and `side_question` events. */ readonly sideQuestions?: { applyReset(value: SideQuestion | null): void; applyEvent(value: unknown): void; }, ) { this.#collapse = collapse; }
trackShell(command: ShellCommand) { const previous = this.shellCommands.find((item) => item.id === command.id); this.shellCommands = [ ...this.shellCommands.filter((item) => item.id !== command.id), previous ? mergeShell(previous, command) : command, ]; }
/** The first page's read, which a poll that starts during it waits for rather than reading the same page. */ #opening: Promise<void> | null = null;
load(): Promise<void> { return (this.#opening ??= this.#load()); }
async #load() { try { const page = await readHistory(this.sessionId); this.#merge(await this.#hydrateText(page.items)); this.more = page.older !== null; this.error = null; } catch (error) { this.error = String((error as Error).message ?? error); } finally { const tail = this.entries.at(-1)?.position ?? 0; if (this.#notes.some((note) => note.after === null)) { this.#notes = this.#notes.map((note) => note.after === null ? { ...note, after: tail } : note, ); } this.loading = false; } this.#readFailures().catch(() => {}); }
async loadOlder() { const first = this.entries[0]; if (!first || !this.more) return; const page = await readHistory(this.sessionId, { before: first.position }); this.#merge( await this.#hydrateText( page.items.filter((entry) => !this.#ids.has(entry.id)), ), ); this.more = page.older !== null; this.#readFailures(true).catch(() => {}); }
/** * Adds the entries the chat does not have yet, in history order, and * returns them. Reads overlap (a poll racing the first load, or a load * after a reconnect), so an entry may arrive twice; a duplicate key would * stop the whole chat from updating. */ #merge(arrived: HistoryEntry[]): HistoryEntry[] { const added = arrived .filter((entry) => !this.#ids.has(entry.id)) .sort(byPosition); for (const entry of added) this.#ids.add(entry.id); if (added.length) { this.entries = joined(this.entries, added); const addedIds = new Set(added.map((entry) => entry.id)); if (this.#notes.some((note) => addedIds.has(note.id))) { this.#notes = this.#notes.filter((note) => !addedIds.has(note.id)); } } // Initial hydration may finish after a reset that had no loaded rows yet. if (this.#stop && added.some((entry) => entry.kind === 'shell_command')) void this.#refreshShells(); return added; }
/** * Reads everything after the newest entry, then drops the live output that * committed before the read began. A poll while one runs shares it, and it * reads once more, since what that caller was told committed may have * landed after its request went out. */ poll(): Promise<void> { if (this.#reading) { this.#again = true; return this.#reading; } return (this.#reading = this.#readNewer().finally( () => (this.#reading = null), )); }
async #readNewer() { // A read racing the first load may return history from before the chat // opened; only what follows that load counts as arriving. const opened = !this.loading; await this.#opening; do { this.#again = false; const committed = new Set(this.#replacing); for (;;) { const last = this.entries.at(-1); const page = await readHistory( this.sessionId, last ? { after: last.position } : {}, ); const fresh = page.items.filter((entry) => !this.#ids.has(entry.id)); if (fresh.length) { const hydrated = await this.#hydrateText(fresh); const surfaced = opened ? await surfacedBy(hydrated) : { made: [], displayed: [] }; const arrived = this.#merge(hydrated); if (surfaced.made.length) this.made = [...this.made, ...surfaced.made]; if (surfaced.displayed.length) this.displayed = [...this.displayed, ...surfaced.displayed]; const answered = new Set(arrived.map((entry) => entry.input_id)); this.pending = this.pending.filter((send) => !answered.has(send.id)); } if (!page.newer || !fresh.length) break; } this.#dropLive(committed); } while (this.#again); }
/** Follows the session's stream: live output as it is written, and history as it commits. */ attach() { this.#stop ??= follow( this.sessionId, (batch) => this.#apply(batch), (connected) => (this.streaming = connected), ); }
detach() { this.#stop?.(); this.#stop = null; clearTimeout(this.#settle); this.#shellRefresh?.abort(); }
/** A reset may have missed an ACK for an older, already loaded history row. */ async #refreshShells() { this.#shellRefresh?.abort(); const abort = (this.#shellRefresh = new AbortController()); const pending = new Set( this.entries.flatMap((entry) => { if (entry.kind !== 'shell_command') return []; const part = entry.content.find( (part) => part.kind === 'json' && part.field === 'shell_command', ); const command = part?.kind === 'json' ? shellCommandOf(part.value) : null; return command?.delivery === 'pending' ? [command.id] : []; }), ); // Serial reads bound in-flight work even when many idle receipts were loaded. for (const id of pending) { if (abort.signal.aborted) return; try { const command = await getShellCommand(this.sessionId, id, abort.signal); if (abort.signal.aborted) return; this.trackShell(command); } catch { /* Preserve the last observation; the next reconnect or event can refresh it. */ } } }
#apply(batch: Batch) { for (const event of batch.events) { const data = event.data ?? {}; switch (event.type) { case 'reset': { const snapshot = batch.snapshot ?? {}; this.phase = snapshot.status?.phase ?? null; this.compaction = snapshot.status?.compaction ?? null; // A usage object with no measurement and no spend is not usage. A // spend alone still shows the cost of the session. if (snapshot.usage) this.usage = snapshot.usage.observed_at || snapshot.usage.spent ? snapshot.usage : null; this.live = (snapshot.active_output ?? []).flatMap((output: any) => output.kind === 'text' || output.kind === 'thinking' ? [ { id: output.message_id, kind: output.kind, text: output.text ?? '…', }, ] : [], ); this.progress = (snapshot.current_progress ?? []).map(progressOf); this.shellCommands = (snapshot.shell_commands ?? []).flatMap( (command: unknown) => { const checked = shellCommandOf(command); return checked ? [checked] : []; }, ); this.sideQuestions?.applyReset(snapshot.side_question ?? null); void this.#refreshShells(); this.#commit(null); void this.refreshQueue(); break; } case 'invalidate': if (data.kind === 'extension' && data.url?.endsWith('/queue')) void this.refreshQueue(); break; case 'status': this.phase = data.phase ?? null; this.compaction = data.compaction ?? null; if (this.phase === 'idle') this.#commit(null); break; case 'usage': this.usage = data; break; case 'error': if (data.run_id) this.failures = { ...this.failures, [data.run_id]: failureOf(data.message ?? ''), }; break; case 'text': case 'thinking': { const at = this.live.findIndex((item) => item.id === data.message_id); if (at < 0) this.live = [ ...this.live, { id: data.message_id, kind: event.type, text: data.text }, ]; else this.live = this.live.map((item, index) => index === at ? { ...item, text: item.text + data.text } : item, ); break; } case 'shell_command': { const shell = shellCommandOf(data.shell_command); if (shell) this.trackShell(shell); break; } case 'side_question': this.sideQuestions?.applyEvent(data.side_question); break; case 'tool_progress': { const next = progressOf(data.progress); this.progress = [ ...this.progress.filter((item) => item.id !== next.id), next, ]; break; } case 'tool': this.progress = this.progress.filter( (item) => item.id !== data.progress_call_id, ); this.#commit(null); break; case 'committed': this.#commit( data.replaces_all_live ? 'all' : (data.replaces_live_ids ?? []), ); break; case 'message': this.#commit(null); break; case 'note': this.#pushNote(data); this.#commit(null); break; } } }
#pushNote(data: any) { const id = typeof data?.entry_id === 'string' ? data.entry_id : ''; const origin = typeof data?.origin === 'string' ? data.origin : ''; const text = typeof data?.text === 'string' ? data.text : ''; if (origin === 'agent' || !text.trim()) return; if (id && (this.#ids.has(id) || this.#notes.some((note) => note.id === id))) return; this.#notes = [ ...this.#notes, { id: id || `note:${this.#notes.length}`, text, after: this.loading ? null : (this.entries.at(-1)?.position ?? 0), }, ]; }
/** * Reads what committed, then drops the live output it replaces, so a reply * never blinks out between its last delta and its history entry. */ #commit(replaces: 'all' | string[] | null) { // Events arrive in bursts (a commit, then its tool, then a status), so // one read serves them all; what each burst replaces adds up. A model // commit retires everything streamed so far and a resting session has // nothing left streaming, but output that starts later is not theirs. const retired = replaces === 'all' || this.phase === 'idle' ? this.live.map((item) => item.id) : (replaces ?? []); for (const id of retired) this.#replacing.add(id); clearTimeout(this.#settle); this.#settle = setTimeout(async () => { // A failed read keeps the live output; the next poll drops it once history has it. try { await this.poll(); } catch { // Idle cleanup is independent of whether durable history is reachable. } if (this.phase === 'idle') { this.progress = []; await this.#readFailures().catch(() => {}); } }, 60); }
/** * Reads which turns failed from the session's model calls since the oldest * loaded entry: a turn whose last call failed. The stream says so as it * happens; this is what a chat opened later has. Reads on from the last * call read, or, for an `older` page, the calls before the first one read. */ async #readFailures(older = false) { const since = this.entries[0]?.created_at; if (this.loading || !since) return; const last = new Map<string, string | null>(); const until = this.#requestsFrom; let after = older ? 0 : this.#requestsAfter; reading: for (;;) { const page = await readRequests( this.sessionId, after, 200, undefined, after ? undefined : Date.parse(since), ); for (const request of page.items) { if (older && request.sequence >= until) break reading; if (request.run_id) last.set( request.run_id, request.outcome === 'failed' ? (request.failure?.detail ?? '') : null, ); this.#requestsFrom = Math.min(this.#requestsFrom, request.sequence); after = request.sequence; } if (!page.next || !page.items.length) break; } if (!older) this.#requestsAfter = Math.max(this.#requestsAfter, after); if (!last.size) return; const failures = { ...this.failures }; for (const [run, detail] of last) { // A later page already read how an older run ended. if (older && this.#calls.has(run)) continue; if (detail !== null) failures[run] = failureOf(detail); else if (this.#calls.get(run)) delete failures[run]; this.#calls.set(run, detail !== null); } this.failures = failures; }
#dropLive(committed: Set<string>) { if (!committed.size) return; for (const id of committed) this.#replacing.delete(id); this.live = this.live.filter((item) => !committed.has(item.id)); }
async send( text: string, images: Attached[] = [], files: AttachedFile[] = [], ) { const continuation = text.trim() === '.' && !images.length && !files.length; const send: Pending = { id: uuidv7(), text: continuation ? '.' : text, images, files, at: Date.now(), continuation, }; this.pending = [...this.pending, send]; await this.#deliver(send); }
async retry(id: string) { const send = this.pending.find((candidate) => candidate.id === id); if (!send) return; this.pending = this.pending.map((candidate) => candidate.id === id ? { ...send, error: undefined } : candidate, ); await this.#deliver(send); }
discard(id: string) { this.pending = this.pending.filter((send) => send.id !== id); }
/** Reads the queue again; a read that a later one overtook changes nothing. */ async refreshQueue() { const read = ++this.#queueRead; try { const queue = await readQueue(this.sessionId); if (read === this.#queueRead) this.applyQueue(queue); } catch (error) { if (read === this.#queueRead) this.queueError = String((error as Error).message ?? error); } }
/** The queue an edit answered with; a send it no longer holds was dropped. */ applyQueue(queue: QueueCollection, dropped: string[] = []) { ++this.#queueRead; this.queue = queue.items; this.queueTotal = queue.total; this.queueError = null; if (dropped.length) this.pending = this.pending.filter((send) => !dropped.includes(send.id)); }
/** * Whether a person's waiting message can be edited or taken back here: one * this client sent, or one the queue holds whole (sent elsewhere, or before * a reload). */ own(id: string): boolean { return ( waitingSend( this.pending.find((send) => send.id === id), this.queue, ) || !!this.queue.find((item) => item.id === id)?.editable ); }
/** What an edit of `id` starts from: this client's copy, or the queue's. */ #copyOf( id: string, ): { text: string; images: Attached[]; files: AttachedFile[] } | null { const send = this.pending.find((candidate) => candidate.id === id); if (send) return send; const item = this.queue.find((candidate) => candidate.id === id); return item?.editable ? { text: item.text, images: [], files: [] } : null; }
/** The newest of your waiting messages, which the up arrow edits. */ latestOwn(): string | null { return this.queue.findLast((item) => this.own(item.id))?.id ?? null; }
/** * Holds a waiting message and loads it into the composer, with the draft * stashed until the edit ends. A refusal is said in the composer's notice. */ async beginEdit(id: string) { const draft = draftOf(this.sessionId); if (this.editing) return this.#say(draft, 'finish the edit in progress first'); const send = this.#copyOf(id); if (!send || !this.own(id)) return this.#say(draft, "that message isn't waiting any more"); try { const hold = await holdInput(this.sessionId, id); this.#scheduleRenewal(id, hold.lease_ms); } catch (error) { if (isNotWaiting(error)) { void this.refreshQueue(); return this.#say(draft, 'the agent already read it; nothing changed'); } return this.#say(draft, errorText(error)); } const stash = draft.snapshot(); this.editing = { id, stash, draft }; draft.load({ text: '', images: new Map(), files: new Map(), next: stash.next, }); draft.restore([send]); draft.focusRequested = true; draft.focus?.(); }
/** Saves the composer's text as the held message's text; an empty composer cancels the message. */ async saveEdit(text: string, images: Attached[], files: AttachedFile[]) { const edit = this.editing; if (!edit) return; const typed = snapshotOf(text, images, files); const cancel = !text.trim() && !images.length && !files.length; try { if (cancel) { this.applyQueue(await dropQueued(this.sessionId, edit.id), [edit.id]); } else { await editInput( this.sessionId, edit.id, text, images.map(({ mime_type, data }) => ({ mime_type, data })), files.map(({ name, data }) => ({ name, data })), ); this.pending = this.pending.map((send) => send.id === edit.id ? { ...send, text, images, files } : send, ); void this.refreshQueue(); } this.#end(edit); } catch (error) { this.#end(edit, typed); if (isNotWaiting(error)) { void this.refreshQueue(); return this.#say( edit.draft, 'the agent already read it; your edit is kept as a draft', ); } void releaseInput(this.sessionId, edit.id).catch(() => {}); this.#say(edit.draft, `couldn't save the edit: ${errorText(error)}`); } }
/** Ends the edit as it was: the message goes unchanged and the composer returns to its own draft. */ cancelEdit() { const edit = this.editing; if (!edit) return; this.#end(edit); void releaseInput(this.sessionId, edit.id).catch(() => {}); }
/** Cancels one of this client's waiting messages and returns it to the composer; the running turn is left alone. */ async unsend(id: string) { const draft = draftOf(this.sessionId); if (this.editing) return this.#say(draft, 'finish the edit in progress first'); const copy = this.#copyOf(id); if (!copy || !this.own(id)) return; try { const queue = await dropQueued(this.sessionId, id); this.take([id]); this.applyQueue(queue); draft.restore([copy]); } catch (error) { if (isNotWaiting(error)) { void this.refreshQueue(); return this.#say(draft, 'the agent already read it; nothing changed'); } this.#say(draft, errorText(error)); } }
#say(draft: Draft, notice: string) { draft.notice = notice; }
#scheduleRenewal(id: string, leaseMs: number) { clearTimeout(this.#lease); this.#lease = setTimeout(() => void this.#renew(id), renewalDelay(leaseMs)); }
async #renew(id: string) { const edit = this.editing; if (!edit || edit.id !== id) return; try { const hold = await holdInput(this.sessionId, id); if (this.editing === edit) this.#scheduleRenewal(id, hold.lease_ms); } catch (error) { if (this.editing !== edit) return; if (isNotWaiting(error)) { const typed = edit.draft.snapshot(); this.#end(edit, typed); void this.refreshQueue(); return this.#say( edit.draft, 'the agent already read it while you were editing; what you typed is kept as a draft', ); } this.#scheduleRenewal(id, 3000); } }
/** Leaves the edit: the stashed draft returns, with `typed` after it when given. */ #end(edit: Editing, typed?: DraftSnapshot) { clearTimeout(this.#lease); this.#lease = undefined; this.editing = null; edit.draft.load(edit.stash); if (typed && (typed.text.trim() || typed.images.size || typed.files.size)) { const kept = resolve(typed.text, typed.images); edit.draft.restore([ { text: kept.text, images: kept.images, files: [...typed.files.values()], }, ]); } }
/** Removes the sends the daemon cancelled and returns them in the order they were sent. */ take( ids: string[], ): { text: string; images: Attached[]; files: AttachedFile[] }[] { const taken = this.pending.filter( (send) => ids.includes(send.id) && !send.continuation, ); this.pending = this.pending.filter((send) => !ids.includes(send.id)); return taken; }
#receipt(): string | null { for (const block of this.blocks.toReversed()) { if (block.kind === 'assistant' || block.kind === 'failure') return null; if ( block.kind === 'user' && !block.from && !block.mail && block.turnType !== 'agent' ) return block.key; } return null; }
/** Where a turn starts among the loaded entries, for a review of it. */ turnStart(turnId: string): number | null { return ( this.entries.find((entry) => entry.turn_id === turnId)?.position ?? null ); }
/** * Puts tool entries' full arguments and output in place of their * references. Asks made in the same moment, as every work group a page * brings into view makes, share one batched read and one replacement. */ expand(...entries: HistoryEntry[]): Promise<void> { for (const entry of entries) if ( !entry.content_complete && !this.#expanding.has(entry.id) && referenced(entry) ) this.#asked.set(entry.id, entry); if (!this.#asked.size) return Promise.resolve(); return (this.#expansion ??= new Promise((done) => setTimeout(done)).then( () => this.#expandAsked(), )); }
async #expandAsked() { const waiting = [...this.#asked.values()]; this.#asked.clear(); this.#expansion = null; for (const entry of waiting) this.#expanding.add(entry.id); try { const full = new Map( (await hydrateAll(waiting)).map((entry) => [entry.id, entry]), ); this.entries = this.entries.map( (candidate) => full.get(candidate.id) ?? candidate, ); } finally { for (const entry of waiting) this.#expanding.delete(entry.id); } }
async #deliver(send: Pending) { try { if (send.continuation) await sendContinue(this.sessionId, send.id); else await sendMessage( this.sessionId, send.id, send.text, send.images.map(({ mime_type, data }) => ({ mime_type, data })), send.files.map(({ name, data }) => ({ name, data })), ); this.pending = this.pending.map((candidate) => candidate.id === send.id ? { ...candidate, accepted: true } : candidate, ); } catch (error) { const message = String((error as Error).message ?? error); this.pending = this.pending.map((candidate) => candidate.id === send.id ? { ...candidate, error: message } : candidate, ); } }
// Fetch visible messages and bounded shell receipts up front; tool content waits. async #hydrateText(entries: HistoryEntry[]) { const shown = entries.filter((entry) => TEXT_KINDS.has(entry.kind)); const full = new Map( (await hydrateAll(shown)).map((entry) => [entry.id, entry]), ); return entries.map((entry) => full.get(entry.id) ?? entry); }
/** * The blocks history makes, and what the tail after it needs: the turn still * open at its end, who spoke last, and which calls and shell commands * history already shows. Live output changes with every delta, so it stays * out of here: `#tail` adds it without another pass over history. */ #read(): Read { const results = new Set( this.entries.flatMap((entry) => entry.kind === 'tool_result' && entry.tool ? [entry.tool.tool_call_id] : [], ), ); const blocks: Block[] = []; let turn = null as Turn | null; let previous = 0; let speaker = '';
const liveShells = new Map( this.shellCommands.map((command) => [command.id, command]), ); let noteAt = 0; const notes = this.#notes; const flushNotes = (beforePosition: number) => { while (noteAt < notes.length) { const note = notes[noteAt]; if (note.after === null || note.after >= beforePosition) break; blocks.push({ kind: 'note', key: `note:${note.id}`, text: note.text }); noteAt++; } }; for (const entry of this.entries) { // Mid-turn receipts belong to the surrounding turn. Loose idle receipts // still sign it off before shell time starts. if (entry.kind === 'shell_command') { if (!turn || entry.turn_id === null || entry.turn_id !== turn.id) { blocks.push(...this.#ending(turn)); turn = null; } flushNotes(entry.position); speaker = 'you'; const part = entry.content.find( (item) => item.kind === 'json' && item.field === 'shell_command', ); const recorded = part?.kind === 'json' ? shellCommandOf(part.value) : null; const live = recorded ? liveShells.get(recorded.id) : undefined; const command = recorded && live ? mergeShell(recorded, live) : recorded; if (command) blocks.push({ kind: 'shell', key: `shell:${command.id}`, command }); if (at(entry)) previous = at(entry); continue; } const text = textOf(entry.content); // An entry outside any turn (a system or scheduled note) shows where it landed but // does not end the turn around it; that turn would sign off twice. const loose = entry.turn_id === null && entry.kind !== 'user'; if (!turn || (entry.turn_id !== turn.id && !loose)) { blocks.push(...this.#ending(turn)); turn = { id: entry.turn_id, from: entry.position, start: at(entry), last: at(entry), tools: 0, answered: false, files: new Set(), added: 0, removed: 0, text: '', }; } flushNotes(entry.position); turn.last = Math.max(turn.last, at(entry)); switch (entry.kind) { case 'user': { const gap = previous && at(entry) - previous >= AWAY_MS ? formatGap(at(entry) - previous) : null; const label = entry.mail?.sender_label?.trim().toLowerCase(); const from = (label || null) ?? (entry.turn_type && !['user', 'chat'].includes(entry.turn_type) ? entry.turn_type : null); const skill = jsonField(entry, 'skill') as SkillLoad | undefined; const mail = entry.mail ? { senderId: entry.mail.sender_session_id, external: entry.mail.external, answer: entry.mail.answer, } : null; blocks.push({ kind: 'user', key: entry.id, text, images: picturesOf(entry), files: filesOf(entry), from, mail, turnType: entry.turn_type, gap, at: at(entry), state: 'seen', skill: skill?.name, }); speaker = 'you'; break; } case 'assistant': if (!text.trim()) break; blocks.push({ kind: 'assistant', key: entry.id, text, plate: speaker !== 'albedo', phase: entry.phase ?? null, }); speaker = 'albedo'; turn.answered = true; turn.text = text; break; case 'thinking': if (text.trim()) blocks.push({ kind: 'thinking', key: entry.id, text, ms: entry.thinking_duration_ms ?? null, }); break; case 'tool_call': // A call shows until its result replaces it. if (entry.tool && !results.has(entry.tool.tool_call_id)) blocks.push({ kind: 'tool', key: entry.id, name: entry.tool.name, entry, done: false, failed: false, }); break; case 'tool_result': if (!entry.tool) break; turn.tools++; for (const change of traceOf(entry)?.changes ?? []) { turn.files.add(change.path); if (change.kind === 'diff') { turn.added += change.added; turn.removed += change.removed; } } blocks.push({ kind: 'tool', key: entry.id, name: entry.tool.name, entry, done: true, trace: traceOf(entry), failed: failedTool(entry), }); break; case 'note': case 'image_fit': if (text.trim()) blocks.push({ kind: 'note', key: entry.id, text }); break; case 'compaction': blocks.push({ kind: 'compaction', key: entry.id, text }); break; } if (at(entry)) previous = at(entry); } const called = new Set( this.entries.flatMap((entry) => entry.kind === 'tool_call' && entry.tool ? [entry.tool.tool_call_id] : [], ), ); const durable = new Set( blocks.flatMap((block) => block.kind === 'shell' ? [block.command.id] : [], ), ); return { blocks, turn, speaker, called, durable, notesFrom: noteAt }; }
/** A turn's sign-off, once the next one starts or the session rests: its failure, then a face. */ #ending(turn: Turn | null): Block[] { const id = turn?.id; const failed = id ? this.failures[id] : undefined; const ending: Block[] = failed ? [{ kind: 'failure', key: `failure:${id}`, ...failed }] : []; if (!turn || (!turn.answered && !turn.tools)) return ending; const elapsedMs = Math.max(0, turn.last - turn.start); const changed = { files: turn.files.size, added: turn.added, removed: turn.removed, }; ending.push({ kind: 'end', key: `end:${turn.id}:${turn.from}`, turnId: turn.id, from: turn.from, mood: outcome(false, false, elapsedMs), seed: turn.last, elapsedMs, tools: turn.tools, text: turn.text, changed, }); return ending; }
/** What follows history: the open turn's sign-off, live output, running calls and shell commands, and your sends. */ #tail({ turn, speaker, called, durable, notesFrom }: Read): Block[] { const blocks: Block[] = []; // Text still live has not committed yet: signing off now would put the // sign-off above the answer, timed without it. if (!this.running && !this.live.some((item) => item.text.trim())) blocks.push(...this.#ending(turn)); for (const note of this.#notes.slice(notesFrom)) blocks.push({ kind: 'note', key: `note:${note.id}`, text: note.text }); for (const item of this.live) { if (!item.text.trim()) continue; if (item.kind === 'thinking') blocks.push({ kind: 'thinking', key: `live:${item.id}`, text: item.text, ms: null, }); else blocks.push({ kind: 'assistant', key: `live:${item.id}`, text: item.text, plate: speaker !== 'albedo', phase: null, }); } // A call whose entry has committed already shows as that entry. for (const item of this.progress) { if (!called.has(item.call)) blocks.push({ kind: 'progress', key: `progress:${item.id}`, name: item.name, title: item.title, preview: item.preview, }); } for (const command of this.shellCommands) if (!durable.has(command.id)) blocks.push({ kind: 'shell', key: `shell:${command.id}`, command }); // A send the inbox holds shows in the queue until the session reads it. const waiting = new Set(this.queue.map((item) => item.id)); for (const send of this.pending) { if (send.continuation && !send.error) continue; if (!send.error && waiting.has(send.id)) continue; const images = send.images.map((image) => ({ src: image.preview })); blocks.push({ kind: 'user', key: `pending:${send.id}`, text: send.text, images, // The payload itself, so an unchanged pending block stays the same object. files: send.files, from: null, gap: null, at: send.at, state: send.error ? 'failed' : send.accepted ? 'sent' : 'sending', error: send.error, }); } return blocks; }
/** * `blocks` with every one equal to last time's block of its key replaced by * that block, so the chat's keyed rows see the same object and redraw * nothing: a fresh object would re-run each row's template, timestamps and * Markdown included, on every page and every delta. */ #keep(blocks: Block[]): Block[] { const shown = new Map<string, Block>(); const kept = blocks.map((block) => { const earlier = this.#shown.get(block.key); const same = earlier && alike(earlier, block) ? earlier : block; shown.set(block.key, same); return same; }); this.#shown = shown; return kept; }
/** `#keep` for groups: a work group whose steps are all the same objects stays the same group. */ #keepGroups(groups: Group[]): Group[] { const shown = new Map<string, Group>(); const kept = groups.map((group) => { const earlier = this.#shownGroups.get(group.key); const same = group.kind === 'work' && earlier?.kind === 'work' && earlier.steps.length === group.steps.length && earlier.steps.every((step, index) => step === group.steps[index]) ? earlier : group; shown.set(group.key, same); return same; }); this.#shownGroups = shown; return kept; }}
function group(blocks: Block[], collapse: boolean): Group[] { const answers = new Set<string>(); if (collapse) { // A row the daemon labelled final stays out of its work stretch and one // labelled commentary folds. An unlabelled row (older, or still streaming) // stays out when it is a turn's last prose: its answer, or what a running // turn is writing now, until thinking or a tool call follows it. let ended = true; for (const block of blocks.toReversed()) { if (block.kind === 'end') ended = true; else if (block.kind === 'assistant') { if (block.phase === 'final' || (block.phase === null && ended)) answers.add(block.key); ended = false; } else if ( block.kind === 'user' || block.kind === 'thinking' || block.kind === 'tool' || block.kind === 'progress' ) ended = false; } } const groups: Group[] = []; for (const block of blocks) { const last = groups.at(-1); if ( block.kind === 'thinking' || block.kind === 'tool' || block.kind === 'progress' || (collapse && block.kind === 'assistant' && !answers.has(block.key)) ) { if (last?.kind === 'work') last.steps.push(block); else groups.push({ kind: 'work', key: last ? `work:${last.key}` : 'work:root', steps: [block], }); } else groups.push(block); } return groups;}