okami.mom/strata

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

Niko1221merge f-split-agent4 4b5cc08d1 (skills end to end, New skill button, agent skills folder, goal-status race fix) into f-split-int19ea30f6a

main
8.8 KiB160 linesraw
1/**
2 * Live status for a running turn: one small `status` frame that says what the assistant is doing right now.
3 *
4 * The page draws only the LATEST status, so a status must be replaced the moment it stops being true. This reporter therefore sends a
5 * new frame on every change of phase or target (at most one per `gapMs`, the newest change wins), and between changes only repeats the
6 * frame to refresh a counter (reasoning tokens, bytes written) every `beatMs`. It never sends the same words twice in a row.
7 *
8 *   { type:'status', seq, phase, code, text, key?, values?, args?, tokens?, elapsedMs }
9 *   `key`/`values` (only when the sentence has a name or a number in it): the catalog template ("Writing {0}…") and its values, for translation.
10 *
11 * phases: starting waiting thinking answering preparing tool approval helpers goal idle   (see notes-split-agent3.md)
12 */
13
14/** Fill the `{0}` slots of a template (the catalog key of a sentence) with values. */
15export const fillTemplate = (key, values = []) => String(key).replace(/\{(\d+)\}/g, (_, i) => String(values[Number(i)] ?? ''));
16
17/**
18 * The sentence for a tool, in the person's words: what it is doing to what ("Writing pagoda.html…"), as a catalog template and its values
19 * so the page can translate it: `{ key: 'Writing {0}…', values: ['pagoda.html'] }`.
20 */
21export function toolStatus(name, args = {}, { bytes = 0 } = {}) {
22  const base = value => String(value ?? '').split(/[\\/]/).filter(Boolean).pop() ?? '';
23  const file = base(args.file_path ?? args.path ?? args.filePath);
24  const kb = bytes >= 1500 ? (bytes / 1024).toFixed(bytes >= 10240 ? 0 : 1) : null;
25  const act = (verb, noun) => file
26    ? (kb ? { key: `${verb} {0}… ({1} KB)`, values: [file, kb] } : { key: `${verb} {0}…`, values: [file] })
27    : (kb ? { key: `${verb} ${noun}… ({0} KB)`, values: [kb] } : { key: `${verb} ${noun}…`, values: [] });
28  switch (name) {
29    case 'write': return act('Writing', 'a file');
30    case 'edit': return act('Changing', 'a file');
31    case 'read': return file ? { key: 'Reading {0}…', values: [file] } : { key: 'Reading a file…', values: [] };
32    case 'read_image': return { key: 'Looking at a picture…', values: [] };
33    case 'pwsh': case 'bash': return { key: 'Running a command…', values: [] };
34    case 'glob': case 'grep': return { key: 'Searching your files…', values: [] };
35    case 'web_search': return { key: 'Searching the web…', values: [] };
36    case 'web_fetch': { let host = ''; try { host = new URL(args.url).hostname; } catch { /* partial address */ } return host ? { key: 'Opening {0}…', values: [host] } : { key: 'Opening a web page…', values: [] }; }
37    case 'create_goal': return { key: 'Setting the goal…', values: [] };
38    case 'update_goal': return { key: 'Updating the goal…', values: [] };
39    case 'get_goal': return { key: 'Checking the goal…', values: [] };
40    case 'todo_write': return { key: 'Updating its to-do list…', values: [] };
41    case 'skill': return { key: 'Using a saved skill…', values: [] };
42    case 'present': return { key: 'Showing you a result…', values: [] };
43    case 'workflow': return { key: 'Running a multi-step plan…', values: [] };
44    case 'job_list': case 'job_output': case 'job_kill': return { key: 'Checking background tasks…', values: [] };
45    default:
46      if (name.startsWith('mcp__browser__')) return name.endsWith('navigate') ? (args.url ? { key: 'Opening {0}…', values: [String(args.url)] } : { key: 'Opening a page…', values: [] }) : { key: 'Using the browser…', values: [] };
47      if (name.startsWith('mcp__strata-instructions__')) return { key: 'Reading your instructions…', values: [] };
48      if (name.startsWith('mcp__strata-commands__')) return { key: 'Running your tool…', values: [] };
49      return { key: 'Using a tool…', values: [] };
50  }
51}
52
53/** The same, as one English sentence. */
54export function toolStatusText(name, args = {}, options = {}) {
55  const s = toolStatus(name, args, options);
56  return fillTemplate(s.key, s.values);
57}
58
59/** A status update (what the reporter takes) for a tool: text, catalog template and values together. */
60export function toolUpdate(phase, code, name, args, options, extra = {}) {
61  const s = toolStatus(name, args, options);
62  return { phase, code, text: fillTemplate(s.key, s.values), key: s.key, values: s.values, ...extra };
63}
64
65const COUNTERS = new Set(['tokens', 'bytes']);
66const keyOf = u => `${u.phase}|${u.code}|${JSON.stringify(Object.fromEntries(Object.entries(u.args ?? {}).filter(([k]) => !COUNTERS.has(k))))}`;
67
68export class StatusReporter {
69  /**
70   * @param {{emit: (frame: object) => void, now?: () => number, gapMs?: number, beatMs?: number, timers?: {set: Function, clear: Function}}} options
71   */
72  constructor({ emit, now = Date.now, gapMs = 300, beatMs = 2000, timers = { set: setTimeout, clear: clearTimeout } }) {
73    Object.assign(this, { emitFrame: emit, now, gapMs, beatMs, timers });
74    this.seq = 0;
75    this.current = null;      // what the page was last told
76    this.wanted = null;       // the newest thing that is true now
77    this.phaseStartedAt = 0;
78    this.lastEmitAt = -Infinity;
79    this.timer = null;
80    this.closed = false;
81  }
82
83  /** Say what is true now. `{phase, code, text, args?, tokens?}`. */
84  set(update) {
85    if (this.closed) return;
86    const next = { ...update, args: update.args ? { ...update.args } : undefined };
87    const changed = !this.wanted || keyOf(next) !== keyOf(this.wanted);
88    if (changed) this.phaseStartedAt = this.now();
89    this.wanted = next;
90    const sinceEmit = this.now() - this.lastEmitAt;
91    const due = changed ? this.gapMs : this.beatMs;
92    if (!this.current || sinceEmit >= due || update.phase === 'goal') this.#flush();   // a goal step is rare and the page should always hear it
93    else if (this.#differs()) this.#arm(due - sinceEmit);
94  }
95
96  /** Nothing is happening any more: tell the page to drop the line. */
97  clear() {
98    if (this.closed) return;
99    if (this.current && this.current.phase !== 'idle') { this.wanted = { phase: 'idle', code: 'idle', text: '' }; this.#flush(); }
100    this.dispose();
101  }
102
103  dispose() { this.closed = true; if (this.timer) this.timers.clear(this.timer); this.timer = null; }
104
105  #differs() {
106    const a = this.wanted, b = this.current;
107    return !b || a.text !== b.text || a.tokens !== b.tokens;
108  }
109
110  #arm(ms) {
111    if (this.timer || this.closed) return;
112    this.timer = this.timers.set(() => { this.timer = null; if (!this.closed && this.#differs()) this.#flush(); }, Math.max(0, ms));
113    this.timer.unref?.();
114  }
115
116  #flush() {
117    if (this.timer) { this.timers.clear(this.timer); this.timer = null; }
118    const w = this.wanted;
119    if (!w || (this.current && this.current.text === w.text && this.current.phase === w.phase && this.current.tokens === w.tokens)) return;
120    this.current = w;
121    this.lastEmitAt = this.now();
122    this.emitFrame({
123      type: 'status', seq: ++this.seq, phase: w.phase, code: w.code, text: w.text,
124      ...(w.key && w.key !== w.text ? { key: w.key, values: w.values ?? [] } : {}),
125      ...(w.args ? { args: w.args } : {}), ...(w.tokens !== undefined ? { tokens: w.tokens } : {}),
126      elapsedMs: Math.max(0, this.now() - this.phaseStartedAt),
127    });
128  }
129}
130
131/** Counts streamed tokens: one per chunk, or characters / 4 when a server batches many characters into a chunk. */
132export class TokenCount {
133  constructor() { this.chunks = 0; this.chars = 0; }
134  add(text) { this.chunks += 1; this.chars += String(text).length; }
135  get tokens() { return this.chars / Math.max(1, this.chunks) < 8 ? this.chunks : Math.ceil(this.chars / 4); }
136}
137
138export const fmtTokens = n => Number(n).toLocaleString('en-US');
139
140/**
141 * The same status line for a plain chat turn (no tools): the request is being read, the model is thinking (tokens), the model is writing.
142 * Wraps the function that writes frames to the client; the returned function has `dispose()` for a client that left early.
143 */
144export function withPlainStatus(write, options = {}) {
145  const reporter = new StatusReporter({ emit: write, ...options });
146  const reasoning = new TokenCount();
147  reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' });
148  const frame = f => {
149    switch (f.type) {
150      case 'start': reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); break;
151      case 'reasoning': reasoning.add(f.text ?? ''); reporter.set({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(reasoning.tokens)} tokens`, key: 'Thinking… {0} tokens', values: [fmtTokens(reasoning.tokens)], tokens: reasoning.tokens, args: { tokens: reasoning.tokens } }); break;
152      case 'delta': reporter.set({ phase: 'answering', code: 'answering', text: 'Writing the answer…' }); break;
153      case 'done': case 'error': reporter.clear(); break;
154      default: break;
155    }
156    write(f);
157  };
158  frame.dispose = () => reporter.dispose();
159  return frame;
160}