Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501import { uuidv7 } from './api';import { approveExport, cancelExport, cancelTagger, createExport, deleteExport, downloadArchive, installTagger, listExports, readExport, readFindings, readPreview, readTagger, removeTagger, type ExportJob, type ExportScope, type Finding, type FindingCategory, type OmissionKind, type PreviewPage, type Tagger,} from './traceExport';
// What Settings → privacy & export and the /export dialog show: the daemon's// tagger and one export of a session. Both read the daemon's state again// while it is moving (a download, a scan) and stop once it settles; nothing// here invents progress or decides what may be downloaded.
const POLL_MS = 1000;/** Findings read for one preview page at most; past it the page says some are not shown. */const PAGE_FINDINGS = 1000;
/** What each category of finding is called on screen. */export const CATEGORY: Record<FindingCategory, string> = { person: 'names', address: 'addresses', gov_id: 'government IDs', email: 'email addresses', financial: 'financial details', phone: 'phone numbers', sensitive: 'sensitive details', date_of_birth: 'dates of birth', ip_address: 'IP addresses', secret_token: 'tokens', secret_password: 'passwords', secret_connection: 'connection strings', secret_private_key: 'private keys', opaque_blob: 'opaque blobs', known_secret: 'known secrets',};
/** A category as the screen names it; one newer than this client shows as sent. */export function categoryName(category: FindingCategory): string { return CATEGORY[category] ?? category;}
const OMISSIONS: Record<OmissionKind, [string, string]> = { encrypted_reasoning: [ 'encrypted reasoning block', 'encrypted reasoning blocks', ], provider_opaque: ['opaque provider item', 'opaque provider items'], image: ['image', 'images'], attachment: ['attached file', 'attached files'], tool_output_truncated: [ 'tool output already cut short', 'tool outputs already cut short', ], oversized_text: ['oversized text', 'oversized texts'], undecodable_row: ['unreadable row', 'unreadable rows'],};
/** A count of one kind of omission, named; a kind newer than this client shows as sent. */export function omission(kind: OmissionKind, count: number): string { const words = OMISSIONS[kind]; return `${count.toLocaleString()} ${words ? words[count === 1 ? 0 : 1] : kind}`;}
/** A byte count in decimal megabytes, as model downloads are quoted. */export function megabytes(bytes: number): string { return `${Math.round(bytes / 1e6).toLocaleString()} MB`;}
function message(error: unknown): string { return String((error as Error)?.message ?? error);}
/** The tagger as this daemon has it, shared by every view that shows it. */class TaggerStatus { value = $state<Tagger | null>(null); /** Why the last read or action failed. */ problem = $state(''); action = $state<'' | 'install' | 'cancel' | 'remove'>(''); #watchers = 0; #timer: ReturnType<typeof setTimeout> | undefined; #controller: AbortController | undefined;
get moving(): boolean { const state = this.value?.state; return state === 'downloading' || state === 'verifying'; }
get ready(): boolean { return this.value?.state === 'ready' && this.value.runtime.available; }
/** The share downloaded, when the daemon knows the total. */ get share(): number | null { const t = this.value; if (!t || t.state !== 'downloading' || !t.bytes_total) return null; return Math.min(1, t.bytes_done / t.bytes_total); }
/** Reads the tagger now and again while it downloads, until every watcher stops. */ watch(): () => void { this.#watchers++; void this.refresh(); return () => { if (--this.#watchers > 0) return; clearTimeout(this.#timer); this.#controller?.abort(); }; }
async refresh() { clearTimeout(this.#timer); this.#controller?.abort(); const read = new AbortController(); this.#controller = read; try { this.#settle(await readTagger(read.signal)); if (this.problem && !this.action) this.problem = ''; } catch (error) { if (read.signal.aborted) return; this.problem = message(error); this.#schedule(); } }
install = () => this.#act('install', installTagger); cancel = () => this.#act('cancel', cancelTagger); remove = () => this.#act('remove', removeTagger);
async #act( action: 'install' | 'cancel' | 'remove', call: () => Promise<Tagger>, ) { if (this.action) return; this.action = action; this.problem = ''; try { this.#settle(await call()); } catch (error) { this.problem = message(error); await this.refresh(); } finally { this.action = ''; } }
#settle(next: Tagger) { this.value = next; this.#schedule(); }
#schedule() { clearTimeout(this.#timer); if (this.moving && this.#watchers > 0) this.#timer = setTimeout(() => void this.refresh(), POLL_MS); }}
export const tagger = new TaggerStatus();
/** One trace.jsonl row of a preview page, its pieces joined; `whole` when the page holds all of it. */export interface Row { line: number; text: string; whole: boolean; findings: Finding[];}
export type Step = 'configure' | 'scanning' | 'review' | 'ready' | 'failed' | 'cancelled';
/** One /export of a session: configure, scan on the daemon, review, approve and download. */export class ExportFlow { scope = $state<ExportScope>('session'); job = $state<ExportJob | null>(null); /** Reading the session's earlier exports before showing anything. */ resuming = $state(true); /** A request in flight that the buttons wait on. */ busy = $state<'' | 'start' | 'cancel' | 'approve' | 'download' | 'discard'>( '', ); /** Why the last action failed; the flow stays where it was. */ problem = $state(''); /** The person's acknowledgement that they read the redacted copy, at this revision. */ reviewed = $state(false); /** Whether this dialog has handed the archive to the browser's downloads. */ saved = $state(false); preview = $state<PreviewPage | null>(null); previewProblem = $state(''); previewLoading = $state(false); /** Which page of the preview is shown, from 0; only that page is held. */ pageIndex = $state(0); /** The findings on the shown page's rows. */ findings = $state.raw<Finding[]>([]); /** Whether the shown page has more findings than were read. */ findingsCut = $state(false); /** Only rows with this category are shown, and only its marks; null shows all. */ category = $state<FindingCategory | null>(null); #cursors: (string | null)[] = [null]; #etag = ''; /** The id a create used, so a retry of the same scope replays it. */ #attempt: { id: string; scope: ExportScope } | null = null; #timer: ReturnType<typeof setTimeout> | undefined; #controller = new AbortController(); #previewController: AbortController | undefined;
constructor(readonly sessionId: string) { void this.#resume(); }
get step(): Step { return this.job?.state ?? 'configure'; }
get hasNextPage(): boolean { return !!this.preview?.next; }
/** The shown page as rows, each with its findings. */ get rows(): Row[] { const rows: (Row & { first: number })[] = []; for (const piece of this.preview?.items ?? []) { let row = rows[rows.length - 1]; if (row?.line !== piece.line) { row = { line: piece.line, text: '', whole: false, findings: [], first: piece.offset, }; rows.push(row); } row.text += piece.text; row.whole = row.first === 0 && piece.complete; } return rows.map(({ first: _, ...row }) => ({ ...row, findings: this.findings.filter((finding) => finding.line === row.line), })); }
/** Stops reading the daemon; the export itself goes on there. */ close() { clearTimeout(this.#timer); this.#controller.abort(); this.#previewController?.abort(); }
async start() { if (this.busy) return; this.busy = 'start'; this.problem = ''; if (this.#attempt?.scope !== this.scope) this.#attempt = { id: uuidv7(), scope: this.scope }; try { this.#adopt( await createExport(this.sessionId, this.#attempt.id, this.scope), ); await this.#read(); } catch (error) { this.problem = message(error); } finally { this.busy = ''; } }
async cancel() { const job = this.job; if (!job || this.busy) return; this.busy = 'cancel'; this.problem = ''; try { this.#adopt(await cancelExport(job.id)); } catch (error) { this.problem = message(error); await this.#read(); } finally { this.busy = ''; } }
/** Approves the reviewed copy and downloads it. */ async approve() { const job = this.job; if (!job || job.state !== 'review' || !this.reviewed || this.busy) return; this.busy = 'approve'; this.problem = ''; try { this.#adopt(await approveExport(job.id, this.#etag)); } catch (error) { const before = job.revision; await this.#read(); if (this.job && this.job.revision !== before) { this.reviewed = false; this.problem = 'This export changed while you were reading it. Review it again before approving.'; } else this.problem = message(error); return; } finally { this.busy = ''; } await this.download(); }
/** Reads the export again and, while it is still ready, hands its archive to the browser's downloads. */ async download() { const job = this.job; if (!job || job.state !== 'ready' || this.busy) return; this.busy = 'download'; this.problem = ''; try { await this.#read(); if (this.job?.id === job.id && this.job.state === 'ready') { downloadArchive(job.id); this.saved = true; } } finally { this.busy = ''; } }
/** Deletes this export's copy and returns to the start; the session is untouched. */ async discard() { const job = this.job; if (!job || this.busy) return; this.busy = 'discard'; this.problem = ''; try { if (job.state === 'scanning') await cancelExport(job.id); await deleteExport(job.id); this.#reset(); } catch (error) { this.problem = message(error); } finally { this.busy = ''; } }
/** Leaves a finished, failed or cancelled export as it is and configures a new one. */ again() { if (this.busy) return; this.#reset(); }
async nextPage() { if (!this.preview?.next || this.previewLoading) return; this.#cursors[this.pageIndex + 1] = this.preview.next; await this.#page(this.pageIndex + 1); }
async previousPage() { if (this.pageIndex === 0 || this.previewLoading) return; await this.#page(this.pageIndex - 1); }
async retryPreview() { await this.#page(this.pageIndex); }
#reset() { clearTimeout(this.#timer); this.#previewController?.abort(); this.job = null; this.#etag = ''; this.#attempt = null; this.reviewed = false; this.saved = false; this.preview = null; this.previewProblem = ''; this.previewLoading = false; this.findings = []; this.findingsCut = false; this.category = null; this.pageIndex = 0; this.#cursors = [null]; }
async #resume() { try { const open = (await listExports(this.sessionId, this.#controller.signal)) .filter((job) => job.state === 'scanning' || job.state === 'review') .sort((a, b) => b.created_at.localeCompare(a.created_at))[0]; if (open) { this.scope = open.scope; this.#adopt(open); await this.#read(); } } catch (error) { if (!this.#controller.signal.aborted) this.problem = message(error); } finally { this.resuming = false; } }
async #read() { const job = this.job; if (!job) return; try { const read = await readExport(job.id, this.#controller.signal); if (this.job?.id !== job.id) return; this.#etag = read.etag; this.#adopt(read.job); } catch (error) { if (this.#controller.signal.aborted || this.job?.id !== job.id) return; this.problem = message(error); this.#schedule(); } }
#adopt(next: ExportJob) { const before = this.job; if ( before?.id !== next.id || before.revision !== next.revision || before.archive?.sha256 !== next.archive?.sha256 ) this.reviewed = false; this.job = next; this.#schedule(); const previewable = next.state === 'review' || next.state === 'ready'; if (previewable && (!this.preview || before?.id !== next.id)) { this.#cursors = [null]; void this.#page(0); } }
#schedule() { clearTimeout(this.#timer); if (this.job?.state === 'scanning' && !this.#controller.signal.aborted) this.#timer = setTimeout(() => void this.#read(), POLL_MS); }
async #page(index: number) { const job = this.job; if (!job) return; this.#previewController?.abort(); const read = new AbortController(); this.#previewController = read; this.previewLoading = true; this.previewProblem = ''; try { const page = await readPreview(job.id, this.#cursors[index], read.signal); const lines = page.items.map((item) => item.line); const found = lines.length ? await this.#findings( job.id, Math.min(...lines), Math.max(...lines), read.signal, ) : { items: [], cut: false }; if (read.signal.aborted) return; this.preview = page; this.findings = found.items; this.findingsCut = found.cut; this.pageIndex = index; } catch (error) { if (!read.signal.aborted) this.previewProblem = message(error); } finally { if (!read.signal.aborted) this.previewLoading = false; } }
/** The findings on rows `from` through `to`, at most PAGE_FINDINGS of them. */ async #findings( id: string, from: number, to: number, signal: AbortSignal, ): Promise<{ items: Finding[]; cut: boolean }> { const items: Finding[] = []; let next: string | null = null; do { const page = await readFindings(id, { next, line: from }, signal); for (const finding of page.items) { if (finding.line > to) return { items, cut: false }; if (items.length === PAGE_FINDINGS) return { items, cut: true }; items.push(finding); } next = page.next; } while (next); return { items, cut: false }; }}