@lightblues/jig 0.0.9 → 0.0.11

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/README.md CHANGED
@@ -9,5 +9,6 @@ Planned parts (design: baton `.ea/log/2026-11-24-shared-agent-ui.md`, item #274)
9
9
  | `@lightblues/jig/agent-paseo` | server adapter: a Paseo agent's timeline as AG-UI events, with replay and recovery |
10
10
  | `@lightblues/jig/agent-pi` | server runtime for in-app pi agents: router models with tiers, sessions and runs in the host's own Postgres tables, one run as AG-UI events (run registry and SSE route: next) |
11
11
  | `@lightblues/jig/agent-chat` | a thin headless client: follow a thread over SSE, reconnect, fold events into messages |
12
+ | `@lightblues/jig/markdown` | one markdown-it config for server and client: CJK, KaTeX, highlighting, safe for innerHTML, streaming-aware |
12
13
 
13
14
  The protocol is AG-UI (`@ag-ui/core`), used as is.
@@ -1,5 +1,10 @@
1
1
  import type { BaseEvent } from "@ag-ui/core";
2
2
  import { type ThreadState } from "./reduce.ts";
3
+ /**
4
+ * How often `onState` may fire: `false` (default) after every event; `"frame"` at most once per animation frame
5
+ * (`requestAnimationFrame` when the platform has it, else every 16 ms); a number: at most once per that many ms.
6
+ */
7
+ export type Batch = "frame" | number | false;
3
8
  export interface FollowOptions {
4
9
  /** `fetch` to use (cookies, auth headers, expo/fetch on React Native). Default: the global `fetch`. */
5
10
  fetch?: (url: string, init: {
@@ -11,8 +16,15 @@ export interface FollowOptions {
11
16
  headers?: Record<string, string>;
12
17
  /** Default `same-origin`; ignored by fetches that do not know it. */
13
18
  credentials?: "include" | "same-origin" | "omit";
14
- /** Each new state (after every event and every connect / drop). */
19
+ /** Each new state (after every event and every connect / drop; with `batch`, at most once per frame). */
15
20
  onState?: (state: ThreadState) => void;
21
+ /**
22
+ * Coalesce `onState`: events still fold one by one and `onEvent` still fires per event, but `onState` gets only
23
+ * the latest state, at most once per frame (`"frame"`) or per `n` ms. `RUN_FINISHED`, `RUN_ERROR`, `READY` and
24
+ * connect / drop deliver at once (with everything before them). Nothing is delivered after `close()`. Default
25
+ * `false`: every state, as before.
26
+ */
27
+ batch?: Batch;
16
28
  /** Each event, after it was folded (for a host's own side effects: refetch on `RUN_FINISHED`, a toast on `RUN_ERROR`). */
17
29
  onEvent?: (event: BaseEvent, state: ThreadState) => void;
18
30
  /** Stops following: aborts the request and any pending retry. */
@@ -1,5 +1,8 @@
1
1
  import { initialState, reduce } from "./reduce.js";
2
2
  import { readSse } from "./sse.js";
3
+ /** Events whose state is delivered at once when batching: the run's end, and the resync. */
4
+ const TERMINAL = new Set(["RUN_FINISHED", "RUN_ERROR"]);
5
+ const isFlushing = (e) => TERMINAL.has(e.type) || (e.type === "CUSTOM" && e.name === "READY");
3
6
  /**
4
7
  * Follows a thread's SSE stream: connects, folds every event with `reduce`, and reconnects with backoff when the
5
8
  * response fails or the stream ends or stalls. The server sends `READY` (+ `RUN_STARTED` and a replay of a run in
@@ -17,13 +20,51 @@ export function followThread(url, o = {}) {
17
20
  let wake = null;
18
21
  /** `reconnect()` asked for the next connection at once. */
19
22
  let skip = false;
20
- const set = (s) => {
21
- if (s === state || stop.signal.aborted)
23
+ const batch = o.batch ?? false;
24
+ /** A state not yet given to `onState`, and how its delivery is scheduled. */
25
+ let pending = false;
26
+ let cancelFlush = null;
27
+ const deliver = () => {
28
+ cancelFlush?.();
29
+ cancelFlush = null;
30
+ if (!pending || stop.signal.aborted)
22
31
  return;
32
+ pending = false;
33
+ o.onState?.(state);
34
+ };
35
+ const schedule = () => {
36
+ if (cancelFlush)
37
+ return;
38
+ const raf = globalThis.requestAnimationFrame;
39
+ if (batch === "frame" && typeof raf === "function") {
40
+ const h = raf(() => ((cancelFlush = null), deliver()));
41
+ cancelFlush = () => globalThis.cancelAnimationFrame?.(h);
42
+ }
43
+ else {
44
+ const t = setTimeout(() => ((cancelFlush = null), deliver()), batch === "frame" ? 16 : Math.max(0, Number(batch)));
45
+ cancelFlush = () => clearTimeout(t);
46
+ }
47
+ };
48
+ /** Sets the state; `now` delivers it (and any pending one) at once even when batching. */
49
+ const set = (s, now = false) => {
50
+ if (s === state || stop.signal.aborted) {
51
+ if (now && pending)
52
+ deliver();
53
+ return;
54
+ }
23
55
  state = s;
24
- o.onState?.(s);
56
+ if (batch === false)
57
+ return void o.onState?.(s);
58
+ pending = true;
59
+ if (now)
60
+ deliver();
61
+ else
62
+ schedule();
25
63
  };
26
64
  const close = () => {
65
+ cancelFlush?.();
66
+ cancelFlush = null;
67
+ pending = false;
27
68
  stop.abort();
28
69
  current?.abort();
29
70
  wake?.();
@@ -71,7 +112,7 @@ export function followThread(url, o = {}) {
71
112
  void res.body.cancel().catch(() => { });
72
113
  return false;
73
114
  }
74
- set({ ...state, connected: true });
115
+ set({ ...state, connected: true }, true);
75
116
  for await (const e of readSse({ body: tap(res.body, poke) })) {
76
117
  if (stop.signal.aborted || ctl.signal.aborted)
77
118
  break;
@@ -79,7 +120,7 @@ export function followThread(url, o = {}) {
79
120
  // once is retried with growing delays, not every `baseMs`.
80
121
  ok = true;
81
122
  const next = reduce(state, e);
82
- set(next);
123
+ set(next, isFlushing(e));
83
124
  if (!stop.signal.aborted)
84
125
  o.onEvent?.(e, state);
85
126
  }
@@ -92,7 +133,7 @@ export function followThread(url, o = {}) {
92
133
  if (current === ctl)
93
134
  current = null;
94
135
  if (state.connected)
95
- set({ ...state, connected: false });
136
+ set({ ...state, connected: false }, true);
96
137
  }
97
138
  return ok;
98
139
  };
@@ -1,12 +1,16 @@
1
1
  /**
2
2
  * `@lightblues/jig/agent-chat`: a headless client that follows a thread's AG-UI event stream (agent-paseo's runner and
3
- * follower, agent-pi) over SSE and folds it into `{ messages, live, error, connected }`. No UI, no Markdown, no store:
4
- * the host renders. Browser-safe: no `node:` imports, no runtime dependency (`@ag-ui/core` for types only).
3
+ * follower, agent-pi) over SSE and folds it into `{ messages, live, error, connected }`. No UI, no Markdown renderer,
4
+ * no store: the host renders. Browser-safe: no `node:` imports, no runtime dependency (`@ag-ui/core` for types only).
5
5
  * React bindings: `@lightblues/jig/agent-chat/react`. See `.ea/docs/agent-chat.md`.
6
6
  */
7
7
  export { readSse } from "./sse.ts";
8
8
  export type { SseSource } from "./sse.ts";
9
9
  export { initialState, reduce, runMessages, toolLine, toolViews } from "./reduce.ts";
10
- export type { LiveActivity, LivePart, LiveRun, LiveTool, RunEnd, ThreadState } from "./reduce.ts";
10
+ export type { LiveActivity, LivePart, LiveRun, LiveTool, PartTimes, RunEnd, RunTiming, ThreadState } from "./reduce.ts";
11
+ export { timeline } from "./timeline.ts";
12
+ export type { GroupThought, TimelineItem } from "./timeline.ts";
13
+ export { closeOpenMarkdown } from "./markdown.ts";
14
+ export type { CloseOpenMarkdownOptions } from "./markdown.ts";
11
15
  export { followThread } from "./follow.ts";
12
- export type { Follow, FollowOptions } from "./follow.ts";
16
+ export type { Batch, Follow, FollowOptions } from "./follow.ts";
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * `@lightblues/jig/agent-chat`: a headless client that follows a thread's AG-UI event stream (agent-paseo's runner and
3
- * follower, agent-pi) over SSE and folds it into `{ messages, live, error, connected }`. No UI, no Markdown, no store:
4
- * the host renders. Browser-safe: no `node:` imports, no runtime dependency (`@ag-ui/core` for types only).
3
+ * follower, agent-pi) over SSE and folds it into `{ messages, live, error, connected }`. No UI, no Markdown renderer,
4
+ * no store: the host renders. Browser-safe: no `node:` imports, no runtime dependency (`@ag-ui/core` for types only).
5
5
  * React bindings: `@lightblues/jig/agent-chat/react`. See `.ea/docs/agent-chat.md`.
6
6
  */
7
7
  export { readSse } from "./sse.js";
8
8
  export { initialState, reduce, runMessages, toolLine, toolViews } from "./reduce.js";
9
+ export { timeline } from "./timeline.js";
10
+ export { closeOpenMarkdown } from "./markdown.js";
9
11
  export { followThread } from "./follow.js";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `closeOpenMarkdown`: closes, for display only, what a partial (streaming) Markdown answer has left open, so it
3
+ * renders as it will once complete instead of flashing as raw markup. Dependency-free; shared with jig's Markdown
4
+ * renderer (`@lightblues/jig/markdown`, markdown-it + markdown-it-texmath with `dollars` delimiters), whose rules
5
+ * the math handling follows.
6
+ */
7
+ export interface CloseOpenMarkdownOptions {
8
+ /**
9
+ * Removed from the end of the text before anything is closed: a host's half-written marker (lemma:
10
+ * `/\[\[quiz:[^\]]*\]?$/`). Matched only where it ends at the end of the text; a `g`, `y` or `m` flag is ignored.
11
+ */
12
+ strip?: RegExp;
13
+ }
14
+ /**
15
+ * Returns `text` with what is left open at its end closed: a code fence (closed on a new line with the same fence),
16
+ * an inline code span, display math `$$`, inline math `$`, and `**`. Nothing inside a closed fence or a code span
17
+ * is read. Math follows markdown-it-texmath's `dollars` rules: a `$` after a digit or a backslash, or before a space,
18
+ * opens nothing, and an inline `$` closes only on its own line, so `$5 and $6` is prose. An inline `$` left open
19
+ * before a digit (`costs $5`) is read as money and left alone. A closer is never placed where the renderer would not
20
+ * read it (after a space or a backslash); an opener with nothing after it yet is dropped instead.
21
+ */
22
+ export declare function closeOpenMarkdown(text: string, o?: CloseOpenMarkdownOptions): string;
@@ -0,0 +1,186 @@
1
+ /**
2
+ * `closeOpenMarkdown`: closes, for display only, what a partial (streaming) Markdown answer has left open, so it
3
+ * renders as it will once complete instead of flashing as raw markup. Dependency-free; shared with jig's Markdown
4
+ * renderer (`@lightblues/jig/markdown`, markdown-it + markdown-it-texmath with `dollars` delimiters), whose rules
5
+ * the math handling follows.
6
+ */
7
+ const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
8
+ const INLINE_MATH = /\$((?:[^\s\\])|(?:\S.*?[^\s\\]))\$/y;
9
+ /**
10
+ * Returns `text` with what is left open at its end closed: a code fence (closed on a new line with the same fence),
11
+ * an inline code span, display math `$$`, inline math `$`, and `**`. Nothing inside a closed fence or a code span
12
+ * is read. Math follows markdown-it-texmath's `dollars` rules: a `$` after a digit or a backslash, or before a space,
13
+ * opens nothing, and an inline `$` closes only on its own line, so `$5 and $6` is prose. An inline `$` left open
14
+ * before a digit (`costs $5`) is read as money and left alone. A closer is never placed where the renderer would not
15
+ * read it (after a space or a backslash); an opener with nothing after it yet is dropped instead.
16
+ */
17
+ export function closeOpenMarkdown(text, o = {}) {
18
+ if (o.strip) {
19
+ const tail = new RegExp(`(?:${o.strip.source})$`, o.strip.flags.replace(/[gym]/g, ""));
20
+ const m = tail.exec(text);
21
+ if (m)
22
+ text = text.slice(0, m.index);
23
+ }
24
+ // Fences and display math blocks, line by line.
25
+ const lines = text.split("\n");
26
+ let fence = null;
27
+ /** Where the text outside fences starts: inline scanning only looks at text after the last fence. */
28
+ let from = 0;
29
+ let pos = 0;
30
+ for (const line of lines) {
31
+ const m = FENCE.exec(line);
32
+ if (fence) {
33
+ if (m && m[1][0] === fence.char && m[1].length >= fence.len && !m[2].trim()) {
34
+ fence = null;
35
+ from = pos + line.length + 1;
36
+ }
37
+ }
38
+ else if (m && !(m[1][0] === "`" && m[2].includes("`")) && !inDisplayMath(text.slice(from, pos))) {
39
+ fence = { char: m[1][0], len: m[1].length };
40
+ }
41
+ pos += line.length + 1;
42
+ }
43
+ if (fence)
44
+ return text + (text.endsWith("\n") ? "" : "\n") + fence.char.repeat(fence.len);
45
+ const open = scan(text, from);
46
+ if (!open.length)
47
+ return text;
48
+ let out = text;
49
+ // Close innermost first.
50
+ for (const x of open.reverse())
51
+ out = close(out, x);
52
+ return out;
53
+ }
54
+ /** Whether the inline text has a `$$` left open (a fence inside display math is math). */
55
+ function inDisplayMath(s) {
56
+ return scan(s, 0).some((x) => x.kind === "math2");
57
+ }
58
+ /** What is open at the end of `text`, scanning from `from` (outside any fence), outermost first. */
59
+ function scan(text, from) {
60
+ const open = [];
61
+ let bold = null;
62
+ let i = from;
63
+ const n = text.length;
64
+ while (i < n) {
65
+ const c = text[i];
66
+ if (c === "\\") {
67
+ i += 2;
68
+ continue;
69
+ }
70
+ if (c === "\n") {
71
+ // A blank line ends the paragraph: emphasis and code spans do not cross it.
72
+ if (text[i + 1] === "\n" || (text[i + 1] === "\r" && text[i + 2] === "\n"))
73
+ bold = null;
74
+ i++;
75
+ continue;
76
+ }
77
+ if (c === "`") {
78
+ let j = i;
79
+ while (text[j] === "`")
80
+ j++;
81
+ const ticks = text.slice(i, j);
82
+ const end = closingTicks(text, j, ticks);
83
+ if (end < 0) {
84
+ if (paragraphEnd(text, j) < n) {
85
+ i = j;
86
+ continue;
87
+ }
88
+ return [...withBold(open, bold), { kind: "code", ticks }];
89
+ }
90
+ i = end + ticks.length;
91
+ continue;
92
+ }
93
+ if (c === "$") {
94
+ const prev = i > 0 ? text[i - 1] : "";
95
+ const preOk = prev !== "\\" && !(prev >= "0" && prev <= "9");
96
+ if (text[i + 1] === "$") {
97
+ if (!preOk) {
98
+ i += 2;
99
+ continue;
100
+ }
101
+ const end = text.indexOf("$$", i + 2);
102
+ if (end < 0) {
103
+ const lineStart = i === 0 || text[i - 1] === "\n";
104
+ return [...withBold(open, bold), { kind: "math2", at: i, block: lineStart }];
105
+ }
106
+ i = end + 2;
107
+ continue;
108
+ }
109
+ if (preOk) {
110
+ INLINE_MATH.lastIndex = i;
111
+ const m = INLINE_MATH.exec(text);
112
+ if (m) {
113
+ const nxt = text[INLINE_MATH.lastIndex] ?? "";
114
+ if (!(nxt >= "0" && nxt <= "9")) {
115
+ i = INLINE_MATH.lastIndex;
116
+ continue;
117
+ }
118
+ }
119
+ else if (!text.includes("\n", i) && /^\S/.test(text.slice(i + 1)) && !/^[0-9]/.test(text.slice(i + 1))) {
120
+ // Open on the last line, before something that is not a space or a digit.
121
+ return [...withBold(open, bold), { kind: "math1", at: i }];
122
+ }
123
+ }
124
+ i++;
125
+ continue;
126
+ }
127
+ if (c === "*" && text[i + 1] === "*") {
128
+ bold = bold === null ? i : null;
129
+ i += 2;
130
+ continue;
131
+ }
132
+ i++;
133
+ }
134
+ return withBold(open, bold);
135
+ }
136
+ const withBold = (open, bold) => (bold === null ? open : [...open, { kind: "bold", at: bold }]);
137
+ /** Index of a run of exactly `ticks` after `from` within the paragraph, or -1. */
138
+ function closingTicks(text, from, ticks) {
139
+ const stop = paragraphEnd(text, from);
140
+ let i = from;
141
+ while (i < stop) {
142
+ if (text[i] !== "`") {
143
+ i++;
144
+ continue;
145
+ }
146
+ let j = i;
147
+ while (text[j] === "`")
148
+ j++;
149
+ if (j - i === ticks.length)
150
+ return i;
151
+ i = j;
152
+ }
153
+ return -1;
154
+ }
155
+ function paragraphEnd(text, from) {
156
+ const m = /\n[ \t]*\r?\n/.exec(text.slice(from));
157
+ return m ? from + m.index : text.length;
158
+ }
159
+ function close(text, x) {
160
+ switch (x.kind) {
161
+ case "code":
162
+ return text + x.ticks;
163
+ case "bold": {
164
+ const body = text.slice(x.at + 2);
165
+ if (!body.trim())
166
+ return text.slice(0, x.at) + body;
167
+ const end = text.trimEnd();
168
+ return end + "**" + text.slice(end.length);
169
+ }
170
+ case "math2": {
171
+ const body = text.slice(x.at + 2);
172
+ if (!body.trim())
173
+ return text.slice(0, x.at) + body;
174
+ const end = trimBackslash(text);
175
+ return x.block ? end + (end.endsWith("\n") ? "" : "\n") + "$$" : end.trimEnd() + "$$";
176
+ }
177
+ case "math1": {
178
+ const end = trimBackslash(text.trimEnd());
179
+ if (end.length <= x.at + 1)
180
+ return text.slice(0, x.at);
181
+ return end.trimEnd() + "$";
182
+ }
183
+ }
184
+ }
185
+ /** A trailing lone backslash is half a command (`\frac` being typed): drop it so the closer is read. */
186
+ const trimBackslash = (s) => (/(^|[^\\])\\$/.test(s) ? s.slice(0, -1) : s);
@@ -21,6 +21,8 @@ export interface UseThreadOptions<TSend extends unknown[] = [string], TSent = un
21
21
  baseMs?: number;
22
22
  maxMs?: number;
23
23
  idleMs?: number;
24
+ /** `followThread`'s `batch`: `"frame"` re-renders at most once per animation frame while text streams. Read once per `streamUrl`. */
25
+ batch?: FollowOptions["batch"];
24
26
  }
25
27
  export interface UseThread<TSend extends unknown[], TSent> extends ThreadState {
26
28
  /** Calls the host's `send`; rejects as it does. */
@@ -34,7 +36,7 @@ export interface UseThread<TSend extends unknown[], TSent> extends ThreadState {
34
36
  }
35
37
  /** Follows one thread's stream while mounted; the state is `agent-chat`'s `ThreadState`. */
36
38
  export declare function useThread<TSend extends unknown[] = [string], TSent = unknown>(o: UseThreadOptions<TSend, TSent>): UseThread<TSend, TSent>;
37
- /** What `useStickToBottom` needs from the scroller (a DOM element). */
39
+ /** What `useStickToBottom` needs from the scroller (a DOM element, or `document.scrollingElement`). */
38
40
  interface Scroller {
39
41
  scrollTop: number;
40
42
  scrollHeight: number;
@@ -43,15 +45,36 @@ interface Scroller {
43
45
  passive?: boolean;
44
46
  }) => void;
45
47
  removeEventListener?: (type: "scroll", f: () => void) => void;
48
+ ownerDocument?: {
49
+ scrollingElement?: unknown;
50
+ defaultView?: unknown;
51
+ } | null;
46
52
  }
53
+ /** What `useStickToBottom` needs from a window: its scroll events, and its document's scrolling element. */
54
+ interface WindowLike {
55
+ document: {
56
+ scrollingElement?: Scroller | null;
57
+ documentElement?: Scroller | null;
58
+ };
59
+ addEventListener: (type: "scroll", f: () => void, o?: {
60
+ passive?: boolean;
61
+ }) => void;
62
+ removeEventListener: (type: "scroll", f: () => void) => void;
63
+ }
64
+ /** The scroller of `useStickToBottom`: an element, the window, or a ref to the window or the document's scrolling element. */
65
+ export type StickTarget = RefObject<Scroller | WindowLike | null> | "window";
47
66
  /**
48
67
  * Keeps a scroller at its end while content grows, unless the reader scrolled up (more than `slack` px from the end).
49
- * `deps` are what grows (`[messages.length, live?.text.length, live?.tools.length]`). Returns `pinned` (a ref, no
50
- * re-render on scroll) and `toBottom()` to jump to the end and pin again (after the user sends). Without a DOM
51
- * element (React Native: use `ScrollView.onContentSizeChange` instead) it does nothing.
68
+ * `deps` are what grows (`[messages.length, live?.text.length, live?.tools.length]`). The scroller is an element ref,
69
+ * `"window"` (the page scrolls: a phone layout), or a ref to `window` / `document.scrollingElement`. Returns
70
+ * `pinned` (a ref, no re-render on scroll), `below` (state: content arrived under the fold while the reader was
71
+ * scrolled up; cleared when they scroll back to the end or call `toBottom()`), for a "new messages ↓" button, and
72
+ * `toBottom()` to jump to the end and pin again (after the user sends). Without a DOM (React Native: use
73
+ * `ScrollView.onContentSizeChange` instead) it does nothing.
52
74
  */
53
- export declare function useStickToBottom(ref: RefObject<Scroller | null>, deps: readonly unknown[], slack?: number): {
75
+ export declare function useStickToBottom(ref: StickTarget, deps: readonly unknown[], slack?: number): {
54
76
  pinned: RefObject<boolean>;
77
+ below: boolean;
55
78
  toBottom: () => void;
56
79
  };
57
80
  export {};
@@ -26,6 +26,7 @@ export function useThread(o) {
26
26
  baseMs: opts.current.baseMs,
27
27
  maxMs: opts.current.maxMs,
28
28
  idleMs: opts.current.idleMs,
29
+ batch: opts.current.batch,
29
30
  onState: setState,
30
31
  onEvent: (e, s) => opts.current.onEvent?.(e, s),
31
32
  });
@@ -56,35 +57,62 @@ export function useThread(o) {
56
57
  }
57
58
  /** `useLayoutEffect` where there is a DOM (no flash of the old scroll position), `useEffect` elsewhere (SSR, React Native). */
58
59
  const useLayout = typeof document === "undefined" ? useEffect : useLayoutEffect;
60
+ /** What to read and write (`el`) and where scroll events come from (`on`); null without a DOM. */
61
+ function resolve(target) {
62
+ const cur = target === "window" ? (typeof window === "undefined" ? null : window) : target.current;
63
+ if (!cur)
64
+ return null;
65
+ if ("document" in cur && typeof cur.addEventListener === "function") {
66
+ const el = cur.document.scrollingElement ?? cur.document.documentElement;
67
+ return el ? { el, on: cur } : null;
68
+ }
69
+ const el = cur;
70
+ if (!el.addEventListener)
71
+ return null;
72
+ // The page's scrolling element scrolls with the window: its scroll events fire on the window, not on it.
73
+ const view = el.ownerDocument?.scrollingElement === el ? el.ownerDocument.defaultView : null;
74
+ return { el, on: view && typeof view.addEventListener === "function" ? view : el };
75
+ }
59
76
  /**
60
77
  * Keeps a scroller at its end while content grows, unless the reader scrolled up (more than `slack` px from the end).
61
- * `deps` are what grows (`[messages.length, live?.text.length, live?.tools.length]`). Returns `pinned` (a ref, no
62
- * re-render on scroll) and `toBottom()` to jump to the end and pin again (after the user sends). Without a DOM
63
- * element (React Native: use `ScrollView.onContentSizeChange` instead) it does nothing.
78
+ * `deps` are what grows (`[messages.length, live?.text.length, live?.tools.length]`). The scroller is an element ref,
79
+ * `"window"` (the page scrolls: a phone layout), or a ref to `window` / `document.scrollingElement`. Returns
80
+ * `pinned` (a ref, no re-render on scroll), `below` (state: content arrived under the fold while the reader was
81
+ * scrolled up; cleared when they scroll back to the end or call `toBottom()`), for a "new messages ↓" button, and
82
+ * `toBottom()` to jump to the end and pin again (after the user sends). Without a DOM (React Native: use
83
+ * `ScrollView.onContentSizeChange` instead) it does nothing.
64
84
  */
65
85
  export function useStickToBottom(ref, deps, slack = 80) {
66
86
  const pinned = useRef(true);
87
+ const [below, setBelow] = useState(false);
67
88
  useEffect(() => {
68
- const el = ref.current;
69
- if (!el?.addEventListener)
89
+ const r = resolve(ref);
90
+ if (!r)
70
91
  return;
71
- const on = () => {
92
+ const { el, on } = r;
93
+ const f = () => {
72
94
  pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < slack;
95
+ if (pinned.current)
96
+ setBelow(false);
73
97
  };
74
- el.addEventListener("scroll", on, { passive: true });
75
- return () => el.removeEventListener?.("scroll", on);
98
+ on.addEventListener("scroll", f, { passive: true });
99
+ return () => on.removeEventListener("scroll", f);
76
100
  }, [ref, slack]);
77
101
  useLayout(() => {
78
- const el = ref.current;
79
- if (!pinned.current || !el?.addEventListener)
102
+ const r = resolve(ref);
103
+ if (!r)
80
104
  return;
81
- el.scrollTop = el.scrollHeight;
105
+ if (pinned.current)
106
+ r.el.scrollTop = r.el.scrollHeight;
107
+ else if (r.el.scrollHeight - r.el.scrollTop - r.el.clientHeight >= slack)
108
+ setBelow(true);
82
109
  }, deps);
83
110
  const toBottom = useCallback(() => {
84
- const el = ref.current;
111
+ const r = resolve(ref);
85
112
  pinned.current = true;
86
- if (el?.addEventListener)
87
- el.scrollTop = el.scrollHeight;
113
+ setBelow(false);
114
+ if (r)
115
+ r.el.scrollTop = r.el.scrollHeight;
88
116
  }, [ref]);
89
- return { pinned, toBottom };
117
+ return { pinned, below, toBottom };
90
118
  }
@@ -17,22 +17,31 @@ export interface LiveActivity {
17
17
  activityType: string;
18
18
  content: Record<string, unknown>;
19
19
  }
20
+ /**
21
+ * When a part was seen (ms since the epoch): the event's `timestamp` when the server set one, else the client's
22
+ * clock when the reducer folded it. `endedAt` is null while the part is open: a text or reasoning part ends at its
23
+ * `…_END` or when the next part starts, a tool at its `TOOL_CALL_END`, a card at once.
24
+ */
25
+ export interface PartTimes {
26
+ startedAt: number;
27
+ endedAt: number | null;
28
+ }
20
29
  /** The run's parts in the order they came, for hosts that interleave text and tools. */
21
- export type LivePart = {
30
+ export type LivePart = ({
22
31
  kind: "text";
23
32
  id: string;
24
33
  text: string;
25
- } | {
34
+ } & PartTimes) | ({
26
35
  kind: "reasoning";
27
36
  id: string;
28
37
  text: string;
29
- } | {
38
+ } & PartTimes) | ({
30
39
  kind: "tool";
31
40
  id: string;
32
- } | {
41
+ } & PartTimes) | ({
33
42
  kind: "activity";
34
43
  id: string;
35
- };
44
+ } & PartTimes);
36
45
  /** The run in progress. */
37
46
  export interface LiveRun {
38
47
  runId: string;
@@ -51,6 +60,17 @@ export interface LiveRun {
51
60
  tools: LiveTool[];
52
61
  activities: LiveActivity[];
53
62
  parts: LivePart[];
63
+ /** When `RUN_STARTED` was seen (as `PartTimes`). */
64
+ startedAt: number;
65
+ }
66
+ /**
67
+ * How long a run took, as the server measured it from the run's start (`metadata.timing` of `RUN_FINISHED` /
68
+ * `RUN_ERROR`). `ttfbMs`: to the first text or reasoning delta (null when none came). Absent on a run the server
69
+ * did not see start (a recovered or replayed one).
70
+ */
71
+ export interface RunTiming {
72
+ ttfbMs: number | null;
73
+ durationMs: number;
54
74
  }
55
75
  /** How the last run ended. `unknown`: it ended while the stream was down (`READY {running:false}` replaced it); refetch. */
56
76
  export interface RunEnd {
@@ -59,6 +79,8 @@ export interface RunEnd {
59
79
  /** `RUN_FINISHED.result` (agent-paseo's runner: what the host's `saveAnswer` returned). */
60
80
  result?: unknown;
61
81
  error?: string;
82
+ /** `metadata.timing` of the end event, when the server measured it. */
83
+ timing?: RunTiming;
62
84
  }
63
85
  export interface ThreadState {
64
86
  /**
@@ -78,7 +100,8 @@ export interface ThreadState {
78
100
  }
79
101
  export declare const initialState: ThreadState;
80
102
  /**
81
- * Folds one AG-UI event into the thread state, without changing `state`. Follows the follower contract of
103
+ * Folds one AG-UI event into the thread state, without changing `state`. Parts are stamped with the event's
104
+ * `timestamp`, or the clock when it has none (`PartTimes`). Follows the follower contract of
82
105
  * agent-paseo and agent-pi: `CUSTOM READY` drops the run being drawn (the stream resyncs: `RUN_STARTED` and a replay
83
106
  * follow when one is running), so a reconnect or a server-side gap never duplicates text. Unknown events return
84
107
  * `state` unchanged.