@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/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,107 @@
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
+ message_id?: string;
54
+ role?: string;
55
+ part_id?: string;
56
+ kind?: string;
57
+ meta?: Record<string, unknown>;
58
+ text?: string;
59
+ final?: unknown;
60
+ approval_id?: string;
61
+ descriptor?: {
62
+ tool: string;
63
+ input?: unknown;
64
+ description?: string;
65
+ standing?: boolean;
66
+ };
67
+ value?: Record<string, unknown>;
68
+ ext?: Record<string, unknown>;
69
+ }
70
+ /** The host refused or failed a request. `code` is the host's own word for it, when it gave one. */
71
+ export declare class HostError extends Error {
72
+ readonly status: number;
73
+ readonly 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>);
77
+ }
78
+ export interface HostOptions {
79
+ /** The wire's prefix. Default "/api/agent". */
80
+ base?: string;
81
+ fetch?: typeof fetch;
82
+ headers?: Record<string, string>;
83
+ }
84
+ export type HostApi = ReturnType<typeof hostApi>;
85
+ /** The host's routes. */
86
+ export declare function hostApi(opts?: HostOptions): {
87
+ state: () => Promise<HostState>;
88
+ thread: () => Promise<ThreadState>;
89
+ newThread: () => Promise<void>;
90
+ turn: (body: {
91
+ text: string;
92
+ client_id: string;
93
+ auto?: string;
94
+ }) => Promise<{
95
+ run_id: string;
96
+ }>;
97
+ cancel: (run: string) => Promise<void>;
98
+ approve: (run: string, approval_id: string, decision: Decision) => Promise<void>;
99
+ /**
100
+ * Follow a run to its end, calling onEvent for each event in order. A dropped connection
101
+ * is resumed from the last event seen. Resolves when the terminal event has arrived (or the
102
+ * run is long over: the thread has it); rejects when the run cannot be followed.
103
+ */
104
+ follow(run: string, onEvent: (ev: StreamEvent) => void, signal: AbortSignal): Promise<void>;
105
+ };
106
+ /** One SSE frame's event, or null for a keepalive comment. */
107
+ export declare function parseFrame(frame: string): StreamEvent | null;
package/dist/wire.js ADDED
@@ -0,0 +1,120 @@
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
+ /** The rest of what the host said with the refusal (a new conversation id, a generation). */
11
+ data;
12
+ constructor(status, message, code = "", data = {}) {
13
+ super(message);
14
+ this.status = status;
15
+ this.code = code;
16
+ this.data = data;
17
+ }
18
+ }
19
+ const TERMINAL = new Set(["run.finish", "run.error", "run.abort"]);
20
+ /** The host's routes. */
21
+ export function hostApi(opts = {}) {
22
+ const base = (opts.base ?? "/api/agent").replace(/\/$/, "");
23
+ const doFetch = opts.fetch ?? ((input, init) => fetch(input, { credentials: "same-origin", ...init }));
24
+ async function request(path, method = "GET", body) {
25
+ const res = await doFetch(`${base}${path}`, {
26
+ method,
27
+ headers: { ...opts.headers, ...(body !== undefined ? { "Content-Type": "application/json" } : {}) },
28
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
29
+ });
30
+ if (!res.ok) {
31
+ let message = `The agent host answered ${res.status}.`;
32
+ let code = "";
33
+ try {
34
+ const data = (await res.json());
35
+ const said = typeof data.error === "string" ? data.error : (data.error?.message ?? data.message);
36
+ if (said)
37
+ message = said;
38
+ if (typeof data.code === "string")
39
+ code = data.code;
40
+ }
41
+ catch {
42
+ // No body to read: the status says it.
43
+ }
44
+ throw new HostError(res.status, message, code);
45
+ }
46
+ if (res.status === 204)
47
+ return undefined;
48
+ return (await res.json());
49
+ }
50
+ return {
51
+ state: () => request(""),
52
+ thread: () => request("/thread"),
53
+ newThread: () => request("/thread", "DELETE"),
54
+ turn: (body) => request("/turns", "POST", { ...body, tools: [] }),
55
+ cancel: (run) => request(`/runs/${run}/cancel`, "POST", {}),
56
+ approve: (run, approval_id, decision) => request(`/runs/${run}/approvals`, "POST", { approval_id, decision }),
57
+ /**
58
+ * Follow a run to its end, calling onEvent for each event in order. A dropped connection
59
+ * is resumed from the last event seen. Resolves when the terminal event has arrived (or the
60
+ * run is long over: the thread has it); rejects when the run cannot be followed.
61
+ */
62
+ async follow(run, onEvent, signal) {
63
+ let last = 0;
64
+ let failures = 0;
65
+ for (;;) {
66
+ if (signal.aborted)
67
+ return;
68
+ try {
69
+ const res = await doFetch(`${base}/runs/${run}/events`, {
70
+ headers: { ...opts.headers, ...(last ? { "Last-Event-ID": String(last) } : {}) },
71
+ signal,
72
+ });
73
+ if (res.status === 410 || res.status === 404)
74
+ return;
75
+ if (!res.ok || !res.body)
76
+ throw new Error(`events: ${res.status}`);
77
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
78
+ let buffer = "";
79
+ for (;;) {
80
+ const { value, done } = await reader.read();
81
+ if (done)
82
+ break;
83
+ buffer += value;
84
+ let cut = buffer.indexOf("\n\n");
85
+ while (cut >= 0) {
86
+ const frame = buffer.slice(0, cut);
87
+ buffer = buffer.slice(cut + 2);
88
+ cut = buffer.indexOf("\n\n");
89
+ const ev = parseFrame(frame);
90
+ if (!ev || ev.seq <= last)
91
+ continue;
92
+ last = ev.seq;
93
+ failures = 0;
94
+ onEvent(ev);
95
+ if (TERMINAL.has(ev.verb))
96
+ return;
97
+ }
98
+ }
99
+ // The stream closed without a terminal event: reconnect and resume.
100
+ }
101
+ catch (err) {
102
+ if (signal.aborted)
103
+ return;
104
+ if (++failures > 5)
105
+ throw err;
106
+ }
107
+ await new Promise((r) => setTimeout(r, Math.min(4000, 300 * 2 ** failures)));
108
+ }
109
+ },
110
+ };
111
+ }
112
+ /** One SSE frame's event, or null for a keepalive comment. */
113
+ export function parseFrame(frame) {
114
+ const data = frame
115
+ .split("\n")
116
+ .filter((l) => l.startsWith("data:"))
117
+ .map((l) => l.slice(l[5] === " " ? 6 : 5))
118
+ .join("\n");
119
+ return data ? JSON.parse(data) : null;
120
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@hollis-labs/surface-chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.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
+ }