@hollis-labs/surface-chat 0.0.0-stage → 0.2.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 +69 -2
- package/dist/conversation-reduce.d.ts +17 -0
- package/dist/conversation-reduce.js +149 -0
- package/dist/conversation-store.d.ts +54 -0
- package/dist/conversation-store.js +288 -0
- package/dist/conversation.d.ts +88 -0
- package/dist/conversation.js +135 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/react.d.ts +27 -0
- package/dist/react.js +57 -0
- package/dist/reduce.d.ts +82 -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 +107 -0
- package/dist/wire.js +120 -0
- package/package.json +39 -4
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation wire, as a page sees it: one durable conversation per agent, outliving
|
|
3
|
+
* any turn and any client. A client attaches as a viewer or a controller, reads one event
|
|
4
|
+
* stream (chatstream/v1, unchanged) from wherever it says, and submits turns when it holds
|
|
5
|
+
* the right to type. Nothing here knows which agent runs the turns: any server that speaks
|
|
6
|
+
* the wire works, at any base URL.
|
|
7
|
+
*/
|
|
8
|
+
import { HostError, parseFrame } from "./wire.js";
|
|
9
|
+
/** The attachment is from before the agent's side was replaced: attach again. */
|
|
10
|
+
export const isStale = (err) => err instanceof HostError && err.status === 409 && err.code === "stale_attachment";
|
|
11
|
+
/** The conversation was reset: `data.conversation_id` is the one that replaced it. */
|
|
12
|
+
export const isClosed = (err) => err instanceof HostError && err.status === 410 && err.code === "conversation_closed";
|
|
13
|
+
async function refusal(res) {
|
|
14
|
+
let message = `The agent host answered ${res.status}.`;
|
|
15
|
+
let code = "";
|
|
16
|
+
let data = {};
|
|
17
|
+
try {
|
|
18
|
+
data = (await res.json());
|
|
19
|
+
const error = data.error;
|
|
20
|
+
const said = typeof error === "string" ? error : (error?.message ?? data.message);
|
|
21
|
+
if (typeof said === "string" && said)
|
|
22
|
+
message = said;
|
|
23
|
+
if (typeof data.code === "string")
|
|
24
|
+
code = data.code;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// No body to read: the status says it.
|
|
28
|
+
}
|
|
29
|
+
return new HostError(res.status, message, code, data);
|
|
30
|
+
}
|
|
31
|
+
export function conversationApi(opts = {}) {
|
|
32
|
+
const base = (opts.base ?? "/api/agent").replace(/\/$/, "");
|
|
33
|
+
const doFetch = opts.fetch ?? ((input, init) => fetch(input, { credentials: "same-origin", ...init }));
|
|
34
|
+
const enc = encodeURIComponent;
|
|
35
|
+
async function request(path, method = "GET", body, keepalive = false) {
|
|
36
|
+
const res = await doFetch(`${base}${path}`, {
|
|
37
|
+
method,
|
|
38
|
+
// keepalive lets a request made as the page goes away still reach the host.
|
|
39
|
+
...(keepalive ? { keepalive: true } : {}),
|
|
40
|
+
headers: { ...opts.headers, ...(body !== undefined ? { "Content-Type": "application/json" } : {}) },
|
|
41
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
42
|
+
});
|
|
43
|
+
if (!res.ok)
|
|
44
|
+
throw await refusal(res);
|
|
45
|
+
if (res.status === 204)
|
|
46
|
+
return undefined;
|
|
47
|
+
const text = await res.text();
|
|
48
|
+
return (text ? JSON.parse(text) : undefined);
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
/** The agent's current conversation, made on first use. */
|
|
52
|
+
open: (agent) => request(`/agents/${enc(agent)}/conversation`, "POST", {}),
|
|
53
|
+
/** End the agent's conversation and start a new one. The holder of the input names its attachment. */
|
|
54
|
+
reset: (agent, attachment) => request(`/agents/${enc(agent)}/conversation/reset`, "POST", attachment ? { attachment } : {}),
|
|
55
|
+
get: (id) => request(`/conversations/${enc(id)}`),
|
|
56
|
+
attach: (id, role, stream) => request(`/conversations/${enc(id)}/attachments`, "POST", { role, stream }),
|
|
57
|
+
/** Let go of an attachment, and of the input if it held it. `leaving` is for a page that is closing. */
|
|
58
|
+
detach: (id, attachment, leaving = false) => request(`/conversations/${enc(id)}/attachments/${enc(attachment)}`, "DELETE", undefined, leaving),
|
|
59
|
+
/** Take or renew the right to type. 409 when another attachment holds it. */
|
|
60
|
+
lease: (id, attachment) => request(`/conversations/${enc(id)}/lease`, "POST", { attachment }),
|
|
61
|
+
takeover: (id, attachment) => request(`/conversations/${enc(id)}/lease/takeover`, "POST", { attachment }),
|
|
62
|
+
/**
|
|
63
|
+
* Submit a turn. The events come on the event stream, not here. 403 without the right to
|
|
64
|
+
* type, 409 while a run is going, 422 when the host refuses the turn (with its reason).
|
|
65
|
+
*/
|
|
66
|
+
submit: (id, turn) => request(`/conversations/${enc(id)}/turns`, "POST", turn),
|
|
67
|
+
cancel: (id, run, attachment) => request(`/conversations/${enc(id)}/runs/${enc(run)}/cancel`, "POST", { attachment }),
|
|
68
|
+
approve: (id, approval, attachment, answer) => request(`/conversations/${enc(id)}/approvals/${enc(approval)}`, "POST", { attachment, ...answer }),
|
|
69
|
+
/**
|
|
70
|
+
* Follow a conversation's events, calling onEvent for each in order, until the signal
|
|
71
|
+
* aborts. The first connect starts where `start` says; every reconnect resumes after the
|
|
72
|
+
* last event seen, so nothing is shown twice or missed. Rejects when the stream cannot
|
|
73
|
+
* be followed any more: the attachment is stale (isStale), the conversation was reset
|
|
74
|
+
* (isClosed), or the connection keeps failing.
|
|
75
|
+
*/
|
|
76
|
+
async follow(id, attachment, start, onEvent, signal) {
|
|
77
|
+
// A cursor to resume after, once any event has been seen or the start was a number.
|
|
78
|
+
let last = typeof start === "number" ? start : -1;
|
|
79
|
+
let first = true;
|
|
80
|
+
let failures = 0;
|
|
81
|
+
for (;;) {
|
|
82
|
+
if (signal.aborted)
|
|
83
|
+
return;
|
|
84
|
+
try {
|
|
85
|
+
const after = first || last < 0 ? `&after=${first ? start : "head"}` : "";
|
|
86
|
+
const res = await doFetch(`${base}/conversations/${enc(id)}/events?attachment=${enc(attachment)}${after}`, {
|
|
87
|
+
headers: { ...opts.headers, ...(!first && last >= 0 ? { "Last-Event-ID": String(last) } : {}) },
|
|
88
|
+
signal,
|
|
89
|
+
});
|
|
90
|
+
if (res.status === 409 || res.status === 410 || res.status === 403 || res.status === 404) {
|
|
91
|
+
throw await refusal(res);
|
|
92
|
+
}
|
|
93
|
+
if (!res.ok || !res.body)
|
|
94
|
+
throw new Error(`events: ${res.status}`);
|
|
95
|
+
first = false;
|
|
96
|
+
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
97
|
+
let buffer = "";
|
|
98
|
+
for (;;) {
|
|
99
|
+
const { value, done } = await reader.read();
|
|
100
|
+
if (done)
|
|
101
|
+
break;
|
|
102
|
+
buffer += value;
|
|
103
|
+
let cut = buffer.indexOf("\n\n");
|
|
104
|
+
while (cut >= 0) {
|
|
105
|
+
const frame = buffer.slice(0, cut);
|
|
106
|
+
buffer = buffer.slice(cut + 2);
|
|
107
|
+
cut = buffer.indexOf("\n\n");
|
|
108
|
+
const ev = parseFrame(frame);
|
|
109
|
+
if (!ev)
|
|
110
|
+
continue;
|
|
111
|
+
// A gap has no cursor of its own: it is passed on and the place is kept.
|
|
112
|
+
if (typeof ev.seq === "number" && ev.seq > 0) {
|
|
113
|
+
if (ev.seq <= last)
|
|
114
|
+
continue;
|
|
115
|
+
last = ev.seq;
|
|
116
|
+
}
|
|
117
|
+
failures = 0;
|
|
118
|
+
onEvent(ev);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// The server closed the stream (a slow client, a generation change): connect again.
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
if (signal.aborted)
|
|
125
|
+
return;
|
|
126
|
+
if (err instanceof HostError)
|
|
127
|
+
throw err;
|
|
128
|
+
if (++failures > 8)
|
|
129
|
+
throw err;
|
|
130
|
+
}
|
|
131
|
+
await new Promise((r) => setTimeout(r, Math.min(4000, 150 * 2 ** failures)));
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
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
|
+
/** Anything that holds a conversation's state and tells when it changes: either store, or a wrapper. */
|
|
9
|
+
export type ChatSource = Pick<ChatStore, "get" | "subscribe">;
|
|
10
|
+
export declare function useChat<T>(store: ChatSource, select: (s: ChatState) => T): T;
|
|
11
|
+
/** The order of the items: changes only when one is added or removed. */
|
|
12
|
+
export declare const useChatIds: (store: ChatSource) => readonly string[];
|
|
13
|
+
/** One item: changes only when that item does. */
|
|
14
|
+
export declare const useChatItem: (store: ChatSource, id: string) => ChatItem | undefined;
|
|
15
|
+
/** True while a run is followed. */
|
|
16
|
+
export declare const useChatBusy: (store: ChatSource) => boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Keep a scrolling list at its end while its content grows, unless the person has scrolled
|
|
19
|
+
* up to read; scrolling back down (or scrollToBottom) resumes following. Put viewportRef on
|
|
20
|
+
* the element that scrolls and contentRef on the element inside it that grows.
|
|
21
|
+
*/
|
|
22
|
+
export declare function useStickToBottom<V extends HTMLElement = HTMLDivElement, C extends HTMLElement = HTMLDivElement>(): {
|
|
23
|
+
viewportRef: import("react").RefObject<V | null>;
|
|
24
|
+
contentRef: import("react").RefObject<C | null>;
|
|
25
|
+
atBottom: boolean;
|
|
26
|
+
scrollToBottom: () => void;
|
|
27
|
+
};
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
export function useChat(store, select) {
|
|
7
|
+
const get = () => select(store.get());
|
|
8
|
+
return useSyncExternalStore(store.subscribe, get, get);
|
|
9
|
+
}
|
|
10
|
+
/** The order of the items: changes only when one is added or removed. */
|
|
11
|
+
export const useChatIds = (store) => useChat(store, (s) => s.ids);
|
|
12
|
+
/** One item: changes only when that item does. */
|
|
13
|
+
export const useChatItem = (store, id) => useChat(store, (s) => s.items[id]);
|
|
14
|
+
/** True while a run is followed. */
|
|
15
|
+
export const useChatBusy = (store) => useChat(store, (s) => s.run !== null);
|
|
16
|
+
/** How close to the end counts as "at the end", in pixels. */
|
|
17
|
+
const SLACK = 48;
|
|
18
|
+
/**
|
|
19
|
+
* Keep a scrolling list at its end while its content grows, unless the person has scrolled
|
|
20
|
+
* up to read; scrolling back down (or scrollToBottom) resumes following. Put viewportRef on
|
|
21
|
+
* the element that scrolls and contentRef on the element inside it that grows.
|
|
22
|
+
*/
|
|
23
|
+
export function useStickToBottom() {
|
|
24
|
+
const viewportRef = useRef(null);
|
|
25
|
+
const contentRef = useRef(null);
|
|
26
|
+
const stick = useRef(true);
|
|
27
|
+
const [atBottom, setAtBottom] = useState(true);
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
const view = viewportRef.current;
|
|
30
|
+
const content = contentRef.current;
|
|
31
|
+
if (!view || !content)
|
|
32
|
+
return;
|
|
33
|
+
const onScroll = () => {
|
|
34
|
+
const near = view.scrollHeight - view.scrollTop - view.clientHeight <= SLACK;
|
|
35
|
+
stick.current = near;
|
|
36
|
+
setAtBottom(near);
|
|
37
|
+
};
|
|
38
|
+
const grown = new ResizeObserver(() => {
|
|
39
|
+
if (stick.current)
|
|
40
|
+
view.scrollTop = view.scrollHeight;
|
|
41
|
+
});
|
|
42
|
+
view.addEventListener("scroll", onScroll, { passive: true });
|
|
43
|
+
grown.observe(content);
|
|
44
|
+
view.scrollTop = view.scrollHeight;
|
|
45
|
+
return () => {
|
|
46
|
+
view.removeEventListener("scroll", onScroll);
|
|
47
|
+
grown.disconnect();
|
|
48
|
+
};
|
|
49
|
+
}, []);
|
|
50
|
+
const scrollToBottom = useCallback(() => {
|
|
51
|
+
const view = viewportRef.current;
|
|
52
|
+
stick.current = true;
|
|
53
|
+
setAtBottom(true);
|
|
54
|
+
view?.scrollTo({ top: view.scrollHeight, behavior: "smooth" });
|
|
55
|
+
}, []);
|
|
56
|
+
return { viewportRef, contentRef, atBottom, scrollToBottom };
|
|
57
|
+
}
|
package/dist/reduce.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
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
|
+
/** On the conversation wire: the last event taken, so a reconnect resumes after it. */
|
|
63
|
+
cursor?: number;
|
|
64
|
+
/** On the conversation wire: the attachment that may type now, or null when nobody holds it. */
|
|
65
|
+
holder?: string | null;
|
|
66
|
+
/** On the conversation wire: rises when the agent's side was replaced. */
|
|
67
|
+
generation?: number;
|
|
68
|
+
}
|
|
69
|
+
export declare const initialState: ChatState;
|
|
70
|
+
/** Add an item at the end (or replace one with the same id in place). */
|
|
71
|
+
export declare function append(s: ChatState, item: ChatItem): ChatState;
|
|
72
|
+
/** Change one item. Nothing else changes identity; an unknown id changes nothing. */
|
|
73
|
+
export declare function patch(s: ChatState, id: string, change: (it: ChatItem) => ChatItem): ChatState;
|
|
74
|
+
export declare function remove(s: ChatState, id: string): ChatState;
|
|
75
|
+
/** The stored thread as items. The run still going is left out: its stream rebuilds it. */
|
|
76
|
+
export declare function fromThread(messages: StoredMessage[], skipRun?: string): Pick<ChatState, "ids" | "items">;
|
|
77
|
+
/** A run begins to be followed. */
|
|
78
|
+
export declare function startRun(s: ChatState, run: string): ChatState;
|
|
79
|
+
/** The followed run is over: nothing in it is still running or streaming. */
|
|
80
|
+
export declare function endRun(s: ChatState): ChatState;
|
|
81
|
+
/** One event of the followed run. Events of any other run change nothing. */
|
|
82
|
+
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>;
|