okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-preview (68bead108) into f-0213-inte82c70698

main
11.5 KiB170 linesraw
1import { api } from './client';
2import type { PreviewArtifact } from './artifacts';
3import { tidyAnswer } from './answer-text';
4
5/**
6 * Deliverables and grouped activity (notes-split-agent8.md, item 12). The host sends `deliverable` frames for every file the assistant wrote or
7 * changed and `activity-group` frames for runs of tool use between two pieces of text. A reply keeps them in the order they came, so the text
8 * that arrives between activities reads as one continuous piece.
9 */
10export type DeliverableKind = 'html' | 'markdown' | 'pdf' | 'csv' | 'image' | 'code' | 'text' | 'other';
11export interface Deliverable { path: string; abs: string; name: string; kind: DeliverableKind; status: 'created' | 'changed'; size: number; lines: number | null; added: number; removed: number;
12  /** Which write came last in this reply (set when the host's frames are merged): the newest is the run's main result. */ order?: number }
13export interface GroupFile { path: string; name: string; kind: DeliverableKind; status: string; added: number; removed: number }
14/** What is happening in a run right now (the host sends it while the group is open and drops it when the group closes): `label` is the step in plain words
15 *  ("Writing pagoda.html"), `output` the last line the step printed or the progress it can name ("412 lines written"). Optional: a group without it draws as before. */
16export interface GroupLive { label?: string; output?: string;
17  /** A file being written right now (from `message.drafts`): characters so far, lines so far and the last lines of the text. */
18  bytes?: number; lines?: number; tail?: string }
19export interface ActivityGroup { id: string; closed: boolean; line: string; added: number; removed: number; files: GroupFile[]; live?: GroupLive }
20export type MessageBlock = { kind: 'text'; text: string } | ({ kind: 'group' } & ActivityGroup);
21
22const KINDS = ['html', 'markdown', 'pdf', 'csv', 'image', 'code', 'text', 'other'];
23const num = (v: unknown) => (Number.isFinite(Number(v)) ? Number(v) : 0);
24
25export function readDeliverable(raw: unknown): Deliverable | null {
26  if (!raw || typeof raw !== 'object') return null;
27  const f = raw as Record<string, unknown>;
28  if (typeof f.path !== 'string' || !f.path) return null;
29  const name = typeof f.name === 'string' && f.name ? f.name : f.path.split(/[\\/]/).at(-1) ?? f.path;
30  return {
31    path: f.path, abs: typeof f.abs === 'string' ? f.abs : f.path, name, kind: KINDS.includes(String(f.kind)) ? f.kind as DeliverableKind : 'other',
32    status: f.status === 'changed' ? 'changed' : 'created', size: num(f.size), lines: f.lines === null || f.lines === undefined ? null : num(f.lines), added: num(f.added), removed: num(f.removed),
33  };
34}
35
36export function readGroup(raw: unknown): ActivityGroup | null {
37  if (!raw || typeof raw !== 'object') return null;
38  const g = raw as Record<string, unknown>;
39  if (typeof g.id !== 'string' || !g.id) return null;
40  const files = Array.isArray(g.files) ? g.files.flatMap((x): GroupFile[] => {
41    const d = readDeliverable(x);
42    return d ? [{ path: d.path, name: d.name, kind: d.kind, status: d.status, added: d.added, removed: d.removed }] : [];
43  }) : [];
44  const liveRaw = g.live && typeof g.live === 'object' ? g.live as Record<string, unknown> : null;
45  const last = (text: string) => text.trim().split(/\r?\n/).at(-1)!.slice(0, 200);
46  const live: GroupLive | undefined = liveRaw && g.closed !== true ? { ...(typeof liveRaw.label === 'string' && liveRaw.label ? { label: liveRaw.label.slice(0, 160) } : {}), ...(typeof liveRaw.output === 'string' && liveRaw.output.trim() ? { output: last(liveRaw.output) } : {}) } : undefined;
47  return { id: g.id, closed: g.closed === true, line: typeof g.line === 'string' ? g.line : '', added: num(g.added), removed: num(g.removed), files, ...(live && (live.label || live.output) ? { live } : {}) };
48}
49
50/** The `skills-used` frame: the skills this reply used, each with the name the person gave it and a one-line description. */
51export function readSkills(raw: unknown): { name: string; description: string }[] {
52  const list = (raw as { skills?: unknown } | null)?.skills;
53  if (!Array.isArray(list)) return [];
54  return list.flatMap(x => {
55    const s = x as Record<string, unknown>;
56    return typeof s?.name === 'string' && s.name ? [{ name: s.name, description: typeof s.description === 'string' ? s.description : '' }] : [];
57  }).slice(0, 20);
58}
59
60/** Add streamed text to the reply's ordered pieces: it continues the last text piece, or starts a new one after an activity line. */
61export function appendText(blocks: MessageBlock[] | undefined, text: string): MessageBlock[] {
62  const list = blocks ?? [], last = list.at(-1);
63  if (last?.kind === 'text') return [...list.slice(0, -1), { kind: 'text', text: tidyAnswer(last.text + text) }];
64  return [...list, { kind: 'text', text: tidyAnswer(text) }];
65}
66
67/** A group frame is re-sent while it grows: the same id replaces its line; a new id goes after what came before. */
68export function upsertGroup(blocks: MessageBlock[] | undefined, group: ActivityGroup): MessageBlock[] {
69  const list = blocks ?? [], at = list.findIndex(b => b.kind === 'group' && b.id === group.id);
70  const next: MessageBlock = { kind: 'group', ...group };
71  return at >= 0 ? list.map((b, i) => (i === at ? next : b)) : [...list, next];
72}
73
74/** The same file may be written more than once in a run: one card per path, with its latest numbers. */
75export function mergeDeliverable(list: Deliverable[] | undefined, file: Deliverable): Deliverable[] {
76  const have = list ?? [], at = have.findIndex(f => f.path === file.path);
77  const order = have.reduce((n, f) => Math.max(n, f.order ?? 0), 0) + 1;
78  if (at < 0) return [...have, { ...file, order }];
79  const old = have[at];
80  return have.map((f, i) => (i === at ? { ...file, order, status: old.status === 'created' ? 'created' : file.status, added: old.added + file.added, removed: old.removed + file.removed } : f));
81}
82
83/** The kinds the sidebar preview shows and a finished run may open by itself: pages, markdown, PDFs, pictures, tables and plain text (not code or unknown files). */
84export const SIDEBAR_KINDS: DeliverableKind[] = ['html', 'markdown', 'pdf', 'image', 'csv', 'text'];
85
86/**
87 * The one file a finished run opens in the sidebar, or null. The file the answer names wins (the last one it mentions); otherwise the one
88 * written last. Only kinds the sidebar can show count, so a run that made a script and a page opens the page, and several files open one.
89 */
90export function mainResult(files: Deliverable[] | undefined, answer: string): Deliverable | null {
91  const shown = (files ?? []).filter(f => SIDEBAR_KINDS.includes(f.kind));
92  if (!shown.length) return null;
93  const text = answer.toLowerCase();
94  let named: Deliverable | null = null, at = -1;
95  for (const f of shown) {
96    const mention = Math.max(text.lastIndexOf(f.name.toLowerCase()), text.lastIndexOf(f.path.toLowerCase()));
97    if (mention > at) { at = mention; named = f; }
98  }
99  if (named) return named;
100  return shown.reduce((best, f) => ((f.order ?? 0) >= (best.order ?? 0) ? f : best));
101}
102
103/** Past this many files a run's results are one compact summary (the two folders and a count that opens the list) instead of one card per file. */
104export const COMPACT_FILES_FROM = 6;
105
106/** The folder part of a path inside the chat's folder, with forward slashes ('' for a file that sits directly in it). */
107export const dirOf = (path: string): string => { const parts = path.replace(/\\/g, '/').split('/').filter(Boolean); parts.pop(); return parts.join('/'); };
108
109/**
110 * The folder a run delivered to, relative to the chat's folder ('' means the chat's folder itself): the folder of the run's main result (the file the
111 * answer names, else the one written last); with no previewable result, the top-level folder that holds the most files. A tie goes to the folder written to last.
112 */
113export function deliveryFolder(files: Deliverable[] | undefined, answer: string): string {
114  const list = files ?? [];
115  const main = mainResult(list, answer);
116  if (main) return dirOf(main.path);
117  const counts = new Map<string, { n: number; last: number }>();
118  for (const f of list) {
119    const top = dirOf(f.path).split('/')[0] ?? '';
120    const c = counts.get(top) ?? { n: 0, last: 0 };
121    counts.set(top, { n: c.n + 1, last: Math.max(c.last, f.order ?? 0) });
122  }
123  let best = '', at: { n: number; last: number } | null = null;
124  for (const [dir, c] of counts) if (!at || c.n > at.n || (c.n === at.n && c.last > at.last)) { best = dir; at = c; }
125  return best;
126}
127
128/** The chat's folder on disk, worked out from a file's absolute and relative paths (for a host that does not say it). */
129export function rootOf(file: { abs: string; path: string } | undefined): string {
130  if (!file) return '';
131  const abs = file.abs.replace(/\\/g, '/'), rel = file.path.replace(/\\/g, '/').replace(/^\.?\//, '');
132  return abs.endsWith('/' + rel) ? abs.slice(0, abs.length - rel.length - 1) : '';
133}
134
135export const fileTypeLabel = (d: { kind: DeliverableKind; name: string }) => {
136  const ext = d.name.includes('.') ? d.name.split('.').at(-1)!.toUpperCase() : '';
137  return d.kind === 'markdown' ? 'MD' : d.kind === 'html' ? 'HTML' : d.kind === 'csv' ? 'CSV' : d.kind === 'pdf' ? 'PDF' : ext && ext.length <= 10 ? ext : d.kind.toUpperCase();
138};
139
140export function fileSize(bytes: number): string {
141  if (bytes < 1024) return `${bytes} B`;
142  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10240 ? 1 : 0)} KB`;
143  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
144}
145
146const csvText = (rows: string[][]) => rows.map(r => r.map(c => (/[",\n]/.test(c) ? `"${c.replace(/"/g, '""')}"` : c)).join(',')).join('\n');
147
148interface PreviewAnswer { kind: DeliverableKind; name: string; path: string; size: number; mtime?: number; url?: string; text?: string; rows?: string[][]; rawUrl?: string; note?: string }
149
150/** The sidebar preview of a file: the host reads it (only inside the chat's folder) and the page draws it as a website, markdown, table, picture, PDF or code. */
151export async function previewOf(sessionId: string, file: { path: string; name: string }): Promise<PreviewArtifact> {
152  const a = await api.get<PreviewAnswer>(`/api/files/preview?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(file.path)}`);
153  const id = `file:${a.path}`, title = a.name || file.name, at = Date.now(), version = a.mtime !== undefined ? `${a.mtime}:${a.size}` : undefined;
154  if (a.kind === 'image' && a.rawUrl) return { id, kind: 'image', title, url: a.rawUrl, version, at };
155  if (a.kind === 'pdf' && a.rawUrl) return { id, kind: 'pdf', title, url: a.rawUrl, version, at };
156  if (a.kind === 'html' && a.text !== undefined) return { id, kind: 'website', title, content: a.text, at };
157  if (a.kind === 'markdown' && a.text !== undefined) return { id, kind: 'markdown', title, content: a.text, at };
158  if (a.kind === 'csv' && a.rows) return { id, kind: 'table', title, content: csvText(a.rows), at };
159  if (a.text !== undefined) return { id, kind: 'code', title, content: a.text, at };
160  throw new Error(a.note || 'This file has no preview. Open it in its own app.');
161}
162
163export const fileAction = {
164  open: (sessionId: string, path: string, how: 'browser' | 'app' | 'folder') => api.post('/api/files/open', { sessionId, path, how }),
165  fullPath: async (sessionId: string, path: string) => (await api.get<{ path: string }>(`/api/files/path?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(path)}`)).path,
166  attach: (sessionId: string, path: string) => api.post('/api/chat/attachments', { sessionId, path }),
167};
168
169export const rawUrlOf = (sessionId: string, path: string) => `/api/files/raw?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(path)}`;
170