@tangle-network/agent-app 0.60.141 → 0.60.143

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.
@@ -45,6 +45,10 @@ export interface ChatStreamCallbacks {
45
45
  onIntent?: (intent: TurnIntentData) => void;
46
46
  onText?: (delta: string) => void;
47
47
  onReasoning?: (delta: string) => void;
48
+ /** The message's reasoning so far, when it started and when it ended, after every reasoning delta and once
49
+ * when thinking ends. Spread it onto `ReasoningRow`. `consumeChatStream` and `streamChatTurn` keep it;
50
+ * a consumer that calls `dispatchChatStreamLine` itself wraps its callbacks with `trackChatReasoning`. */
51
+ onReasoningState?: (state: ChatReasoningState) => void;
48
52
  onToolCall?: (call: ChatStreamToolCall) => void;
49
53
  onToolResult?: (result: ChatStreamToolResult) => void;
50
54
  onUsage?: (usage: {
@@ -79,6 +83,51 @@ export interface ChatStreamCallbacks {
79
83
  /** A durable-plan snapshot from any plan lifecycle event. */
80
84
  onPlan?: (plan: ChatPlan) => void;
81
85
  }
86
+ /**
87
+ * One message's reasoning as the stream delivers it: the text so far, when the
88
+ * model started reasoning and when it stopped. Its fields are `ReasoningRow`'s
89
+ * props. Live state comes from `onReasoningState`; a saved message's comes from
90
+ * `chatReasoningFromParts`.
91
+ */
92
+ export interface ChatReasoningState {
93
+ text: string;
94
+ /** Epoch ms of the first reasoning delta. Absent only on history saved without times. */
95
+ startedAt?: number;
96
+ /** Epoch ms the reasoning ended: the answer's first text, an error, or the end of the turn. */
97
+ endedAt?: number;
98
+ /** Reasoning deltas are still arriving and nothing has ended them yet. */
99
+ thinking: boolean;
100
+ }
101
+ /** Callbacks that keep the turn's reasoning state, plus the two moments only the transport knows. */
102
+ export type TrackedChatStreamCallbacks = ChatStreamCallbacks & {
103
+ /** The turn's stream is over, or failed for good: thinking that is still open ends now. */
104
+ end: () => void;
105
+ /** The stream will replay the turn from its first event (a resume from 0): the text is rebuilt from the
106
+ * replay, and the start time of the first delta is kept, so "Thought for N seconds" still counts from it. */
107
+ replay: () => void;
108
+ };
109
+ /**
110
+ * Keep one turn's reasoning state from its stream: the first reasoning delta
111
+ * starts the clock, the answer's first text, an error or `end()` stops it, and
112
+ * every change reaches `callbacks.onReasoningState`. Reasoning that resumes
113
+ * after a tool call or an answer continues the same state as a new paragraph,
114
+ * the way a reload joins the turn's saved reasoning parts.
115
+ *
116
+ * It takes callbacks, not a stream, so it is the entry point for any
117
+ * transport: `streamChatTurn` and `consumeChatStream` apply it themselves; an
118
+ * app that dispatches lines one at a time (`dispatchChatStreamLine`) or reads
119
+ * its own frames (a Durable Object's live parts, server-side events) wraps its
120
+ * handlers with it, feeds `onReasoning` / `onText` / `onToolCall`, and calls
121
+ * `end()` when its stream closes.
122
+ */
123
+ export declare function trackChatReasoning(callbacks: ChatStreamCallbacks, now?: () => number): TrackedChatStreamCallbacks;
124
+ /**
125
+ * A saved message's reasoning, settled, from its persisted parts: every
126
+ * `{ type: 'reasoning', text, time }` part joined in order, from the first
127
+ * part's start to the last part's end. A reload shows it collapsed with how
128
+ * long the model thought. Undefined when the message has no reasoning text.
129
+ */
130
+ export declare function chatReasoningFromParts(parts: ReadonlyArray<unknown> | null | undefined): ChatReasoningState | undefined;
82
131
  /** Represent the result of consuming a chat stream including turn ID and content reception status */
83
132
  export interface ConsumeChatStreamResult {
84
133
  turnId: string | null;
@@ -3,7 +3,7 @@
3
3
  * every agent app's web UI hand-rolls: a model picker over the runtime's
4
4
  * model catalogue, a reasoning-effort selector, and a message thread with
5
5
  * User/Agent identity, per-message model + cost + tokens/sec metrics,
6
- * canonical tool rows, and a collapsible thinking section.
6
+ * canonical tool rows, and the shared reasoning row (`ReasoningRow`).
7
7
  *
8
8
  * Works for BOTH chat shapes: router-backed copilots (LoopEvents from
9
9
  * `runtime/openai-stream`) and sandbox-backed chats — the thread renders
@@ -30,6 +30,7 @@ import type { WorkProductPersistedPart } from '../work-product/types';
30
30
  import type { TurnPhaseData } from '../chat-routes/turn-progress';
31
31
  export * from './chat-stream';
32
32
  export { TurnProgress, type TurnProgressProps } from './turn-progress';
33
+ export { ReasoningRow, type ReasoningRowProps } from './reasoning-row';
33
34
  export * from './chat-interactions';
34
35
  export * from './chat-composer';
35
36
  export * from './workspace-prewarm';
@@ -157,7 +158,12 @@ export interface ChatUiMessage extends ChatMessageMetrics {
157
158
  id: string;
158
159
  role: 'user' | 'assistant' | 'system';
159
160
  content: string;
161
+ /** The model's reasoning for this message, shown in a {@link ReasoningRow} above the answer. */
160
162
  reasoning?: string;
163
+ /** When the model started reasoning (epoch ms): `ChatReasoningState.startedAt` from the stream or the saved parts. */
164
+ reasoningStartedAt?: number;
165
+ /** When the reasoning ended (epoch ms). Set, the row reads "Thought for N seconds"; unset while streaming, it is still thinking. */
166
+ reasoningEndedAt?: number;
161
167
  toolCalls?: ChatToolCallInfo[];
162
168
  /** Ordered text/tool sequence for true chronological interleaving. When
163
169
  * present and non-empty it is rendered in place of `content` + `toolCalls`;
@@ -291,10 +297,10 @@ export type ToolDetailRenderers = Record<string, (call: ChatToolCallInfo, messag
291
297
  * so `state.time` stays unset and the row shows no duration.
292
298
  */
293
299
  export declare function chatToolCallPart(call: ChatToolCallInfo): ToolPart;
294
- /** Whole seconds elapsed while `active`, ticking once a second. Powers the live
295
- * "thinking" timers (the pre-first-token row and the reasoning box) so a long
296
- * thinking gap shows progress instead of a frozen label. Counts from when
297
- * `active` first turns true; freezes when it clears. */
300
+ /** Whole seconds elapsed while `active`, ticking once a second; counts from
301
+ * when `active` first turns true and freezes when it clears. Kept for
302
+ * existing consumers: `ReasoningRow` times reasoning from the stream's own
303
+ * start instead. */
298
304
  export declare function useThinkingSeconds(active: boolean): number;
299
305
  /**
300
306
  * The message thread: one centered column; user messages are right-aligned
@@ -37,6 +37,7 @@ import {
37
37
  ProvenanceLegend,
38
38
  ProvenanceValue,
39
39
  QuestionOptionList,
40
+ ReasoningRow,
40
41
  RecordGrid,
41
42
  RunDrillIn,
42
43
  SeatPaywall,
@@ -46,6 +47,7 @@ import {
46
47
  activityTone,
47
48
  buildAnswerData,
48
49
  cancelChatInteraction,
50
+ chatReasoningFromParts,
49
51
  chatToolCallPart,
50
52
  consumeChatStream,
51
53
  createDurableInteractionAnswerSubmitter,
@@ -119,6 +121,7 @@ import {
119
121
  streamChatTurn,
120
122
  sumRecordGridColumn,
121
123
  terminalizePendingChatInteractions,
124
+ trackChatReasoning,
122
125
  triggerAttachmentDownload,
123
126
  upsertChatInteraction,
124
127
  useChatInteractions,
@@ -138,7 +141,7 @@ import {
138
141
  withoutRecordGridCreated,
139
142
  withoutRecordGridRemoved,
140
143
  withoutRecordGridUpdate
141
- } from "../chunk-EGEULRT2.js";
144
+ } from "../chunk-T4JJXUJI.js";
142
145
  import {
143
146
  SessionHistoryPanel,
144
147
  formatSessionTimestamp,
@@ -369,6 +372,7 @@ export {
369
372
  ProviderLogo,
370
373
  QualityCheckList,
371
374
  QuestionOptionList,
375
+ ReasoningRow,
372
376
  RecordGrid,
373
377
  ReviewQueuePanel,
374
378
  RouteChunkBoundary,
@@ -402,6 +406,7 @@ export {
402
406
  canTransitionInteractionStatus,
403
407
  cancelChatInteraction,
404
408
  cancelStatusFor,
409
+ chatReasoningFromParts,
405
410
  chatToolCallPart,
406
411
  chatTurnRequestInit,
407
412
  composerAnswerData,
@@ -521,6 +526,7 @@ export {
521
526
  sumRecordGridColumn,
522
527
  tabTerminalConnectionId,
523
528
  terminalizePendingChatInteractions,
529
+ trackChatReasoning,
524
530
  triggerAttachmentDownload,
525
531
  upsertChatInteraction,
526
532
  useChatInteractions,
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The reasoning row every agent app shows above an answer. While the model
3
+ * reasons, its reasoning streams in live under "Thinking · 12s"; when the
4
+ * answer starts the row collapses to "Thought for 12 seconds", and a click
5
+ * opens it again. It renders nothing when the turn has no reasoning.
6
+ *
7
+ * The props are a `ChatReasoningState` (`./chat-stream`): spread the state the
8
+ * stream keeps (`onReasoningState`), or a saved message's
9
+ * (`chatReasoningFromParts`), onto the row. `ChatMessages` renders it for
10
+ * every assistant message that carries `reasoning`.
11
+ *
12
+ * It is built on the shared run-row shell (`RunRowShell` from
13
+ * `@tangle-network/ui/run`), so it reads as one family with the tool rows, and
14
+ * styles only with the shared design tokens.
15
+ */
16
+ import { type ReactNode } from 'react';
17
+ /** Props for {@link ReasoningRow}: the fields of a `ChatReasoningState`, plus presentation. */
18
+ export interface ReasoningRowProps {
19
+ /** The reasoning so far. While it is blank the row renders nothing. */
20
+ text: string;
21
+ /** When the model started reasoning (epoch ms). The live timer counts from here; without it, from when the row first saw the model thinking. */
22
+ startedAt?: number;
23
+ /** When the reasoning ended (epoch ms). With `startedAt`, the settled row reads "Thought for N seconds". */
24
+ endedAt?: number;
25
+ /** The model is still reasoning. Defaults to true while `startedAt` is set and `endedAt` is not. */
26
+ thinking?: boolean;
27
+ /** Open a settled row. Default false: once thinking ends the row is collapsed until the reader opens it. */
28
+ defaultOpen?: boolean;
29
+ /** Render the reasoning text. Default: the shared markdown renderer. */
30
+ renderText?: (text: string) => ReactNode;
31
+ className?: string;
32
+ }
33
+ /** The model's reasoning for one message: live while it thinks, collapsed once it answers. */
34
+ export declare function ReasoningRow({ text, startedAt, endedAt, thinking: thinkingProp, defaultOpen, renderText, className, }: ReasoningRowProps): import("react").JSX.Element | null;
@@ -660,14 +660,22 @@ function createExportEngine(options) {
660
660
  pendingLength = 0;
661
661
  };
662
662
  const reader = stream.getReader();
663
- for (; ; ) {
664
- const { done, value } = await reader.read();
665
- if (done) break;
666
- pending.push(value);
667
- pendingLength += value.length;
668
- if (pendingLength >= SEGMENT_BYTES) await flush();
663
+ try {
664
+ for (; ; ) {
665
+ const { done, value } = await reader.read();
666
+ if (done) break;
667
+ pending.push(value);
668
+ pendingLength += value.length;
669
+ if (pendingLength >= SEGMENT_BYTES) await flush();
670
+ }
671
+ await flush();
672
+ } catch (err) {
673
+ await reader.cancel(err).catch(() => {
674
+ });
675
+ throw err;
676
+ } finally {
677
+ reader.releaseLock();
669
678
  }
670
- await flush();
671
679
  return {
672
680
  path,
673
681
  method: compress ? 8 : 0,
@@ -708,7 +716,7 @@ function createExportEngine(options) {
708
716
  const omit = new Set(source.omitColumns ?? []);
709
717
  unit.expectedRows = source.expectedCount ? await source.expectedCount() : void 0;
710
718
  const csv = source.format === "csv";
711
- const columns = source.columns ?? [];
719
+ const columns = (source.columns ?? []).filter((column) => !omit.has(column));
712
720
  if (csv && !columns.length) throw new Error(`workspace-export: csv source "${source.name}" needs columns`);
713
721
  let rows = 0;
714
722
  const iterator = source.rows()[Symbol.asyncIterator]();
@@ -766,37 +774,47 @@ function createExportEngine(options) {
766
774
  const used = new Set(unit.entries.map((e) => e.path.slice(folder.length)));
767
775
  const start = unit.cursor ?? 0;
768
776
  let seen = 0;
769
- let written = 0;
770
777
  let chunk = [];
771
778
  const flush = async () => {
772
- const written_ = await Promise.all(
773
- chunk.map(async ({ file, position, path }) => {
779
+ const results = await Promise.allSettled(chunk.map(({ entry }) => entry));
780
+ for (const result of results) if (result.status === "rejected") throw result.reason;
781
+ for (const result of results) {
782
+ if (result.status === "fulfilled" && result.value) {
783
+ unit.entries.push(result.value);
784
+ }
785
+ }
786
+ unit.cursor = chunk.at(-1).position + 1;
787
+ chunk = [];
788
+ };
789
+ try {
790
+ for await (const file of source.files()) {
791
+ if (seen < start) {
792
+ seen += 1;
793
+ continue;
794
+ }
795
+ if (seen - start >= FILES_PER_REQUEST || now() > deadline) {
796
+ if (chunk.length) await flush();
797
+ unit.cursor = seen;
798
+ return;
799
+ }
800
+ const position = seen;
801
+ const path = folder + safePath(file.path, used);
802
+ const entry = (async () => {
774
803
  const body = await file.open();
775
804
  if (body === null) return null;
776
805
  const masked = toStream(body).pipeThrough(scanner.maskBytes((n) => unit.redactions += n));
777
806
  return writeEntry(`${keyBase}/p${position}`, path, masked, false);
778
- })
779
- );
780
- for (const entry of written_) if (entry) unit.entries.push(entry);
781
- written += written_.filter(Boolean).length;
782
- unit.cursor = chunk.at(-1).position + 1;
783
- chunk = [];
784
- };
785
- for await (const file of source.files()) {
786
- if (seen < start) {
807
+ })();
808
+ void entry.catch(() => {
809
+ });
810
+ chunk.push({ position, entry });
787
811
  seen += 1;
788
- continue;
789
- }
790
- if (written + chunk.length >= FILES_PER_REQUEST || now() > deadline) {
791
- if (chunk.length) await flush();
792
- unit.cursor = seen;
793
- return;
812
+ if (chunk.length >= FILES_IN_PARALLEL) await flush();
794
813
  }
795
- chunk.push({ file, position: seen, path: folder + safePath(file.path, used) });
796
- seen += 1;
797
- if (chunk.length >= FILES_IN_PARALLEL) await flush();
814
+ if (chunk.length) await flush();
815
+ } finally {
816
+ await Promise.allSettled(chunk.map(({ entry }) => entry));
798
817
  }
799
- if (chunk.length) await flush();
800
818
  unit.cursor = void 0;
801
819
  unit.files = unit.entries.length;
802
820
  unit.status = unit.entries.length ? "done" : "empty";
@@ -808,8 +826,17 @@ function createExportEngine(options) {
808
826
  return;
809
827
  }
810
828
  const stats = { files: 0, bytes: 0, blanked: [] };
811
- const tarGz = archive.pipeThrough(new DecompressionStream("gzip")).pipeThrough(createTarInspector(stats, source.exclude)).pipeThrough(scanner.maskBytes((n) => unit.redactions += n)).pipeThrough(new CompressionStream("gzip"));
812
- unit.entries.push(await writeEntry(`${keyBase}/0`, `sandbox/${source.name}.tar.gz`, tarGz, false));
829
+ const decompressor = new DecompressionStream("gzip");
830
+ const pumping = archive.pipeTo(decompressor.writable);
831
+ void pumping.catch(() => {
832
+ });
833
+ const tarGz = decompressor.readable.pipeThrough(createTarInspector(stats, source.exclude)).pipeThrough(scanner.maskBytes((n) => unit.redactions += n)).pipeThrough(new CompressionStream("gzip"));
834
+ try {
835
+ unit.entries.push(await writeEntry(`${keyBase}/0`, `sandbox/${source.name}.tar.gz`, tarGz, false));
836
+ } finally {
837
+ await pumping.catch(() => {
838
+ });
839
+ }
813
840
  unit.archive = stats;
814
841
  unit.files = stats.files;
815
842
  unit.status = "done";
@@ -1522,18 +1549,28 @@ async function openRunning(getBox, timeoutMs) {
1522
1549
  const box = await getBox();
1523
1550
  if (!box || GONE.has(box.status)) return null;
1524
1551
  const wasStopped = box.status === "stopped";
1552
+ let resumed = false;
1553
+ let restoring;
1554
+ const restore = () => restoring ??= (async () => {
1555
+ if (resumed && box.stop) {
1556
+ try {
1557
+ await box.stop();
1558
+ } catch {
1559
+ }
1560
+ }
1561
+ })();
1525
1562
  try {
1526
- if (wasStopped) await box.resume();
1563
+ if (wasStopped) {
1564
+ await box.resume();
1565
+ resumed = true;
1566
+ }
1527
1567
  if (box.status !== "running" || wasStopped) await box.waitFor("running", { timeoutMs });
1528
1568
  } catch (err) {
1569
+ await restore();
1529
1570
  if (isLifecycleBusy(err)) throw new ExportRetryLater("the sandbox is busy with another operation; retrying shortly");
1530
1571
  if (isServerFailure(err)) throw new ExportRetryLater("the sandbox could not be started; retrying shortly");
1531
1572
  throw err;
1532
1573
  }
1533
- const restore = async () => {
1534
- if (wasStopped && box.stop) await box.stop().catch(() => {
1535
- });
1536
- };
1537
1574
  return { box, restore };
1538
1575
  }
1539
1576
  function sandboxArchive(args) {
@@ -1546,8 +1583,45 @@ function sandboxArchive(args) {
1546
1583
  async open() {
1547
1584
  const opened = await openRunning(args.getBox, args.resumeTimeoutMs ?? 12e4);
1548
1585
  if (!opened) return null;
1549
- const archive = await opened.box.fs.openArchive(args.dir ?? ".");
1550
- return archive.pipeThrough(new TransformStream({ flush: () => opened.restore() }));
1586
+ try {
1587
+ const archive = await opened.box.fs.openArchive(args.dir ?? ".");
1588
+ const reader = archive.getReader();
1589
+ let ended = false;
1590
+ return new ReadableStream({
1591
+ async pull(controller) {
1592
+ try {
1593
+ const { done, value } = await reader.read();
1594
+ if (ended) return;
1595
+ if (!done) {
1596
+ controller.enqueue(value);
1597
+ return;
1598
+ }
1599
+ ended = true;
1600
+ await opened.restore();
1601
+ reader.releaseLock();
1602
+ controller.close();
1603
+ } catch (err) {
1604
+ if (ended) return;
1605
+ ended = true;
1606
+ await opened.restore();
1607
+ reader.releaseLock();
1608
+ controller.error(err);
1609
+ }
1610
+ },
1611
+ async cancel(reason) {
1612
+ ended = true;
1613
+ try {
1614
+ await reader.cancel(reason);
1615
+ } finally {
1616
+ await opened.restore();
1617
+ reader.releaseLock();
1618
+ }
1619
+ }
1620
+ });
1621
+ } catch (err) {
1622
+ await opened.restore();
1623
+ throw err;
1624
+ }
1551
1625
  }
1552
1626
  };
1553
1627
  }
@@ -1562,14 +1636,26 @@ function sandboxFiles(args) {
1562
1636
  if (!listed.length) return;
1563
1637
  const opened = await openRunning(args.getBox, args.resumeTimeoutMs ?? 12e4);
1564
1638
  if (!opened) return;
1565
- const read = opened.box.fs.read;
1566
- if (!read) throw new Error("workspace-export: this sandbox client cannot read files");
1639
+ const reading = /* @__PURE__ */ new Set();
1567
1640
  try {
1641
+ const read = opened.box.fs.read;
1642
+ if (!read) throw new Error("workspace-export: this sandbox client cannot read files");
1568
1643
  for (const file of listed) {
1569
- const text = await read.call(opened.box.fs, file.boxPath);
1570
- yield { path: file.path, open: async () => text };
1644
+ yield {
1645
+ path: file.path,
1646
+ async open() {
1647
+ const pending = read.call(opened.box.fs, file.boxPath);
1648
+ reading.add(pending);
1649
+ try {
1650
+ return await pending;
1651
+ } finally {
1652
+ reading.delete(pending);
1653
+ }
1654
+ }
1655
+ };
1571
1656
  }
1572
1657
  } finally {
1658
+ await Promise.allSettled(reading);
1573
1659
  await opened.restore();
1574
1660
  }
1575
1661
  }