@theokit/presenter 0.5.0 → 0.6.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.
package/dist/index.d.ts CHANGED
@@ -156,7 +156,7 @@ declare function fromSdkMessage(msg: SdkMessage): AgentOutputEvent[];
156
156
  declare function fromInteractionUpdate(update: InteractionUpdate): AgentOutputEvent[];
157
157
 
158
158
  /**
159
- * The frame type is TheoKit's own since the `remover-dependencia-ai` plan; it is structurally the
159
+ * The frame type is TheoKit's own since the `remove-ai-dependency` plan; it is structurally the
160
160
  * ai-sdk `UIMessageChunk`, so the emitted wire is unchanged and an ai-sdk client still reads it.
161
161
  */
162
162
  type UIMessageChunk = WireChunk;
@@ -277,4 +277,86 @@ declare class JsonPresenter implements Presenter<JsonRecord> {
277
277
  present(event: AgentOutputEvent): JsonRecord[];
278
278
  }
279
279
 
280
- export { AGENT_OUTPUT_EVENT_TYPES, type AgentErrorEvent, type AgentFinishEvent, type AgentOutputEvent, type AgentOutputEventType, type AgentPartialToolCallEvent, type AgentReasoningEvent, type AgentStatusEvent, type AgentTextEvent, type AgentToolCallEvent, type AgentToolResultEvent, JsonPresenter, type JsonPresenterOptions, type JsonRecord, type Presenter, PresenterRegistry, type SdkMessage, TerminalPresenter, type TerminalPresenterOptions, type TerminalRow, type TurnMetadata, UIMessageStreamPresenter, type UIMessageStreamPresenterOptions, UnknownPresenterError, fromInteractionUpdate, fromSdkMessage, isErrorEvent, isFinishEvent, isPartialToolCallEvent, isReasoningEvent, isStatusEvent, isTextEvent, isToolCallEvent, isToolResultEvent };
280
+ /**
281
+ * Fold a content-event stream into a product's own lifecycle vocabulary.
282
+ *
283
+ * ADR 0007 records the split this implements. `AgentOutputEvent` is CONTENT-shaped — this chunk is
284
+ * text, this one is a tool call — while every wire contract a CLI actually speaks is
285
+ * LIFECYCLE-shaped: a thread has turns, a turn has items, a turn ends once with usage aggregated
286
+ * across it. The presenter's three surfaces model the first axis and are structurally unable to
287
+ * model the second.
288
+ *
289
+ * The NAMES stay with the product. `thread.started` is one dialect among several — ACP and the
290
+ * OpenAI-style contracts name the same moments differently — and a framework that ships one has
291
+ * picked a side for every consumer. So the vocabulary arrives as a record of constructors and
292
+ * nothing in this file names an event.
293
+ *
294
+ * ## What the fold is for
295
+ *
296
+ * One invariant, and it is not stylistic: **a turn opens exactly once and closes exactly once,
297
+ * never both completed and failed, and never left open.** A turn that never closes leaves a
298
+ * consumer waiting forever; a turn that closes twice makes a failed run look successful to whoever
299
+ * read the second event. Measured in the one existing hand-rolled emitter, the error path and the
300
+ * finish path each close the turn, and only a flag threaded through both keeps them from doing it
301
+ * twice — which is exactly the kind of thing that is right until someone edits one path.
302
+ *
303
+ * @public
304
+ */
305
+ /** An item within a turn: a tool call, a message, whatever the product's dialect names. @public */
306
+ interface LifecycleItem {
307
+ readonly id: string;
308
+ /** The product's word for what this item is — a tool name, `message`, an error kind. */
309
+ readonly kind: string;
310
+ }
311
+ /** The product's dialect, as constructors. Nothing here is named by the framework. @public */
312
+ interface LifecycleVocabulary<E> {
313
+ readonly threadStarted: (threadId: string) => E;
314
+ readonly turnStarted: () => E;
315
+ readonly itemStarted: (item: LifecycleItem) => E;
316
+ readonly itemCompleted: (item: LifecycleItem) => E;
317
+ readonly turnCompleted: (usage: unknown) => E;
318
+ readonly turnFailed: (error: {
319
+ readonly message: string;
320
+ }) => E;
321
+ }
322
+ /** A chunk off the content stream, in the shape this fold needs to see it. @public */
323
+ type ContentChunk = {
324
+ readonly kind: 'text';
325
+ readonly delta: string;
326
+ } | {
327
+ readonly kind: 'tool-call';
328
+ readonly id?: string;
329
+ readonly name: string;
330
+ } | {
331
+ readonly kind: 'tool-result';
332
+ readonly id?: string;
333
+ readonly name: string;
334
+ } | {
335
+ readonly kind: 'error';
336
+ readonly message: string;
337
+ };
338
+ /** How the stream ended, as the caller understands it. @public */
339
+ interface TurnOutcome {
340
+ readonly status: 'ok' | 'error';
341
+ readonly error?: string;
342
+ readonly usage?: unknown;
343
+ }
344
+ /** @public */
345
+ interface TurnLifecycle<E> {
346
+ /** The events emitted when the turn opened, in order. */
347
+ readonly opened: readonly E[];
348
+ /** False once the turn has closed. Lets a caller ASSERT the invariant rather than trust it. */
349
+ readonly isOpen: boolean;
350
+ /** Events this chunk produces. Empty is normal — text accumulates and emits nothing until the end. */
351
+ observe(chunk: ContentChunk): readonly E[];
352
+ /** Closes the turn. Idempotent: a second call emits nothing. */
353
+ finish(outcome: TurnOutcome): readonly E[];
354
+ }
355
+ /**
356
+ * @returns a turn that has already opened — the thread and turn events are in `opened`, because a
357
+ * turn whose opening is optional is one a caller can forget to open.
358
+ * @public
359
+ */
360
+ declare function foldTurnLifecycle<E>(vocabulary: LifecycleVocabulary<E>, threadId: string): TurnLifecycle<E>;
361
+
362
+ export { AGENT_OUTPUT_EVENT_TYPES, type AgentErrorEvent, type AgentFinishEvent, type AgentOutputEvent, type AgentOutputEventType, type AgentPartialToolCallEvent, type AgentReasoningEvent, type AgentStatusEvent, type AgentTextEvent, type AgentToolCallEvent, type AgentToolResultEvent, type ContentChunk, JsonPresenter, type JsonPresenterOptions, type JsonRecord, type LifecycleItem, type LifecycleVocabulary, type Presenter, PresenterRegistry, type SdkMessage, TerminalPresenter, type TerminalPresenterOptions, type TerminalRow, type TurnLifecycle, type TurnMetadata, type TurnOutcome, UIMessageStreamPresenter, type UIMessageStreamPresenterOptions, UnknownPresenterError, foldTurnLifecycle, fromInteractionUpdate, fromSdkMessage, isErrorEvent, isFinishEvent, isPartialToolCallEvent, isReasoningEvent, isStatusEvent, isTextEvent, isToolCallEvent, isToolResultEvent };
package/dist/index.js CHANGED
@@ -1,7 +1,3 @@
1
- import {
2
- __name
3
- } from "./chunk-Z4QWC7IK.js";
4
-
5
1
  // src/agent-output-event.ts
