@hollis-labs/surface-chat 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/react.d.ts +25 -0
- package/dist/react.js +62 -0
- package/dist/reduce.d.ts +76 -0
- package/dist/reduce.js +165 -0
- package/dist/store.d.ts +44 -0
- package/dist/store.js +208 -0
- package/dist/wire.d.ts +103 -0
- package/dist/wire.js +117 -0
- package/package.json +39 -4
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hollis-labs/surface-chat
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A conversation with an agent host, without any styling. It is the behaviour half of Surface's chat; the visuals
|
|
4
|
+
are the registry's chat components (`conversation`, `message`, `markdown`, `prompt-input`, `tool`), and
|
|
5
|
+
`web/src/agent/AgentPanel.tsx` puts the two together.
|
|
6
|
+
|
|
7
|
+
Unpublished for now. Another app can take it as source (the page aliases `@hollis-labs/surface-chat` to `src/index.ts`); it
|
|
8
|
+
has no dependency but React, and React only for `src/react.ts`.
|
|
9
|
+
|
|
10
|
+
| File | What it is |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `src/wire.ts` | The agent-host/1 routes (libs/agent/host `WIRE.md`) and a follower for a run's chatstream/v1 events that resumes a dropped stream from the last event seen |
|
|
13
|
+
| `src/reduce.ts` | The conversation as data, and what each event does to it. Pure functions |
|
|
14
|
+
| `src/store.ts` | The store: start, send, stop, answer an approval, new thread, reload, follow a turn started elsewhere |
|
|
15
|
+
| `src/react.ts` | `useChat(store, select)` and its shorthands; `useStickToBottom` |
|
|
16
|
+
|
|
17
|
+
## Why drawing stays cheap
|
|
18
|
+
|
|
19
|
+
- **The shape.** Items are held by id (`items`) with their order beside them (`ids`). A streamed token replaces one
|
|
20
|
+
item and nothing else: `ids` keeps its identity unless an item is added or removed, and so does every other
|
|
21
|
+
item. A list drawn from `ids`, with each row subscribed to its own item, redraws only the row that changed.
|
|
22
|
+
- **The composer owns its draft.** Typing changes component state in the composer and nothing in the store.
|
|
23
|
+
- **One notification per frame.** A burst of tokens between two frames is one redraw.
|
|
24
|
+
|
|
25
|
+
Measured on a live turn in the page (development build, `window.__chatRenders`, commits per component): typing 30
|
|
26
|
+
characters gave the composer 30 commits and the list and every row 0; a reply of 77 streamed tokens gave its own
|
|
27
|
+
row 73 commits, the list 2 (its two new items) and each of the four earlier messages 0.
|
|
28
|
+
|
|
29
|
+
## History policy
|
|
30
|
+
|
|
31
|
+
1. The thread is read once, by `start()`, and kept for the life of the page. Opening the panel again reads nothing.
|
|
32
|
+
2. A run this store started, or found active, is drawn from its event stream, never from the stored copy.
|
|
33
|
+
3. The thread is read again only when someone else changed it: a turn started outside this page
|
|
34
|
+
(`turnElsewhere`, wired to the host's `agent.turn` event) or an explicit `reload()`. Never on a timer or on focus.
|
|
35
|
+
4. `newThread()` empties the store and reads nothing.
|
|
36
|
+
|
|
37
|
+
## Not here
|
|
38
|
+
|
|
39
|
+
- **Page tools.** The wire lets a page declare tools and run them; Surface's tools are all server tools, so turns
|
|
40
|
+
declare none. Add a runner here if an app needs one.
|
|
41
|
+
- **Cards.** The panel draws each item through a table (`web/src/agent/items.tsx`): a tool with a card of its own
|
|
42
|
+
goes to that card, every other tool to the plain row.
|
|
43
|
+
|
|
44
|
+
`npm test` runs the reducer and store tests (`node --test`).
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ChatItem, ChatState } from "./reduce.ts";
|
|
2
|
+
import type { ChatStore } from "./store.ts";
|
|
3
|
+
/**
|
|
4
|
+
* A slice of the conversation; the component redraws only when the slice changes identity.
|
|
5
|
+
* Select what the component draws and nothing more: `s => s.ids` for the list,
|
|
6
|
+
* `s => s.items[id]` for one row, `s => s.run !== null` for the composer.
|
|
7
|
+
*/
|
|
8
|
+
export declare function useChat<T>(store: ChatStore, select: (s: ChatState) => T): T;
|
|
9
|
+
/** The order of the items: changes only when one is added or removed. */
|
|
10
|
+
export declare const useChatIds: (store: ChatStore) => readonly string[];
|
|
11
|
+
/** One item: changes only when that item does. */
|
|
12
|
+
export declare const useChatItem: (store: ChatStore, id: string) => ChatItem | undefined;
|
|
13
|
+
/** True while a run is followed. */
|
|
14
|
+
export declare const useChatBusy: (store: ChatStore) => boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Keep a scrolling list at its end while its content grows, unless the person has scrolled
|
|
17
|
+
* up to read; scrolling back down (or scrollToBottom) resumes following. Put viewportRef on
|
|
18
|
+
* the element that scrolls and contentRef on the element inside it that grows.
|
|
19
|
+
*/
|
|
20
|
+
export declare function useStickToBottom<V extends HTMLElement = HTMLDivElement, C extends HTMLElement = HTMLDivElement>(): {
|
|
21
|
+
viewportRef: import("react").RefObject<V | null>;
|
|
22
|
+
contentRef: import("react").RefObject<C | null>;
|
|
23
|
+
atBottom: boolean;
|
|
24
|
+
scrollToBottom: () => void;
|
|
25
|
+
};
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React bindings, still without styling: subscribe to a slice of the store, and keep a
|
|
3
|
+
* scrolling list at its end while it grows.
|
|
4
|
+
*/
|
|
5
|
+
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
|
|
6
|
+
/**
|
|
7
|
+
* A slice of the conversation; the component redraws only when the slice changes identity.
|
|
8
|
+
* Select what the component draws and nothing more: `s => s.ids` for the list,
|
|
9
|
+
* `s => s.items[id]` for one row, `s => s.run !== null` for the composer.
|
|
10
|
+
*/
|
|
11
|
+
export function useChat(store, select) {
|
|
12
|
+
const get = () => select(store.get());
|
|
13
|
+
return useSyncExternalStore(store.subscribe, get, get);
|
|
14
|
+
}
|
|
15
|
+
/** The order of the items: changes only when one is added or removed. */
|
|
16
|
+
export const useChatIds = (store) => useChat(store, (s) => s.ids);
|
|
17
|
+
/** One item: changes only when that item does. */
|
|
18
|
+
export const useChatItem = (store, id) => useChat(store, (s) => s.items[id]);
|
|
19
|
+
/** True while a run is followed. */
|
|
20
|
+
export const useChatBusy = (store) => useChat(store, (s) => s.run !== null);
|
|
21
|
+
/** How close to the end counts as "at the end", in pixels. */
|
|
22
|
+
const SLACK = 48;
|
|
23
|
+
/**
|
|
24
|
+
* Keep a scrolling list at its end while its content grows, unless the person has scrolled
|
|
25
|
+
* up to read; scrolling back down (or scrollToBottom) resumes following. Put viewportRef on
|
|
26
|
+
* the element that scrolls and contentRef on the element inside it that grows.
|
|
27
|
+
*/
|
|
28
|
+
export function useStickToBottom() {
|
|
29
|
+
const viewportRef = useRef(null);
|
|
30
|
+
const contentRef = useRef(null);
|
|
31
|
+
const stick = useRef(true);
|
|
32
|
+
const [atBottom, setAtBottom] = useState(true);
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
const view = viewportRef.current;
|
|
35
|
+
const content = contentRef.current;
|
|
36
|
+
if (!view || !content)
|
|
37
|
+
return;
|
|
38
|
+
const onScroll = () => {
|
|
39
|
+
const near = view.scrollHeight - view.scrollTop - view.clientHeight <= SLACK;
|
|
40
|
+
stick.current = near;
|
|
41
|
+
setAtBottom(near);
|
|
42
|
+
};
|
|
43
|
+
const grown = new ResizeObserver(() => {
|
|
44
|
+
if (stick.current)
|
|
45
|
+
view.scrollTop = view.scrollHeight;
|
|
46
|
+
});
|
|
47
|
+
view.addEventListener("scroll", onScroll, { passive: true });
|
|
48
|
+
grown.observe(content);
|
|
49
|
+
view.scrollTop = view.scrollHeight;
|
|
50
|
+
return () => {
|
|
51
|
+
view.removeEventListener("scroll", onScroll);
|
|
52
|
+
grown.disconnect();
|
|
53
|
+
};
|
|
54
|
+
}, []);
|
|
55
|
+
const scrollToBottom = useCallback(() => {
|
|
56
|
+
const view = viewportRef.current;
|
|
57
|
+
stick.current = true;
|
|
58
|
+
setAtBottom(true);
|
|
59
|
+
view?.scrollTo({ top: view.scrollHeight, behavior: "smooth" });
|
|
60
|
+
}, []);
|
|
61
|
+
return { viewportRef, contentRef, atBottom, scrollToBottom };
|
|
62
|
+
}
|
package/dist/reduce.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation as data, and how each chatstream/v1 event changes it. Pure functions: no
|
|
3
|
+
* network, no timers, no framework.
|
|
4
|
+
*
|
|
5
|
+
* The shape is what keeps drawing cheap. `ids` is the order of the items and `items` holds
|
|
6
|
+
* each one by id. A change to one item replaces that item's object and the `items` record,
|
|
7
|
+
* and nothing else: `ids` keeps its identity unless an item is added or removed, and every
|
|
8
|
+
* other item keeps its identity. So a view that draws the list from `ids` and each row from
|
|
9
|
+
* its own item redraws only the row that changed: a streamed token redraws the last message.
|
|
10
|
+
*/
|
|
11
|
+
import type { StoredMessage, StreamEvent } from "./wire.ts";
|
|
12
|
+
export type ChatItem = {
|
|
13
|
+
kind: "user";
|
|
14
|
+
id: string;
|
|
15
|
+
text: string;
|
|
16
|
+
auto?: string;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "text";
|
|
19
|
+
id: string;
|
|
20
|
+
text: string;
|
|
21
|
+
streaming: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
kind: "tool";
|
|
24
|
+
id: string;
|
|
25
|
+
name: string;
|
|
26
|
+
input?: unknown;
|
|
27
|
+
result?: string;
|
|
28
|
+
status: "running" | "done" | "error";
|
|
29
|
+
} | {
|
|
30
|
+
kind: "notice";
|
|
31
|
+
id: string;
|
|
32
|
+
text: string;
|
|
33
|
+
tone: "error" | "quiet";
|
|
34
|
+
};
|
|
35
|
+
export interface Approval {
|
|
36
|
+
run: string;
|
|
37
|
+
id: string;
|
|
38
|
+
tool: string;
|
|
39
|
+
input: unknown;
|
|
40
|
+
description?: string;
|
|
41
|
+
/** "This session" and "Always" are on offer (not for a tool that asks every time). */
|
|
42
|
+
standing: boolean;
|
|
43
|
+
}
|
|
44
|
+
export interface ChatState {
|
|
45
|
+
/** Whether the host has an agent and a model, once asked. */
|
|
46
|
+
host: {
|
|
47
|
+
available: boolean;
|
|
48
|
+
ready: boolean;
|
|
49
|
+
model: string;
|
|
50
|
+
} | null;
|
|
51
|
+
/** The thread has been read (or could not be). */
|
|
52
|
+
loaded: boolean;
|
|
53
|
+
ids: readonly string[];
|
|
54
|
+
items: Readonly<Record<string, ChatItem>>;
|
|
55
|
+
/** The run being followed, when there is one. */
|
|
56
|
+
run: string | null;
|
|
57
|
+
/** The followed run's parts: part id → "text", "tool_call" or "result:<item id>". */
|
|
58
|
+
parts: Readonly<Record<string, string>>;
|
|
59
|
+
/** A question waiting for the person. */
|
|
60
|
+
approval: Approval | null;
|
|
61
|
+
error: string;
|
|
62
|
+
}
|
|
63
|
+
export declare const initialState: ChatState;
|
|
64
|
+
/** Add an item at the end (or replace one with the same id in place). */
|
|
65
|
+
export declare function append(s: ChatState, item: ChatItem): ChatState;
|
|
66
|
+
/** Change one item. Nothing else changes identity; an unknown id changes nothing. */
|
|
67
|
+
export declare function patch(s: ChatState, id: string, change: (it: ChatItem) => ChatItem): ChatState;
|
|
68
|
+
export declare function remove(s: ChatState, id: string): ChatState;
|
|
69
|
+
/** The stored thread as items. The run still going is left out: its stream rebuilds it. */
|
|
70
|
+
export declare function fromThread(messages: StoredMessage[], skipRun?: string): Pick<ChatState, "ids" | "items">;
|
|
71
|
+
/** A run begins to be followed. */
|
|
72
|
+
export declare function startRun(s: ChatState, run: string): ChatState;
|
|
73
|
+
/** The followed run is over: nothing in it is still running or streaming. */
|
|
74
|
+
export declare function endRun(s: ChatState): ChatState;
|
|
75
|
+
/** One event of the followed run. Events of any other run change nothing. */
|
|
76
|
+
export declare function reduceEvent(s: ChatState, ev: StreamEvent): ChatState;
|
package/dist/reduce.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
export const initialState = {
|
|
2
|
+
host: null,
|
|
3
|
+
loaded: false,
|
|
4
|
+
ids: [],
|
|
5
|
+
items: {},
|
|
6
|
+
run: null,
|
|
7
|
+
parts: {},
|
|
8
|
+
approval: null,
|
|
9
|
+
error: "",
|
|
10
|
+
};
|
|
11
|
+
/** Add an item at the end (or replace one with the same id in place). */
|
|
12
|
+
export function append(s, item) {
|
|
13
|
+
const ids = item.id in s.items ? s.ids : [...s.ids, item.id];
|
|
14
|
+
return { ...s, ids, items: { ...s.items, [item.id]: item } };
|
|
15
|
+
}
|
|
16
|
+
/** Change one item. Nothing else changes identity; an unknown id changes nothing. */
|
|
17
|
+
export function patch(s, id, change) {
|
|
18
|
+
const it = s.items[id];
|
|
19
|
+
if (!it)
|
|
20
|
+
return s;
|
|
21
|
+
const next = change(it);
|
|
22
|
+
return next === it ? s : { ...s, items: { ...s.items, [id]: next } };
|
|
23
|
+
}
|
|
24
|
+
export function remove(s, id) {
|
|
25
|
+
if (!(id in s.items))
|
|
26
|
+
return s;
|
|
27
|
+
const { [id]: _gone, ...items } = s.items;
|
|
28
|
+
return { ...s, ids: s.ids.filter((i) => i !== id), items };
|
|
29
|
+
}
|
|
30
|
+
/** The stored thread as items. The run still going is left out: its stream rebuilds it. */
|
|
31
|
+
export function fromThread(messages, skipRun = "") {
|
|
32
|
+
const ids = [];
|
|
33
|
+
const items = {};
|
|
34
|
+
const add = (it) => {
|
|
35
|
+
ids.push(it.id);
|
|
36
|
+
items[it.id] = it;
|
|
37
|
+
};
|
|
38
|
+
for (const m of messages) {
|
|
39
|
+
if (m.role === "user" && typeof m.meta?.text === "string") {
|
|
40
|
+
add(m.meta.auto
|
|
41
|
+
? { kind: "user", id: m.id, text: "", auto: m.meta.auto }
|
|
42
|
+
: { kind: "user", id: m.id, text: m.meta.text });
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (skipRun && m.run_id === skipRun)
|
|
46
|
+
continue;
|
|
47
|
+
m.blocks.forEach((b, i) => {
|
|
48
|
+
if (b.type === "text" && b.text)
|
|
49
|
+
add({ kind: "text", id: `${m.id}:${i}`, text: b.text, streaming: false });
|
|
50
|
+
else if (b.type === "tool_use" && b.id)
|
|
51
|
+
add({ kind: "tool", id: b.id, name: b.name ?? "", input: b.input, status: "done" });
|
|
52
|
+
else if (b.type === "tool_result" && b.tool_use_id) {
|
|
53
|
+
const call = items[b.tool_use_id];
|
|
54
|
+
if (call?.kind === "tool")
|
|
55
|
+
items[call.id] = { ...call, result: b.content ?? "", status: b.is_error ? "error" : "done" };
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
return { ids, items };
|
|
60
|
+
}
|
|
61
|
+
/** A run begins to be followed. */
|
|
62
|
+
export function startRun(s, run) {
|
|
63
|
+
return { ...s, run, parts: {}, approval: null };
|
|
64
|
+
}
|
|
65
|
+
/** The followed run is over: nothing in it is still running or streaming. */
|
|
66
|
+
export function endRun(s) {
|
|
67
|
+
let next = { ...s, run: null, parts: {}, approval: null };
|
|
68
|
+
for (const id of s.ids) {
|
|
69
|
+
const it = s.items[id];
|
|
70
|
+
if (it?.kind === "tool" && it.status === "running")
|
|
71
|
+
next = patch(next, id, () => ({ ...it, status: "done" }));
|
|
72
|
+
else if (it?.kind === "text" && it.streaming)
|
|
73
|
+
next = patch(next, id, () => ({ ...it, streaming: false }));
|
|
74
|
+
}
|
|
75
|
+
return next;
|
|
76
|
+
}
|
|
77
|
+
const note = (s, id, text, tone) => append(s, { kind: "notice", id, text, tone });
|
|
78
|
+
/** One event of the followed run. Events of any other run change nothing. */
|
|
79
|
+
export function reduceEvent(s, ev) {
|
|
80
|
+
const run = s.run;
|
|
81
|
+
if (!run || (ev.run_id && ev.run_id !== run))
|
|
82
|
+
return s;
|
|
83
|
+
// An item's id carries the run, so two runs' part ids never collide.
|
|
84
|
+
const key = (part) => `${run}:${part}`;
|
|
85
|
+
switch (ev.verb) {
|
|
86
|
+
case "part.start": {
|
|
87
|
+
if (!ev.part_id)
|
|
88
|
+
return s;
|
|
89
|
+
if (ev.kind === "text") {
|
|
90
|
+
const next = { ...s, parts: { ...s.parts, [ev.part_id]: "text" } };
|
|
91
|
+
return append(next, { kind: "text", id: key(ev.part_id), text: "", streaming: true });
|
|
92
|
+
}
|
|
93
|
+
if (ev.kind === "tool_call") {
|
|
94
|
+
const next = { ...s, parts: { ...s.parts, [ev.part_id]: "tool_call" } };
|
|
95
|
+
return append(next, { kind: "tool", id: key(ev.part_id), name: String(ev.meta?.name ?? ""), status: "running" });
|
|
96
|
+
}
|
|
97
|
+
if (ev.kind === "tool_result") {
|
|
98
|
+
const call = key(String(ev.meta?.call_id ?? ""));
|
|
99
|
+
const next = { ...s, parts: { ...s.parts, [ev.part_id]: `result:${call}` } };
|
|
100
|
+
const failed = ev.meta?.is_error === true;
|
|
101
|
+
return patch(next, call, (it) => it.kind === "tool" ? { ...it, result: "", status: failed ? "error" : "done" } : it);
|
|
102
|
+
}
|
|
103
|
+
return s;
|
|
104
|
+
}
|
|
105
|
+
case "part.delta": {
|
|
106
|
+
if (!ev.part_id || !ev.text)
|
|
107
|
+
return s;
|
|
108
|
+
const kind = s.parts[ev.part_id] ?? "";
|
|
109
|
+
const add = ev.text;
|
|
110
|
+
if (kind === "text")
|
|
111
|
+
return patch(s, key(ev.part_id), (it) => (it.kind === "text" ? { ...it, text: it.text + add } : it));
|
|
112
|
+
if (kind.startsWith("result:"))
|
|
113
|
+
return patch(s, kind.slice(7), (it) => (it.kind === "tool" ? { ...it, result: (it.result ?? "") + add } : it));
|
|
114
|
+
return s;
|
|
115
|
+
}
|
|
116
|
+
case "part.end": {
|
|
117
|
+
if (!ev.part_id)
|
|
118
|
+
return s;
|
|
119
|
+
const kind = s.parts[ev.part_id];
|
|
120
|
+
if (kind === "text")
|
|
121
|
+
return patch(s, key(ev.part_id), (it) => (it.kind === "text" ? { ...it, streaming: false } : it));
|
|
122
|
+
if (kind === "tool_call")
|
|
123
|
+
return patch(s, key(ev.part_id), (it) => (it.kind === "tool" ? { ...it, input: ev.final } : it));
|
|
124
|
+
return s;
|
|
125
|
+
}
|
|
126
|
+
case "approval.request":
|
|
127
|
+
if (!ev.approval_id || !ev.descriptor)
|
|
128
|
+
return s;
|
|
129
|
+
return {
|
|
130
|
+
...s,
|
|
131
|
+
approval: {
|
|
132
|
+
run,
|
|
133
|
+
id: ev.approval_id,
|
|
134
|
+
tool: ev.descriptor.tool,
|
|
135
|
+
input: ev.descriptor.input,
|
|
136
|
+
description: ev.descriptor.description,
|
|
137
|
+
standing: ev.descriptor.standing !== false,
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
case "activity": {
|
|
141
|
+
const what = (ev.kind ?? "").replace(/^[a-z]+\./, "");
|
|
142
|
+
if (what === "approval" && s.approval?.id === ev.value?.approval_id)
|
|
143
|
+
return { ...s, approval: null };
|
|
144
|
+
if (what === "compact" && typeof ev.value?.state === "string")
|
|
145
|
+
return note(s, key("compact"), ev.value.state === "start"
|
|
146
|
+
? "Summarising the older part of this conversation for the model…"
|
|
147
|
+
: ev.value.state === "done"
|
|
148
|
+
? "The older part of this conversation was summarised for the model. Every message is still here."
|
|
149
|
+
: "The conversation could not be shortened this time.", "quiet");
|
|
150
|
+
return s;
|
|
151
|
+
}
|
|
152
|
+
case "run.error":
|
|
153
|
+
return note(s, key("error"), ev.message || "The agent could not finish.", "error");
|
|
154
|
+
case "run.abort":
|
|
155
|
+
return note(s, key("abort"), "Stopped.", "quiet");
|
|
156
|
+
case "run.finish":
|
|
157
|
+
if (ev.reason === "turn_limit" || ev.reason === "length")
|
|
158
|
+
return note(s, key("limit"), ev.reason === "length"
|
|
159
|
+
? "The answer was cut off at the length limit."
|
|
160
|
+
: "Stopped after many steps. Say “continue” to go on.", "quiet");
|
|
161
|
+
return s;
|
|
162
|
+
default:
|
|
163
|
+
return s;
|
|
164
|
+
}
|
|
165
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A conversation with an agent host, kept outside any interface framework: a run goes on
|
|
3
|
+
* whether or not anything is showing it, and whatever draws it subscribes.
|
|
4
|
+
*
|
|
5
|
+
* History policy (the one rule for when the thread is read):
|
|
6
|
+
*
|
|
7
|
+
* 1. The thread is read once, by start(), and kept in this store for the life of the page.
|
|
8
|
+
* Closing and opening a panel does not read it again.
|
|
9
|
+
* 2. A run this store started, or one it picks up as active, is drawn from its event stream,
|
|
10
|
+
* never from the stored copy; a dropped stream resumes from the last event seen.
|
|
11
|
+
* 3. The thread is read again only when someone else changed it: a turn started outside
|
|
12
|
+
* this page (turnElsewhere), or an explicit reload(). Never on a timer, never on focus.
|
|
13
|
+
* 4. newThread() empties the store; nothing is read.
|
|
14
|
+
*
|
|
15
|
+
* Every tool runs on the server, so the turns this store sends declare none. Notifications
|
|
16
|
+
* are coalesced to one per animation frame, so a burst of tokens is one redraw.
|
|
17
|
+
*/
|
|
18
|
+
import { type ChatState } from "./reduce.ts";
|
|
19
|
+
import { type Decision, type HostApi, type HostOptions } from "./wire.ts";
|
|
20
|
+
export interface ChatStoreOptions extends HostOptions {
|
|
21
|
+
/** A host made elsewhere (tests). */
|
|
22
|
+
api?: HostApi;
|
|
23
|
+
/** How listeners are told: default once per animation frame (a microtask without one). */
|
|
24
|
+
schedule?: (flush: () => void) => void;
|
|
25
|
+
}
|
|
26
|
+
/** How a followed run ended: "finish", "error", "abort", or "lost" (the stream could not be followed). */
|
|
27
|
+
export type RunEnd = "finish" | "error" | "abort" | "lost";
|
|
28
|
+
export declare function createChatStore(opts?: ChatStoreOptions): {
|
|
29
|
+
client: string;
|
|
30
|
+
get: () => ChatState;
|
|
31
|
+
subscribe: (fn: () => void) => () => void;
|
|
32
|
+
start: () => Promise<void>;
|
|
33
|
+
send: (text: string, how?: {
|
|
34
|
+
auto?: string;
|
|
35
|
+
}) => Promise<boolean>;
|
|
36
|
+
stop: () => void;
|
|
37
|
+
answer: (decision: Decision) => Promise<void>;
|
|
38
|
+
newThread: () => Promise<void>;
|
|
39
|
+
reload: () => Promise<void>;
|
|
40
|
+
turnElsewhere: (run: string) => void;
|
|
41
|
+
/** Told when a run this store followed has ended. Returns the way to stop being told. */
|
|
42
|
+
onRunEnd: (fn: (run: string, how: RunEnd) => void) => () => void;
|
|
43
|
+
};
|
|
44
|
+
export type ChatStore = ReturnType<typeof createChatStore>;
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A conversation with an agent host, kept outside any interface framework: a run goes on
|
|
3
|
+
* whether or not anything is showing it, and whatever draws it subscribes.
|
|
4
|
+
*
|
|
5
|
+
* History policy (the one rule for when the thread is read):
|
|
6
|
+
*
|
|
7
|
+
* 1. The thread is read once, by start(), and kept in this store for the life of the page.
|
|
8
|
+
* Closing and opening a panel does not read it again.
|
|
9
|
+
* 2. A run this store started, or one it picks up as active, is drawn from its event stream,
|
|
10
|
+
* never from the stored copy; a dropped stream resumes from the last event seen.
|
|
11
|
+
* 3. The thread is read again only when someone else changed it: a turn started outside
|
|
12
|
+
* this page (turnElsewhere), or an explicit reload(). Never on a timer, never on focus.
|
|
13
|
+
* 4. newThread() empties the store; nothing is read.
|
|
14
|
+
*
|
|
15
|
+
* Every tool runs on the server, so the turns this store sends declare none. Notifications
|
|
16
|
+
* are coalesced to one per animation frame, so a burst of tokens is one redraw.
|
|
17
|
+
*/
|
|
18
|
+
import { append, endRun, fromThread, initialState, reduceEvent, remove, startRun, } from "./reduce.js";
|
|
19
|
+
import { HostError, hostApi } from "./wire.js";
|
|
20
|
+
const newId = () => typeof crypto !== "undefined" && "randomUUID" in crypto
|
|
21
|
+
? crypto.randomUUID()
|
|
22
|
+
: `c${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
23
|
+
const defaultSchedule = (flush) => {
|
|
24
|
+
if (typeof requestAnimationFrame === "function")
|
|
25
|
+
requestAnimationFrame(flush);
|
|
26
|
+
else
|
|
27
|
+
queueMicrotask(flush);
|
|
28
|
+
};
|
|
29
|
+
export function createChatStore(opts = {}) {
|
|
30
|
+
const api = opts.api ?? hostApi(opts);
|
|
31
|
+
const schedule = opts.schedule ?? defaultSchedule;
|
|
32
|
+
/** This page, to the host. */
|
|
33
|
+
const client = newId();
|
|
34
|
+
/** Runs this store started, so their agent.turn echo is not taken for someone else's. */
|
|
35
|
+
const mine = new Set();
|
|
36
|
+
let state = initialState;
|
|
37
|
+
let sending = false;
|
|
38
|
+
let started = null;
|
|
39
|
+
let following = null;
|
|
40
|
+
let pending = false;
|
|
41
|
+
let pendingSeq = 0;
|
|
42
|
+
const listeners = new Set();
|
|
43
|
+
const runEnd = new Set();
|
|
44
|
+
const flush = () => {
|
|
45
|
+
pending = false;
|
|
46
|
+
for (const fn of [...listeners])
|
|
47
|
+
fn();
|
|
48
|
+
};
|
|
49
|
+
const set = (next) => {
|
|
50
|
+
if (next === state)
|
|
51
|
+
return;
|
|
52
|
+
state = next;
|
|
53
|
+
if (!pending) {
|
|
54
|
+
pending = true;
|
|
55
|
+
schedule(flush);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
async function follow(run) {
|
|
59
|
+
following?.abort();
|
|
60
|
+
const control = new AbortController();
|
|
61
|
+
following = control;
|
|
62
|
+
set(startRun(state, run));
|
|
63
|
+
let ended = "lost";
|
|
64
|
+
const onEvent = (ev) => {
|
|
65
|
+
if (ev.verb === "run.finish")
|
|
66
|
+
ended = "finish";
|
|
67
|
+
else if (ev.verb === "run.error")
|
|
68
|
+
ended = "error";
|
|
69
|
+
else if (ev.verb === "run.abort")
|
|
70
|
+
ended = "abort";
|
|
71
|
+
set(reduceEvent(state, ev));
|
|
72
|
+
};
|
|
73
|
+
try {
|
|
74
|
+
await api.follow(run, onEvent, control.signal);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
if (!control.signal.aborted)
|
|
78
|
+
set({ ...state, error: "The connection to the agent was lost. Reload to pick it up." });
|
|
79
|
+
}
|
|
80
|
+
if (following === control) {
|
|
81
|
+
following = null;
|
|
82
|
+
set(endRun(state));
|
|
83
|
+
for (const fn of [...runEnd])
|
|
84
|
+
fn(run, ended);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** Read the thread and pick up a run that is still going. */
|
|
88
|
+
async function read() {
|
|
89
|
+
const loaded = await api.thread();
|
|
90
|
+
set({ ...state, ...fromThread(loaded.messages, loaded.active_run), loaded: true, error: "" });
|
|
91
|
+
if (loaded.active_run)
|
|
92
|
+
void follow(loaded.active_run);
|
|
93
|
+
}
|
|
94
|
+
/** Ask the host what it is and read the thread, once. Safe to call more than once. */
|
|
95
|
+
function start() {
|
|
96
|
+
started ??= (async () => {
|
|
97
|
+
try {
|
|
98
|
+
const host = await api.state();
|
|
99
|
+
set({ ...state, host });
|
|
100
|
+
if (!host.available) {
|
|
101
|
+
set({ ...state, loaded: true });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
await read();
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
set({ ...state, loaded: true, error: err instanceof Error ? err.message : "The agent could not be reached." });
|
|
108
|
+
}
|
|
109
|
+
})();
|
|
110
|
+
return started;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Send a message. With `auto`, it is one the application wrote and the person did not
|
|
114
|
+
* type: the label is shown in its place. Resolves false when it was not sent (a run is
|
|
115
|
+
* going, the host refused it); a message a reflex answered counts as sent.
|
|
116
|
+
*/
|
|
117
|
+
async function send(text, how = {}) {
|
|
118
|
+
if (state.run || sending || !text.trim())
|
|
119
|
+
return false;
|
|
120
|
+
sending = true;
|
|
121
|
+
const temp = `pending:${++pendingSeq}`;
|
|
122
|
+
set(append({ ...state, error: "" }, how.auto ? { kind: "user", id: temp, text: "", auto: how.auto } : { kind: "user", id: temp, text: text.trim() }));
|
|
123
|
+
try {
|
|
124
|
+
const { run_id } = await api.turn({ text, client_id: client, ...(how.auto ? { auto: how.auto } : {}) });
|
|
125
|
+
mine.add(run_id);
|
|
126
|
+
sending = false;
|
|
127
|
+
void follow(run_id);
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
sending = false;
|
|
132
|
+
// A reflex answered instead of the model: the message stays, with its answer.
|
|
133
|
+
if (err instanceof HostError && err.code === "halted") {
|
|
134
|
+
set(append(state, { kind: "notice", id: `${temp}:halted`, text: err.message, tone: "quiet" }));
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
set({ ...remove(state, temp), error: err instanceof HostError ? err.message : "The message could not be sent." });
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function stop() {
|
|
142
|
+
if (state.run)
|
|
143
|
+
void api.cancel(state.run).catch(() => undefined);
|
|
144
|
+
}
|
|
145
|
+
async function answer(decision) {
|
|
146
|
+
const q = state.approval;
|
|
147
|
+
if (!q)
|
|
148
|
+
return;
|
|
149
|
+
set({ ...state, approval: null });
|
|
150
|
+
await api.approve(q.run, q.id, decision).catch(() => undefined);
|
|
151
|
+
}
|
|
152
|
+
/** Put the thread away and start a new one. */
|
|
153
|
+
async function newThread() {
|
|
154
|
+
if (state.run)
|
|
155
|
+
return;
|
|
156
|
+
try {
|
|
157
|
+
await api.newThread();
|
|
158
|
+
set({ ...state, ids: [], items: {}, error: "" });
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
set({ ...state, error: err instanceof Error ? err.message : "A new conversation could not be started." });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** Read the thread again (rule 3). Does nothing while a run is followed. */
|
|
165
|
+
async function reload() {
|
|
166
|
+
if (state.run || sending)
|
|
167
|
+
return;
|
|
168
|
+
try {
|
|
169
|
+
await read();
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Left as it was.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Someone started a turn: the host announces every one. One this store did not start (the
|
|
177
|
+
* agent driven from outside, another tab) is read and followed here too (rule 3).
|
|
178
|
+
*/
|
|
179
|
+
function turnElsewhere(run) {
|
|
180
|
+
if (!run || mine.has(run) || sending || state.run === run)
|
|
181
|
+
return;
|
|
182
|
+
void reload();
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
client,
|
|
186
|
+
get: () => state,
|
|
187
|
+
subscribe: (fn) => {
|
|
188
|
+
listeners.add(fn);
|
|
189
|
+
return () => {
|
|
190
|
+
listeners.delete(fn);
|
|
191
|
+
};
|
|
192
|
+
},
|
|
193
|
+
start,
|
|
194
|
+
send,
|
|
195
|
+
stop,
|
|
196
|
+
answer,
|
|
197
|
+
newThread,
|
|
198
|
+
reload,
|
|
199
|
+
turnElsewhere,
|
|
200
|
+
/** Told when a run this store followed has ended. Returns the way to stop being told. */
|
|
201
|
+
onRunEnd: (fn) => {
|
|
202
|
+
runEnd.add(fn);
|
|
203
|
+
return () => {
|
|
204
|
+
runEnd.delete(fn);
|
|
205
|
+
};
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
}
|
package/dist/wire.d.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent-host/1 wire, as a page sees it (libs/agent/host WIRE.md): the host's routes and a
|
|
3
|
+
* follower for a run's chatstream/v1 events that resumes a dropped connection from the last
|
|
4
|
+
* event seen, so nothing is shown twice or missed.
|
|
5
|
+
*/
|
|
6
|
+
/** What the host says about itself. */
|
|
7
|
+
export interface HostState {
|
|
8
|
+
/** The server has an agent at all. */
|
|
9
|
+
available: boolean;
|
|
10
|
+
/** A model is configured, so a message can be answered. */
|
|
11
|
+
ready: boolean;
|
|
12
|
+
model: string;
|
|
13
|
+
}
|
|
14
|
+
/** A content block as the model sees it. */
|
|
15
|
+
export interface Block {
|
|
16
|
+
type: "text" | "tool_use" | "tool_result" | "thinking";
|
|
17
|
+
text?: string;
|
|
18
|
+
id?: string;
|
|
19
|
+
name?: string;
|
|
20
|
+
input?: Record<string, unknown>;
|
|
21
|
+
tool_use_id?: string;
|
|
22
|
+
content?: string;
|
|
23
|
+
is_error?: boolean;
|
|
24
|
+
}
|
|
25
|
+
export interface StoredMessage {
|
|
26
|
+
id: string;
|
|
27
|
+
seq: number;
|
|
28
|
+
role: "user" | "assistant";
|
|
29
|
+
blocks: Block[];
|
|
30
|
+
meta?: {
|
|
31
|
+
text?: string;
|
|
32
|
+
context?: unknown;
|
|
33
|
+
auto?: string;
|
|
34
|
+
};
|
|
35
|
+
run_id?: string;
|
|
36
|
+
created_at: string;
|
|
37
|
+
}
|
|
38
|
+
export interface ThreadState {
|
|
39
|
+
thread_id: string;
|
|
40
|
+
messages: StoredMessage[];
|
|
41
|
+
active_run: string;
|
|
42
|
+
}
|
|
43
|
+
export type Decision = "once" | "session" | "always" | "deny";
|
|
44
|
+
/** One chatstream/v1 event: the fields a page reads. */
|
|
45
|
+
export interface StreamEvent {
|
|
46
|
+
v?: string;
|
|
47
|
+
seq: number;
|
|
48
|
+
run_id?: string;
|
|
49
|
+
verb: string;
|
|
50
|
+
reason?: string;
|
|
51
|
+
code?: string;
|
|
52
|
+
message?: string;
|
|
53
|
+
part_id?: string;
|
|
54
|
+
kind?: string;
|
|
55
|
+
meta?: Record<string, unknown>;
|
|
56
|
+
text?: string;
|
|
57
|
+
final?: unknown;
|
|
58
|
+
approval_id?: string;
|
|
59
|
+
descriptor?: {
|
|
60
|
+
tool: string;
|
|
61
|
+
input?: unknown;
|
|
62
|
+
description?: string;
|
|
63
|
+
standing?: boolean;
|
|
64
|
+
};
|
|
65
|
+
value?: Record<string, unknown>;
|
|
66
|
+
ext?: Record<string, unknown>;
|
|
67
|
+
}
|
|
68
|
+
/** The host refused or failed a request. `code` is the host's own word for it, when it gave one. */
|
|
69
|
+
export declare class HostError extends Error {
|
|
70
|
+
readonly status: number;
|
|
71
|
+
readonly code: string;
|
|
72
|
+
constructor(status: number, message: string, code?: string);
|
|
73
|
+
}
|
|
74
|
+
export interface HostOptions {
|
|
75
|
+
/** The wire's prefix. Default "/api/agent". */
|
|
76
|
+
base?: string;
|
|
77
|
+
fetch?: typeof fetch;
|
|
78
|
+
headers?: Record<string, string>;
|
|
79
|
+
}
|
|
80
|
+
export type HostApi = ReturnType<typeof hostApi>;
|
|
81
|
+
/** The host's routes. */
|
|
82
|
+
export declare function hostApi(opts?: HostOptions): {
|
|
83
|
+
state: () => Promise<HostState>;
|
|
84
|
+
thread: () => Promise<ThreadState>;
|
|
85
|
+
newThread: () => Promise<void>;
|
|
86
|
+
turn: (body: {
|
|
87
|
+
text: string;
|
|
88
|
+
client_id: string;
|
|
89
|
+
auto?: string;
|
|
90
|
+
}) => Promise<{
|
|
91
|
+
run_id: string;
|
|
92
|
+
}>;
|
|
93
|
+
cancel: (run: string) => Promise<void>;
|
|
94
|
+
approve: (run: string, approval_id: string, decision: Decision) => Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* Follow a run to its end, calling onEvent for each event in order. A dropped connection
|
|
97
|
+
* is resumed from the last event seen. Resolves when the terminal event has arrived (or the
|
|
98
|
+
* run is long over: the thread has it); rejects when the run cannot be followed.
|
|
99
|
+
*/
|
|
100
|
+
follow(run: string, onEvent: (ev: StreamEvent) => void, signal: AbortSignal): Promise<void>;
|
|
101
|
+
};
|
|
102
|
+
/** One SSE frame's event, or null for a keepalive comment. */
|
|
103
|
+
export declare function parseFrame(frame: string): StreamEvent | null;
|
package/dist/wire.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent-host/1 wire, as a page sees it (libs/agent/host WIRE.md): the host's routes and a
|
|
3
|
+
* follower for a run's chatstream/v1 events that resumes a dropped connection from the last
|
|
4
|
+
* event seen, so nothing is shown twice or missed.
|
|
5
|
+
*/
|
|
6
|
+
/** The host refused or failed a request. `code` is the host's own word for it, when it gave one. */
|
|
7
|
+
export class HostError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
code;
|
|
10
|
+
constructor(status, message, code = "") {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const TERMINAL = new Set(["run.finish", "run.error", "run.abort"]);
|
|
17
|
+
/** The host's routes. */
|
|
18
|
+
export function hostApi(opts = {}) {
|
|
19
|
+
const base = (opts.base ?? "/api/agent").replace(/\/$/, "");
|
|
20
|
+
const doFetch = opts.fetch ?? ((input, init) => fetch(input, { credentials: "same-origin", ...init }));
|
|
21
|
+
async function request(path, method = "GET", body) {
|
|
22
|
+
const res = await doFetch(`${base}${path}`, {
|
|
23
|
+
method,
|
|
24
|
+
headers: { ...opts.headers, ...(body !== undefined ? { "Content-Type": "application/json" } : {}) },
|
|
25
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
26
|
+
});
|
|
27
|
+
if (!res.ok) {
|
|
28
|
+
let message = `The agent host answered ${res.status}.`;
|
|
29
|
+
let code = "";
|
|
30
|
+
try {
|
|
31
|
+
const data = (await res.json());
|
|
32
|
+
const said = typeof data.error === "string" ? data.error : (data.error?.message ?? data.message);
|
|
33
|
+
if (said)
|
|
34
|
+
message = said;
|
|
35
|
+
if (typeof data.code === "string")
|
|
36
|
+
code = data.code;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// No body to read: the status says it.
|
|
40
|
+
}
|
|
41
|
+
throw new HostError(res.status, message, code);
|
|
42
|
+
}
|
|
43
|
+
if (res.status === 204)
|
|
44
|
+
return undefined;
|
|
45
|
+
return (await res.json());
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
state: () => request(""),
|
|
49
|
+
thread: () => request("/thread"),
|
|
50
|
+
newThread: () => request("/thread", "DELETE"),
|
|
51
|
+
turn: (body) => request("/turns", "POST", { ...body, tools: [] }),
|
|
52
|
+
cancel: (run) => request(`/runs/${run}/cancel`, "POST", {}),
|
|
53
|
+
approve: (run, approval_id, decision) => request(`/runs/${run}/approvals`, "POST", { approval_id, decision }),
|
|
54
|
+
/**
|
|
55
|
+
* Follow a run to its end, calling onEvent for each event in order. A dropped connection
|
|
56
|
+
* is resumed from the last event seen. Resolves when the terminal event has arrived (or the
|
|
57
|
+
* run is long over: the thread has it); rejects when the run cannot be followed.
|
|
58
|
+
*/
|
|
59
|
+
async follow(run, onEvent, signal) {
|
|
60
|
+
let last = 0;
|
|
61
|
+
let failures = 0;
|
|
62
|
+
for (;;) {
|
|
63
|
+
if (signal.aborted)
|
|
64
|
+
return;
|
|
65
|
+
try {
|
|
66
|
+
const res = await doFetch(`${base}/runs/${run}/events`, {
|
|
67
|
+
headers: { ...opts.headers, ...(last ? { "Last-Event-ID": String(last) } : {}) },
|
|
68
|
+
signal,
|
|
69
|
+
});
|
|
70
|
+
if (res.status === 410 || res.status === 404)
|
|
71
|
+
return;
|
|
72
|
+
if (!res.ok || !res.body)
|
|
73
|
+
throw new Error(`events: ${res.status}`);
|
|
74
|
+
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
75
|
+
let buffer = "";
|
|
76
|
+
for (;;) {
|
|
77
|
+
const { value, done } = await reader.read();
|
|
78
|
+
if (done)
|
|
79
|
+
break;
|
|
80
|
+
buffer += value;
|
|
81
|
+
let cut = buffer.indexOf("\n\n");
|
|
82
|
+
while (cut >= 0) {
|
|
83
|
+
const frame = buffer.slice(0, cut);
|
|
84
|
+
buffer = buffer.slice(cut + 2);
|
|
85
|
+
cut = buffer.indexOf("\n\n");
|
|
86
|
+
const ev = parseFrame(frame);
|
|
87
|
+
if (!ev || ev.seq <= last)
|
|
88
|
+
continue;
|
|
89
|
+
last = ev.seq;
|
|
90
|
+
failures = 0;
|
|
91
|
+
onEvent(ev);
|
|
92
|
+
if (TERMINAL.has(ev.verb))
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// The stream closed without a terminal event: reconnect and resume.
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
if (signal.aborted)
|
|
100
|
+
return;
|
|
101
|
+
if (++failures > 5)
|
|
102
|
+
throw err;
|
|
103
|
+
}
|
|
104
|
+
await new Promise((r) => setTimeout(r, Math.min(4000, 300 * 2 ** failures)));
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** One SSE frame's event, or null for a keepalive comment. */
|
|
110
|
+
export function parseFrame(frame) {
|
|
111
|
+
const data = frame
|
|
112
|
+
.split("\n")
|
|
113
|
+
.filter((l) => l.startsWith("data:"))
|
|
114
|
+
.map((l) => l.slice(l[5] === " " ? 6 : 5))
|
|
115
|
+
.join("\n");
|
|
116
|
+
return data ? JSON.parse(data) : null;
|
|
117
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hollis-labs/surface-chat",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A conversation with an agent host, without any styling: the agent-host/1 wire, the chatstream/v1 event reducer, a store whose messages update one at a time, and scroll-follow. Visuals are the Surface registry's chat components.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/hollis-labs/surface.git",
|
|
9
|
+
"directory": "packages/chat"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/hollis-labs/surface/tree/main/packages/chat#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/hollis-labs/surface/issues"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public",
|
|
17
|
+
"registry": "https://registry.npmjs.org/"
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"main": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
36
|
+
"prepack": "npm run build"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"react": ">=19"
|
|
40
|
+
}
|
|
41
|
+
}
|