reifyui 0.13.9 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,476 @@
1
+ // One agent turn as data, built from the events that really happened.
2
+ //
3
+ // A Turn is what the agent-chat components render:
4
+ //
5
+ // { id, sessionId, status: 'running'|'done'|'failed'|'cancelled'|'incomplete',
6
+ // user: { text, files: [{name}] } | null,
7
+ // items: Item[], // in the order they happened
8
+ // files: [{container_id, file_id, filename, download_url?}],
9
+ // startedAt, endedAt, // epoch ms, or null when nobody observed them
10
+ // lastEventAt, // epoch ms of the last live event, or null
11
+ // usage, error, incomplete: {reason, detail} | null, model }
12
+ //
13
+ // Item = { kind: 'text', id, text }
14
+ // | { kind: 'thinking', id, text, startedAt, endedAt }
15
+ // | { kind: 'tool', id, name, args, output, status: 'running'|'done'|'failed'|'stopped',
16
+ // startedAt, endedAt }
17
+ //
18
+ // THE CLOCK RULE. Every time on a Turn is a moment someone observed. reduceTurn(turn, ev, at) takes
19
+ // `at` from the caller: the receive time for a live event, and null for a replayed one (a catch-up
20
+ // frame, a history read). A null never becomes a time, so a replay cannot invent a duration, and a
21
+ // view shows a duration only when both of its ends are real.
22
+ //
23
+ // Pure functions. No React, no fetch. The reducer never mutates its input.
24
+
25
+ import { toolKind } from './tools.js';
26
+
27
+ const TERMINAL = new Set(['done', 'failed', 'cancelled', 'incomplete']);
28
+
29
+ /** A turn that has been sent and not yet answered. */
30
+ export function newTurn(opts = {}) {
31
+ return {
32
+ id: opts.id || null,
33
+ sessionId: opts.sessionId || null,
34
+ status: opts.status || 'running',
35
+ user: opts.user ? { text: String(opts.user.text || ''), files: (opts.user.files || []).map((f) => ({ name: f.name, size: f.size, src: f.src })) } : null,
36
+ items: [],
37
+ files: [],
38
+ startedAt: opts.startedAt ?? null,
39
+ endedAt: null,
40
+ elapsedMs: null,
41
+ lastEventAt: null,
42
+ usage: null,
43
+ error: null,
44
+ incomplete: null,
45
+ model: opts.model || null,
46
+ _oi: {}, // output_index -> item id, to route deltas that name only their index
47
+ };
48
+ }
49
+
50
+ export function isTerminal(status) { return TERMINAL.has(status); }
51
+
52
+ function mapStatus(s) {
53
+ const v = String(s || '').toLowerCase();
54
+ if (v === 'completed' || v === 'done' || v === 'succeeded') return 'done';
55
+ if (v === 'cancelled' || v === 'canceled') return 'cancelled';
56
+ if (v === 'incomplete' || v === 'max_turns' || v === 'timeout' || v === 'max_steps') return 'incomplete';
57
+ if (v === 'failed' || v === 'error') return 'failed';
58
+ if (v === 'running' || v === 'in_progress' || v === 'queued' || v === 'starting') return 'running';
59
+ return 'done';
60
+ }
61
+
62
+ function findIdx(items, pred) {
63
+ for (let i = items.length - 1; i >= 0; i--) if (pred(items[i])) return i;
64
+ return -1;
65
+ }
66
+
67
+ function patchItem(turn, i, patch) {
68
+ const items = turn.items.slice();
69
+ items[i] = { ...items[i], ...patch };
70
+ return { ...turn, items };
71
+ }
72
+
73
+ function pushItem(turn, item, oi) {
74
+ const t = { ...turn, items: [...turn.items, item] };
75
+ if (oi !== undefined && oi !== null) t._oi = { ...turn._oi, [oi]: item.id };
76
+ return t;
77
+ }
78
+
79
+ function isAgentTool(name) { return toolKind(name) === 'agent'; }
80
+
81
+ /** The model only speaks again once the calls it made have answered. A call still open when it
82
+ * does was answered off the record (Codex reports some calls with no result at all), so it is
83
+ * closed: done, with no output and no end time, which is what is actually known. A sub-agent's
84
+ * call is the exception, since its own messages stream while it is still working. */
85
+ function settleOpenCalls(turn) {
86
+ let changed = false;
87
+ const items = turn.items.map((it) => {
88
+ if (it.kind === 'tool' && it.status === 'running' && !isAgentTool(it.name)) { changed = true; return { ...it, status: 'done' }; }
89
+ return it;
90
+ });
91
+ return changed ? { ...turn, items } : turn;
92
+ }
93
+
94
+ function closeThinking(turn, at) {
95
+ const i = findIdx(turn.items, (x) => x.kind === 'thinking' && x.endedAt == null && x.open);
96
+ if (i < 0) return turn;
97
+ return patchItem(turn, i, { open: false, endedAt: at ?? null });
98
+ }
99
+
100
+ function outputFailed(item) {
101
+ if (!item) return false;
102
+ if (item.is_error === true || item.isError === true) return true;
103
+ const s = String(item.status || '').toLowerCase();
104
+ return s === 'failed' || s === 'error' || s === 'incomplete';
105
+ }
106
+
107
+ function textOf(v) { return v == null ? '' : typeof v === 'string' ? v : JSON.stringify(v); }
108
+
109
+ function idOf(prefix, turn) { return `${prefix}_${turn.items.length}`; }
110
+
111
+ /**
112
+ * Fold one event into a turn. `ev` is a Responses stream event (`response.output_text.delta`, …),
113
+ * an `error` event, or the broadcast feed's `harness.turn.started`. `at` is the receive time in
114
+ * epoch ms for a live event, null for a replayed one. Unknown events return the turn unchanged.
115
+ */
116
+ export function reduceTurn(turn, ev, at = null) {
117
+ if (!ev || typeof ev !== 'object') return turn;
118
+ let t = turn || newTurn();
119
+ const type = String(ev.type || '');
120
+ if (at != null) t = { ...t, lastEventAt: at };
121
+ switch (type) {
122
+ case 'harness.turn.started': {
123
+ if (!t.user && ev.user_text) t = { ...t, user: { text: String(ev.user_text), files: [] } };
124
+ return t;
125
+ }
126
+ case 'response.created':
127
+ case 'response.in_progress':
128
+ case 'response.queued': {
129
+ const r = ev.response || {};
130
+ return {
131
+ ...t,
132
+ id: r.id || t.id,
133
+ sessionId: (r.metadata && r.metadata.session_id) || t.sessionId,
134
+ model: r.model || t.model,
135
+ startedAt: t.startedAt ?? (at ?? (r.created_at ? r.created_at * 1000 : null)),
136
+ };
137
+ }
138
+ case 'response.output_item.added':
139
+ case 'response.output_item.done': {
140
+ const item = ev.item || {};
141
+ const added = type.endsWith('.added');
142
+ const oi = ev.output_index;
143
+ if (item.type === 'reasoning') {
144
+ const i = findIdx(t.items, (x) => x.id === item.id);
145
+ const summary = Array.isArray(item.summary) ? item.summary.map((p) => p && p.text).filter(Boolean).join('\n\n') : '';
146
+ if (i < 0) {
147
+ t = settleOpenCalls(t);
148
+ t = pushItem(t, { kind: 'thinking', id: item.id || idOf('rs', t), text: summary, startedAt: at, endedAt: added ? null : at, open: added }, oi);
149
+ return t;
150
+ }
151
+ if (!added) {
152
+ const cur = t.items[i];
153
+ return patchItem(t, i, { open: false, endedAt: cur.endedAt ?? at, text: cur.text || summary });
154
+ }
155
+ return t;
156
+ }
157
+ if (item.type === 'message') {
158
+ const i = findIdx(t.items, (x) => x.id === item.id);
159
+ const full = Array.isArray(item.content) ? item.content.map((p) => (p && (p.text || p.refusal)) || '').join('') : '';
160
+ if (i < 0) {
161
+ t = closeThinking(settleOpenCalls(t), at);
162
+ const last = t.items[t.items.length - 1];
163
+ // a message that continues the prose already on screen extends it (one paragraph flow)
164
+ if (last && last.kind === 'text' && !last.closed) {
165
+ t = { ...t, _oi: oi != null ? { ...t._oi, [oi]: last.id } : t._oi };
166
+ if (!added && full && !last.text) t = patchItem(t, t.items.length - 1, { text: full });
167
+ return t;
168
+ }
169
+ return pushItem(t, { kind: 'text', id: item.id || idOf('msg', t), text: added ? '' : full }, oi);
170
+ }
171
+ if (!added && full && !t.items[i].text) return patchItem(t, i, { text: full });
172
+ return t;
173
+ }
174
+ if (item.type === 'function_call' || item.type === 'custom_tool_call' || item.type === 'mcp_call') {
175
+ const callId = item.call_id || item.id || idOf('call', t);
176
+ const args = textOf(item.arguments ?? item.input ?? '');
177
+ const i = findIdx(t.items, (x) => x.kind === 'tool' && (x.id === callId || x.itemId === item.id));
178
+ if (i >= 0) {
179
+ const cur = t.items[i];
180
+ const patch = {};
181
+ if (args && (!cur.args || cur.args === '{}')) patch.args = args;
182
+ if (item.name && (!cur.name || cur.name === 'tool')) patch.name = item.name;
183
+ return Object.keys(patch).length ? patchItem(t, i, patch) : t;
184
+ }
185
+ t = closeThinking(t, at);
186
+ const lastText = findIdx(t.items, (x) => x.kind === 'text');
187
+ if (lastText >= 0) t = patchItem(t, lastText, { closed: true });
188
+ return pushItem(t, { kind: 'tool', id: callId, itemId: item.id || null, name: item.name || 'tool', args,
189
+ output: undefined, status: 'running', startedAt: at, endedAt: null }, oi);
190
+ }
191
+ if (item.type === 'function_call_output' || item.type === 'custom_tool_call_output') {
192
+ const callId = item.call_id || '';
193
+ const i = findIdx(t.items, (x) => x.kind === 'tool' && x.id === callId);
194
+ const failed = outputFailed(item);
195
+ const output = textOf(item.output);
196
+ if (i < 0) {
197
+ // a result whose call never reached this view (joined mid-turn): keep it, unnamed
198
+ return pushItem(t, { kind: 'tool', id: callId || idOf('out', t), itemId: null, name: 'tool', args: '',
199
+ output, status: failed ? 'failed' : 'done', startedAt: null, endedAt: at });
200
+ }
201
+ const cur = t.items[i];
202
+ if (cur.output !== undefined && cur.status !== 'running') return t; // the same result, twice
203
+ return patchItem(t, i, { output, status: failed ? 'failed' : 'done', endedAt: at });
204
+ }
205
+ return t;
206
+ }
207
+ case 'response.reasoning_summary_part.added':
208
+ return t;
209
+ case 'response.reasoning_summary_text.delta':
210
+ case 'response.reasoning_text.delta': {
211
+ const d = String(ev.delta || '');
212
+ let i = findIdx(t.items, (x) => x.kind === 'thinking' && (x.id === ev.item_id || (ev.output_index != null && t._oi[ev.output_index] === x.id)));
213
+ if (i < 0) i = (t.items.length && t.items[t.items.length - 1].kind === 'thinking') ? t.items.length - 1 : -1;
214
+ if (i < 0) {
215
+ t = settleOpenCalls(t);
216
+ return pushItem(t, { kind: 'thinking', id: ev.item_id || idOf('rs', t), text: d, startedAt: at, endedAt: null, open: true }, ev.output_index);
217
+ }
218
+ const cur = t.items[i];
219
+ // a new summary part of the same reasoning reads as a new paragraph
220
+ return patchItem(t, i, { text: cur.text + d });
221
+ }
222
+ case 'response.reasoning_summary_part.done':
223
+ return t;
224
+ case 'response.output_text.delta': {
225
+ const d = String(ev.delta || '');
226
+ if (!d) return t;
227
+ let i = findIdx(t.items, (x) => x.kind === 'text' && (x.id === ev.item_id || (ev.output_index != null && t._oi[ev.output_index] === x.id)));
228
+ if (i < 0 && t.items.length && t.items[t.items.length - 1].kind === 'text' && !t.items[t.items.length - 1].closed) i = t.items.length - 1;
229
+ if (i < 0) {
230
+ t = closeThinking(settleOpenCalls(t), at);
231
+ return pushItem(t, { kind: 'text', id: ev.item_id || idOf('msg', t), text: d }, ev.output_index);
232
+ }
233
+ if (i !== t.items.length - 1) {
234
+ // text for a message that is no longer last: the model is speaking again, after its calls
235
+ t = closeThinking(settleOpenCalls(t), at);
236
+ }
237
+ return patchItem(t, i, { text: t.items[i].text + d });
238
+ }
239
+ case 'response.output_text.done': {
240
+ const i = findIdx(t.items, (x) => x.kind === 'text' && x.id === ev.item_id);
241
+ if (i >= 0 && !t.items[i].text && ev.text) return patchItem(t, i, { text: String(ev.text) });
242
+ return t;
243
+ }
244
+ case 'response.function_call_arguments.delta': {
245
+ const i = findIdx(t.items, (x) => x.kind === 'tool' && (x.itemId === ev.item_id || (ev.output_index != null && t._oi[ev.output_index] === x.id)));
246
+ if (i < 0) return t;
247
+ return patchItem(t, i, { args: (t.items[i].args || '') + String(ev.delta || '') });
248
+ }
249
+ case 'response.function_call_arguments.done': {
250
+ const i = findIdx(t.items, (x) => x.kind === 'tool' && (x.itemId === ev.item_id || (ev.output_index != null && t._oi[ev.output_index] === x.id)));
251
+ if (i < 0) return t;
252
+ return patchItem(t, i, { args: String(ev.arguments ?? t.items[i].args ?? '') });
253
+ }
254
+ case 'response.output_text.annotation.added': {
255
+ const a = ev.annotation || {};
256
+ if (a.type !== 'container_file_citation') return t;
257
+ const same = (f) => (a.file_id ? f.file_id === a.file_id && f.container_id === a.container_id : f.filename === a.filename);
258
+ if (t.files.some(same)) return t;
259
+ return { ...t, files: [...t.files, { container_id: a.container_id, file_id: a.file_id, filename: a.filename,
260
+ ...(a.download_url ? { download_url: a.download_url } : {}) }] };
261
+ }
262
+ case 'response.completed':
263
+ case 'response.incomplete':
264
+ case 'response.failed':
265
+ case 'response.cancelled': {
266
+ const r = ev.response || {};
267
+ let status = type === 'response.completed' ? 'done' : type === 'response.incomplete' ? 'incomplete'
268
+ : type === 'response.cancelled' ? 'cancelled' : mapStatus(r.status || 'failed');
269
+ if (type === 'response.failed' && (ev.reason === 'cancelled' || r.status === 'cancelled')) status = 'cancelled';
270
+ if (type === 'response.failed' && status === 'done') status = 'failed';
271
+ return finish(t, status, at, r);
272
+ }
273
+ case 'error': {
274
+ const msg = String(ev.message || (ev.error && ev.error.message) || '').trim();
275
+ return msg ? { ...t, error: msg } : t;
276
+ }
277
+ default:
278
+ return t;
279
+ }
280
+ }
281
+
282
+ /** Settle a turn: its status, its end, what it used, and every call still open. */
283
+ export function finish(turn, status, at = null, response = null) {
284
+ const r = response || {};
285
+ const st = isTerminal(status) ? status : mapStatus(status);
286
+ const items = turn.items.map((it) => {
287
+ if (it.kind === 'tool' && it.status === 'running') return { ...it, status: st === 'done' ? 'done' : 'stopped' };
288
+ if (it.kind === 'thinking' && it.open) return { ...it, open: false, endedAt: it.endedAt ?? at };
289
+ return it;
290
+ });
291
+ const inc = r.incomplete_details;
292
+ const err = r.error && (r.error.message || r.error.code);
293
+ return {
294
+ ...turn,
295
+ items,
296
+ status: st,
297
+ endedAt: turn.endedAt ?? at,
298
+ id: r.id || turn.id,
299
+ usage: r.usage || turn.usage,
300
+ model: r.served_model || r.model || turn.model,
301
+ error: turn.error || (st === 'failed' && err ? String(err) : turn.error),
302
+ incomplete: st === 'incomplete' && inc ? { reason: inc.reason || '', detail: inc.detail || '' } : turn.incomplete,
303
+ };
304
+ }
305
+
306
+ /** Fold a list of events (a replay) into one turn. Pass `at` only for events observed live. */
307
+ export function turnFromEvents(events, opts = {}) {
308
+ let t = newTurn(opts);
309
+ for (const ev of events || []) t = reduceTurn(t, ev, opts.at ?? null);
310
+ return t;
311
+ }
312
+
313
+ /** A stored Responses object (GET /v1/responses/{id}) as a turn: its output in order. */
314
+ export function turnFromResponse(resp, opts = {}) {
315
+ const r = resp || {};
316
+ let t = newTurn({ ...opts, id: r.id, model: r.model });
317
+ const events = [];
318
+ (r.output || []).forEach((item, i) => events.push({ type: 'response.output_item.done', output_index: i, item }));
319
+ for (const ev of events) t = reduceTurn(t, ev, null);
320
+ const st = mapStatus(r.status);
321
+ if (st === 'running') return { ...t, status: 'running' };
322
+ const created = r.created_at ? r.created_at * 1000 : null;
323
+ t = finish(t, st, null, r);
324
+ return { ...t, startedAt: opts.startedAt ?? created, endedAt: opts.endedAt ?? null };
325
+ }
326
+
327
+ /**
328
+ * One turn of a session's history (the gateway's /v1/sessions/{sid}/turns entry) as a turn.
329
+ * That record keeps the calls and the answer but not their interleaving, so its calls come first
330
+ * and its answer after; `elapsed` (seconds) is kept as the turn's measured length.
331
+ */
332
+ export function turnFromHistory(h) {
333
+ const x = h || {};
334
+ let t = newTurn({ id: x.id, user: (x.user || (x.user_files || []).length) ? { text: x.user || '', files: x.user_files || [] } : null });
335
+ const items = [];
336
+ (x.tools || []).forEach((c, i) => {
337
+ const out = c.output ?? c.result;
338
+ items.push({ kind: 'tool', id: c.call_id || `call_${i}`, itemId: null, name: c.name || 'tool', args: textOf(c.arguments ?? ''),
339
+ output: out == null ? undefined : String(out), status: c.is_error ? 'failed' : 'done', startedAt: null, endedAt: null,
340
+ truncated: c.output_truncated || null });
341
+ });
342
+ if (x.assistant) items.push({ kind: 'text', id: `msg_${items.length}`, text: String(x.assistant) });
343
+ const status = mapStatus(x.status);
344
+ t = { ...t, items, files: (x.files || []).slice(), status, model: x.served_model || x._model || null,
345
+ elapsedMs: typeof x.elapsed === 'number' ? Math.round(x.elapsed * 1000) : null,
346
+ error: x.error || null,
347
+ incomplete: status === 'incomplete' && (x.incomplete_reason || x.incomplete_detail)
348
+ ? { reason: x.incomplete_reason || '', detail: x.incomplete_detail || '' } : null };
349
+ if (status === 'running') {
350
+ // the calls still without a result are the ones running
351
+ t.items = t.items.map((it) => (it.kind === 'tool' && it.output === undefined ? { ...it, status: 'running' } : it));
352
+ }
353
+ return t;
354
+ }
355
+
356
+ /**
357
+ * A message in the ChatMessages/blocks model ({role:'assistant', blocks, status, files, elapsed})
358
+ * as a turn. Content comes from the blocks; times come from `clock`, a turn the host folded from
359
+ * the same live events with reduceTurn, matched call by call. Without a clock nothing is timed.
360
+ */
361
+ export function turnFromMessage(msg, clock = null, user = null) {
362
+ const m = msg || {};
363
+ const status = m.status ? mapStatus(m.status) : 'done';
364
+ const byCall = {};
365
+ const thinkingClocks = [];
366
+ if (clock) {
367
+ for (const it of clock.items) {
368
+ if (it.kind === 'tool') byCall[it.id] = it;
369
+ else if (it.kind === 'thinking') thinkingClocks.push(it);
370
+ }
371
+ }
372
+ const items = [];
373
+ let errText = '';
374
+ let thinkN = 0;
375
+ (m.blocks || []).forEach((b, bi) => {
376
+ if (b.kind === 'text') {
377
+ if (b.error) { errText = String(b.text || '').replace(/^\s*Error:\s*/, '').trim(); return; }
378
+ if (b.text) items.push({ kind: 'text', id: `msg_${bi}`, text: b.text });
379
+ return;
380
+ }
381
+ if (b.kind === 'tools') {
382
+ if (b.reasoning) {
383
+ const c = thinkingClocks[thinkN++];
384
+ items.push({ kind: 'thinking', id: `rs_${bi}`, text: b.reasoning, startedAt: c ? c.startedAt : null,
385
+ endedAt: c ? c.endedAt : null, open: c ? !!c.open : false });
386
+ }
387
+ (b.steps || []).forEach((s, si) => {
388
+ const c = s.callId ? byCall[s.callId] : null;
389
+ const answered = s.result !== undefined;
390
+ let st = c ? c.status : (answered ? 'done' : (status === 'running' ? 'running' : (status === 'done' ? 'done' : 'stopped')));
391
+ if (answered && st === 'running') st = 'done';
392
+ // a clock that missed the end (its stream dropped) must not keep a finished turn's call running
393
+ if (st === 'running' && status !== 'running') st = status === 'done' ? 'done' : 'stopped';
394
+ items.push({ kind: 'tool', id: s.callId || `call_${bi}_${si}`, itemId: null, name: s.name || 'tool', args: textOf(s.args ?? ''),
395
+ output: answered ? String(s.result) : (c ? c.output : undefined), status: st,
396
+ startedAt: c ? c.startedAt : null, endedAt: c ? c.endedAt : null });
397
+ });
398
+ }
399
+ });
400
+ let t = {
401
+ ...newTurn({ user: user || null }),
402
+ id: (clock && clock.id) || m.id || null,
403
+ status,
404
+ items,
405
+ files: (m.files || []).slice(),
406
+ startedAt: clock ? clock.startedAt : null,
407
+ endedAt: clock ? clock.endedAt : null,
408
+ lastEventAt: clock ? clock.lastEventAt : null,
409
+ usage: clock ? clock.usage : null,
410
+ model: (clock && clock.model) || null,
411
+ error: errText || (clock && clock.error) || null,
412
+ elapsedMs: typeof m.elapsed === 'number' ? Math.round(m.elapsed * 1000) : null,
413
+ incomplete: status === 'incomplete' && (m.incompleteReason || m.incompleteDetail)
414
+ ? { reason: m.incompleteReason || '', detail: m.incompleteDetail || '' } : null,
415
+ };
416
+ if (status === 'running') {
417
+ // the model speaking after a call closes it (see settleOpenCalls); applied to blocks the same way
418
+ let lastSpeech = -1;
419
+ t.items.forEach((it, i) => { if (it.kind === 'text' || it.kind === 'thinking') lastSpeech = i; });
420
+ t.items = t.items.map((it, i) => (it.kind === 'tool' && it.status === 'running' && i < lastSpeech && !isAgentTool(it.name)
421
+ ? { ...it, status: 'done' } : it));
422
+ }
423
+ return t;
424
+ }
425
+
426
+ /**
427
+ * What the turn is doing right now, for the live line:
428
+ * { phase: 'starting'|'thinking'|'tool'|'writing', tool: Item|null }
429
+ * or null when the turn is not running. Derived from the items alone, never from a timer.
430
+ */
431
+ export function liveState(turn) {
432
+ if (!turn || turn.status !== 'running') return null;
433
+ const items = turn.items || [];
434
+ for (let i = items.length - 1; i >= 0; i--) {
435
+ const it = items[i];
436
+ if (it.kind === 'tool' && it.status === 'running') return { phase: 'tool', tool: it };
437
+ if (it.kind === 'text' || it.kind === 'thinking') break;
438
+ }
439
+ const last = items[items.length - 1];
440
+ if (!last) return { phase: turn.id ? 'thinking' : 'starting', tool: null };
441
+ if (last.kind === 'thinking') return { phase: 'thinking', tool: null };
442
+ if (last.kind === 'text' && !last.closed) return { phase: 'writing', tool: null };
443
+ return { phase: 'thinking', tool: null };
444
+ }
445
+
446
+ /**
447
+ * The turn's items cut into what a reader sees: prose, and runs of work between prose.
448
+ * [{ type: 'text', item }, { type: 'work', items: [...] }, ...]
449
+ * A run of work is every call and thought between two pieces of prose.
450
+ */
451
+ export function segments(turn) {
452
+ const out = [];
453
+ for (const it of (turn && turn.items) || []) {
454
+ if (it.kind === 'text') {
455
+ if (!it.text) continue;
456
+ out.push({ type: 'text', item: it });
457
+ } else {
458
+ const last = out[out.length - 1];
459
+ if (last && last.type === 'work') last.items.push(it);
460
+ else out.push({ type: 'work', items: [it] });
461
+ }
462
+ }
463
+ return out;
464
+ }
465
+
466
+ /** The plan as the turn last stated it, or null: the todo list of the latest planning call. */
467
+ export function latestPlan(turn, describe) {
468
+ const items = (turn && turn.items) || [];
469
+ for (let i = items.length - 1; i >= 0; i--) {
470
+ const it = items[i];
471
+ if (it.kind !== 'tool' || toolKind(it.name) !== 'todo') continue;
472
+ const d = describe(it.name, it.args);
473
+ if (d.todos && d.todos.length) return d.todos;
474
+ }
475
+ return null;
476
+ }