6
2
  var AGENT_OUTPUT_EVENT_TYPES = [
7
3
  "text",
@@ -13,29 +9,25 @@ var AGENT_OUTPUT_EVENT_TYPES = [
13
9
  "finish",
14
10
  "status"
15
11
  ];
16
- var isTextEvent = /* @__PURE__ */ __name((e) => e.type === "text", "isTextEvent");
17
- var isReasoningEvent = /* @__PURE__ */ __name((e) => e.type === "reasoning", "isReasoningEvent");
18
- var isToolCallEvent = /* @__PURE__ */ __name((e) => e.type === "tool-call", "isToolCallEvent");
19
- var isPartialToolCallEvent = /* @__PURE__ */ __name((e) => e.type === "partial-tool-call", "isPartialToolCallEvent");
20
- var isToolResultEvent = /* @__PURE__ */ __name((e) => e.type === "tool-result", "isToolResultEvent");
21
- var isErrorEvent = /* @__PURE__ */ __name((e) => e.type === "error", "isErrorEvent");
22
- var isFinishEvent = /* @__PURE__ */ __name((e) => e.type === "finish", "isFinishEvent");
23
- var isStatusEvent = /* @__PURE__ */ __name((e) => e.type === "status", "isStatusEvent");
12
+ var isTextEvent = (e) => e.type === "text";
13
+ var isReasoningEvent = (e) => e.type === "reasoning";
14
+ var isToolCallEvent = (e) => e.type === "tool-call";
15
+ var isPartialToolCallEvent = (e) => e.type === "partial-tool-call";
16
+ var isToolResultEvent = (e) => e.type === "tool-result";
17
+ var isErrorEvent = (e) => e.type === "error";
18
+ var isFinishEvent = (e) => e.type === "finish";
19
+ var isStatusEvent = (e) => e.type === "status";
24
20
 
25
21
  // src/presenter.ts
26
22
  var UnknownPresenterError = class extends Error {
27
- static {
28
- __name(this, "UnknownPresenterError");
29
- }
30
23
  name = "UnknownPresenterError";
31
24
  constructor(surface, known) {
32
- super(`No presenter registered for surface "${surface}". Known: ${known.join(", ") || "(none)"}.`);
25
+ super(
26
+ `No presenter registered for surface "${surface}". Known: ${known.join(", ") || "(none)"}.`
27
+ );
33
28
  }
34
29
  };
35
30
  var PresenterRegistry = class {
36
- static {
37
- __name(this, "PresenterRegistry");
38
- }
39
31
  #presenters = /* @__PURE__ */ new Map();
40
32
  /** Register (or replace) the presenter for its surface. Returns `this` for fluent wiring. */
41
33
  register(presenter) {
@@ -48,9 +40,7 @@ var PresenterRegistry = class {
48
40
  }
49
41
  /** The registered surface keys. */
50
42
  surfaces() {
51
- return [
52
- ...this.#presenters.keys()
53
- ];
43
+ return [...this.#presenters.keys()];
54
44
  }
55
45
  /** Resolve the presenter for `surface`, or throw {@link UnknownPresenterError} (never returns undefined). */
56
46
  resolve(surface) {
@@ -64,7 +54,6 @@ var PresenterRegistry = class {
64
54
  function asString(value, fallback) {
65
55
  return typeof value === "string" ? value : fallback;
66
56
  }
67
- __name(asString, "asString");
68
57
  function serializeToolResult(value, fallback) {
69
58
  if (typeof value === "string") return value;
70
59
  if (value === void 0 || value === null) return fallback;
@@ -74,17 +63,13 @@ function serializeToolResult(value, fallback) {
74
63
  return typeof value === "bigint" ? value.toString() : fallback;
75
64
  }
76
65
  }
77
- __name(serializeToolResult, "serializeToolResult");
78
66
  function fromAssistant(msg) {
79
67
  const events = [];
80
68
  const content = msg.message?.content;
81
69
  if (!Array.isArray(content)) return events;
82
70
  for (const block of content) {
83
71
  const b = block;
84
- if (b.type === "text" && b.text) events.push({
85
- type: "text",
86
- text: b.text
87
- });
72
+ if (b.type === "text" && b.text) events.push({ type: "text", text: b.text });
88
73
  if (b.type === "tool_use") {
89
74
  events.push({
90
75
  type: "tool-call",
@@ -96,7 +81,6 @@ function fromAssistant(msg) {
96
81
  }
97
82
  return events;
98
83
  }
99
- __name(fromAssistant, "fromAssistant");
100
84
  function fromToolUse(msg) {
101
85
  const status = msg.status;
102
86
  const callId = asString(msg.call_id, `tc-${Date.now()}`);
@@ -125,37 +109,19 @@ function fromToolUse(msg) {
125
109
  }
126
110
  if (status === "running") {
127
111
  return [
128
- {
129
- type: "tool-call",
130
- callId,
131
- name,
132
- input: msg.args ?? msg.input ?? msg.arguments ?? {}
133
- }
112
+ { type: "tool-call", callId, name, input: msg.args ?? msg.input ?? msg.arguments ?? {} }
134
113
  ];
135
114
  }
136
115
  return [];
137
116
  }
138
- __name(fromToolUse, "fromToolUse");
139
117
  function fromStatus(msg) {
140
118
  const s = msg.status;
141
- if (s === "FINISHED" || s === "CANCELLED") return [
142
- {
143
- type: "finish",
144
- reason: s.toLowerCase()
145
- }
146
- ];
119
+ if (s === "FINISHED" || s === "CANCELLED") return [{ type: "finish", reason: s.toLowerCase() }];
147
120
  if (s === "ERROR" || s === "EXPIRED") {
148
- return [
149
- {
150
- type: "error",
151
- message: asString(msg.message, "Agent error"),
152
- code: "AGENT_ERROR"
153
- }
154
- ];
121
+ return [{ type: "error", message: asString(msg.message, "Agent error"), code: "AGENT_ERROR" }];
155
122
  }
156
123
  return [];
157
124
  }
158
- __name(fromStatus, "fromStatus");
159
125
  function fromSdkMessage(msg) {
160
126
  switch (msg.type) {
161
127
  case "assistant":
@@ -163,12 +129,7 @@ function fromSdkMessage(msg) {
163
129
  case "tool_call":
164
130
  return fromToolUse(msg);
165
131
  case "thinking":
166
- return [
167
- {
168
- type: "reasoning",
169
- text: asString(msg.text, "")
170
- }
171
- ];
132
+ return [{ type: "reasoning", text: asString(msg.text, "") }];
172
133
  case "status":
173
134
  return fromStatus(msg);
174
135
  // `system` / run-lifecycle is framework framing, not pure output — intentionally skipped (ADR-4).
@@ -176,23 +137,12 @@ function fromSdkMessage(msg) {
176
137
  return [];
177
138
  }
178
139
  }
179
- __name(fromSdkMessage, "fromSdkMessage");
180
140
  function fromInteractionUpdate(update) {
181
141
  switch (update.type) {
182
142
  case "text-delta":
183
- return update.text ? [
184
- {
185
- type: "text",
186
- text: update.text
187
- }
188
- ] : [];
143
+ return update.text ? [{ type: "text", text: update.text }] : [];
189
144
  case "thinking-delta":
190
- return update.text ? [
191
- {
192
- type: "reasoning",
193
- text: update.text
194
- }
195
- ] : [];
145
+ return update.text ? [{ type: "reasoning", text: update.text }] : [];
196
146
  case "tool-call-started":
197
147
  return [
198
148
  {
@@ -225,13 +175,9 @@ function fromInteractionUpdate(update) {
225
175
  return [];
226
176
  }
227
177
  }
228
- __name(fromInteractionUpdate, "fromInteractionUpdate");
229
178
 
230
179
  // src/presenters/ui-message-stream.ts
231
180
  var UIMessageStreamPresenter = class {
232
- static {
233
- __name(this, "UIMessageStreamPresenter");
234
- }
235
181
  surface = "ui-message-stream";
236
182
  #textId;
237
183
  #openBlock = null;
@@ -242,11 +188,7 @@ var UIMessageStreamPresenter = class {
242
188
  }
243
189
  /** Emit the opening `start` chunk (exactly once, before any event). */
244
190
  start() {
245
- return [
246
- {
247
- type: "start"
248
- }
249
- ];
191
+ return [{ type: "start" }];
250
192
  }
251
193
  present(event) {
252
194
  switch (event.type) {
@@ -265,12 +207,7 @@ var UIMessageStreamPresenter = class {
265
207
  ...this.#emitToolResult(event.callId, event.name, event.result, event.isError ?? false)
266
208
  ];
267
209
  case "error":
268
- return [
269
- {
270
- type: "error",
271
- errorText: event.message
272
- }
273
- ];
210
+ return [{ type: "error", errorText: event.message }];
274
211
  // `partial-tool-call` streams incremental args — the current web path emits no chunk for it
275
212
  // (args are shown on the committed `tool-call`); `finish` / `status` are handled by finish()/host.
276
213
  default:
@@ -278,32 +215,27 @@ var UIMessageStreamPresenter = class {
278
215
  }
279
216
  }
280
217
  /**
281
- * Close any open text/reasoning block and emit the terminal `finish` chunk. When `metadata` is given
282
- * (a clean run's turn totals from the framework `done`), it rides `messageMetadata`; otherwise the
283
- * finish is bare (error/abort turns), byte-identical to the original translator.
284
- */
218
+ * Close any open text/reasoning block and emit the terminal `finish` chunk. When `metadata` is given
219
+ * (a clean run's turn totals from the framework `done`), it rides `messageMetadata`; otherwise the
220
+ * finish is bare (error/abort turns), byte-identical to the original translator.
221
+ */
285
222
  finish(metadata) {
286
223
  const out = this.#closeOpenBlock();
287
- out.push(metadata ? {
288
- type: "finish",
289
- messageMetadata: metadata
290
- } : {
291
- type: "finish"
292
- });
224
+ out.push(metadata ? { type: "finish", messageMetadata: metadata } : { type: "finish" });
293
225
  return out;
294
226
  }
295
227
  /**
296
- * Close any open text/reasoning block WITHOUT finishing the stream. The host calls this before
297
- * interleaving a framework chunk (HITL approval / checkpoint) that must not appear inside an open text
298
- * block — mirroring the original translator's `closeOpenBlock` before those chunks. Idempotent.
299
- */
228
+ * Close any open text/reasoning block WITHOUT finishing the stream. The host calls this before
229
+ * interleaving a framework chunk (HITL approval / checkpoint) that must not appear inside an open text
230
+ * block — mirroring the original translator's `closeOpenBlock` before those chunks. Idempotent.
231
+ */
300
232
  closeBlock() {
301
233
  return this.#closeOpenBlock();
302
234
  }
303
235
  /**
304
- * Whether a `callId` has already been introduced (a `tool-call` or a synthesized `tool-input`). The host
305
- * uses this so a framework `approval_required` reuses the EC-1 synthesize-input-first rule exactly once.
306
- */
236
+ * Whether a `callId` has already been introduced (a `tool-call` or a synthesized `tool-input`). The host
237
+ * uses this so a framework `approval_required` reuses the EC-1 synthesize-input-first rule exactly once.
238
+ */
307
239
  hasSeen(callId) {
308
240
  return this.#seen.has(callId);
309
241
  }
@@ -315,15 +247,9 @@ var UIMessageStreamPresenter = class {
315
247
  #closeOpenBlock() {
316
248
  const out = [];
317
249
  if (this.#openBlock === "text") {
318
- out.push({
319
- type: "text-end",
320
- id: this.#textId
321
- });
250
+ out.push({ type: "text-end", id: this.#textId });
322
251
  } else if (this.#openBlock === "reasoning" && this.#reasoningId) {
323
- out.push({
324
- type: "reasoning-end",
325
- id: this.#reasoningId
326
- });
252
+ out.push({ type: "reasoning-end", id: this.#reasoningId });
327
253
  }
328
254
  this.#openBlock = null;
329
255
  this.#reasoningId = null;
@@ -332,17 +258,10 @@ var UIMessageStreamPresenter = class {
332
258
  #emitTextDelta(content) {
333
259
  const out = [];
334
260
  if (this.#openBlock !== "text") {
335
- out.push(...this.#closeOpenBlock(), {
336
- type: "text-start",
337
- id: this.#textId
338
- });
261
+ out.push(...this.#closeOpenBlock(), { type: "text-start", id: this.#textId });
339
262
  this.#openBlock = "text";
340
263
  }
341
- out.push({
342
- type: "text-delta",
343
- id: this.#textId,
344
- delta: content
345
- });
264
+ out.push({ type: "text-delta", id: this.#textId, delta: content });
346
265
  return out;
347
266
  }
348
267
  #emitReasoningDelta(content) {
@@ -352,29 +271,16 @@ var UIMessageStreamPresenter = class {
352
271
  out.push(...this.#closeOpenBlock());
353
272
  reasoningId = crypto.randomUUID();
354
273
  this.#reasoningId = reasoningId;
355
- out.push({
356
- type: "reasoning-start",
357
- id: reasoningId
358
- });
274
+ out.push({ type: "reasoning-start", id: reasoningId });
359
275
  this.#openBlock = "reasoning";
360
276
  }
361
- out.push({
362
- type: "reasoning-delta",
363
- id: reasoningId,
364
- delta: content
365
- });
277
+ out.push({ type: "reasoning-delta", id: reasoningId, delta: content });
366
278
  return out;
367
279
  }
368
280
  #emitToolCall(callId, name, input) {
369
281
  this.#seen.add(callId);
370
282
  return [
371
- {
372
- type: "tool-input-available",
373
- toolCallId: callId,
374
- toolName: name,
375
- input,
376
- dynamic: true
377
- }
283
+ { type: "tool-input-available", toolCallId: callId, toolName: name, input, dynamic: true }
378
284
  ];
379
285
  }
380
286
  #emitToolResult(callId, name, result, isError) {
@@ -391,17 +297,9 @@ var UIMessageStreamPresenter = class {
391
297
  }
392
298
  const output = typeof result === "string" ? result : "";
393
299
  if (isError) {
394
- out.push({
395
- type: "tool-output-error",
396
- toolCallId: callId,
397
- errorText: output
398
- });
300
+ out.push({ type: "tool-output-error", toolCallId: callId, errorText: output });
399
301
  } else {
400
- out.push({
401
- type: "tool-output-available",
402
- toolCallId: callId,
403
- output
404
- });
302
+ out.push({ type: "tool-output-available", toolCallId: callId, output });
405
303
  }
406
304
  return out;
407
305
  }
@@ -411,11 +309,15 @@ var UIMessageStreamPresenter = class {
411
309
  var ANSI = {
412
310
  text: "",
413
311
  reasoning: "\x1B[2m",
312
+ // dim
414
313
  tool: "\x1B[36m",
314
+ // cyan
415
315
  "tool-result": "\x1B[2m",
416
316
  "tool-error": "\x1B[31m",
317
+ // red
417
318
  error: "\x1B[31m",
418
319
  status: "\x1B[35m",
320
+ // magenta
419
321
  finish: "\x1B[2m"
420
322
  };
421
323
  var RESET = "\x1B[0m";
@@ -424,7 +326,6 @@ function preview(value, max) {
424
326
  const flat = raw.replace(/\s+/g, " ").trim();
425
327
  return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
426
328
  }
427
- __name(preview, "preview");
428
329
  function safeJson(value) {
429
330
  if (value === void 0 || value === null) return "";
430
331
  try {
@@ -433,15 +334,10 @@ function safeJson(value) {
433
334
  return typeof value === "bigint" ? value.toString() : "";
434
335
  }
435
336
  }
436
- __name(safeJson, "safeJson");
437
337
  function suffix(open, value, close) {
438
338
  return value === void 0 ? "" : open + value + close;
439
339
  }
440
- __name(suffix, "suffix");
441
340
  var TerminalPresenter = class {
442
- static {
443
- __name(this, "TerminalPresenter");
444
- }
445
341
  surface = "terminal";
446
342
  #ansi;
447
343
  #max;
@@ -452,33 +348,21 @@ var TerminalPresenter = class {
452
348
  present(event) {
453
349
  switch (event.type) {
454
350
  case "text":
455
- return event.text.length > 0 ? [
456
- this.#row("text", event.text)
457
- ] : [];
351
+ return event.text.length > 0 ? [this.#row("text", event.text)] : [];
458
352
  case "reasoning":
459
- return event.text.length > 0 ? [
460
- this.#row("reasoning", `\xB7 ${event.text}`)
461
- ] : [];
353
+ return event.text.length > 0 ? [this.#row("reasoning", `\xB7 ${event.text}`)] : [];
462
354
  case "tool-call":
463
- return [
464
- this.#row("tool", `\u23FA ${event.name}(${preview(event.input, this.#max)})`)
465
- ];
355
+ return [this.#row("tool", `\u23FA ${event.name}(${preview(event.input, this.#max)})`)];
466
356
  case "tool-result":
467
- return [
468
- this.#toolResult(event.isError === true, preview(event.result, this.#max))
469
- ];
357
+ return [this.#toolResult(event.isError === true, preview(event.result, this.#max))];
470
358
  case "error":
471
- return [
472
- this.#row("error", `\u2716 ${event.message}${suffix(" (", event.code, ")")}`)
473
- ];
359
+ return [this.#row("error", `\u2716 ${event.message}${suffix(" (", event.code, ")")}`)];
474
360
  case "status":
475
361
  return [
476
362
  this.#row("status", `\u25CF ${event.status}${suffix(" \u2014 ", event.detail, "")}`)
477
363
  ];
478
364
  case "finish":
479
- return [
480
- this.#row("finish", this.#finishText(event.reason, event.usage?.totalTokens))
481
- ];
365
+ return [this.#row("finish", this.#finishText(event.reason, event.usage?.totalTokens))];
482
366
  // `partial-tool-call` streams incremental args — the committed `tool-call` renders them.
483
367
  default:
484
368
  return [];
@@ -493,18 +377,12 @@ var TerminalPresenter = class {
493
377
  return `<<${r}${t} >>`;
494
378
  }
495
379
  #row(kind, text) {
496
- return {
497
- kind,
498
- text: this.#ansi && ANSI[kind] !== "" ? `${ANSI[kind]}${text}${RESET}` : text
499
- };
380
+ return { kind, text: this.#ansi && ANSI[kind] !== "" ? `${ANSI[kind]}${text}${RESET}` : text };
500
381
  }
501
382
  };
502
383
 
503
384
  // src/presenters/json.ts
504
385
  var JsonPresenter = class {
505
- static {
506
- __name(this, "JsonPresenter");
507
- }
508
386
  surface = "json";
509
387
  #ns;
510
388
  constructor(options = {}) {
@@ -512,14 +390,60 @@ var JsonPresenter = class {
512
390
  }
513
391
  present(event) {
514
392
  const { type, ...payload } = event;
515
- return [
516
- {
517
- type: `${this.#ns}${type}`,
518
- ...payload
519
- }
520
- ];
393
+ return [{ type: `${this.#ns}${type}`, ...payload }];
521
394
  }
522
395
  };
396
+
397
+ // src/turn-lifecycle.ts
398
+ function foldTurnLifecycle(vocabulary, threadId) {
399
+ let open = true;
400
+ let text = "";
401
+ let failure;
402
+ let nextItem = 0;
403
+ const idOf = (chunk) => chunk.id ?? `item_${nextItem}`;
404
+ const observe = (chunk) => {
405
+ if (!open) return [];
406
+ switch (chunk.kind) {
407
+ case "text":
408
+ text += chunk.delta;
409
+ return [];
410
+ case "tool-call":
411
+ return [vocabulary.itemStarted({ id: idOf(chunk), kind: chunk.name })];
412
+ case "tool-result": {
413
+ const closing = vocabulary.itemCompleted({ id: idOf(chunk), kind: chunk.name });
414
+ nextItem += 1;
415
+ return [closing];
416
+ }
417
+ case "error":
418
+ failure ??= chunk.message;
419
+ return [];
420
+ default:
421
+ return [];
422
+ }
423
+ };
424
+ const finish = (outcome) => {
425
+ if (!open) return [];
426
+ open = false;
427
+ const events = [];
428
+ const message = text.trim();
429
+ if (message.length > 0) {
430
+ events.push(vocabulary.itemCompleted({ id: "message", kind: message }));
431
+ }
432
+ const reason = failure ?? (outcome.status === "error" ? outcome.error ?? "turn failed" : void 0);
433
+ events.push(
434
+ reason === void 0 ? vocabulary.turnCompleted(outcome.usage) : vocabulary.turnFailed({ message: reason })
435
+ );
436
+ return events;
437
+ };
438
+ return {
439
+ opened: [vocabulary.threadStarted(threadId), vocabulary.turnStarted()],
440
+ get isOpen() {
441
+ return open;
442
+ },
443
+ observe,
444
+ finish
445
+ };
446
+ }
523
447
  export {
524
448
  AGENT_OUTPUT_EVENT_TYPES,
525
449
  JsonPresenter,
@@ -527,6 +451,7 @@ export {
527
451
  TerminalPresenter,
528
452
  UIMessageStreamPresenter,
529
453
  UnknownPresenterError,
454
+ foldTurnLifecycle,
530
455
  fromInteractionUpdate,
531
456
  fromSdkMessage,
532
457
  isErrorEvent,