@hollis-labs/surface-chat 0.1.0 → 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 CHANGED
@@ -42,3 +42,29 @@ row 73 commits, the list 2 (its two new items) and each of the four earlier mess
42
42
  goes to that card, every other tool to the plain row.
43
43
 
44
44
  `npm test` runs the reducer and store tests (`node --test`).
45
+
46
+ ## The conversation wire
47
+
48
+ `conversation.ts`, `conversation-reduce.ts` and `conversation-store.ts` bind the same reducer and
49
+ components to a durable conversation instead of one run at a time: the page attaches as a viewer or a
50
+ controller, reads one event stream from wherever it says, and submits turns when it holds the right to
51
+ type. `createConversationStore` offers what `createChatStore` offers, so a panel draws either.
52
+
53
+ | What it handles | How |
54
+ |---|---|
55
+ | First paint and reload | Attach, read the stream from 0 (history arrives without deltas), then follow it. No separate history read |
56
+ | The sender's own message | Drawn at once under its request id; the stream's copy takes the same item, so it is never shown twice |
57
+ | A client that takes no deltas | A finished part carries its whole content, so `stream: "committed"` draws the same messages |
58
+ | A dropped connection | Resumes after the last event seen |
59
+ | The agent's side replaced (409 `stale_attachment`) | Attaches again and keeps its cursor |
60
+ | The conversation reset (410 `conversation_closed`) | Moves to the new conversation |
61
+ | Another window typing | A refused send says so; `takeover()` takes the input |
62
+ | A turn the host refuses (422) | The message stays, with the reason under it |
63
+
64
+ It assumes nothing about which agent runs the turns, only the wire (`github.com/hollis-labs/libs/agent/chat`),
65
+ at any base URL. The tests run it against an in-memory host (`test/fake-host.ts`) that follows the wire's
66
+ rules and event shapes. Surface's panel uses it when the server says the conversation wire is on, and the
67
+ run store otherwise.
68
+
69
+ A window that only watches (`role: "viewer"`) becomes a controller when it takes over. A page that is going
70
+ away should call `dispose()`: it detaches, which releases the input for the next page.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The conversation stream as items. One stream carries every run of a conversation, the
3
+ * user's own messages included, so the same reducer draws a first paint from history, a
4
+ * live answer, another tab's turn, and a reconnect. It is pure: events in, state out.
5
+ *
6
+ * It builds on the run reducer (reduce.ts) and adds what a conversation needs: a run starts
7
+ * when its run.start arrives, the user's message comes from the stream (and takes the place
8
+ * of the one the sending page already drew, by request id), a finished part carries its
9
+ * whole content in `final` (so a client that takes no deltas draws the same thing), and the
10
+ * cursor, the holder of the input and the generation are kept.
11
+ */
12
+ import { type ChatState } from "./reduce.ts";
13
+ import type { StreamEvent } from "./wire.ts";
14
+ /** The id of the item for a message the user sent with this request id. */
15
+ export declare const userItemId: (requestId: string) => string;
16
+ /** One event of the conversation, in order. An event at or before the cursor changes nothing. */
17
+ export declare function reduceConversation(state: ChatState, ev: StreamEvent): ChatState;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The conversation stream as items. One stream carries every run of a conversation, the
3
+ * user's own messages included, so the same reducer draws a first paint from history, a
4
+ * live answer, another tab's turn, and a reconnect. It is pure: events in, state out.
5
+ *
6
+ * It builds on the run reducer (reduce.ts) and adds what a conversation needs: a run starts
7
+ * when its run.start arrives, the user's message comes from the stream (and takes the place
8
+ * of the one the sending page already drew, by request id), a finished part carries its
9
+ * whole content in `final` (so a client that takes no deltas draws the same thing), and the
10
+ * cursor, the holder of the input and the generation are kept.
11
+ */
12
+ import { append, endRun, patch, reduceEvent, remove, startRun } from "./reduce.js";
13
+ const TERMINAL = new Set(["run.finish", "run.error", "run.abort"]);
14
+ /** In `parts`: the item the user's message of this run is, while that message is open. */
15
+ const USER = "@user";
16
+ /** The id of the item for a message the user sent with this request id. */
17
+ export const userItemId = (requestId) => `user:${requestId}`;
18
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
19
+ /** A finished part's text: `final` is `{text}` for text parts and `{text, is_error}` for a tool's result. */
20
+ function finalText(final) {
21
+ const text = record(final).text;
22
+ return typeof text === "string" ? text : undefined;
23
+ }
24
+ /** The label of a message the app wrote and nobody typed, from the turn's meta. */
25
+ function autoLabel(meta) {
26
+ const own = record(meta);
27
+ const auto = own.auto ?? record(own.meta).auto;
28
+ if (typeof auto === "string" && auto)
29
+ return auto;
30
+ return auto === true ? "automatic" : undefined;
31
+ }
32
+ /** One event of the conversation, in order. An event at or before the cursor changes nothing. */
33
+ export function reduceConversation(state, ev) {
34
+ if (typeof ev.seq === "number" && ev.seq > 0) {
35
+ if (ev.seq <= (state.cursor ?? 0))
36
+ return state;
37
+ state = { ...state, cursor: ev.seq };
38
+ }
39
+ const s = state;
40
+ // Conversation-level events carry no run.
41
+ if (ev.verb === "activity" && ev.kind?.startsWith("chat.")) {
42
+ const value = record(ev.value);
43
+ if (ev.kind === "chat.lease") {
44
+ // {state: "acquired" | "released", attachment, previous?}; a renewal is not published.
45
+ const holder = value.state === "released" ? null : value.attachment;
46
+ return { ...s, holder: typeof holder === "string" && holder ? holder : null };
47
+ }
48
+ if (ev.kind === "chat.generation" && typeof value.generation === "number") {
49
+ return { ...s, generation: value.generation, holder: null };
50
+ }
51
+ if (ev.kind !== "chat.approval")
52
+ return s;
53
+ }
54
+ if (ev.verb === "gap") {
55
+ // What was being drawn of the run in progress cannot be trusted: drop it and say so.
56
+ let next = s;
57
+ for (const id of s.ids) {
58
+ const it = s.items[id];
59
+ if ((it?.kind === "text" && it.streaming) || (it?.kind === "tool" && it.status === "running"))
60
+ next = remove(next, id);
61
+ }
62
+ return append({ ...next, parts: {} }, {
63
+ kind: "notice",
64
+ // A gap carries no cursor of its own: it is named by the last event taken.
65
+ id: `gap:${s.cursor ?? 0}`,
66
+ text: "Part of this conversation could not be replayed.",
67
+ tone: "quiet",
68
+ });
69
+ }
70
+ if (!ev.run_id)
71
+ return s;
72
+ // A run begins with run.start; one joined part-way is picked up at its next event.
73
+ let cur = s;
74
+ if (ev.verb === "run.start" || (cur.run !== ev.run_id && !TERMINAL.has(ev.verb))) {
75
+ if (cur.run && cur.run !== ev.run_id)
76
+ cur = endRun(cur);
77
+ cur = { ...startRun(cur, ev.run_id), error: "" };
78
+ if (ev.verb === "run.start")
79
+ return cur;
80
+ }
81
+ if (cur.run !== ev.run_id)
82
+ return cur;
83
+ const run = ev.run_id;
84
+ const key = (part) => `${run}:${part}`;
85
+ switch (ev.verb) {
86
+ case "message.start": {
87
+ if (ev.role !== "user") {
88
+ if (!(USER in cur.parts))
89
+ return cur;
90
+ const { [USER]: _open, ...parts } = cur.parts;
91
+ return { ...cur, parts };
92
+ }
93
+ const meta = record(ev.meta);
94
+ const request = typeof meta.request_id === "string" ? meta.request_id : "";
95
+ const id = request ? userItemId(request) : key(`user:${ev.message_id ?? ""}`);
96
+ const auto = autoLabel(meta);
97
+ const had = cur.items[id];
98
+ // The page that sent it already shows it: the item stays, in its place.
99
+ const item = had?.kind === "user" ? had : auto ? { kind: "user", id, text: "", auto } : { kind: "user", id, text: "" };
100
+ return append({ ...cur, parts: { ...cur.parts, [USER]: id } }, item);
101
+ }
102
+ case "message.end": {
103
+ if (!(USER in cur.parts))
104
+ return cur;
105
+ const { [USER]: _open, ...parts } = cur.parts;
106
+ return { ...cur, parts };
107
+ }
108
+ case "part.start": {
109
+ const user = cur.parts[USER];
110
+ if (user && ev.part_id && ev.kind === "text") {
111
+ return { ...cur, parts: { ...cur.parts, [ev.part_id]: `user:${user}` } };
112
+ }
113
+ return reduceEvent(cur, ev);
114
+ }
115
+ case "part.delta": {
116
+ const kind = ev.part_id ? cur.parts[ev.part_id] : undefined;
117
+ if (kind?.startsWith("user:") && ev.text) {
118
+ const add = ev.text;
119
+ return patch(cur, kind.slice(5), (it) => (it.kind === "user" && !it.auto ? { ...it, text: it.text + add } : it));
120
+ }
121
+ return reduceEvent(cur, ev);
122
+ }
123
+ case "part.end": {
124
+ const kind = ev.part_id ? cur.parts[ev.part_id] : undefined;
125
+ if (!ev.part_id || !kind)
126
+ return cur;
127
+ const text = finalText(ev.final);
128
+ if (kind.startsWith("user:")) {
129
+ if (text === undefined)
130
+ return cur;
131
+ return patch(cur, kind.slice(5), (it) => it.kind === "user" && !it.auto && it.text !== text ? { ...it, text } : it);
132
+ }
133
+ if (kind === "text") {
134
+ return patch(cur, key(ev.part_id), (it) => it.kind === "text" ? { ...it, text: text ?? it.text, streaming: false } : it);
135
+ }
136
+ if (kind.startsWith("result:")) {
137
+ const failed = record(ev.final).is_error === true;
138
+ return patch(cur, kind.slice(7), (it) => it.kind === "tool" ? { ...it, result: text ?? it.result ?? "", status: failed ? "error" : it.status } : it);
139
+ }
140
+ return reduceEvent(cur, ev);
141
+ }
142
+ case "run.finish":
143
+ case "run.error":
144
+ case "run.abort":
145
+ return endRun(reduceEvent(cur, ev));
146
+ default:
147
+ return reduceEvent(cur, ev);
148
+ }
149
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * A conversation on the conversation wire, kept outside any interface framework. It offers
3
+ * what the run store (store.ts) offers, so whatever draws one draws the other, and adds
4
+ * what a durable conversation brings: it survives a reload, another tab can watch or take
5
+ * over, and a turn started anywhere shows here.
6
+ *
7
+ * History policy, in one rule: everything is the event stream. start() attaches and reads
8
+ * the stream from the beginning (history arrives without deltas); from then on the store
9
+ * follows it, and a reconnect resumes after the last event seen. There is no separate
10
+ * history read and nothing is fetched on a timer or on focus.
11
+ *
12
+ * It assumes nothing about which agent runs the turns: only the wire.
13
+ */
14
+ import { type ConversationApi, type ConversationOptions, type Role, type StreamMode } from "./conversation.ts";
15
+ import { type ChatState } from "./reduce.ts";
16
+ import type { RunEnd } from "./store.ts";
17
+ import { type Decision, type HostState } from "./wire.ts";
18
+ export interface ConversationStoreOptions extends ConversationOptions {
19
+ /** The agent whose conversation this is. */
20
+ agent: string;
21
+ /** "controller" may type; "viewer" only watches. Default controller. */
22
+ role?: Role;
23
+ /** Default "deltas". */
24
+ stream?: StreamMode;
25
+ /** Whether the host has an agent and a model. The wire does not say; a host that knows passes this. */
26
+ hostState?: () => Promise<HostState>;
27
+ /** An api made elsewhere (tests). */
28
+ api?: ConversationApi;
29
+ /** How listeners are told: default once per animation frame (a microtask without one). */
30
+ schedule?: (flush: () => void) => void;
31
+ }
32
+ export declare function createConversationStore(opts: ConversationStoreOptions): {
33
+ get: () => ChatState;
34
+ subscribe: (fn: () => void) => () => void;
35
+ start: () => Promise<void>;
36
+ send: (text: string, how?: {
37
+ auto?: string;
38
+ }) => Promise<boolean>;
39
+ stop: () => void;
40
+ answer: (decision: Decision) => Promise<void>;
41
+ newThread: () => Promise<void>;
42
+ takeover: () => Promise<boolean>;
43
+ dispose: () => void;
44
+ /** This page's attachment, to compare with `holder`. Empty until attached. */
45
+ attachment: () => string;
46
+ /** "viewer" while this window only watches; a takeover makes it a controller. */
47
+ role: () => Role;
48
+ /** The stream is the history: there is nothing to read again. Kept so a caller of the run store need not change. */
49
+ reload: () => Promise<void>;
50
+ turnElsewhere: (_run: string) => void;
51
+ /** Told when a run ended while this page watched. Returns the way to stop being told. */
52
+ onRunEnd: (fn: (run: string, how: RunEnd) => void) => () => void;
53
+ };
54
+ export type ConversationStore = ReturnType<typeof createConversationStore>;
@@ -0,0 +1,288 @@
1
+ /**
2
+ * A conversation on the conversation wire, kept outside any interface framework. It offers
3
+ * what the run store (store.ts) offers, so whatever draws one draws the other, and adds
4
+ * what a durable conversation brings: it survives a reload, another tab can watch or take
5
+ * over, and a turn started anywhere shows here.
6
+ *
7
+ * History policy, in one rule: everything is the event stream. start() attaches and reads
8
+ * the stream from the beginning (history arrives without deltas); from then on the store
9
+ * follows it, and a reconnect resumes after the last event seen. There is no separate
10
+ * history read and nothing is fetched on a timer or on focus.
11
+ *
12
+ * It assumes nothing about which agent runs the turns: only the wire.
13
+ */
14
+ import { conversationApi, isClosed, isStale, } from "./conversation.js";
15
+ import { reduceConversation, userItemId } from "./conversation-reduce.js";
16
+ import { append, initialState, remove } from "./reduce.js";
17
+ import { HostError } from "./wire.js";
18
+ const newId = () => typeof crypto !== "undefined" && "randomUUID" in crypto
19
+ ? crypto.randomUUID()
20
+ : `c${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
21
+ const defaultSchedule = (flush) => {
22
+ if (typeof requestAnimationFrame === "function")
23
+ requestAnimationFrame(flush);
24
+ else
25
+ queueMicrotask(flush);
26
+ };
27
+ const ENDS = { "run.finish": "finish", "run.error": "error", "run.abort": "abort" };
28
+ export function createConversationStore(opts) {
29
+ const api = opts.api ?? conversationApi(opts);
30
+ const schedule = opts.schedule ?? defaultSchedule;
31
+ let role = opts.role ?? "controller";
32
+ const mode = opts.stream ?? "deltas";
33
+ let state = initialState;
34
+ let conversation = "";
35
+ let attachment = "";
36
+ /** The head when this store attached: history is everything up to it. */
37
+ let historyHead = 0;
38
+ let sending = false;
39
+ let started = null;
40
+ let following = null;
41
+ let disposed = false;
42
+ let pending = false;
43
+ const listeners = new Set();
44
+ const runEnd = new Set();
45
+ const flush = () => {
46
+ pending = false;
47
+ for (const fn of [...listeners])
48
+ fn();
49
+ };
50
+ const set = (next) => {
51
+ if (next === state)
52
+ return;
53
+ state = next;
54
+ if (!pending) {
55
+ pending = true;
56
+ schedule(flush);
57
+ }
58
+ };
59
+ const onEvent = (ev) => {
60
+ let next = reduceConversation(state, ev);
61
+ if (!next.loaded && (next.cursor ?? 0) >= historyHead)
62
+ next = { ...next, loaded: true };
63
+ set(next);
64
+ const how = ENDS[ev.verb];
65
+ // Only a run that ended while this page watched is announced, not one replayed from history.
66
+ if (how && ev.run_id && ev.seq > historyHead)
67
+ for (const fn of [...runEnd])
68
+ fn(ev.run_id, how);
69
+ };
70
+ async function attach() {
71
+ const a = await api.attach(conversation, role, mode);
72
+ attachment = a.attachment_id;
73
+ return a;
74
+ }
75
+ /** Follow the stream until this store is disposed, attaching again when it must. */
76
+ async function follow() {
77
+ following?.abort();
78
+ const control = new AbortController();
79
+ following = control;
80
+ while (!control.signal.aborted && !disposed) {
81
+ try {
82
+ await api.follow(conversation, attachment, state.cursor ?? 0, onEvent, control.signal);
83
+ return;
84
+ }
85
+ catch (err) {
86
+ if (control.signal.aborted || disposed)
87
+ return;
88
+ try {
89
+ if (isStale(err)) {
90
+ // The agent's side was replaced. The log and the cursor are as they were.
91
+ await attach();
92
+ continue;
93
+ }
94
+ if (isClosed(err)) {
95
+ await moveTo(String(err.data.conversation_id ?? ""));
96
+ continue;
97
+ }
98
+ }
99
+ catch {
100
+ // Could not attach again: reported below.
101
+ }
102
+ set({ ...state, loaded: true, error: "The connection to the agent was lost. Reload to pick it up." });
103
+ return;
104
+ }
105
+ }
106
+ }
107
+ /** The conversation was replaced by a new one: start over on it. */
108
+ async function moveTo(id) {
109
+ if (!id) {
110
+ const now = await api.open(opts.agent);
111
+ id = now.conversation_id;
112
+ }
113
+ conversation = id;
114
+ const a = await attach();
115
+ historyHead = a.head;
116
+ set({ ...initialState, host: state.host, loaded: a.head === 0 });
117
+ }
118
+ /** Attach to the agent's conversation and follow it, once. Safe to call more than once. */
119
+ function start() {
120
+ started ??= (async () => {
121
+ try {
122
+ if (opts.hostState) {
123
+ const host = await opts.hostState();
124
+ set({ ...state, host });
125
+ if (!host.available) {
126
+ set({ ...state, loaded: true });
127
+ return;
128
+ }
129
+ }
130
+ else {
131
+ set({ ...state, host: { available: true, ready: true, model: "" } });
132
+ }
133
+ const conv = await api.open(opts.agent);
134
+ conversation = conv.conversation_id;
135
+ const a = await attach();
136
+ historyHead = a.head;
137
+ set({ ...state, loaded: a.head === 0, holder: conv.lease?.attachment ?? null, generation: conv.generation });
138
+ void follow();
139
+ }
140
+ catch (err) {
141
+ set({ ...state, loaded: true, error: err instanceof Error ? err.message : "The agent could not be reached." });
142
+ }
143
+ })();
144
+ return started;
145
+ }
146
+ /**
147
+ * Send a message. With `auto`, it is one the application wrote and the person did not
148
+ * type. Resolves false when it was not sent: a run is going, this page may not type, or
149
+ * the host refused it. A message the host answered itself counts as sent.
150
+ */
151
+ async function send(text, how = {}) {
152
+ if (state.run || sending || !text.trim() || !attachment)
153
+ return false;
154
+ if (role !== "controller") {
155
+ set({ ...state, error: "This window is only watching. Take over to type." });
156
+ return false;
157
+ }
158
+ sending = true;
159
+ const request = newId();
160
+ const id = userItemId(request);
161
+ set(append({ ...state, error: "" }, how.auto ? { kind: "user", id, text: "", auto: how.auto } : { kind: "user", id, text: text.trim() }));
162
+ const turn = () => api.submit(conversation, {
163
+ attachment,
164
+ text,
165
+ request_id: request,
166
+ ...(how.auto ? { meta: { auto: how.auto } } : {}),
167
+ });
168
+ try {
169
+ try {
170
+ await turn();
171
+ }
172
+ catch (err) {
173
+ if (!isStale(err))
174
+ throw err;
175
+ // Attach again and send the same request: its id makes the retry safe.
176
+ await attach();
177
+ await turn();
178
+ }
179
+ return true;
180
+ }
181
+ catch (err) {
182
+ // The host refused the turn and said why (a reflex stopped it): the message stays.
183
+ if (err instanceof HostError && err.status === 422) {
184
+ set(append(state, { kind: "notice", id: `${id}:refused`, text: err.message, tone: "quiet" }));
185
+ return true;
186
+ }
187
+ const message = err instanceof HostError && err.status === 403
188
+ ? "Another window has the input. Take over to type here."
189
+ : err instanceof HostError
190
+ ? err.message
191
+ : "The message could not be sent.";
192
+ set({ ...remove(state, id), error: message });
193
+ return false;
194
+ }
195
+ finally {
196
+ sending = false;
197
+ }
198
+ }
199
+ function stop() {
200
+ if (state.run)
201
+ void api.cancel(conversation, state.run, attachment).catch(() => undefined);
202
+ }
203
+ /** Answer the question the agent is waiting on. "session" lasts this conversation. */
204
+ async function answer(decision) {
205
+ const q = state.approval;
206
+ if (!q)
207
+ return;
208
+ set({ ...state, approval: null });
209
+ await api
210
+ .approve(conversation, q.id, attachment, decision === "deny"
211
+ ? { decision: "deny", scope: "once" }
212
+ : { decision: "allow", scope: decision === "session" ? "conversation" : decision })
213
+ .catch((err) => {
214
+ if (err instanceof HostError)
215
+ set({ ...state, approval: q, error: err.message });
216
+ });
217
+ }
218
+ /** End this conversation and start a new one. Every attached page follows to it. */
219
+ async function newThread() {
220
+ if (state.run)
221
+ return;
222
+ try {
223
+ await api.reset(opts.agent, attachment);
224
+ // This page's own stream ends with "conversation closed" and follow() moves on.
225
+ }
226
+ catch (err) {
227
+ set({ ...state, error: err instanceof Error ? err.message : "A new conversation could not be started." });
228
+ }
229
+ }
230
+ /** Take the right to type from whoever holds it. A window that was only watching becomes a controller first. */
231
+ async function takeover() {
232
+ try {
233
+ if (role === "viewer") {
234
+ const was = attachment;
235
+ role = "controller";
236
+ await attach();
237
+ void api.detach(conversation, was).catch(() => undefined);
238
+ // The stream goes on under the new attachment, from where this window already is.
239
+ void follow();
240
+ }
241
+ await api.takeover(conversation, attachment);
242
+ set({ ...state, holder: attachment, error: "" });
243
+ return true;
244
+ }
245
+ catch (err) {
246
+ set({ ...state, error: err instanceof Error ? err.message : "The input could not be taken over." });
247
+ return false;
248
+ }
249
+ }
250
+ /** Stop following and let go of the attachment. A run in progress goes on without this page. */
251
+ function dispose() {
252
+ disposed = true;
253
+ following?.abort();
254
+ // Detaching releases the input, so the next page (a reload, another tab) can type at once.
255
+ if (conversation && attachment)
256
+ void api.detach(conversation, attachment, true).catch(() => undefined);
257
+ }
258
+ return {
259
+ get: () => state,
260
+ subscribe: (fn) => {
261
+ listeners.add(fn);
262
+ return () => {
263
+ listeners.delete(fn);
264
+ };
265
+ },
266
+ start,
267
+ send,
268
+ stop,
269
+ answer,
270
+ newThread,
271
+ takeover,
272
+ dispose,
273
+ /** This page's attachment, to compare with `holder`. Empty until attached. */
274
+ attachment: () => attachment,
275
+ /** "viewer" while this window only watches; a takeover makes it a controller. */
276
+ role: () => role,
277
+ /** The stream is the history: there is nothing to read again. Kept so a caller of the run store need not change. */
278
+ reload: async () => { },
279
+ turnElsewhere: (_run) => { },
280
+ /** Told when a run ended while this page watched. Returns the way to stop being told. */
281
+ onRunEnd: (fn) => {
282
+ runEnd.add(fn);
283
+ return () => {
284
+ runEnd.delete(fn);
285
+ };
286
+ },
287
+ };
288
+ }
@@ -0,0 +1,88 @@
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, type StreamEvent } from "./wire.ts";
9
+ export type Role = "viewer" | "controller";
10
+ /** "deltas" takes text as it is written; "committed" takes each part once, whole. */
11
+ export type StreamMode = "deltas" | "committed";
12
+ export interface Conversation {
13
+ conversation_id: string;
14
+ /** The cursor of the latest event. */
15
+ head: number;
16
+ active_run?: string | null;
17
+ lease?: {
18
+ attachment: string;
19
+ expires_at?: string;
20
+ } | null;
21
+ generation?: number;
22
+ /** What to expect: deltas (false: whole messages only), approvals, always (standing grants are kept). */
23
+ capabilities?: {
24
+ deltas?: boolean;
25
+ approvals?: boolean;
26
+ always?: boolean;
27
+ };
28
+ }
29
+ export interface Attachment {
30
+ attachment_id: string;
31
+ head: number;
32
+ }
33
+ /** What a person decided about a tool the agent asked to run. */
34
+ export interface ApprovalAnswer {
35
+ decision: "allow" | "deny";
36
+ /** "once" is this call; "conversation" the rest of this conversation; "always" a standing grant. */
37
+ scope: "once" | "conversation" | "always";
38
+ }
39
+ export interface ConversationOptions {
40
+ /** The wire's prefix. Default "/api/agent". */
41
+ base?: string;
42
+ fetch?: typeof fetch;
43
+ headers?: Record<string, string>;
44
+ }
45
+ /** Where a first connect starts reading: 0 for everything, a cursor, or "head" for new events only. */
46
+ export type Start = number | "head";
47
+ export type ConversationApi = ReturnType<typeof conversationApi>;
48
+ /** The attachment is from before the agent's side was replaced: attach again. */
49
+ export declare const isStale: (err: unknown) => err is HostError;
50
+ /** The conversation was reset: `data.conversation_id` is the one that replaced it. */
51
+ export declare const isClosed: (err: unknown) => err is HostError;
52
+ export declare function conversationApi(opts?: ConversationOptions): {
53
+ /** The agent's current conversation, made on first use. */
54
+ open: (agent: string) => Promise<Conversation>;
55
+ /** End the agent's conversation and start a new one. The holder of the input names its attachment. */
56
+ reset: (agent: string, attachment?: string) => Promise<Conversation>;
57
+ get: (id: string) => Promise<Conversation>;
58
+ attach: (id: string, role: Role, stream: StreamMode) => Promise<Attachment>;
59
+ /** Let go of an attachment, and of the input if it held it. `leaving` is for a page that is closing. */
60
+ detach: (id: string, attachment: string, leaving?: boolean) => Promise<void>;
61
+ /** Take or renew the right to type. 409 when another attachment holds it. */
62
+ lease: (id: string, attachment: string) => Promise<void>;
63
+ takeover: (id: string, attachment: string) => Promise<void>;
64
+ /**
65
+ * Submit a turn. The events come on the event stream, not here. 403 without the right to
66
+ * type, 409 while a run is going, 422 when the host refuses the turn (with its reason).
67
+ */
68
+ submit: (id: string, turn: {
69
+ attachment: string;
70
+ text: string;
71
+ request_id: string;
72
+ meta?: Record<string, unknown>;
73
+ context?: unknown;
74
+ }) => Promise<{
75
+ run_id: string;
76
+ cursor: number;
77
+ }>;
78
+ cancel: (id: string, run: string, attachment: string) => Promise<void>;
79
+ approve: (id: string, approval: string, attachment: string, answer: ApprovalAnswer) => Promise<void>;
80
+ /**
81
+ * Follow a conversation's events, calling onEvent for each in order, until the signal
82
+ * aborts. The first connect starts where `start` says; every reconnect resumes after the
83
+ * last event seen, so nothing is shown twice or missed. Rejects when the stream cannot
84
+ * be followed any more: the attachment is stale (isStale), the conversation was reset
85
+ * (isClosed), or the connection keeps failing.
86
+ */
87
+ follow(id: string, attachment: string, start: Start, onEvent: (ev: StreamEvent) => void, signal: AbortSignal): Promise<void>;
88
+ };
@@ -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 CHANGED
@@ -1,3 +1,6 @@
1
+ export * from "./conversation.ts";
2
+ export * from "./conversation-reduce.ts";
3
+ export * from "./conversation-store.ts";
1
4
  export * from "./react.ts";
2
5
  export * from "./reduce.ts";
3
6
  export * from "./store.ts";
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ export * from "./conversation.js";
2
+ export * from "./conversation-reduce.js";
3
+ export * from "./conversation-store.js";
1
4
  export * from "./react.js";
2
5
  export * from "./reduce.js";
3
6
  export * from "./store.js";
package/dist/react.d.ts CHANGED
@@ -5,13 +5,15 @@ import type { ChatStore } from "./store.ts";
5
5
  * Select what the component draws and nothing more: `s => s.ids` for the list,
6
6
  * `s => s.items[id]` for one row, `s => s.run !== null` for the composer.
7
7
  */
8
- export declare function useChat<T>(store: ChatStore, select: (s: ChatState) => T): T;
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;
9
11
  /** The order of the items: changes only when one is added or removed. */
10
- export declare const useChatIds: (store: ChatStore) => readonly string[];
12
+ export declare const useChatIds: (store: ChatSource) => readonly string[];
11
13
  /** One item: changes only when that item does. */
12
- export declare const useChatItem: (store: ChatStore, id: string) => ChatItem | undefined;
14
+ export declare const useChatItem: (store: ChatSource, id: string) => ChatItem | undefined;
13
15
  /** True while a run is followed. */
14
- export declare const useChatBusy: (store: ChatStore) => boolean;
16
+ export declare const useChatBusy: (store: ChatSource) => boolean;
15
17
  /**
16
18
  * Keep a scrolling list at its end while its content grows, unless the person has scrolled
17
19
  * up to read; scrolling back down (or scrollToBottom) resumes following. Put viewportRef on
package/dist/react.js CHANGED
@@ -3,11 +3,6 @@
3
3
  * scrolling list at its end while it grows.
4
4
  */
5
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
6
  export function useChat(store, select) {
12
7
  const get = () => select(store.get());
13
8
  return useSyncExternalStore(store.subscribe, get, get);
package/dist/reduce.d.ts CHANGED
@@ -59,6 +59,12 @@ export interface ChatState {
59
59
  /** A question waiting for the person. */
60
60
  approval: Approval | null;
61
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;
62
68
  }
63
69
  export declare const initialState: ChatState;
64
70
  /** Add an item at the end (or replace one with the same id in place). */
package/dist/wire.d.ts CHANGED
@@ -50,6 +50,8 @@ export interface StreamEvent {
50
50
  reason?: string;
51
51
  code?: string;
52
52
  message?: string;
53
+ message_id?: string;
54
+ role?: string;
53
55
  part_id?: string;
54
56
  kind?: string;
55
57
  meta?: Record<string, unknown>;
@@ -69,7 +71,9 @@ export interface StreamEvent {
69
71
  export declare class HostError extends Error {
70
72
  readonly status: number;
71
73
  readonly code: string;
72
- constructor(status: number, message: string, code?: string);
74
+ /** The rest of what the host said with the refusal (a new conversation id, a generation). */
75
+ readonly data: Record<string, unknown>;
76
+ constructor(status: number, message: string, code?: string, data?: Record<string, unknown>);
73
77
  }
74
78
  export interface HostOptions {
75
79
  /** The wire's prefix. Default "/api/agent". */
package/dist/wire.js CHANGED
@@ -7,10 +7,13 @@
7
7
  export class HostError extends Error {
8
8
  status;
9
9
  code;
10
- constructor(status, message, code = "") {
10
+ /** The rest of what the host said with the refusal (a new conversation id, a generation). */
11
+ data;
12
+ constructor(status, message, code = "", data = {}) {
11
13
  super(message);
12
14
  this.status = status;
13
15
  this.code = code;
16
+ this.data = data;
14
17
  }
15
18
  }
16
19
  const TERMINAL = new Set(["run.finish", "run.error", "run.abort"]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hollis-labs/surface-chat",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
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
5
  "license": "MIT",
6
6
  "repository": {