@supersolutions/super-chat-client 0.0.0 → 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 SUPER SOLUTION LABS INC
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ superchat
2
+ Copyright 2026 SUPER SOLUTION LABS INC
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
1
  # @supersolutions/super-chat-client
2
2
 
3
- Placeholder. Releases are published from https://github.com/Super-Solution/super-chat by GitHub Actions.
3
+ The framework-agnostic client for [@supersolutions/super-chat-core](../core/README.md). One
4
+ `AgentClient` store per thread: it owns the state, drives `runAgent()`, and persists
5
+ threads and jobs. It has no UI framework dependency, so React, Vue, Svelte, React Native or a
6
+ plain script can all bind to the same client.
7
+
8
+ Part of the [superchat](../../README.md) monorepo.
9
+
10
+ ## What's in here
11
+
12
+ - `client.ts` — `AgentClient`.
13
+ - `store.ts` — the subscribe/notify primitive that framework bindings select over.
14
+
15
+ Framework bindings live in their own packages, for example
16
+ [`@supersolutions/super-chat-react`](../react/README.md).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pnpm add @supersolutions/super-chat-core @supersolutions/super-chat-client
22
+ ```
23
+
24
+ ## Develop
25
+
26
+ ```bash
27
+ pnpm --filter @supersolutions/super-chat-client build
28
+ pnpm --filter @supersolutions/super-chat-client typecheck
29
+ pnpm vitest run packages/client
30
+ ```
@@ -0,0 +1,209 @@
1
+ import { Message, RunState, Card, StoredJob, ContentPart, Provider, ContextBuilder, ToolRegistry, ToolResolution, RunMode, RunConfig, JobStore, ThreadStore, ToolCallRequest, DocumentStore, DocumentQuoteRef, CardAction } from '@supersolutions/super-chat-core';
2
+
3
+ type Listener = () => void;
4
+ declare class Store<T> {
5
+ private state;
6
+ private listeners;
7
+ constructor(initial: T);
8
+ get: () => T;
9
+ set: (next: T | ((prev: T) => T)) => void;
10
+ subscribe: (listener: Listener) => (() => void);
11
+ }
12
+
13
+ type ThreadState = {
14
+ id: string;
15
+ /**
16
+ * The ACTIVE PATH — root to head — which is what the UI renders and a run
17
+ * consumes. Always derived from `tree` + `headId`; treat as read-only.
18
+ */
19
+ messages: Message[];
20
+ /**
21
+ * Every message ever sent in this thread, abandoned branches included.
22
+ * Replaced on every change, never mutated in place — `useBranches` caches
23
+ * its sibling index per array. Treat as read-only.
24
+ */
25
+ tree: Message[];
26
+ /** Leaf of the active branch. */
27
+ headId: string | null;
28
+ run: RunState;
29
+ /** Cards from the CURRENT run; committed to messages when the run finishes. */
30
+ cards: Card[];
31
+ jobs: StoredJob[];
32
+ /** Parts staged for the NEXT send (file/image attachments). Thread-scoped. */
33
+ attachments: ContentPart[];
34
+ status: RunState["status"];
35
+ error?: unknown;
36
+ /**
37
+ * A stop was requested but the run has not unwound yet.
38
+ *
39
+ * Needed because `stop()` only aborts a signal — a tool that ignores its
40
+ * signal keeps running, and without this the UI cannot distinguish "stopping"
41
+ * from "the button did nothing".
42
+ */
43
+ stopping?: boolean;
44
+ };
45
+ /** What a finished turn cost, attached to the committed message. */
46
+ type TurnMeta = {
47
+ model: string;
48
+ ms: number;
49
+ usage?: RunState["usage"];
50
+ steps?: number;
51
+ };
52
+ type AgentClientConfig = {
53
+ provider: Provider;
54
+ model: string;
55
+ contextBuilder: ContextBuilder;
56
+ tools: ToolRegistry;
57
+ toolResolution: ToolResolution;
58
+ mode?: RunMode;
59
+ maxSteps?: number;
60
+ vars?: Record<string, unknown>;
61
+ temperature?: number;
62
+ maxOutputTokens?: number;
63
+ reasoning?: RunConfig["reasoning"];
64
+ stopWhen?: RunConfig["stopWhen"];
65
+ toolTimeoutMs?: number;
66
+ useServerHistory?: boolean;
67
+ toolChoice?: RunConfig["toolChoice"];
68
+ providerTools?: RunConfig["providerTools"];
69
+ responseFormat?: RunConfig["responseFormat"];
70
+ topP?: number;
71
+ stopSequences?: string[];
72
+ store?: boolean;
73
+ metadata?: Record<string, string>;
74
+ providerOptions?: RunConfig["providerOptions"];
75
+ meter?: RunConfig["meter"];
76
+ meteringMetadata?: RunConfig["meteringMetadata"];
77
+ jobStore?: JobStore;
78
+ /** When set, the thread is saved after each user and assistant turn. */
79
+ threadStore?: ThreadStore;
80
+ onHostTool?: (call: ToolCallRequest) => Promise<unknown>;
81
+ /** Persisted thread to hydrate from (linear list or a parentId tree). */
82
+ initialMessages?: Message[];
83
+ /** Active-branch leaf when `initialMessages` is a tree. Default: last message. */
84
+ initialHeadId?: string | null;
85
+ threadId?: string;
86
+ /**
87
+ * Where quoted documents can be looked up at send time, to catch a quote
88
+ * taken from a revision the document has since moved past. Only `get` is
89
+ * used; a host whose store lives on a server can pass a fetch-backed one.
90
+ * Unset, quotes are sent as taken.
91
+ */
92
+ documentStore?: Pick<DocumentStore, "get">;
93
+ };
94
+ declare class AgentClient {
95
+ readonly store: Store<ThreadState>;
96
+ private config;
97
+ private controller;
98
+ private pending;
99
+ /** Meta of the last snapshot saved, so createdAt/title survive re-saves. */
100
+ private threadMeta;
101
+ /**
102
+ * Bumped by every thread switch. A run captures the value it started under
103
+ * and stops writing to the store the moment they diverge — so a run dying
104
+ * from `openThread()`'s stop() cannot leak its error/status/commit into the
105
+ * thread the user just opened.
106
+ */
107
+ private generation;
108
+ /** Wall-clock start of the current turn, for the committed TurnMeta. */
109
+ private turnStartedAt;
110
+ constructor(config: AgentClientConfig);
111
+ /**
112
+ * Append under `parent` (default: the current head) and move the head there.
113
+ *
114
+ * `extra` merges into the SAME `store.set()` — e.g. clearing `attachments`
115
+ * alongside the append — so a caller touching both fields does not force two
116
+ * notifications for one logical change.
117
+ */
118
+ private appendMessage;
119
+ /**
120
+ * Stage a part (a file/image the host uploaded) for the next send. The
121
+ * Composer only carries text; this is how binary content joins the turn.
122
+ */
123
+ attach(part: ContentPart): void;
124
+ removeAttachment(index: number): void;
125
+ clearAttachments(): void;
126
+ /** Update config in place (model switch, preset toggle) without losing the thread. */
127
+ configure(patch: Partial<AgentClientConfig>): void;
128
+ getConfig(): AgentClientConfig;
129
+ get isRunning(): boolean;
130
+ /**
131
+ * Append a user message (plus any staged attachments) and run a turn.
132
+ *
133
+ * `quotes` are spans the user highlighted in a document artifact. They are
134
+ * flattened into the message's own text rather than injected as context, and
135
+ * the reasoning is in content/quotes.ts: a quote is part of what the user
136
+ * SAID, so it must not go stale between turns and must not be droppable
137
+ * under budget pressure. The structured form rides on `metadata`, which never
138
+ * reaches a provider, so the chips can be re-rendered from history.
139
+ *
140
+ * With a `documentStore` configured, each quote is first checked against the
141
+ * document as it is now, and a quote taken from an older revision goes out
142
+ * with its drift — in the text, so the model re-reads, and in the metadata,
143
+ * so the UI can say so.
144
+ */
145
+ send(input: string | ContentPart[], opts?: {
146
+ forceSkillIds?: string[];
147
+ quotes?: readonly DocumentQuoteRef[];
148
+ }): Promise<void>;
149
+ /**
150
+ * Re-run from the last user message. A FORK, not a rewrite: the head moves
151
+ * back to that user message and the new answer grows as a sibling of the
152
+ * old one, which stays switchable via `switchBranch`.
153
+ */
154
+ regenerate(opts?: {
155
+ forceSkillIds?: string[];
156
+ }): Promise<void>;
157
+ /**
158
+ * Edit a user message: a SIBLING fork under the same parent, preserving the
159
+ * original and everything under it. The edited branch runs immediately.
160
+ */
161
+ editMessage(messageId: string, input: string | ContentPart[], opts?: {
162
+ forceSkillIds?: string[];
163
+ }): Promise<void>;
164
+ /**
165
+ * Move the active branch to a SIBLING of `messageId` (delta −1/+1 in
166
+ * insertion order), resuming at that branch's latest leaf.
167
+ */
168
+ switchBranch(messageId: string, delta: number): void;
169
+ private run;
170
+ private apply;
171
+ /**
172
+ * Fold the finished run's parts into the thread as one assistant message.
173
+ *
174
+ * Cards are attached as artifact parts so a reloaded thread still renders
175
+ * them — the ContextBuilder strips artifacts before they reach a provider,
176
+ * so this costs nothing at request time.
177
+ */
178
+ private commitRun;
179
+ /**
180
+ * Fire-and-forget save, the same posture as the job store put: persistence
181
+ * must not stall the run, and a failed save degrades to "not saved", never
182
+ * to a broken thread.
183
+ */
184
+ private persist;
185
+ /**
186
+ * Load a stored thread and replace the current one. Returns false when the
187
+ * id is unknown (the current thread is left untouched).
188
+ */
189
+ openThread(id: string): Promise<boolean>;
190
+ /** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */
191
+ newThread(): void;
192
+ /** Answer an interactive card. Unblocks the suspended tool. */
193
+ respond(action: CardAction): void;
194
+ /** The card currently blocking the run, if any. */
195
+ pendingCard(): Card | undefined;
196
+ stop(): void;
197
+ clear(): void;
198
+ /**
199
+ * Re-poll background jobs from a previous session. Call on mount.
200
+ *
201
+ * Results are routed by `StoredJob.threadId`: the current thread gets its
202
+ * results appended live; another thread's results are written into its
203
+ * stored snapshot (when a ThreadStore is configured), so an answer to
204
+ * thread A never gets pasted into thread B.
205
+ */
206
+ resumeBackgroundJobs(): Promise<void>;
207
+ }
208
+
209
+ export { AgentClient, type AgentClientConfig, type Listener, Store, type ThreadState, type TurnMeta };
package/dist/index.js ADDED
@@ -0,0 +1,491 @@
1
+ // src/client.ts
2
+ import {
3
+ initialRunState,
4
+ reduceRunEvent,
5
+ runAgent,
6
+ resumeJobs,
7
+ assistantMessage,
8
+ latestLeaf,
9
+ linkLinear,
10
+ nextId,
11
+ pathTo,
12
+ siblingsOf,
13
+ threadSnapshot,
14
+ userMessage,
15
+ withQuotes,
16
+ formatQuotes,
17
+ checkQuoteDrift,
18
+ QUOTES_METADATA_KEY
19
+ } from "@supersolutions/super-chat-core";
20
+
21
+ // src/store.ts
22
+ var Store = class {
23
+ state;
24
+ listeners = /* @__PURE__ */ new Set();
25
+ constructor(initial) {
26
+ this.state = initial;
27
+ }
28
+ get = () => this.state;
29
+ set = (next) => {
30
+ const value = typeof next === "function" ? next(this.state) : next;
31
+ if (Object.is(value, this.state)) return;
32
+ this.state = value;
33
+ for (const listener of this.listeners) listener();
34
+ };
35
+ subscribe = (listener) => {
36
+ this.listeners.add(listener);
37
+ return () => {
38
+ this.listeners.delete(listener);
39
+ };
40
+ };
41
+ };
42
+
43
+ // src/client.ts
44
+ var AgentClient = class {
45
+ store;
46
+ config;
47
+ controller = null;
48
+ pending = /* @__PURE__ */ new Map();
49
+ /** Meta of the last snapshot saved, so createdAt/title survive re-saves. */
50
+ threadMeta;
51
+ /**
52
+ * Bumped by every thread switch. A run captures the value it started under
53
+ * and stops writing to the store the moment they diverge — so a run dying
54
+ * from `openThread()`'s stop() cannot leak its error/status/commit into the
55
+ * thread the user just opened.
56
+ */
57
+ generation = 0;
58
+ /** Wall-clock start of the current turn, for the committed TurnMeta. */
59
+ turnStartedAt = 0;
60
+ constructor(config) {
61
+ this.config = config;
62
+ const tree = linkLinear(config.initialMessages ?? []);
63
+ const headId = config.initialHeadId ?? tree.at(-1)?.id ?? null;
64
+ this.store = new Store({
65
+ id: config.threadId ?? nextId("thread"),
66
+ messages: pathTo(tree, headId),
67
+ tree,
68
+ headId,
69
+ run: initialRunState("", config.mode ?? "stream"),
70
+ cards: [],
71
+ jobs: [],
72
+ attachments: [],
73
+ status: "idle"
74
+ });
75
+ }
76
+ /**
77
+ * Append under `parent` (default: the current head) and move the head there.
78
+ *
79
+ * `extra` merges into the SAME `store.set()` — e.g. clearing `attachments`
80
+ * alongside the append — so a caller touching both fields does not force two
81
+ * notifications for one logical change.
82
+ */
83
+ appendMessage(message, parent, extra) {
84
+ this.store.set((s) => {
85
+ const parentId = parent !== void 0 ? parent : s.headId;
86
+ const linked = { ...message, parentId };
87
+ const tree = [...s.tree, linked];
88
+ return { ...s, tree, headId: linked.id, messages: pathTo(tree, linked.id), ...extra };
89
+ });
90
+ }
91
+ /**
92
+ * Stage a part (a file/image the host uploaded) for the next send. The
93
+ * Composer only carries text; this is how binary content joins the turn.
94
+ */
95
+ attach(part) {
96
+ this.store.set((s) => ({ ...s, attachments: [...s.attachments, part] }));
97
+ }
98
+ removeAttachment(index) {
99
+ this.store.set((s) => ({ ...s, attachments: s.attachments.filter((_, i) => i !== index) }));
100
+ }
101
+ clearAttachments() {
102
+ this.store.set((s) => s.attachments.length ? { ...s, attachments: [] } : s);
103
+ }
104
+ /** Update config in place (model switch, preset toggle) without losing the thread. */
105
+ configure(patch) {
106
+ this.config = { ...this.config, ...patch };
107
+ }
108
+ getConfig() {
109
+ return this.config;
110
+ }
111
+ get isRunning() {
112
+ const { status } = this.store.get();
113
+ return status === "running" || status === "awaiting-user";
114
+ }
115
+ /**
116
+ * Append a user message (plus any staged attachments) and run a turn.
117
+ *
118
+ * `quotes` are spans the user highlighted in a document artifact. They are
119
+ * flattened into the message's own text rather than injected as context, and
120
+ * the reasoning is in content/quotes.ts: a quote is part of what the user
121
+ * SAID, so it must not go stale between turns and must not be droppable
122
+ * under budget pressure. The structured form rides on `metadata`, which never
123
+ * reaches a provider, so the chips can be re-rendered from history.
124
+ *
125
+ * With a `documentStore` configured, each quote is first checked against the
126
+ * document as it is now, and a quote taken from an older revision goes out
127
+ * with its drift — in the text, so the model re-reads, and in the metadata,
128
+ * so the UI can say so.
129
+ */
130
+ async send(input, opts = {}) {
131
+ if (this.isRunning) throw new Error("A run is already in progress. Call stop() first.");
132
+ const { documentStore } = this.config;
133
+ const gen = this.generation;
134
+ const quotes = opts.quotes?.length && documentStore ? await checkQuoteDrift(opts.quotes, documentStore) : opts.quotes ?? [];
135
+ if (this.isRunning) throw new Error("A run is already in progress. Call stop() first.");
136
+ if (gen !== this.generation) return;
137
+ const staged = this.store.get().attachments;
138
+ const quoted = quotes.length === 0 ? input : typeof input === "string" ? withQuotes(input, quotes) : [{ type: "text", text: formatQuotes(quotes) }, ...input];
139
+ const parts = typeof quoted === "string" ? [{ type: "text", text: quoted }] : [...quoted];
140
+ const base = userMessage(staged.length ? [...parts, ...staged] : quoted);
141
+ const message = quotes.length ? { ...base, metadata: { ...base.metadata, [QUOTES_METADATA_KEY]: quotes } } : base;
142
+ this.appendMessage(message, void 0, { attachments: [] });
143
+ this.persist();
144
+ await this.run([...this.store.get().messages], opts);
145
+ }
146
+ /**
147
+ * Re-run from the last user message. A FORK, not a rewrite: the head moves
148
+ * back to that user message and the new answer grows as a sibling of the
149
+ * old one, which stays switchable via `switchBranch`.
150
+ */
151
+ async regenerate(opts = {}) {
152
+ if (this.isRunning) throw new Error("A run is already in progress.");
153
+ const { messages } = this.store.get();
154
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
155
+ const m = messages[i];
156
+ if (m.role === "user") {
157
+ this.store.set((s) => ({ ...s, headId: m.id, messages: pathTo(s.tree, m.id) }));
158
+ await this.run([...this.store.get().messages], opts);
159
+ return;
160
+ }
161
+ }
162
+ }
163
+ /**
164
+ * Edit a user message: a SIBLING fork under the same parent, preserving the
165
+ * original and everything under it. The edited branch runs immediately.
166
+ */
167
+ async editMessage(messageId, input, opts = {}) {
168
+ if (this.isRunning) throw new Error("A run is already in progress.");
169
+ const original = this.store.get().tree.find((m) => m.id === messageId);
170
+ if (!original || original.role !== "user") return;
171
+ this.appendMessage(userMessage(input), original.parentId ?? null);
172
+ this.persist();
173
+ await this.run([...this.store.get().messages], opts);
174
+ }
175
+ /**
176
+ * Move the active branch to a SIBLING of `messageId` (delta −1/+1 in
177
+ * insertion order), resuming at that branch's latest leaf.
178
+ */
179
+ switchBranch(messageId, delta) {
180
+ if (this.isRunning) return;
181
+ const s = this.store.get();
182
+ const siblings = siblingsOf(s.tree, messageId);
183
+ if (siblings.length < 2) return;
184
+ const index = siblings.findIndex((m) => m.id === messageId);
185
+ const next = siblings[(index + delta + siblings.length) % siblings.length];
186
+ const headId = latestLeaf(s.tree, next.id);
187
+ this.store.set((prev) => ({ ...prev, headId, messages: pathTo(prev.tree, headId) }));
188
+ this.persist();
189
+ }
190
+ async run(messages, opts) {
191
+ const gen = this.generation;
192
+ this.controller = new AbortController();
193
+ const mode = this.config.mode ?? "stream";
194
+ this.turnStartedAt = Date.now();
195
+ this.store.set((s) => ({
196
+ ...s,
197
+ run: initialRunState(nextId("run"), mode),
198
+ cards: [],
199
+ status: "running",
200
+ error: void 0,
201
+ stopping: false
202
+ }));
203
+ const runConfig = {
204
+ provider: this.config.provider,
205
+ model: this.config.model,
206
+ contextBuilder: this.config.contextBuilder,
207
+ tools: this.config.tools,
208
+ toolResolution: this.config.toolResolution,
209
+ mode,
210
+ maxSteps: this.config.maxSteps,
211
+ vars: this.config.vars,
212
+ temperature: this.config.temperature,
213
+ maxOutputTokens: this.config.maxOutputTokens,
214
+ reasoning: this.config.reasoning,
215
+ stopWhen: this.config.stopWhen,
216
+ toolTimeoutMs: this.config.toolTimeoutMs,
217
+ useServerHistory: this.config.useServerHistory,
218
+ toolChoice: this.config.toolChoice,
219
+ providerTools: this.config.providerTools,
220
+ responseFormat: this.config.responseFormat,
221
+ topP: this.config.topP,
222
+ stopSequences: this.config.stopSequences,
223
+ store: this.config.store,
224
+ metadata: this.config.metadata,
225
+ providerOptions: this.config.providerOptions,
226
+ meter: this.config.meter,
227
+ meteringMetadata: this.config.meteringMetadata,
228
+ signal: this.controller.signal,
229
+ forceSkillIds: opts.forceSkillIds,
230
+ onHostTool: this.config.onHostTool,
231
+ // Suspend the run on an interactive card; `respond()` resolves it.
232
+ onUserDecision: (callId, card) => new Promise((resolve) => {
233
+ this.pending.set(callId, { card, resolve });
234
+ })
235
+ };
236
+ try {
237
+ for await (const event of runAgent(messages, runConfig)) {
238
+ if (gen !== this.generation) return;
239
+ this.apply(event);
240
+ }
241
+ } catch (e) {
242
+ if (gen === this.generation) this.store.set((s) => ({ ...s, status: "error", error: e }));
243
+ } finally {
244
+ this.controller = null;
245
+ if (gen === this.generation) this.commitRun();
246
+ }
247
+ }
248
+ apply(event) {
249
+ this.store.set((s) => {
250
+ const run = reduceRunEvent(s.run, event);
251
+ const next = { ...s, run, status: run.status, cards: run.cards };
252
+ if (event.type === "job-started" && this.config.jobStore) {
253
+ const job = {
254
+ handle: event.handle,
255
+ status: "queued",
256
+ threadId: s.id,
257
+ createdAt: Date.now(),
258
+ updatedAt: Date.now()
259
+ };
260
+ void this.config.jobStore.put(job);
261
+ next.jobs = [job, ...s.jobs];
262
+ }
263
+ if (event.type === "job-status") {
264
+ next.jobs = s.jobs.map((j) => j.handle.id === event.handle.id ? { ...j, status: event.status, updatedAt: Date.now() } : j);
265
+ }
266
+ if (event.type === "error") next.error = event.error;
267
+ return next;
268
+ });
269
+ }
270
+ /**
271
+ * Fold the finished run's parts into the thread as one assistant message.
272
+ *
273
+ * Cards are attached as artifact parts so a reloaded thread still renders
274
+ * them — the ContextBuilder strips artifacts before they reach a provider,
275
+ * so this costs nothing at request time.
276
+ */
277
+ commitRun() {
278
+ this.store.set((s) => {
279
+ const status = s.status === "error" ? "error" : s.run.status;
280
+ const run = s.run.partialTools && Object.keys(s.run.partialTools).length ? { ...s.run, partialTools: {} } : s.run;
281
+ const parts = run.parts;
282
+ if (!parts.length && !run.cards.length) return { ...s, run, status };
283
+ const cardParts = s.run.cards.map((c) => ({
284
+ type: "artifact",
285
+ id: c.id,
286
+ kind: `card:${c.spec.kind ?? "unknown"}`,
287
+ data: c.spec,
288
+ ...c.action ? { action: c.action } : {}
289
+ }));
290
+ const meta = {
291
+ model: this.config.model,
292
+ ms: this.turnStartedAt ? Date.now() - this.turnStartedAt : 0,
293
+ ...s.run.usage && Object.keys(s.run.usage).length ? { usage: s.run.usage } : {},
294
+ ...s.run.steps ? { steps: s.run.steps } : {}
295
+ };
296
+ const linked = {
297
+ ...assistantMessage([...toolResultsInCallOrder(parts), ...cardParts]),
298
+ parentId: s.headId,
299
+ metadata: { turn: meta }
300
+ };
301
+ const tree = [...s.tree, linked];
302
+ return {
303
+ ...s,
304
+ run,
305
+ tree,
306
+ headId: linked.id,
307
+ messages: pathTo(tree, linked.id),
308
+ status: s.run.status,
309
+ stopping: false
310
+ };
311
+ });
312
+ this.persist();
313
+ }
314
+ /**
315
+ * Fire-and-forget save, the same posture as the job store put: persistence
316
+ * must not stall the run, and a failed save degrades to "not saved", never
317
+ * to a broken thread.
318
+ */
319
+ persist() {
320
+ const store = this.config.threadStore;
321
+ if (!store) return;
322
+ const s = this.store.get();
323
+ if (this.threadMeta && this.threadMeta.id !== s.id) this.threadMeta = void 0;
324
+ void (async () => {
325
+ const prior = this.threadMeta ?? (await store.load(s.id))?.meta;
326
+ const snapshot = threadSnapshot(s.id, s.tree, prior, s.headId);
327
+ this.threadMeta = snapshot.meta;
328
+ await store.save(snapshot);
329
+ })().catch(() => {
330
+ });
331
+ }
332
+ /**
333
+ * Load a stored thread and replace the current one. Returns false when the
334
+ * id is unknown (the current thread is left untouched).
335
+ */
336
+ async openThread(id) {
337
+ const store = this.config.threadStore;
338
+ if (!store) return false;
339
+ const stored = await store.load(id);
340
+ if (!stored) return false;
341
+ this.generation += 1;
342
+ this.stop();
343
+ this.threadMeta = stored.meta;
344
+ const tree = linkLinear(stored.messages);
345
+ const headId = stored.headId ?? tree.at(-1)?.id ?? null;
346
+ this.store.set((s) => ({
347
+ ...s,
348
+ id: stored.meta.id,
349
+ tree,
350
+ headId,
351
+ messages: pathTo(tree, headId),
352
+ cards: [],
353
+ attachments: [],
354
+ run: initialRunState("", this.config.mode ?? "stream"),
355
+ status: "idle",
356
+ error: void 0
357
+ }));
358
+ return true;
359
+ }
360
+ /** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */
361
+ newThread() {
362
+ this.generation += 1;
363
+ this.stop();
364
+ this.threadMeta = void 0;
365
+ this.store.set((s) => ({
366
+ ...s,
367
+ id: nextId("thread"),
368
+ messages: [],
369
+ tree: [],
370
+ headId: null,
371
+ cards: [],
372
+ attachments: [],
373
+ run: initialRunState("", this.config.mode ?? "stream"),
374
+ status: "idle",
375
+ error: void 0
376
+ }));
377
+ }
378
+ /** Answer an interactive card. Unblocks the suspended tool. */
379
+ respond(action) {
380
+ const entry = this.pending.get(action.callId ?? "");
381
+ if (!entry) return;
382
+ this.pending.delete(action.callId ?? "");
383
+ entry.resolve(action);
384
+ }
385
+ /** The card currently blocking the run, if any. */
386
+ pendingCard() {
387
+ return this.store.get().run.pendingCard;
388
+ }
389
+ stop() {
390
+ if (!this.isRunning) return;
391
+ this.store.set((s) => ({ ...s, stopping: true }));
392
+ this.controller?.abort();
393
+ const job = this.store.get().run.job;
394
+ if (job && this.config.provider.cancelJob && !["completed", "failed", "cancelled"].includes(job.status)) {
395
+ void this.config.provider.cancelJob(job.handle).catch(() => {
396
+ });
397
+ void this.config.jobStore?.remove(job.handle.id);
398
+ }
399
+ for (const [callId, entry] of this.pending) {
400
+ entry.resolve({ cardId: entry.card.id, callId, kind: "cancel", type: "cancel", at: Date.now() });
401
+ }
402
+ this.pending.clear();
403
+ }
404
+ clear() {
405
+ this.generation += 1;
406
+ this.stop();
407
+ this.store.set((s) => ({
408
+ ...s,
409
+ messages: [],
410
+ tree: [],
411
+ headId: null,
412
+ cards: [],
413
+ attachments: [],
414
+ run: initialRunState("", this.config.mode ?? "stream"),
415
+ status: "idle",
416
+ error: void 0,
417
+ stopping: false
418
+ }));
419
+ this.persist();
420
+ }
421
+ /**
422
+ * Re-poll background jobs from a previous session. Call on mount.
423
+ *
424
+ * Results are routed by `StoredJob.threadId`: the current thread gets its
425
+ * results appended live; another thread's results are written into its
426
+ * stored snapshot (when a ThreadStore is configured), so an answer to
427
+ * thread A never gets pasted into thread B.
428
+ */
429
+ async resumeBackgroundJobs() {
430
+ const store = this.config.jobStore;
431
+ if (!store) return;
432
+ const results = await resumeJobs(store, { [this.config.provider.id]: this.config.provider });
433
+ this.store.set((s) => ({ ...s, jobs: results.map((r) => r.job) }));
434
+ const currentId = this.store.get().id;
435
+ const away = /* @__PURE__ */ new Map();
436
+ for (const { job, snapshot } of results) {
437
+ const parts = snapshot.status === "completed" && snapshot.result ? snapshot.result.parts : snapshot.status === "failed" ? [{ type: "text", text: `_${snapshot.error?.message ?? "A background job failed."}_` }] : null;
438
+ if (!parts) continue;
439
+ if (!job.threadId || job.threadId === currentId) {
440
+ this.appendMessage(assistantMessage(parts));
441
+ if (job.threadId === currentId) this.persist();
442
+ continue;
443
+ }
444
+ const bucket = away.get(job.threadId) ?? [];
445
+ bucket.push(parts);
446
+ away.set(job.threadId, bucket);
447
+ }
448
+ const threads = this.config.threadStore;
449
+ if (!threads || !away.size) return;
450
+ await Promise.all(
451
+ [...away].map(async ([threadId, partsList]) => {
452
+ for (const parts of partsList) {
453
+ const stored = await threads.load(threadId);
454
+ if (!stored) continue;
455
+ const awayHead = stored.headId ?? stored.messages.at(-1)?.id ?? null;
456
+ const appended = { ...assistantMessage(parts), parentId: awayHead };
457
+ await threads.save(
458
+ threadSnapshot(threadId, [...stored.messages, appended], stored.meta, appended.id)
459
+ );
460
+ }
461
+ })
462
+ );
463
+ }
464
+ };
465
+ function toolResultsInCallOrder(parts) {
466
+ const callAt = /* @__PURE__ */ new Map();
467
+ parts.forEach((p, i) => {
468
+ if (p.type === "tool-call") callAt.set(p.callId, i);
469
+ });
470
+ const rank = (p) => p.type === "tool-result" ? callAt.get(p.callId) ?? Number.MAX_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
471
+ const out = [];
472
+ let batch = [];
473
+ const flush = () => {
474
+ out.push(...batch.sort((a, b) => rank(a) - rank(b)));
475
+ batch = [];
476
+ };
477
+ for (const p of parts) {
478
+ if (p.type === "tool-result") batch.push(p);
479
+ else {
480
+ flush();
481
+ out.push(p);
482
+ }
483
+ }
484
+ flush();
485
+ return out;
486
+ }
487
+ export {
488
+ AgentClient,
489
+ Store
490
+ };
491
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/store.ts"],"sourcesContent":["// AgentClient — the framework-agnostic controller the React hooks wrap.\n//\n// It owns: the thread, the current run, pending user decisions, and background\n// jobs. Kept outside React so the same object can be driven from a test, a CLI,\n// or a non-React host — the hooks are a thin `useSyncExternalStore` over it.\n\nimport {\n initialRunState,\n reduceRunEvent,\n runAgent,\n resumeJobs,\n type Card,\n type CardAction,\n type ContentPart,\n type ContextBuilder,\n type JobStore,\n type Message,\n type Provider,\n type RunConfig,\n type RunEvent,\n type RunMode,\n type RunState,\n type StoredJob,\n type ThreadMeta,\n type ThreadStore,\n type ToolCallRequest,\n type ToolRegistry,\n type ToolResolution,\n assistantMessage,\n latestLeaf,\n linkLinear,\n nextId,\n pathTo,\n siblingsOf,\n threadSnapshot,\n userMessage,\n withQuotes,\n formatQuotes,\n checkQuoteDrift,\n QUOTES_METADATA_KEY,\n type DocumentQuoteRef,\n type DocumentStore,\n} from \"@supersolutions/super-chat-core\";\nimport { Store } from \"./store.js\";\n\nexport type ThreadState = {\n id: string;\n /**\n * The ACTIVE PATH — root to head — which is what the UI renders and a run\n * consumes. Always derived from `tree` + `headId`; treat as read-only.\n */\n messages: Message[];\n /**\n * Every message ever sent in this thread, abandoned branches included.\n * Replaced on every change, never mutated in place — `useBranches` caches\n * its sibling index per array. Treat as read-only.\n */\n tree: Message[];\n /** Leaf of the active branch. */\n headId: string | null;\n run: RunState;\n /** Cards from the CURRENT run; committed to messages when the run finishes. */\n cards: Card[];\n jobs: StoredJob[];\n /** Parts staged for the NEXT send (file/image attachments). Thread-scoped. */\n attachments: ContentPart[];\n status: RunState[\"status\"];\n error?: unknown;\n /**\n * A stop was requested but the run has not unwound yet.\n *\n * Needed because `stop()` only aborts a signal — a tool that ignores its\n * signal keeps running, and without this the UI cannot distinguish \"stopping\"\n * from \"the button did nothing\".\n */\n stopping?: boolean;\n};\n\n/** What a finished turn cost, attached to the committed message. */\nexport type TurnMeta = { model: string; ms: number; usage?: RunState[\"usage\"]; steps?: number };\n\nexport type AgentClientConfig = {\n provider: Provider;\n model: string;\n contextBuilder: ContextBuilder;\n tools: ToolRegistry;\n toolResolution: ToolResolution;\n mode?: RunMode;\n maxSteps?: number;\n vars?: Record<string, unknown>;\n temperature?: number;\n maxOutputTokens?: number;\n reasoning?: RunConfig[\"reasoning\"];\n // Full RunConfig surface — a React host must not get LESS control than a\n // direct runAgent caller.\n stopWhen?: RunConfig[\"stopWhen\"];\n toolTimeoutMs?: number;\n useServerHistory?: boolean;\n toolChoice?: RunConfig[\"toolChoice\"];\n providerTools?: RunConfig[\"providerTools\"];\n responseFormat?: RunConfig[\"responseFormat\"];\n topP?: number;\n stopSequences?: string[];\n store?: boolean;\n metadata?: Record<string, string>;\n providerOptions?: RunConfig[\"providerOptions\"];\n meter?: RunConfig[\"meter\"];\n meteringMetadata?: RunConfig[\"meteringMetadata\"];\n jobStore?: JobStore;\n /** When set, the thread is saved after each user and assistant turn. */\n threadStore?: ThreadStore;\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /** Persisted thread to hydrate from (linear list or a parentId tree). */\n initialMessages?: Message[];\n /** Active-branch leaf when `initialMessages` is a tree. Default: last message. */\n initialHeadId?: string | null;\n threadId?: string;\n /**\n * Where quoted documents can be looked up at send time, to catch a quote\n * taken from a revision the document has since moved past. Only `get` is\n * used; a host whose store lives on a server can pass a fetch-backed one.\n * Unset, quotes are sent as taken.\n */\n documentStore?: Pick<DocumentStore, \"get\">;\n};\n\n/** A card waiting on the user, with the resolver that unblocks the run. */\ntype PendingDecision = { card: Card; resolve: (action: CardAction) => void };\n\nexport class AgentClient {\n readonly store: Store<ThreadState>;\n private config: AgentClientConfig;\n private controller: AbortController | null = null;\n private pending = new Map<string, PendingDecision>();\n /** Meta of the last snapshot saved, so createdAt/title survive re-saves. */\n private threadMeta: ThreadMeta | undefined;\n /**\n * Bumped by every thread switch. A run captures the value it started under\n * and stops writing to the store the moment they diverge — so a run dying\n * from `openThread()`'s stop() cannot leak its error/status/commit into the\n * thread the user just opened.\n */\n private generation = 0;\n /** Wall-clock start of the current turn, for the committed TurnMeta. */\n private turnStartedAt = 0;\n\n constructor(config: AgentClientConfig) {\n this.config = config;\n // `initialMessages` may be a plain linear list (pre-branching hosts) or a\n // tree with parentIds (a v2 snapshot); linkLinear handles both.\n const tree = linkLinear(config.initialMessages ?? []);\n const headId = config.initialHeadId ?? tree.at(-1)?.id ?? null;\n this.store = new Store<ThreadState>({\n id: config.threadId ?? nextId(\"thread\"),\n messages: pathTo(tree, headId),\n tree,\n headId,\n run: initialRunState(\"\", config.mode ?? \"stream\"),\n cards: [],\n jobs: [],\n attachments: [],\n status: \"idle\",\n });\n }\n\n /**\n * Append under `parent` (default: the current head) and move the head there.\n *\n * `extra` merges into the SAME `store.set()` — e.g. clearing `attachments`\n * alongside the append — so a caller touching both fields does not force two\n * notifications for one logical change.\n */\n private appendMessage(message: Message, parent?: string | null, extra?: Partial<ThreadState>): void {\n this.store.set((s) => {\n const parentId = parent !== undefined ? parent : s.headId;\n const linked: Message = { ...message, parentId };\n const tree = [...s.tree, linked];\n return { ...s, tree, headId: linked.id, messages: pathTo(tree, linked.id), ...extra };\n });\n }\n\n /**\n * Stage a part (a file/image the host uploaded) for the next send. The\n * Composer only carries text; this is how binary content joins the turn.\n */\n attach(part: ContentPart): void {\n this.store.set((s) => ({ ...s, attachments: [...s.attachments, part] }));\n }\n\n removeAttachment(index: number): void {\n this.store.set((s) => ({ ...s, attachments: s.attachments.filter((_, i) => i !== index) }));\n }\n\n clearAttachments(): void {\n this.store.set((s) => (s.attachments.length ? { ...s, attachments: [] } : s));\n }\n\n /** Update config in place (model switch, preset toggle) without losing the thread. */\n configure(patch: Partial<AgentClientConfig>): void {\n this.config = { ...this.config, ...patch };\n }\n\n getConfig(): AgentClientConfig {\n return this.config;\n }\n\n get isRunning(): boolean {\n const { status } = this.store.get();\n return status === \"running\" || status === \"awaiting-user\";\n }\n\n /**\n * Append a user message (plus any staged attachments) and run a turn.\n *\n * `quotes` are spans the user highlighted in a document artifact. They are\n * flattened into the message's own text rather than injected as context, and\n * the reasoning is in content/quotes.ts: a quote is part of what the user\n * SAID, so it must not go stale between turns and must not be droppable\n * under budget pressure. The structured form rides on `metadata`, which never\n * reaches a provider, so the chips can be re-rendered from history.\n *\n * With a `documentStore` configured, each quote is first checked against the\n * document as it is now, and a quote taken from an older revision goes out\n * with its drift — in the text, so the model re-reads, and in the metadata,\n * so the UI can say so.\n */\n async send(\n input: string | ContentPart[],\n opts: { forceSkillIds?: string[]; quotes?: readonly DocumentQuoteRef[] } = {},\n ): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n const { documentStore } = this.config;\n const gen = this.generation;\n const quotes =\n opts.quotes?.length && documentStore ? await checkQuoteDrift(opts.quotes, documentStore) : (opts.quotes ?? []);\n // The drift lookup is an await, and a second send could have started in it.\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n // The user opened or started another thread while the drift lookup was out: the text they\n // typed belongs to the thread they left, and appending it to this one would be worse than\n // dropping it.\n if (gen !== this.generation) return;\n const staged = this.store.get().attachments;\n const quoted: string | ContentPart[] =\n quotes.length === 0\n ? input\n : typeof input === \"string\"\n ? withQuotes(input, quotes)\n : [{ type: \"text\", text: formatQuotes(quotes) } as ContentPart, ...input];\n const parts: ContentPart[] = typeof quoted === \"string\" ? [{ type: \"text\", text: quoted }] : [...quoted];\n const base = userMessage(staged.length ? [...parts, ...staged] : quoted);\n const message: Message = quotes.length\n ? { ...base, metadata: { ...base.metadata, [QUOTES_METADATA_KEY]: quotes } }\n : base;\n this.appendMessage(message, undefined, { attachments: [] });\n // Persist the user turn before running — a reload mid-run keeps it.\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Re-run from the last user message. A FORK, not a rewrite: the head moves\n * back to that user message and the new answer grows as a sibling of the\n * old one, which stays switchable via `switchBranch`.\n */\n async regenerate(opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const { messages } = this.store.get();\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const m = messages[i]!;\n if (m.role === \"user\") {\n this.store.set((s) => ({ ...s, headId: m.id, messages: pathTo(s.tree, m.id) }));\n await this.run([...this.store.get().messages], opts);\n return;\n }\n }\n }\n\n /**\n * Edit a user message: a SIBLING fork under the same parent, preserving the\n * original and everything under it. The edited branch runs immediately.\n */\n async editMessage(messageId: string, input: string | ContentPart[], opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const original = this.store.get().tree.find((m) => m.id === messageId);\n if (!original || original.role !== \"user\") return;\n this.appendMessage(userMessage(input), original.parentId ?? null);\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Move the active branch to a SIBLING of `messageId` (delta −1/+1 in\n * insertion order), resuming at that branch's latest leaf.\n */\n switchBranch(messageId: string, delta: number): void {\n if (this.isRunning) return; // switching under a live run would cross-write threads of the same id\n const s = this.store.get();\n const siblings = siblingsOf(s.tree, messageId);\n if (siblings.length < 2) return;\n const index = siblings.findIndex((m) => m.id === messageId);\n const next = siblings[(index + delta + siblings.length) % siblings.length]!;\n const headId = latestLeaf(s.tree, next.id);\n this.store.set((prev) => ({ ...prev, headId, messages: pathTo(prev.tree, headId) }));\n this.persist();\n }\n\n private async run(messages: Message[], opts: { forceSkillIds?: string[] }): Promise<void> {\n const gen = this.generation;\n this.controller = new AbortController();\n const mode = this.config.mode ?? \"stream\";\n this.turnStartedAt = Date.now();\n this.store.set((s) => ({\n ...s,\n run: initialRunState(nextId(\"run\"), mode),\n cards: [],\n status: \"running\",\n error: undefined,\n stopping: false,\n }));\n\n const runConfig: RunConfig = {\n provider: this.config.provider,\n model: this.config.model,\n contextBuilder: this.config.contextBuilder,\n tools: this.config.tools,\n toolResolution: this.config.toolResolution,\n mode,\n maxSteps: this.config.maxSteps,\n vars: this.config.vars,\n temperature: this.config.temperature,\n maxOutputTokens: this.config.maxOutputTokens,\n reasoning: this.config.reasoning,\n stopWhen: this.config.stopWhen,\n toolTimeoutMs: this.config.toolTimeoutMs,\n useServerHistory: this.config.useServerHistory,\n toolChoice: this.config.toolChoice,\n providerTools: this.config.providerTools,\n responseFormat: this.config.responseFormat,\n topP: this.config.topP,\n stopSequences: this.config.stopSequences,\n store: this.config.store,\n metadata: this.config.metadata,\n providerOptions: this.config.providerOptions,\n meter: this.config.meter,\n meteringMetadata: this.config.meteringMetadata,\n signal: this.controller.signal,\n forceSkillIds: opts.forceSkillIds,\n onHostTool: this.config.onHostTool,\n // Suspend the run on an interactive card; `respond()` resolves it.\n onUserDecision: (callId, card) =>\n new Promise<CardAction>((resolve) => {\n this.pending.set(callId, { card, resolve });\n }),\n };\n\n try {\n for await (const event of runAgent(messages, runConfig)) {\n if (gen !== this.generation) return; // thread switched under us — drop the rest\n this.apply(event);\n }\n } catch (e) {\n if (gen === this.generation) this.store.set((s) => ({ ...s, status: \"error\", error: e }));\n } finally {\n this.controller = null;\n if (gen === this.generation) this.commitRun();\n }\n }\n\n private apply(event: RunEvent): void {\n this.store.set((s) => {\n const run = reduceRunEvent(s.run, event);\n const next: ThreadState = { ...s, run, status: run.status, cards: run.cards };\n if (event.type === \"job-started\" && this.config.jobStore) {\n const job: StoredJob = {\n handle: event.handle,\n status: \"queued\",\n threadId: s.id,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n // Fire and forget: persistence must not stall the run.\n void this.config.jobStore.put(job);\n next.jobs = [job, ...s.jobs];\n }\n if (event.type === \"job-status\") {\n next.jobs = s.jobs.map((j) => (j.handle.id === event.handle.id ? { ...j, status: event.status, updatedAt: Date.now() } : j));\n }\n if (event.type === \"error\") next.error = event.error;\n return next;\n });\n }\n\n /**\n * Fold the finished run's parts into the thread as one assistant message.\n *\n * Cards are attached as artifact parts so a reloaded thread still renders\n * them — the ContextBuilder strips artifacts before they reach a provider,\n * so this costs nothing at request time.\n */\n private commitRun(): void {\n this.store.set((s) => {\n // run.status reflects only what the agent loop itself saw, never a\n // throw caught in run()'s catch block — so a caught error must win\n // over it here, or the catch's \"error\" status gets overwritten back\n // to whatever the loop last reduced to (e.g. \"running\").\n const status = s.status === \"error\" ? \"error\" : s.run.status;\n // Streaming-argument previews are live-only. run-finish already clears\n // them; a run that died by throwing never sent one, so clear them here\n // too rather than leave a half-drawn card on an errored turn.\n const run = s.run.partialTools && Object.keys(s.run.partialTools).length ? { ...s.run, partialTools: {} } : s.run;\n const parts = run.parts;\n if (!parts.length && !run.cards.length) return { ...s, run, status };\n\n // `data` carries the answer alongside the spec: an answered card that\n // re-renders from history has to show what the user actually chose, and\n // the renderer's own state is gone by then.\n const cardParts: ContentPart[] = s.run.cards.map((c) => ({\n type: \"artifact\",\n id: c.id,\n kind: `card:${(c.spec as { kind?: string }).kind ?? \"unknown\"}`,\n data: c.spec,\n ...(c.action ? { action: c.action } : {}),\n }));\n\n // What the turn cost, recorded on the message. The UI has no other way to\n // show it after the fact: run state is reset by the next turn.\n const meta: TurnMeta = {\n model: this.config.model,\n ms: this.turnStartedAt ? Date.now() - this.turnStartedAt : 0,\n ...(s.run.usage && Object.keys(s.run.usage).length ? { usage: s.run.usage } : {}),\n ...(s.run.steps ? { steps: s.run.steps } : {}),\n };\n\n const linked: Message = {\n ...assistantMessage([...toolResultsInCallOrder(parts), ...cardParts]),\n parentId: s.headId,\n metadata: { turn: meta },\n };\n const tree = [...s.tree, linked];\n return {\n ...s,\n run,\n tree,\n headId: linked.id,\n messages: pathTo(tree, linked.id),\n status: s.run.status,\n stopping: false,\n };\n });\n this.persist();\n }\n\n /**\n * Fire-and-forget save, the same posture as the job store put: persistence\n * must not stall the run, and a failed save degrades to \"not saved\", never\n * to a broken thread.\n */\n private persist(): void {\n const store = this.config.threadStore;\n if (!store) return;\n const s = this.store.get();\n if (this.threadMeta && this.threadMeta.id !== s.id) this.threadMeta = undefined;\n void (async () => {\n // A client hydrated via config (threadId/initialMessages) has no meta in\n // hand; read the stored one so createdAt and title survive the reload.\n const prior = this.threadMeta ?? (await store.load(s.id))?.meta;\n // The TREE persists — abandoned branches included — plus the active head.\n const snapshot = threadSnapshot(s.id, s.tree, prior, s.headId);\n this.threadMeta = snapshot.meta;\n await store.save(snapshot);\n })().catch(() => {\n // Fire-and-forget: a failed save degrades to \"not saved\", never a crash.\n });\n }\n\n /**\n * Load a stored thread and replace the current one. Returns false when the\n * id is unknown (the current thread is left untouched).\n */\n async openThread(id: string): Promise<boolean> {\n const store = this.config.threadStore;\n if (!store) return false;\n const stored = await store.load(id);\n if (!stored) return false;\n this.generation += 1; // invalidate any in-flight run before replacing state\n this.stop();\n this.threadMeta = stored.meta;\n const tree = linkLinear(stored.messages);\n const headId = stored.headId ?? tree.at(-1)?.id ?? null;\n this.store.set((s) => ({\n ...s,\n id: stored.meta.id,\n tree,\n headId,\n messages: pathTo(tree, headId),\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n }));\n return true;\n }\n\n /** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */\n newThread(): void {\n this.generation += 1;\n this.stop();\n this.threadMeta = undefined;\n this.store.set((s) => ({\n ...s,\n id: nextId(\"thread\"),\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n }));\n }\n\n /** Answer an interactive card. Unblocks the suspended tool. */\n respond(action: CardAction): void {\n const entry = this.pending.get(action.callId ?? \"\");\n if (!entry) return;\n this.pending.delete(action.callId ?? \"\");\n entry.resolve(action);\n }\n\n /** The card currently blocking the run, if any. */\n pendingCard(): Card | undefined {\n return this.store.get().run.pendingCard;\n }\n\n stop(): void {\n if (!this.isRunning) return;\n // Mark the request immediately. Aborting is not the same as having stopped:\n // a tool that ignores its signal runs to completion, and the UI has to be\n // able to say \"stopping\" instead of looking inert.\n this.store.set((s) => ({ ...s, stopping: true }));\n this.controller?.abort();\n // A background job keeps running (and billing) server-side after a local\n // abort — cancel it there too, best-effort.\n const job = this.store.get().run.job;\n if (job && this.config.provider.cancelJob && ![\"completed\", \"failed\", \"cancelled\"].includes(job.status)) {\n void this.config.provider.cancelJob(job.handle).catch(() => {});\n void this.config.jobStore?.remove(job.handle.id);\n }\n // Release any suspended tool so the run can unwind instead of hanging.\n for (const [callId, entry] of this.pending) {\n entry.resolve({ cardId: entry.card.id, callId, kind: \"cancel\", type: \"cancel\", at: Date.now() });\n }\n this.pending.clear();\n }\n\n clear(): void {\n this.generation += 1;\n this.stop();\n this.store.set((s) => ({\n ...s,\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n stopping: false,\n }));\n // Without this, reload restores the conversation the user just cleared.\n this.persist();\n }\n\n /**\n * Re-poll background jobs from a previous session. Call on mount.\n *\n * Results are routed by `StoredJob.threadId`: the current thread gets its\n * results appended live; another thread's results are written into its\n * stored snapshot (when a ThreadStore is configured), so an answer to\n * thread A never gets pasted into thread B.\n */\n async resumeBackgroundJobs(): Promise<void> {\n const store = this.config.jobStore;\n if (!store) return;\n const results = await resumeJobs(store, { [this.config.provider.id]: this.config.provider });\n this.store.set((s) => ({ ...s, jobs: results.map((r) => r.job) }));\n\n const currentId = this.store.get().id;\n // Jobs landing in an AWAY thread are grouped by threadId: two jobs for the\n // SAME away thread read-modify-write that thread's one stored snapshot, so\n // they must land in order or the second save clobbers the first. Jobs for\n // DIFFERENT away threads touch different snapshots and have no ordering\n // dependency on each other, so those groups load/save concurrently.\n const away = new Map<string, ContentPart[][]>();\n\n for (const { job, snapshot } of results) {\n const parts: ContentPart[] | null =\n snapshot.status === \"completed\" && snapshot.result\n ? snapshot.result.parts\n : snapshot.status === \"failed\"\n ? [{ type: \"text\", text: `_${snapshot.error?.message ?? \"A background job failed.\"}_` }]\n : null;\n if (!parts) continue;\n\n if (!job.threadId || job.threadId === currentId) {\n this.appendMessage(assistantMessage(parts));\n if (job.threadId === currentId) this.persist();\n continue;\n }\n\n const bucket = away.get(job.threadId) ?? [];\n bucket.push(parts);\n away.set(job.threadId, bucket);\n }\n\n const threads = this.config.threadStore;\n if (!threads || !away.size) return; // nowhere to put it; the handle was already reaped\n\n await Promise.all(\n [...away].map(async ([threadId, partsList]) => {\n for (const parts of partsList) {\n const stored = await threads.load(threadId);\n if (!stored) continue;\n const awayHead = stored.headId ?? stored.messages.at(-1)?.id ?? null;\n const appended: Message = { ...assistantMessage(parts), parentId: awayHead };\n await threads.save(\n threadSnapshot(threadId, [...stored.messages, appended], stored.meta, appended.id),\n );\n }\n }),\n );\n }\n}\n\n/**\n * Run state appends tool results as they finish; a committed turn keeps them in\n * the order they were called, the same order runAgent writes back to history.\n * Only results that sit next to each other move, and only among themselves.\n */\nfunction toolResultsInCallOrder(parts: readonly ContentPart[]): ContentPart[] {\n const callAt = new Map<string, number>();\n parts.forEach((p, i) => {\n if (p.type === \"tool-call\") callAt.set(p.callId, i);\n });\n const rank = (p: ContentPart) =>\n p.type === \"tool-result\" ? (callAt.get(p.callId) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n const out: ContentPart[] = [];\n let batch: ContentPart[] = [];\n const flush = () => {\n out.push(...batch.sort((a, b) => rank(a) - rank(b)));\n batch = [];\n };\n for (const p of parts) {\n if (p.type === \"tool-result\") batch.push(p);\n else {\n flush();\n out.push(p);\n }\n }\n flush();\n return out;\n}\n","// A tiny external store, consumed via useSyncExternalStore.\n//\n// Hand-rolled rather than pulling in zustand/valtio for two reasons: the state\n// shape is already defined by the core's `RunState` reducer, and a chat thread\n// under a streaming run notifies at token frequency — a store that allocates a\n// new subscriber array per notify shows up in a profile at 60+ notifies/sec.\n\nexport type Listener = () => void;\n\nexport class Store<T> {\n private state: T;\n private listeners = new Set<Listener>();\n\n constructor(initial: T) {\n this.state = initial;\n }\n\n get = (): T => this.state;\n\n set = (next: T | ((prev: T) => T)): void => {\n const value = typeof next === \"function\" ? (next as (prev: T) => T)(this.state) : next;\n // Reference equality guard: a reducer that returns the same object (a\n // no-op event) must not wake every subscriber.\n if (Object.is(value, this.state)) return;\n this.state = value;\n for (const listener of this.listeners) listener();\n };\n\n subscribe = (listener: Listener): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n}\n"],"mappings":";AAMA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAkBA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACjCA,IAAM,QAAN,MAAe;AAAA,EACZ;AAAA,EACA,YAAY,oBAAI,IAAc;AAAA,EAEtC,YAAY,SAAY;AACtB,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAM,MAAS,KAAK;AAAA,EAEpB,MAAM,CAAC,SAAqC;AAC1C,UAAM,QAAQ,OAAO,SAAS,aAAc,KAAwB,KAAK,KAAK,IAAI;AAGlF,QAAI,OAAO,GAAG,OAAO,KAAK,KAAK,EAAG;AAClC,SAAK,QAAQ;AACb,eAAW,YAAY,KAAK,UAAW,UAAS;AAAA,EAClD;AAAA,EAEA,YAAY,CAAC,aAAqC;AAChD,SAAK,UAAU,IAAI,QAAQ;AAC3B,WAAO,MAAM;AACX,WAAK,UAAU,OAAO,QAAQ;AAAA,IAChC;AAAA,EACF;AACF;;;AD+FO,IAAM,cAAN,MAAkB;AAAA,EACd;AAAA,EACD;AAAA,EACA,aAAqC;AAAA,EACrC,UAAU,oBAAI,IAA6B;AAAA;AAAA,EAE3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa;AAAA;AAAA,EAEb,gBAAgB;AAAA,EAExB,YAAY,QAA2B;AACrC,SAAK,SAAS;AAGd,UAAM,OAAO,WAAW,OAAO,mBAAmB,CAAC,CAAC;AACpD,UAAM,SAA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H;AAAA,EACF;AACF;AAOA,SAAS,uBAAuB,OAA8C;AAC5E,QAAM,SAAS,oBAAI,IAAoB;AACvC,QAAM,QAAQ,CAAC,GAAG,MAAM;AACtB,QAAI,EAAE,SAAS,YAAa,QAAO,IAAI,EAAE,QAAQ,CAAC;AAAA,EACpD,CAAC;AACD,QAAM,OAAO,CAAC,MACZ,EAAE,SAAS,gBAAiB,OAAO,IAAI,EAAE,MAAM,KAAK,OAAO,mBAAoB,OAAO;AAExF,QAAM,MAAqB,CAAC;AAC5B,MAAI,QAAuB,CAAC;AAC5B,QAAM,QAAQ,MAAM;AAClB,QAAI,KAAK,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC;AACnD,YAAQ,CAAC;AAAA,EACX;AACA,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,cAAe,OAAM,KAAK,CAAC;AAAA,SACrC;AACH,YAAM;AACN,UAAI,KAAK,CAAC;AAAA,IACZ;AAAA,EACF;AACA,QAAM;AACN,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,16 +1,56 @@
1
1
  {
2
2
  "name": "@supersolutions/super-chat-client",
3
- "version": "0.0.0",
4
- "description": "Placeholder; real releases come from GitHub Actions.",
3
+ "version": "0.1.0",
4
+ "description": "Framework-agnostic client for superchat: one AgentClient store per thread that drives the agent runtime. No UI framework dependency.",
5
5
  "license": "Apache-2.0",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/Super-Solution/super-chat.git"
6
+ "author": "SUPER SOLUTION LABS INC",
7
+ "homepage": "https://github.com/Super-Solution/super-chat/tree/main/packages/client#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/Super-Solution/super-chat/issues"
10
+ },
11
+ "keywords": [
12
+ "agent",
13
+ "llm",
14
+ "ai",
15
+ "chat",
16
+ "streaming",
17
+ "store",
18
+ "framework-agnostic"
19
+ ],
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "main": "./dist/index.js",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js",
29
+ "default": "./dist/index.js"
30
+ }
9
31
  },
10
32
  "files": [
11
- "README.md"
33
+ "dist",
34
+ "LICENSE",
35
+ "NOTICE"
12
36
  ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/Super-Solution/super-chat.git",
40
+ "directory": "packages/client"
41
+ },
13
42
  "publishConfig": {
14
43
  "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@supersolutions/super-chat-core": "0.1.0"
47
+ },
48
+ "devDependencies": {
49
+ "tsup": "^8.3.5",
50
+ "typescript": "^5.7.2"
51
+ },
52
+ "scripts": {
53
+ "build": "tsup",
54
+ "typecheck": "tsc --noEmit"
15
55
  }
16
56
  }