@lightblues/jig 0.0.5 → 0.0.7

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,44 @@
1
+ import type { BaseEvent } from "@ag-ui/core";
2
+ import { type ThreadState } from "./reduce.ts";
3
+ export interface FollowOptions {
4
+ /** `fetch` to use (cookies, auth headers, expo/fetch on React Native). Default: the global `fetch`. */
5
+ fetch?: (url: string, init: {
6
+ signal: AbortSignal;
7
+ headers: Record<string, string>;
8
+ credentials?: "include" | "same-origin" | "omit";
9
+ }) => Promise<Response>;
10
+ /** Extra request headers (`accept: text/event-stream` is always sent). */
11
+ headers?: Record<string, string>;
12
+ /** Default `same-origin`; ignored by fetches that do not know it. */
13
+ credentials?: "include" | "same-origin" | "omit";
14
+ /** Each new state (after every event and every connect / drop). */
15
+ onState?: (state: ThreadState) => void;
16
+ /** Each event, after it was folded (for a host's own side effects: refetch on `RUN_FINISHED`, a toast on `RUN_ERROR`). */
17
+ onEvent?: (event: BaseEvent, state: ThreadState) => void;
18
+ /** Stops following: aborts the request and any pending retry. */
19
+ signal?: AbortSignal;
20
+ /** Backoff after a failed or dropped connection: `min(baseMs * 2^n, maxMs)`, n reset on each successful connect. Defaults 1000 / 15000. */
21
+ baseMs?: number;
22
+ maxMs?: number;
23
+ /** A connection that delivered nothing for this long is dropped and reopened (hosts send a ping comment every 15 s; set above that). Default 45000; 0 turns it off. */
24
+ idleMs?: number;
25
+ /** Starting state (default `initialState`). */
26
+ state?: ThreadState;
27
+ }
28
+ export interface Follow {
29
+ /** The current state. */
30
+ readonly state: ThreadState;
31
+ /** Stops following (same as aborting `signal`). */
32
+ close(): void;
33
+ /** Drops the connection and reconnects now, without waiting for the backoff (a host's "retry" after its own POST, or `online`). */
34
+ reconnect(): void;
35
+ /** Resolves when following has stopped. */
36
+ done: Promise<void>;
37
+ }
38
+ /**
39
+ * Follows a thread's SSE stream: connects, folds every event with `reduce`, and reconnects with backoff when the
40
+ * response fails or the stream ends or stalls. The server sends `READY` (+ `RUN_STARTED` and a replay of a run in
41
+ * progress) on each connect, which resets the live run, so a reconnect never duplicates text: no event id or
42
+ * client-side dedupe is involved. The state's `connected` turns false on a drop and true on the next response.
43
+ */
44
+ export declare function followThread(url: string, o?: FollowOptions): Follow;
@@ -0,0 +1,146 @@
1
+ import { initialState, reduce } from "./reduce.js";
2
+ import { readSse } from "./sse.js";
3
+ /**
4
+ * Follows a thread's SSE stream: connects, folds every event with `reduce`, and reconnects with backoff when the
5
+ * response fails or the stream ends or stalls. The server sends `READY` (+ `RUN_STARTED` and a replay of a run in
6
+ * progress) on each connect, which resets the live run, so a reconnect never duplicates text: no event id or
7
+ * client-side dedupe is involved. The state's `connected` turns false on a drop and true on the next response.
8
+ */
9
+ export function followThread(url, o = {}) {
10
+ const doFetch = o.fetch ?? ((u, init) => fetch(u, init));
11
+ const base = o.baseMs ?? 1000;
12
+ const max = o.maxMs ?? 15_000;
13
+ const idleMs = o.idleMs ?? 45_000;
14
+ const stop = new AbortController();
15
+ let state = o.state ?? initialState;
16
+ let current = null;
17
+ let wake = null;
18
+ /** `reconnect()` asked for the next connection at once. */
19
+ let skip = false;
20
+ const set = (s) => {
21
+ if (s === state || stop.signal.aborted)
22
+ return;
23
+ state = s;
24
+ o.onState?.(s);
25
+ };
26
+ const close = () => {
27
+ stop.abort();
28
+ current?.abort();
29
+ wake?.();
30
+ };
31
+ if (o.signal?.aborted)
32
+ close();
33
+ else
34
+ o.signal?.addEventListener("abort", close, { once: true });
35
+ /** Waits `ms`, or less when closed or `reconnect()` is called. */
36
+ const wait = (ms) => new Promise((resolve) => {
37
+ if (stop.signal.aborted)
38
+ return resolve();
39
+ const t = setTimeout(done, ms);
40
+ function done() {
41
+ clearTimeout(t);
42
+ wake = null;
43
+ resolve();
44
+ }
45
+ wake = done;
46
+ });
47
+ const once = async () => {
48
+ const ctl = new AbortController();
49
+ current = ctl;
50
+ let idle;
51
+ const poke = () => {
52
+ if (!idleMs)
53
+ return;
54
+ clearTimeout(idle);
55
+ idle = setTimeout(() => ctl.abort(), idleMs);
56
+ };
57
+ let ok = false;
58
+ try {
59
+ poke();
60
+ const res = await doFetch(url, {
61
+ signal: ctl.signal,
62
+ headers: { accept: "text/event-stream", ...o.headers },
63
+ ...(o.credentials !== undefined ? { credentials: o.credentials } : { credentials: "same-origin" }),
64
+ });
65
+ if (!res.ok || !res.body) {
66
+ void res.body?.cancel().catch(() => { });
67
+ return false;
68
+ }
69
+ if (stop.signal.aborted || ctl.signal.aborted) {
70
+ // A fetch that ignored the abort: release the body it handed back.
71
+ void res.body.cancel().catch(() => { });
72
+ return false;
73
+ }
74
+ set({ ...state, connected: true });
75
+ for await (const e of readSse({ body: tap(res.body, poke) })) {
76
+ if (stop.signal.aborted || ctl.signal.aborted)
77
+ break;
78
+ // Only a connection that delivered an event resets the backoff: a server that answers 200 and closes at
79
+ // once is retried with growing delays, not every `baseMs`.
80
+ ok = true;
81
+ const next = reduce(state, e);
82
+ set(next);
83
+ if (!stop.signal.aborted)
84
+ o.onEvent?.(e, state);
85
+ }
86
+ }
87
+ catch {
88
+ // A network error, an abort (close, reconnect, idle): all mean "reconnect unless closed".
89
+ }
90
+ finally {
91
+ clearTimeout(idle);
92
+ if (current === ctl)
93
+ current = null;
94
+ if (state.connected)
95
+ set({ ...state, connected: false });
96
+ }
97
+ return ok;
98
+ };
99
+ const done = (async () => {
100
+ let attempt = 0;
101
+ while (!stop.signal.aborted) {
102
+ const ok = await once();
103
+ if (stop.signal.aborted)
104
+ break;
105
+ if (ok)
106
+ attempt = 0;
107
+ if (!skip) {
108
+ await wait(Math.min(base * 2 ** attempt, max));
109
+ attempt++;
110
+ }
111
+ skip = false;
112
+ }
113
+ o.signal?.removeEventListener("abort", close);
114
+ })();
115
+ return {
116
+ get state() {
117
+ return state;
118
+ },
119
+ close,
120
+ reconnect() {
121
+ if (stop.signal.aborted)
122
+ return;
123
+ // Whichever phase this lands in (request, stream, between the two, backoff), the next connection starts at once.
124
+ skip = true;
125
+ current?.abort();
126
+ wake?.();
127
+ },
128
+ done,
129
+ };
130
+ }
131
+ /** Calls `f` on every chunk, so a stalled stream can be told apart from a quiet one. */
132
+ function tap(body, f) {
133
+ const reader = body.getReader();
134
+ return new ReadableStream({
135
+ async pull(c) {
136
+ const { value, done } = await reader.read();
137
+ if (done)
138
+ return c.close();
139
+ f();
140
+ c.enqueue(value);
141
+ },
142
+ cancel(why) {
143
+ return reader.cancel(why);
144
+ },
145
+ });
146
+ }
@@ -0,0 +1,12 @@
1
+ /**
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).
5
+ * React bindings: `@lightblues/jig/agent-chat/react`. See `.ea/docs/agent-chat.md`.
6
+ */
7
+ export { readSse } from "./sse.ts";
8
+ export type { SseSource } from "./sse.ts";
9
+ export { initialState, reduce, runMessages, toolLine, toolViews } from "./reduce.ts";
10
+ export type { LiveActivity, LivePart, LiveRun, LiveTool, RunEnd, ThreadState } from "./reduce.ts";
11
+ export { followThread } from "./follow.ts";
12
+ export type { Follow, FollowOptions } from "./follow.ts";
@@ -0,0 +1,9 @@
1
+ /**
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).
5
+ * React bindings: `@lightblues/jig/agent-chat/react`. See `.ea/docs/agent-chat.md`.
6
+ */
7
+ export { readSse } from "./sse.js";
8
+ export { initialState, reduce, runMessages, toolLine, toolViews } from "./reduce.js";
9
+ export { followThread } from "./follow.js";
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `@lightblues/jig/agent-chat/react`: React bindings for `agent-chat`. They render nothing, so they work in React DOM
3
+ * and React Native; `useStickToBottom` needs a DOM element and does nothing without one.
4
+ */
5
+ import { type RefObject } from "react";
6
+ import type { BaseEvent } from "@ag-ui/core";
7
+ import { type FollowOptions } from "./follow.ts";
8
+ import { type ThreadState } from "./reduce.ts";
9
+ export interface UseThreadOptions<TSend extends unknown[] = [string], TSent = unknown> {
10
+ /** The thread's SSE route; `null` follows nothing (no thread yet). A new URL starts over from `initialState`. */
11
+ streamUrl: string | null;
12
+ /** The host's "post a message" call. `useThread` only wraps it to track `sending`. */
13
+ send?: (...args: TSend) => Promise<TSent>;
14
+ /** The host's "stop the run" call. */
15
+ stop?: () => Promise<unknown>;
16
+ /** Each folded event: refetch the host's thread on `RUN_FINISHED` / `RUN_ERROR` / `READY`, for example. */
17
+ onEvent?: (event: BaseEvent, state: ThreadState) => void;
18
+ fetch?: FollowOptions["fetch"];
19
+ headers?: Record<string, string>;
20
+ credentials?: FollowOptions["credentials"];
21
+ baseMs?: number;
22
+ maxMs?: number;
23
+ idleMs?: number;
24
+ }
25
+ export interface UseThread<TSend extends unknown[], TSent> extends ThreadState {
26
+ /** Calls the host's `send`; rejects as it does. */
27
+ send: (...args: TSend) => Promise<TSent>;
28
+ /** Calls the host's `stop`. */
29
+ stop: () => Promise<void>;
30
+ /** A `send` is in flight. */
31
+ sending: boolean;
32
+ /** Reconnect now (after the host's own retry, or when the app comes back to the foreground). */
33
+ reconnect: () => void;
34
+ }
35
+ /** Follows one thread's stream while mounted; the state is `agent-chat`'s `ThreadState`. */
36
+ 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). */
38
+ interface Scroller {
39
+ scrollTop: number;
40
+ scrollHeight: number;
41
+ clientHeight: number;
42
+ addEventListener?: (type: "scroll", f: () => void, o?: {
43
+ passive?: boolean;
44
+ }) => void;
45
+ removeEventListener?: (type: "scroll", f: () => void) => void;
46
+ }
47
+ /**
48
+ * 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.
52
+ */
53
+ export declare function useStickToBottom(ref: RefObject<Scroller | null>, deps: readonly unknown[], slack?: number): {
54
+ pinned: RefObject<boolean>;
55
+ toBottom: () => void;
56
+ };
57
+ export {};
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `@lightblues/jig/agent-chat/react`: React bindings for `agent-chat`. They render nothing, so they work in React DOM
3
+ * and React Native; `useStickToBottom` needs a DOM element and does nothing without one.
4
+ */
5
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
6
+ import { followThread } from "./follow.js";
7
+ import { initialState } from "./reduce.js";
8
+ /** Follows one thread's stream while mounted; the state is `agent-chat`'s `ThreadState`. */
9
+ export function useThread(o) {
10
+ const [state, setState] = useState(initialState);
11
+ const [sending, setSending] = useState(0);
12
+ const opts = useRef(o);
13
+ opts.current = o;
14
+ const follow = useRef(null);
15
+ const { streamUrl } = o;
16
+ useEffect(() => {
17
+ setState(initialState);
18
+ if (streamUrl === null)
19
+ return;
20
+ const ctl = new AbortController();
21
+ const f = followThread(streamUrl, {
22
+ signal: ctl.signal,
23
+ fetch: opts.current.fetch,
24
+ headers: opts.current.headers,
25
+ credentials: opts.current.credentials,
26
+ baseMs: opts.current.baseMs,
27
+ maxMs: opts.current.maxMs,
28
+ idleMs: opts.current.idleMs,
29
+ onState: setState,
30
+ onEvent: (e, s) => opts.current.onEvent?.(e, s),
31
+ });
32
+ follow.current = f;
33
+ return () => {
34
+ ctl.abort();
35
+ if (follow.current === f)
36
+ follow.current = null;
37
+ };
38
+ }, [streamUrl]);
39
+ const send = useCallback(async (...args) => {
40
+ const f = opts.current.send;
41
+ if (!f)
42
+ throw new Error("useThread: no send");
43
+ setSending((n) => n + 1);
44
+ try {
45
+ return await f(...args);
46
+ }
47
+ finally {
48
+ setSending((n) => n - 1);
49
+ }
50
+ }, []);
51
+ const stop = useCallback(async () => {
52
+ await opts.current.stop?.();
53
+ }, []);
54
+ const reconnect = useCallback(() => follow.current?.reconnect(), []);
55
+ return { ...state, send, stop, sending: sending > 0, reconnect };
56
+ }
57
+ /** `useLayoutEffect` where there is a DOM (no flash of the old scroll position), `useEffect` elsewhere (SSR, React Native). */
58
+ const useLayout = typeof document === "undefined" ? useEffect : useLayoutEffect;
59
+ /**
60
+ * 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.
64
+ */
65
+ export function useStickToBottom(ref, deps, slack = 80) {
66
+ const pinned = useRef(true);
67
+ useEffect(() => {
68
+ const el = ref.current;
69
+ if (!el?.addEventListener)
70
+ return;
71
+ const on = () => {
72
+ pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < slack;
73
+ };
74
+ el.addEventListener("scroll", on, { passive: true });
75
+ return () => el.removeEventListener?.("scroll", on);
76
+ }, [ref, slack]);
77
+ useLayout(() => {
78
+ const el = ref.current;
79
+ if (!pinned.current || !el?.addEventListener)
80
+ return;
81
+ el.scrollTop = el.scrollHeight;
82
+ }, deps);
83
+ const toBottom = useCallback(() => {
84
+ const el = ref.current;
85
+ pinned.current = true;
86
+ if (el?.addEventListener)
87
+ el.scrollTop = el.scrollHeight;
88
+ }, [ref]);
89
+ return { pinned, toBottom };
90
+ }
@@ -0,0 +1,103 @@
1
+ import type { BaseEvent, Message } from "@ag-ui/core";
2
+ /** A tool call as a follower shows it: never its output. */
3
+ export interface LiveTool {
4
+ id: string;
5
+ name: string;
6
+ /** `metadata.summary` of `TOOL_CALL_START`, or `summary` of a `TOOL_CALL_ARGS` delta that is a JSON object (agent-paseo sends each detail whole). */
7
+ summary: string | null;
8
+ /** The `TOOL_CALL_ARGS` deltas joined, as AG-UI defines them. */
9
+ args: string;
10
+ /** `metadata.status` of `TOOL_CALL_END` (`completed`, `failed`, `canceled`), or `failed` / `completed` from `metadata.isError`; `running` before the end. */
11
+ status: string;
12
+ done: boolean;
13
+ }
14
+ /** An `ACTIVITY_SNAPSHOT` (a card): the host draws it by `activityType`. */
15
+ export interface LiveActivity {
16
+ id: string;
17
+ activityType: string;
18
+ content: Record<string, unknown>;
19
+ }
20
+ /** The run's parts in the order they came, for hosts that interleave text and tools. */
21
+ export type LivePart = {
22
+ kind: "text";
23
+ id: string;
24
+ text: string;
25
+ } | {
26
+ kind: "reasoning";
27
+ id: string;
28
+ text: string;
29
+ } | {
30
+ kind: "tool";
31
+ id: string;
32
+ } | {
33
+ kind: "activity";
34
+ id: string;
35
+ };
36
+ /** The run in progress. */
37
+ export interface LiveRun {
38
+ runId: string;
39
+ threadId: string;
40
+ /** `RUN_STARTED.metadata` (assay: `{message}`, the stored user message's id). */
41
+ metadata: Record<string, unknown> | null;
42
+ /** The run's user message, when the stream carries it (`TEXT_MESSAGE_*` with `role: "user"`: agent-paseo's `followAgent`). */
43
+ user: {
44
+ id: string;
45
+ text: string;
46
+ } | null;
47
+ /** The assistant texts joined with a blank line. */
48
+ text: string;
49
+ /** The reasoning texts joined with a blank line. */
50
+ reasoning: string;
51
+ tools: LiveTool[];
52
+ activities: LiveActivity[];
53
+ parts: LivePart[];
54
+ }
55
+ /** How the last run ended. `unknown`: it ended while the stream was down (`READY {running:false}` replaced it); refetch. */
56
+ export interface RunEnd {
57
+ runId: string;
58
+ status: "done" | "stopped" | "error" | "unknown";
59
+ /** `RUN_FINISHED.result` (agent-paseo's runner: what the host's `saveAnswer` returned). */
60
+ result?: unknown;
61
+ error?: string;
62
+ }
63
+ export interface ThreadState {
64
+ /**
65
+ * The thread's messages, when the stream carries them: `MESSAGES_SNAPSHOT` replaces them, and from then on each
66
+ * finished run is appended (user message, texts, tool calls grouped as agent-paseo's snapshot groups them). A stream
67
+ * without snapshots (agent-paseo's runner) leaves this empty: the host owns the history there.
68
+ */
69
+ messages: Message[];
70
+ live: LiveRun | null;
71
+ /** The last run's error (`RUN_ERROR`); cleared when a run starts. A stored answer of a failed turn has it in `last.error`. */
72
+ error: string | null;
73
+ /** The stream is connected (set by `followThread`, not by events). */
74
+ connected: boolean;
75
+ last: RunEnd | null;
76
+ /** A `MESSAGES_SNAPSHOT` has been seen. */
77
+ history: boolean;
78
+ }
79
+ export declare const initialState: ThreadState;
80
+ /**
81
+ * Folds one AG-UI event into the thread state, without changing `state`. Follows the follower contract of
82
+ * agent-paseo and agent-pi: `CUSTOM READY` drops the run being drawn (the stream resyncs: `RUN_STARTED` and a replay
83
+ * follow when one is running), so a reconnect or a server-side gap never duplicates text. Unknown events return
84
+ * `state` unchanged.
85
+ */
86
+ export declare function reduce(state: ThreadState, event: BaseEvent): ThreadState;
87
+ /** A finished run as AG-UI messages, in agent-paseo's snapshot shape: tool calls grouped in an assistant message, `arguments` = JSON `{summary, status}`. */
88
+ export declare function runMessages(live: LiveRun): Message[];
89
+ /**
90
+ * The tool calls of a message, or of a run's tools: `{name, summary, status}` from `toolCalls[].function.arguments`
91
+ * (agent-paseo's snapshot shape: JSON `{summary, status}`).
92
+ */
93
+ export declare function toolViews(m: Message): {
94
+ id: string;
95
+ name: string;
96
+ summary: string | null;
97
+ status: string | null;
98
+ }[];
99
+ /** One line for a run of tool calls: the count and the last call (`3 steps · Read notes.md`). */
100
+ export declare function toolLine(tools: {
101
+ name: string;
102
+ summary: string | null;
103
+ }[]): string;
@@ -0,0 +1,211 @@
1
+ export const initialState = { messages: [], live: null, error: null, connected: false, last: null, history: false };
2
+ /**
3
+ * Folds one AG-UI event into the thread state, without changing `state`. Follows the follower contract of
4
+ * agent-paseo and agent-pi: `CUSTOM READY` drops the run being drawn (the stream resyncs: `RUN_STARTED` and a replay
5
+ * follow when one is running), so a reconnect or a server-side gap never duplicates text. Unknown events return
6
+ * `state` unchanged.
7
+ */
8
+ export function reduce(state, event) {
9
+ const e = event;
10
+ const meta = (e.metadata ?? {});
11
+ switch (e.type) {
12
+ case "CUSTOM": {
13
+ if (e.name !== "READY")
14
+ return state;
15
+ const running = Boolean(e.value?.running);
16
+ const last = state.live && !running ? { runId: state.live.runId, status: "unknown" } : state.last;
17
+ return { ...state, live: null, last };
18
+ }
19
+ case "MESSAGES_SNAPSHOT":
20
+ return { ...state, messages: Array.isArray(e.messages) ? e.messages : [], history: true };
21
+ case "RUN_STARTED": {
22
+ // A run still open here missed its end (the server closes it before the next starts; this is the fallback).
23
+ const prev = state.live && state.live.runId !== String(e.runId) ? settle(state) : state;
24
+ return {
25
+ ...prev,
26
+ error: null,
27
+ live: { runId: String(e.runId), threadId: String(e.threadId), metadata: e.metadata ?? null, user: null, text: "", reasoning: "", tools: [], activities: [], parts: [] },
28
+ };
29
+ }
30
+ case "RUN_FINISHED": {
31
+ if (!state.live && state.last?.runId === e.runId)
32
+ return state;
33
+ // The end of another run (a recovered one announced late) is recorded, but does not end the one being drawn.
34
+ const other = Boolean(state.live && e.runId && state.live.runId !== String(e.runId));
35
+ const error = typeof meta.error === "string" ? meta.error : undefined;
36
+ const stopped = Boolean(meta.stopped) || e.outcome?.type === "cancelled";
37
+ const status = error ? "error" : stopped ? "stopped" : "done";
38
+ const last = { runId: String(e.runId), status, ...(e.result !== undefined ? { result: e.result } : {}), ...(error ? { error } : {}) };
39
+ return other ? { ...state, last } : { ...settle(state), live: null, last, error: null };
40
+ }
41
+ case "RUN_ERROR": {
42
+ const message = String(e.message ?? "error");
43
+ const runId = String(meta.runId ?? state.live?.runId ?? "");
44
+ const last = { runId, status: "error", error: message };
45
+ if (state.live && meta.runId && state.live.runId !== runId)
46
+ return { ...state, last };
47
+ return { ...settle(state), live: null, error: message, last };
48
+ }
49
+ }
50
+ const live = state.live;
51
+ if (!live)
52
+ return activityOutside(state, e);
53
+ const next = run(live, e, meta);
54
+ return next === live ? state : { ...state, live: next };
55
+ }
56
+ /** One event of the run in progress. Returns `live` itself when nothing changed. */
57
+ function run(live, e, meta) {
58
+ switch (e.type) {
59
+ case "TEXT_MESSAGE_START":
60
+ case "TEXT_MESSAGE_CHUNK":
61
+ case "TEXT_MESSAGE_CONTENT": {
62
+ const id = String(e.messageId ?? "");
63
+ const delta = typeof e.delta === "string" ? e.delta : "";
64
+ if (e.role === "user" || (live.user && live.user.id === id)) {
65
+ const user = live.user?.id === id ? live.user : { id, text: "" };
66
+ return delta ? { ...live, user: { id, text: user.text + delta } } : live.user === user ? live : { ...live, user };
67
+ }
68
+ if (e.type !== "TEXT_MESSAGE_START" && !delta)
69
+ return live;
70
+ return withText(live, "text", id, delta);
71
+ }
72
+ case "REASONING_MESSAGE_START":
73
+ case "REASONING_MESSAGE_CHUNK":
74
+ case "REASONING_MESSAGE_CONTENT": {
75
+ const delta = typeof e.delta === "string" ? e.delta : "";
76
+ if (e.type !== "REASONING_MESSAGE_START" && !delta)
77
+ return live;
78
+ return withText(live, "reasoning", String(e.messageId ?? ""), delta);
79
+ }
80
+ case "TOOL_CALL_START": {
81
+ const id = String(e.toolCallId);
82
+ if (live.tools.some((t) => t.id === id))
83
+ return live;
84
+ const tool = { id, name: String(e.toolCallName ?? ""), summary: str(meta.summary), args: "", status: "running", done: false };
85
+ return { ...live, tools: [...live.tools, tool], parts: [...live.parts, { kind: "tool", id }] };
86
+ }
87
+ case "TOOL_CALL_ARGS": {
88
+ const delta = typeof e.delta === "string" ? e.delta : "";
89
+ return tool(live, String(e.toolCallId), (t) => {
90
+ let summary = t.summary;
91
+ try {
92
+ const v = JSON.parse(delta);
93
+ if (v && typeof v === "object" && "summary" in v)
94
+ summary = str(v.summary) ?? summary;
95
+ }
96
+ catch { }
97
+ return { ...t, args: t.args + delta, summary };
98
+ });
99
+ }
100
+ case "TOOL_CALL_END":
101
+ return tool(live, String(e.toolCallId), (t) => ({
102
+ ...t,
103
+ done: true,
104
+ status: str(meta.status) ?? (meta.isError === true ? "failed" : "completed"),
105
+ }));
106
+ case "ACTIVITY_SNAPSHOT": {
107
+ const id = String(e.messageId);
108
+ const at = live.activities.findIndex((a) => a.id === id);
109
+ const a = { id, activityType: String(e.activityType), content: (e.content ?? {}) };
110
+ if (at < 0)
111
+ return { ...live, activities: [...live.activities, a], parts: [...live.parts, { kind: "activity", id }] };
112
+ if (e.replace === false)
113
+ return live;
114
+ return { ...live, activities: live.activities.map((x, i) => (i === at ? a : x)) };
115
+ }
116
+ }
117
+ return live;
118
+ }
119
+ function withText(live, kind, id, delta) {
120
+ const at = live.parts.findIndex((p) => p.kind === kind && p.id === id);
121
+ const parts = live.parts.slice();
122
+ if (at < 0)
123
+ parts.push({ kind, id, text: delta });
124
+ else if (delta)
125
+ parts[at] = { kind, id, text: parts[at].text + delta };
126
+ else
127
+ return live;
128
+ const joined = parts
129
+ .filter((p) => p.kind === kind)
130
+ .map((p) => p.text)
131
+ .filter(Boolean)
132
+ .join("\n\n");
133
+ return { ...live, parts, [kind]: joined };
134
+ }
135
+ function tool(live, id, f) {
136
+ const at = live.tools.findIndex((t) => t.id === id);
137
+ if (at < 0)
138
+ return live;
139
+ return { ...live, tools: live.tools.map((t, i) => (i === at ? f(t) : t)) };
140
+ }
141
+ /** A card outside a run joins the history when the stream carries one; otherwise it has nowhere to go. */
142
+ function activityOutside(state, e) {
143
+ if (e.type !== "ACTIVITY_SNAPSHOT" || !state.history)
144
+ return state;
145
+ const m = { id: String(e.messageId), role: "activity", activityType: String(e.activityType), content: e.content ?? {} };
146
+ const at = state.messages.findIndex((x) => x.id === m.id);
147
+ if (at >= 0 && e.replace === false)
148
+ return state;
149
+ return { ...state, messages: at < 0 ? [...state.messages, m] : state.messages.map((x, i) => (i === at ? m : x)) };
150
+ }
151
+ /** A run that ended moves into the history, when the stream carries one. */
152
+ function settle(state) {
153
+ if (!state.history || !state.live)
154
+ return state;
155
+ return { ...state, messages: [...state.messages, ...runMessages(state.live)] };
156
+ }
157
+ /** A finished run as AG-UI messages, in agent-paseo's snapshot shape: tool calls grouped in an assistant message, `arguments` = JSON `{summary, status}`. */
158
+ export function runMessages(live) {
159
+ const out = [];
160
+ if (live.user)
161
+ out.push({ id: live.user.id, role: "user", content: live.user.text });
162
+ let group = null;
163
+ for (const p of live.parts) {
164
+ if (p.kind === "text") {
165
+ group = null;
166
+ if (p.text.trim())
167
+ out.push({ id: p.id, role: "assistant", content: p.text });
168
+ }
169
+ else if (p.kind === "reasoning") {
170
+ if (p.text.trim())
171
+ out.push({ id: p.id, role: "reasoning", content: p.text });
172
+ }
173
+ else if (p.kind === "tool") {
174
+ const t = live.tools.find((x) => x.id === p.id);
175
+ if (!group)
176
+ out.push((group = { id: `tools-${t.id}`, role: "assistant", toolCalls: [] }));
177
+ group.toolCalls.push({ id: t.id, type: "function", function: { name: t.name, arguments: JSON.stringify({ summary: t.summary, status: t.status }) } });
178
+ }
179
+ else {
180
+ const a = live.activities.find((x) => x.id === p.id);
181
+ group = null;
182
+ out.push({ id: a.id, role: "activity", activityType: a.activityType, content: a.content });
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+ /**
188
+ * The tool calls of a message, or of a run's tools: `{name, summary, status}` from `toolCalls[].function.arguments`
189
+ * (agent-paseo's snapshot shape: JSON `{summary, status}`).
190
+ */
191
+ export function toolViews(m) {
192
+ if (m.role !== "assistant" || !m.toolCalls)
193
+ return [];
194
+ return m.toolCalls.map((c) => {
195
+ let v = {};
196
+ try {
197
+ v = JSON.parse(c.function.arguments) ?? {};
198
+ }
199
+ catch { }
200
+ return { id: c.id, name: c.function.name, summary: str(v.summary), status: str(v.status) };
201
+ });
202
+ }
203
+ /** One line for a run of tool calls: the count and the last call (`3 steps · Read notes.md`). */
204
+ export function toolLine(tools) {
205
+ const last = tools.at(-1);
206
+ if (!last)
207
+ return "";
208
+ const what = last.summary ? `${last.name} ${last.summary}` : last.name;
209
+ return tools.length > 1 ? `${tools.length} steps · ${what}` : what;
210
+ }
211
+ const str = (v) => (typeof v === "string" ? v : null);
@@ -0,0 +1,13 @@
1
+ import type { BaseEvent } from "@ag-ui/core";
2
+ /** What `readSse` needs from a response: a byte stream (the WHATWG `Response` has it; so do expo/fetch and undici). */
3
+ export interface SseSource {
4
+ body: ReadableStream<Uint8Array> | null;
5
+ }
6
+ /**
7
+ * Reads a `text/event-stream` body as AG-UI events: each SSE event's `data` (lines joined with `\n`) is parsed as JSON
8
+ * and yielded when it has a string `type`. The SSE `event:` name is ignored (hosts name events by type, or `CUSTOM` by
9
+ * its name, for their own logs); comments (`: ping`), `id:` and `retry:` are skipped, and so is data that is not JSON.
10
+ * An event cut off by the end of the stream is dropped, as the SSE spec says, so a connection that breaks in the
11
+ * middle of an event never yields half of it. Stops reading when the iterator is closed (`break`, `return`).
12
+ */
13
+ export declare function readSse(res: SseSource): AsyncGenerator<BaseEvent, void, undefined>;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Reads a `text/event-stream` body as AG-UI events: each SSE event's `data` (lines joined with `\n`) is parsed as JSON
3
+ * and yielded when it has a string `type`. The SSE `event:` name is ignored (hosts name events by type, or `CUSTOM` by
4
+ * its name, for their own logs); comments (`: ping`), `id:` and `retry:` are skipped, and so is data that is not JSON.
5
+ * An event cut off by the end of the stream is dropped, as the SSE spec says, so a connection that breaks in the
6
+ * middle of an event never yields half of it. Stops reading when the iterator is closed (`break`, `return`).
7
+ */
8
+ export async function* readSse(res) {
9
+ if (!res.body)
10
+ throw new Error("readSse: the response has no body");
11
+ const reader = res.body.getReader();
12
+ const decoder = new TextDecoder();
13
+ let buf = "";
14
+ let data = [];
15
+ let finished = false;
16
+ try {
17
+ for (;;) {
18
+ const { value, done } = await reader.read();
19
+ if (done)
20
+ finished = true;
21
+ else
22
+ buf += decoder.decode(value, { stream: true });
23
+ // Complete lines only: a trailing `\r` may be the first half of `\r\n`, so it waits for the next chunk (or the end).
24
+ let start = 0;
25
+ for (let i = 0; i < buf.length; i++) {
26
+ const c = buf.charCodeAt(i);
27
+ if (c !== 10 && c !== 13)
28
+ continue;
29
+ if (c === 13 && i === buf.length - 1 && !done)
30
+ break;
31
+ const line = buf.slice(start, i);
32
+ if (c === 13 && buf.charCodeAt(i + 1) === 10)
33
+ i++;
34
+ start = i + 1;
35
+ if (line === "") {
36
+ const e = parse(data);
37
+ data = [];
38
+ if (e)
39
+ yield e;
40
+ continue;
41
+ }
42
+ if (line.charCodeAt(0) === 58)
43
+ continue; // ":" comment
44
+ const colon = line.indexOf(":");
45
+ const field = colon < 0 ? line : line.slice(0, colon);
46
+ if (field !== "data")
47
+ continue;
48
+ let v = colon < 0 ? "" : line.slice(colon + 1);
49
+ if (v.charCodeAt(0) === 32)
50
+ v = v.slice(1);
51
+ data.push(v);
52
+ }
53
+ buf = buf.slice(start);
54
+ if (done)
55
+ return;
56
+ }
57
+ }
58
+ finally {
59
+ if (!finished)
60
+ await reader.cancel().catch(() => { });
61
+ reader.releaseLock();
62
+ }
63
+ }
64
+ function parse(data) {
65
+ if (!data.length)
66
+ return null;
67
+ try {
68
+ const e = JSON.parse(data.join("\n"));
69
+ return e && typeof e === "object" && typeof e.type === "string" ? e : null;
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
@@ -0,0 +1,64 @@
1
+ import type { MessagesSnapshotEvent } from "@ag-ui/core";
2
+ import type { Daemon } from "./daemon.ts";
3
+ import { type PaseoEvent } from "./turn.ts";
4
+ /** What a follower receives: the runner's events plus `MESSAGES_SNAPSHOT` for the agent's earlier turns. */
5
+ export type FollowEvent = PaseoEvent | MessagesSnapshotEvent;
6
+ export type FollowListener = (e: FollowEvent) => void;
7
+ export interface AgentFollowerOptions {
8
+ /** Timeline entries read for history and after a gap. Default 300. */
9
+ tailLimit?: number;
10
+ /** How long a running turn may go without an event before the daemon is asked how the agent is. Default 60 s. */
11
+ quietMs?: number;
12
+ /** Where errors of background reads go. Default `console.error`. */
13
+ log?: (message: string) => void;
14
+ }
15
+ /**
16
+ * Follows one Paseo agent read-only: never sends, never claims a turn. Every turn of the agent is a run
17
+ * (`runId` = the daemon's `turnId`, `threadId` = the agent id). A listener gets `CUSTOM READY`, a
18
+ * `MESSAGES_SNAPSHOT` of the earlier turns in the tail, and, when a turn is running, `RUN_STARTED` and its
19
+ * replay (the user message as `TEXT_MESSAGE_*` with role `user`, then text and tool calls); then live events.
20
+ * After any gap in the daemon's stream every listener gets that start again, so a follower always resets on
21
+ * `READY`. One subscription to the daemon is shared by all listeners.
22
+ */
23
+ export declare class AgentFollower {
24
+ readonly agentId: string;
25
+ private daemon;
26
+ private tailLimit;
27
+ private quietMs;
28
+ private log;
29
+ private listeners;
30
+ private history;
31
+ private turn;
32
+ private epoch;
33
+ private seq;
34
+ private buffer;
35
+ private again;
36
+ private unsub;
37
+ private watch;
38
+ private last;
39
+ private closed;
40
+ constructor(daemon: Daemon, agentId: string, o?: AgentFollowerOptions);
41
+ /** Subscribes, then reads the history; events that arrive meanwhile are held and folded after it. */
42
+ start(): Promise<void>;
43
+ /** The turn running now, if any. */
44
+ running(): string | null;
45
+ listen(fn: FollowListener): () => void;
46
+ close(): void;
47
+ private emit;
48
+ private resync;
49
+ private started;
50
+ /** Reads the agent and its tail and rebuilds history and the running turn. The status is read first. */
51
+ private read;
52
+ private onEvent;
53
+ private apply;
54
+ /** A new turn: a turn still open ended without us seeing its end (it is closed as finished). */
55
+ private begin;
56
+ private end;
57
+ private regap;
58
+ private lostSub;
59
+ private drain;
60
+ /** A quiet running turn, or a gap that could not be filled: ask the daemon and re-read when needed. */
61
+ private check;
62
+ }
63
+ /** Starts following an agent read-only; resolves once history is read and the live stream is on. */
64
+ export declare function followAgent(daemon: Daemon, agentId: string, o?: AgentFollowerOptions): Promise<AgentFollower>;
@@ -0,0 +1,305 @@
1
+ import { EventType } from "@ag-ui/core";
2
+ import { TurnFolder } from "./turn.js";
3
+ /**
4
+ * Follows one Paseo agent read-only: never sends, never claims a turn. Every turn of the agent is a run
5
+ * (`runId` = the daemon's `turnId`, `threadId` = the agent id). A listener gets `CUSTOM READY`, a
6
+ * `MESSAGES_SNAPSHOT` of the earlier turns in the tail, and, when a turn is running, `RUN_STARTED` and its
7
+ * replay (the user message as `TEXT_MESSAGE_*` with role `user`, then text and tool calls); then live events.
8
+ * After any gap in the daemon's stream every listener gets that start again, so a follower always resets on
9
+ * `READY`. One subscription to the daemon is shared by all listeners.
10
+ */
11
+ export class AgentFollower {
12
+ agentId;
13
+ daemon;
14
+ tailLimit;
15
+ quietMs;
16
+ log;
17
+ listeners = new Set();
18
+ history = [];
19
+ turn = null;
20
+ epoch = null;
21
+ seq = -1;
22
+ buffer = null;
23
+ again = null;
24
+ unsub = null;
25
+ watch = null;
26
+ last = Date.now();
27
+ closed = false;
28
+ constructor(daemon, agentId, o = {}) {
29
+ this.daemon = daemon;
30
+ this.agentId = agentId;
31
+ this.tailLimit = o.tailLimit ?? 300;
32
+ this.quietMs = o.quietMs ?? 60_000;
33
+ this.log = o.log ?? ((m) => console.error(m));
34
+ }
35
+ /** Subscribes, then reads the history; events that arrive meanwhile are held and folded after it. */
36
+ async start() {
37
+ this.buffer = [];
38
+ this.unsub = await this.daemon.subscribe(this.agentId, (e) => this.onEvent(e));
39
+ try {
40
+ await this.read();
41
+ }
42
+ catch (e) {
43
+ this.close();
44
+ throw e;
45
+ }
46
+ this.watch = setInterval(() => void this.check(), Math.max(1000, this.quietMs / 2));
47
+ this.watch.unref();
48
+ this.drain();
49
+ }
50
+ /** The turn running now, if any. */
51
+ running() {
52
+ return this.turn?.turnId ?? null;
53
+ }
54
+ listen(fn) {
55
+ this.listeners.add(fn);
56
+ for (const e of this.resync())
57
+ safe(fn, e);
58
+ return () => void this.listeners.delete(fn);
59
+ }
60
+ close() {
61
+ this.closed = true;
62
+ this.unsub?.();
63
+ this.unsub = null;
64
+ if (this.watch)
65
+ clearInterval(this.watch);
66
+ this.watch = null;
67
+ this.listeners.clear();
68
+ }
69
+ // ---- internals
70
+ emit(e) {
71
+ for (const f of [...this.listeners])
72
+ safe(f, e);
73
+ }
74
+ resync() {
75
+ const t = this.turn;
76
+ const value = { threadId: this.agentId, runId: t?.turnId ?? null, running: Boolean(t) };
77
+ const out = [
78
+ { type: EventType.CUSTOM, name: "READY", value },
79
+ { type: EventType.MESSAGES_SNAPSHOT, messages: [...this.history] },
80
+ ];
81
+ if (t)
82
+ out.push(this.started(t), ...(t.user ? userEvents(t.user) : []), ...t.folder.replay());
83
+ return out;
84
+ }
85
+ started(t) {
86
+ return { type: EventType.RUN_STARTED, threadId: this.agentId, runId: t.turnId };
87
+ }
88
+ /** Reads the agent and its tail and rebuilds history and the running turn. The status is read first. */
89
+ async read() {
90
+ const a = await this.daemon.agent(this.agentId);
91
+ const tail = await this.daemon.tail(this.agentId, this.tailLimit);
92
+ if (tail.epoch) {
93
+ this.epoch = tail.epoch;
94
+ this.seq = tail.seq ?? -1;
95
+ }
96
+ const turns = group(tail.entries);
97
+ const runningNow = a?.status === "running";
98
+ const cur = runningNow ? turns.at(-1) ?? null : null;
99
+ this.history = [];
100
+ for (const t of turns)
101
+ if (t !== cur)
102
+ this.history.push(...messages(t));
103
+ this.turn = cur;
104
+ this.last = Date.now();
105
+ }
106
+ onEvent(e) {
107
+ if (this.closed)
108
+ return;
109
+ this.last = Date.now();
110
+ if (e.type === "lost" || e.type === "replacement" || e.type === "subscription_restored") {
111
+ const resubscribe = e.type === "lost";
112
+ if (this.buffer)
113
+ return void (this.again = { resubscribe: resubscribe || Boolean(this.again?.resubscribe) });
114
+ return void this.regap(e.type === "lost" ? e.error : e.type, resubscribe);
115
+ }
116
+ if (this.buffer)
117
+ return void this.buffer.push(e);
118
+ this.apply(e);
119
+ }
120
+ apply(e) {
121
+ if (e.type === "timeline") {
122
+ if (e.seq != null && e.epoch) {
123
+ if (this.epoch && e.epoch !== this.epoch)
124
+ return void this.regap("epoch changed");
125
+ if (e.epoch === this.epoch && e.seq <= this.seq)
126
+ return;
127
+ this.epoch = e.epoch;
128
+ this.seq = e.seq;
129
+ }
130
+ const it = e.item;
131
+ if (e.turnId && this.turn?.turnId !== e.turnId)
132
+ this.begin(e.turnId);
133
+ const t = this.turn;
134
+ if (!t)
135
+ return;
136
+ if (it.type === "user_message") {
137
+ const text = it.text?.trim();
138
+ if (!text || t.user)
139
+ return;
140
+ t.user = { id: it.clientMessageId ?? it.messageId ?? `u-${t.turnId}`, text };
141
+ for (const x of userEvents(t.user))
142
+ this.emit(x);
143
+ return;
144
+ }
145
+ for (const x of t.folder.push(it))
146
+ this.emit(x);
147
+ return;
148
+ }
149
+ if (e.type === "turn_started") {
150
+ if (e.turnId && this.turn?.turnId !== e.turnId)
151
+ this.begin(e.turnId);
152
+ return;
153
+ }
154
+ if (e.type !== "turn_completed" && e.type !== "turn_canceled" && e.type !== "turn_failed")
155
+ return;
156
+ const t = this.turn;
157
+ if (!t || (e.turnId && e.turnId !== t.turnId))
158
+ return;
159
+ this.end(t, e.type === "turn_completed" ? "done" : e.type === "turn_canceled" ? "stopped" : "error", e.type === "turn_failed" ? e.error : undefined);
160
+ }
161
+ /** A new turn: a turn still open ended without us seeing its end (it is closed as finished). */
162
+ begin(turnId) {
163
+ if (this.turn)
164
+ this.end(this.turn, "done");
165
+ this.turn = { turnId, user: null, folder: new TurnFolder() };
166
+ this.emit(this.started(this.turn));
167
+ }
168
+ end(t, status, error) {
169
+ for (const x of t.folder.end())
170
+ this.emit(x);
171
+ this.history.push(...messages(t));
172
+ this.turn = null;
173
+ if (status === "error")
174
+ this.emit({ type: EventType.RUN_ERROR, message: error ?? "the turn failed", metadata: { threadId: this.agentId, runId: t.turnId } });
175
+ else
176
+ this.emit({
177
+ type: EventType.RUN_FINISHED,
178
+ threadId: this.agentId,
179
+ runId: t.turnId,
180
+ ...(status === "stopped" ? { outcome: { type: "cancelled" }, metadata: { stopped: true } } : {}),
181
+ });
182
+ }
183
+ async regap(why, resubscribe = false) {
184
+ if (this.closed || this.buffer)
185
+ return;
186
+ this.buffer = [];
187
+ try {
188
+ if (resubscribe) {
189
+ this.unsub?.();
190
+ this.unsub = await this.daemon.subscribe(this.agentId, (e) => this.onEvent(e));
191
+ if (this.closed)
192
+ return this.unsub();
193
+ }
194
+ await this.read();
195
+ if (this.closed)
196
+ return;
197
+ for (const e of this.resync())
198
+ this.emit(e);
199
+ this.drain();
200
+ }
201
+ catch (e) {
202
+ this.buffer = null;
203
+ this.again = null;
204
+ this.log(`agent-paseo follow ${this.agentId}: ${why}: ${e.message}`);
205
+ // Try again on the next check; a lost subscription is replaced then.
206
+ this.lostSub = this.lostSub || resubscribe;
207
+ }
208
+ }
209
+ lostSub = false;
210
+ drain() {
211
+ const held = this.buffer ?? [];
212
+ const again = this.again;
213
+ this.buffer = null;
214
+ this.again = null;
215
+ if (again)
216
+ return void this.regap("another gap", again.resubscribe);
217
+ for (const e of held) {
218
+ if (this.closed || this.buffer)
219
+ return;
220
+ this.apply(e);
221
+ }
222
+ }
223
+ /** A quiet running turn, or a gap that could not be filled: ask the daemon and re-read when needed. */
224
+ async check() {
225
+ if (this.closed || this.buffer)
226
+ return;
227
+ if (this.lostSub) {
228
+ this.lostSub = false;
229
+ return void this.regap("retry", true);
230
+ }
231
+ if (!this.turn || Date.now() - this.last < this.quietMs)
232
+ return;
233
+ try {
234
+ const a = await this.daemon.agent(this.agentId);
235
+ if (a?.status === "running" || this.closed)
236
+ return void (this.last = Date.now());
237
+ await this.regap("quiet");
238
+ }
239
+ catch (e) {
240
+ this.log(`agent-paseo follow ${this.agentId}: check: ${e.message}`);
241
+ }
242
+ }
243
+ }
244
+ /** Starts following an agent read-only; resolves once history is read and the live stream is on. */
245
+ export async function followAgent(daemon, agentId, o = {}) {
246
+ const f = new AgentFollower(daemon, agentId, o);
247
+ await f.start();
248
+ return f;
249
+ }
250
+ /** Splits tail entries into turns by `turnId`; items without one join the turn before them. */
251
+ function group(entries) {
252
+ const turns = [];
253
+ for (const x of entries) {
254
+ let t = turns.at(-1);
255
+ if (x.turnId && t?.turnId !== x.turnId)
256
+ turns.push((t = { turnId: x.turnId, user: null, folder: new TurnFolder() }));
257
+ if (!t)
258
+ continue;
259
+ if (x.item.type === "user_message") {
260
+ const text = x.item.text?.trim();
261
+ if (text && !t.user)
262
+ t.user = { id: x.item.clientMessageId ?? x.item.messageId ?? `u-${t.turnId}`, text };
263
+ }
264
+ else
265
+ t.folder.push(x.item);
266
+ }
267
+ return turns;
268
+ }
269
+ /** A finished turn as AG-UI messages: the user message, then assistant texts, tool calls grouped between them. */
270
+ function messages(t) {
271
+ const out = [];
272
+ if (t.user)
273
+ out.push({ id: t.user.id, role: "user", content: t.user.text });
274
+ let tools = null;
275
+ for (const p of t.folder.parts()) {
276
+ if (p.kind === "text") {
277
+ tools = null;
278
+ if (p.text.trim())
279
+ out.push({ id: p.id, role: "assistant", content: p.text });
280
+ }
281
+ else {
282
+ if (!tools)
283
+ out.push((tools = { id: `tools-${p.id}`, role: "assistant", toolCalls: [] }));
284
+ tools.toolCalls.push({
285
+ id: p.id,
286
+ type: "function",
287
+ function: { name: p.tool.name, arguments: JSON.stringify({ summary: p.tool.summary, status: p.tool.status }) },
288
+ });
289
+ }
290
+ }
291
+ return out;
292
+ }
293
+ function userEvents(u) {
294
+ return [
295
+ { type: EventType.TEXT_MESSAGE_START, messageId: u.id, role: "user" },
296
+ { type: EventType.TEXT_MESSAGE_CONTENT, messageId: u.id, delta: u.text },
297
+ { type: EventType.TEXT_MESSAGE_END, messageId: u.id },
298
+ ];
299
+ }
300
+ function safe(f, e) {
301
+ try {
302
+ f(e);
303
+ }
304
+ catch { }
305
+ }
@@ -6,6 +6,8 @@
6
6
  */
7
7
  export { assertLocalDaemon, liveEvent, localAddress, paseoDaemon, paseoHome } from "./daemon.ts";
8
8
  export type { AgentInfo, Daemon, LiveEvent, PaseoDaemonConfig, Tail } from "./daemon.ts";
9
+ export { AgentFollower, followAgent } from "./follow.ts";
10
+ export type { AgentFollowerOptions, FollowEvent, FollowListener } from "./follow.ts";
9
11
  export { PaseoThreadRunner, paseoThreadRunner } from "./runner.ts";
10
12
  export type { Listener, PaseoThreadRunnerOptions, ReadyValue, RecoverRequest, RecoverResult, SendRequest, ThreadStore } from "./runner.ts";
11
13
  export { TurnFolder, afterMessage, chat, finalText, isProviderError, toolSummary } from "./turn.ts";
@@ -5,5 +5,6 @@
5
5
  * See `.ea/docs/agent-paseo.md`.
6
6
  */
7
7
  export { assertLocalDaemon, liveEvent, localAddress, paseoDaemon, paseoHome } from "./daemon.js";
8
+ export { AgentFollower, followAgent } from "./follow.js";
8
9
  export { PaseoThreadRunner, paseoThreadRunner } from "./runner.js";
9
10
  export { TurnFolder, afterMessage, chat, finalText, isProviderError, toolSummary } from "./turn.js";
@@ -94,6 +94,16 @@ export declare class TurnFolder {
94
94
  /** The events that rebuild the turn so far, for a follower that joins mid-turn or after a gap. */
95
95
  replay(): FoldedEvent[];
96
96
  text(): string;
97
+ /** The turn's parts in order: assistant texts and tool calls (for a history snapshot). */
98
+ parts(): ({
99
+ kind: "text";
100
+ id: string;
101
+ text: string;
102
+ } | {
103
+ kind: "tool";
104
+ id: string;
105
+ tool: ToolView;
106
+ })[];
97
107
  toolList(): ToolView[];
98
108
  /** Reconstruct a TurnFolder from a projected tail slice (afterMessage). Used in recovery. */
99
109
  static fromEntries(entries: TimelineEntry[]): TurnFolder;
@@ -199,6 +199,12 @@ export class TurnFolder {
199
199
  }
200
200
  return parts.filter(Boolean).join("\n\n");
201
201
  }
202
+ /** The turn's parts in order: assistant texts and tool calls (for a history snapshot). */
203
+ parts() {
204
+ return this.order.map((x) => x.kind === "text"
205
+ ? { kind: "text", id: x.id, text: this.texts.get(x.id) }
206
+ : { kind: "tool", id: x.id, tool: (({ name, summary, status }) => ({ name, summary, status }))(this.tools.get(x.id)) });
207
+ }
202
208
  toolList() {
203
209
  return [...this.tools.values()].map(({ name, summary, status }) => ({ name, summary, status })).slice(-GROUP_TOOLS);
204
210
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightblues/jig",
3
- "version": "0.0.5",
3
+ "version": "0.0.7",
4
4
  "description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, and more as they prove reusable.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,6 +28,14 @@
28
28
  "types": "./dist/agent-paseo/index.d.ts",
29
29
  "default": "./dist/agent-paseo/index.js"
30
30
  },
31
+ "./agent-chat": {
32
+ "types": "./dist/agent-chat/index.d.ts",
33
+ "default": "./dist/agent-chat/index.js"
34
+ },
35
+ "./agent-chat/react": {
36
+ "types": "./dist/agent-chat/react.d.ts",
37
+ "default": "./dist/agent-chat/react.js"
38
+ },
31
39
  "./package.json": "./package.json"
32
40
  },
33
41
  "scripts": {
@@ -41,11 +49,17 @@
41
49
  "@ag-ui/core": "1.0.5",
42
50
  "@getpaseo/client": "0.16.1",
43
51
  "@types/node": "^24.0.0",
52
+ "@types/react": "19.3.0",
53
+ "@types/react-test-renderer": "19.3.1",
54
+ "esbuild": "0.28.2",
55
+ "react": "19.3.1",
56
+ "react-test-renderer": "19.3.1",
44
57
  "typescript": "^5.9.0"
45
58
  },
46
59
  "peerDependencies": {
47
60
  "@ag-ui/core": "^1.0.5",
48
- "@getpaseo/client": "0.16.1"
61
+ "@getpaseo/client": "0.16.1",
62
+ "react": ">=18"
49
63
  },
50
64
  "peerDependenciesMeta": {
51
65
  "@ag-ui/core": {
@@ -53,6 +67,9 @@
53
67
  },
54
68
  "@getpaseo/client": {
55
69
  "optional": true
70
+ },
71
+ "react": {
72
+ "optional": true
56
73
  }
57
74
  }
58
75
  }