okami.mom/strata

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

Niko1221merge f-split-s4b 0edf5cb9f (Harness in the app chat, Manual approvals, request slots) into f-split-inta16109803

main
8.3 KiB187 linesraw
1/**
2 * Helper agents (the Harness's subagents) as the rows the chat already has.
3 *
4 * A helper is a child session of the chat's Harness session. This module is the pure part: it folds one child's
5 * `session/follow` items into
6 *   - an `agent` frame (the shape `apps/host/src/lib/agents.ts updateAgent` merges into the chat's existing rows:
7 *     id, name, description, status, durationMs, tokens, updatedAt), and
8 *   - tool cards, but only for a helper's request that needs the person (an approval). Everything else a helper does
9 *     stays in its row; the transcript is not filled with the work of four helpers at once.
10 *
11 * A helper's approval card is the same card a direct request gets (state `proposed`, answered with the same
12 * Approve/Deny route). Its id is `<childSessionId>:<callId>`, which is also the key the bridge keeps the pending
13 * question under, so the answer finds the helper that asked and no other chat can answer it.
14 *
15 * Wording is for the person reading the row, not for a log: no session ids, no tool internals.
16 */
17import { friendlyFailure, parseArguments, presentTool, resultText, toolScope } from './events.mjs';
18
19const clip = (value, max) => {
20  const text = String(value ?? '').replace(/\s+/g, ' ').trim();
21  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
22};
23
24/** What a helper is doing, in words (shown as the row's description while it works). */
25export function activityOf(name, args = {}) {
26  const scope = toolScope(name);
27  if (scope === 'shell') return 'Running a command';
28  if (scope === 'write') return 'Changing files';
29  if (name === 'web_fetch' || name === 'web_search') return 'Looking something up online';
30  if (name === 'read' || name === 'glob' || name === 'grep' || name === 'read_image') return 'Reading files';
31  if (name === 'subagent' || name === 'subagent_fork') return 'Handing work to another helper';
32  if (scope === 'read') return 'Looking through the project';
33  return 'Using a tool';
34}
35
36export class ChildProjector {
37  /**
38   * @param {{id:string, name?:string, task?:string, now?:()=>number}} options
39   */
40  constructor({ id, name = 'Helper', task = '', now = () => Date.now() }) {
41    this.id = id;
42    this.name = clip(name, 60) || 'Helper';
43    this.task = clip(task, 140);
44    this.now = now;
45    this.startedAt = now();
46    this.status = 'queued';
47    this.tokens = 0;
48    this.sawUsage = false;
49    this.activity = null;
50    this.closing = '';              // the helper's last words, shown once it finished
51    this.failure = null;
52    this.endedAt = null;
53    this.tools = new Map();         // callId -> { card, calledAt, asked }
54    this.asked = new Map();         // approval id -> callId
55    this.lastEmit = 0;
56  }
57
58  /** The row as the UI merges it. */
59  agent() {
60    const at = this.now();
61    const done = this.status === 'completed' || this.status === 'failed' || this.status === 'cancelled';
62    let description = this.task;
63    if (this.status === 'queued') description = this.task ? `Waiting for its turn. ${this.task}` : 'Waiting for its turn.';
64    if (this.status === 'working' && this.activity) description = this.activity;
65    if (this.status === 'completed') description = this.closing ? clip(this.closing, 140) : 'Finished.';
66    if (this.status === 'failed') description = this.failure ?? 'Stopped because something went wrong.';
67    if (this.status === 'cancelled') description = 'Stopped.';
68    return {
69      id: this.id, name: this.name, description, status: this.status,
70      durationMs: Math.max(0, (done ? this.endedAt : at) - this.startedAt), tokens: this.tokens, updatedAt: at,
71    };
72  }
73
74  #cardId(callId) { return `${this.id}:${callId}`; }
75
76  #card(callId, patch) {
77    const entry = this.tools.get(callId);
78    if (!entry) return null;
79    entry.card = { ...entry.card, ...patch };
80    return { type: 'agent-tool', tool: entry.card };
81  }
82
83  /**
84   * Fold one follow item. Returns `{ frames, row }`: card frames to send now, and whether the row changed
85   * (the caller decides when to send it, so a stream of usage chunks does not flood the page).
86   */
87  consume(item) {
88    const frames = [];
89    let row = false;
90    const set = (status) => { if (this.status !== status) { this.status = status; row = true; } };
91
92    if (item.type === 'assistant-stream') {
93      const f = item.frame;
94      if (f.type === 'chunk' && f.chunk?.type === 'usage' && f.chunk.usage) {
95        this.sawUsage = true;
96        this.tokens += (Number(f.chunk.usage.inputTokens) || 0) + (Number(f.chunk.usage.outputTokens) || 0);
97        row = true;
98      } else if (f.type === 'chunk' && (f.chunk?.type === 'text-delta' || f.chunk?.type === 'reasoning-delta')) {
99        if (this.status === 'queued') set('working');
100      }
101      return { frames, row };
102    }
103    if (item.type !== 'event') return { frames, row };
104    const e = item.event;
105    const d = e.data ?? {};
106    switch (e.type) {
107      case 'step/start':
108      case 'turn/start':
109        // A request was sent. Whether the engine has room for it yet is told by its first word: until then the helper is waiting for its turn.
110        // A helper that had finished and got a new message starts over as waiting.
111        if (this.finished) { this.endedAt = null; this.failure = null; set('queued'); }
112        break;
113      case 'assistant/message': {
114        const text = (d.message?.content ?? []).filter(p => p.type === 'text').map(p => p.text).join('').trim();
115        if (text) this.closing = text;
116        break;
117      }
118      case 'tool/call': {
119        const args = parseArguments(d.arguments);
120        const card = { ...presentTool({ callId: this.#cardId(d.callId), name: d.name, args }), state: 'running', agentName: this.name };
121        this.tools.set(d.callId, { card, calledAt: e.time, asked: false });
122        this.activity = activityOf(d.name, args);
123        set('working');
124        row = true;
125        break;
126      }
127      case 'approval/asked': {
128        if (!d.callId || !this.tools.has(d.callId)) break;
129        this.asked.set(d.id, d.callId);
130        const entry = this.tools.get(d.callId);
131        entry.asked = true;
132        const frame = this.#card(d.callId, { state: 'proposed', effect: clip(`${this.name} asks: ${d.reason ?? 'to use a tool'}`, 400) });
133        if (frame) frames.push(frame);
134        break;
135      }
136      case 'approval/decided': {
137        const callId = this.asked.get(d.id);
138        const entry = callId ? this.tools.get(callId) : null;
139        if (!entry) break;
140        const frame = d.outcome === 'allowed-once'
141          ? this.#card(callId, { state: 'running', approved: true })
142          : this.#card(callId, { state: 'denied', result: d.outcome === 'rejected' ? 'Denied. Nothing ran.' : 'Cancelled. Nothing ran.' });
143        if (frame) frames.push(frame);
144        break;
145      }
146      case 'tool/result': {
147        const callId = d.message?.toolCallId;
148        const entry = this.tools.get(callId);
149        if (!entry) break;
150        if (entry.asked) {
151          const wasDenied = entry.card.state === 'denied';
152          const frame = this.#card(callId, {
153            state: wasDenied ? 'denied' : d.message?.isError === true ? 'error' : 'done',
154            result: wasDenied ? entry.card.result : resultText(d.message),
155            durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt),
156          });
157          if (frame) frames.push(frame);
158        }
159        this.activity = null;
160        row = true;
161        break;
162      }
163      case 'turn/end': {
164        const reason = d.reason ?? { kind: 'completed' };
165        this.endedAt = this.now();
166        if (reason.kind === 'aborted') set('cancelled');
167        else if (reason.kind === 'error') { this.failure = clip(friendlyFailure(reason.error), 140); set('failed'); }
168        else if (reason.kind === 'blocked' || reason.kind === 'interrupted') { this.failure = 'Stopped before it finished.'; set('failed'); }
169        else set('completed');
170        // A request still waiting when its helper ended can no longer be answered.
171        for (const [callId, entry] of this.tools) {
172          if (entry.asked && entry.card.state === 'proposed') {
173            const frame = this.#card(callId, { state: 'denied', result: 'Cancelled. Nothing ran.' });
174            if (frame) frames.push(frame);
175          }
176        }
177        row = true;
178        break;
179      }
180      default:
181        break;
182    }
183    return { frames, row };
184  }
185
186  get finished() { return this.status === 'completed' || this.status === 'failed' || this.status === 'cancelled'; }
187}