@surfaces-ui/agent-loom 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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +23 -2
- package/dist/index.d.ts +98 -0
- package/dist/index.js +287 -0
- package/dist/index.js.map +1 -0
- package/package.json +47 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Generated by scripts/package-readmes.mjs from package.json. Edit the script, not this file. -->
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# @surfaces-ui/agent-loom
|
|
4
|
+
|
|
5
|
+
Loom adapter for Surfaces UI chat: talks to a Loom server over its HTTP gateway.
|
|
6
|
+
|
|
7
|
+
An `AgentBackend` that talks to a running Loom server over its HTTP gateway.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @surfaces-ui/agent-loom
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Part of Surfaces UI
|
|
16
|
+
|
|
17
|
+
Surfaces UI is a UI library for data and analytics: exploring schemas, querying, charting, tables at scale, chat, and pages an agent can build.
|
|
18
|
+
|
|
19
|
+
- [Getting started](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/getting-started.md)
|
|
20
|
+
- [Building with an agent](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/agent-integration.md)
|
|
21
|
+
- [Styling](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/styling.md)
|
|
22
|
+
- [Source for this package](https://github.com/teradata-labs/surfaces-ui/tree/main/packages/agent-loom)
|
|
23
|
+
|
|
24
|
+
Licensed under Apache-2.0. See LICENSE and NOTICE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { type AgentBackend, type AgentEvent, type DescribesAgents } from "@surfaces-ui/agent";
|
|
2
|
+
/**
|
|
3
|
+
* One event from Loom's `POST /v1/weave:stream`, as its HTTP gateway writes
|
|
4
|
+
* it: the `WeaveProgress` message in JSON with snake_case names and numeric
|
|
5
|
+
* enums. Only the fields this adapter reads are listed. Nothing from Loom is
|
|
6
|
+
* vendored; this describes its public wire format.
|
|
7
|
+
*/
|
|
8
|
+
export interface LoomProgress {
|
|
9
|
+
/** 7 is completed, 8 is failed. An error frame carries the text "EXECUTION_STAGE_FAILED". */
|
|
10
|
+
stage?: number | string;
|
|
11
|
+
message?: string;
|
|
12
|
+
/** Set on a frame the gateway writes when the call itself fails. */
|
|
13
|
+
error?: string;
|
|
14
|
+
/** The reply so far (accumulated, not a delta) while `is_token_stream` is set. */
|
|
15
|
+
partial_content?: string;
|
|
16
|
+
is_token_stream?: boolean;
|
|
17
|
+
tool_name?: string;
|
|
18
|
+
tool_call_id?: string;
|
|
19
|
+
is_tool_started?: boolean;
|
|
20
|
+
is_tool_completed?: boolean;
|
|
21
|
+
tool_input?: Record<string, unknown>;
|
|
22
|
+
tool_error?: string;
|
|
23
|
+
tool_success?: boolean;
|
|
24
|
+
tool_duration_ms?: number | string;
|
|
25
|
+
hitl_request?: {
|
|
26
|
+
request_id?: string;
|
|
27
|
+
question_id?: string;
|
|
28
|
+
question?: string;
|
|
29
|
+
request_type?: string;
|
|
30
|
+
kind?: string;
|
|
31
|
+
summary?: string;
|
|
32
|
+
options?: string[];
|
|
33
|
+
params_json?: string;
|
|
34
|
+
};
|
|
35
|
+
cost?: {
|
|
36
|
+
total_cost_usd?: number;
|
|
37
|
+
llm_cost?: {
|
|
38
|
+
input_tokens?: number;
|
|
39
|
+
output_tokens?: number;
|
|
40
|
+
model?: string;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
context_state?: {
|
|
44
|
+
context_tokens_used?: number | string;
|
|
45
|
+
context_tokens_max?: number | string;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export interface LoomTurnState {
|
|
49
|
+
/** Reply text already passed on, to turn Loom's accumulated text into deltas. */
|
|
50
|
+
text: string;
|
|
51
|
+
model: string;
|
|
52
|
+
/** Maps a Loom question to the tool step numbering, so repeated frames are not repeated here. */
|
|
53
|
+
asked: Set<string>;
|
|
54
|
+
steps: number;
|
|
55
|
+
}
|
|
56
|
+
export declare const newLoomTurn: () => LoomTurnState;
|
|
57
|
+
/**
|
|
58
|
+
* Turns one Loom progress event into the events a chat shows. Pure: the
|
|
59
|
+
* turn's running state is passed in and updated, so a recorded stream can be
|
|
60
|
+
* replayed in tests.
|
|
61
|
+
*/
|
|
62
|
+
export declare function mapLoomProgress(frame: LoomProgress, state: LoomTurnState, sessionId: string): AgentEvent[];
|
|
63
|
+
/** Reads `data:` lines from a server-sent event stream as JSON. Comment lines (heartbeats) are skipped. */
|
|
64
|
+
export declare function readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<LoomProgress>;
|
|
65
|
+
export interface LoomAgentOptions {
|
|
66
|
+
/** Where the Loom server's HTTP gateway is, e.g. http://localhost:5006. */
|
|
67
|
+
baseUrl: string;
|
|
68
|
+
/** Supplies a bearer token per request. The token is the host's to manage; it is never stored here. */
|
|
69
|
+
token?(): string | Promise<string>;
|
|
70
|
+
/** Extra headers, e.g. for a proxy. */
|
|
71
|
+
headers?: Record<string, string>;
|
|
72
|
+
/** Uses this instead of the global `fetch`. */
|
|
73
|
+
fetch?: typeof fetch;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* A Loom model as a chat names it: `provider/model` (`anthropic/claude-opus-5-5`,
|
|
77
|
+
* `ollama/qwen3:8b`), since Loom switches a session by both. The provider
|
|
78
|
+
* part never holds a slash.
|
|
79
|
+
*/
|
|
80
|
+
export declare const loomModelId: (provider: string, model: string) => string;
|
|
81
|
+
export declare function splitLoomModel(id: string): {
|
|
82
|
+
provider: string;
|
|
83
|
+
model: string;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* An AgentBackend that talks to a Loom server. Loom stays a separate
|
|
87
|
+
* program: this adapter only calls its HTTP gateway, so nothing from Loom is
|
|
88
|
+
* built into or shipped with this library.
|
|
89
|
+
*
|
|
90
|
+
* - A turn is `POST /v1/weave:stream`; replies, tool calls, questions and
|
|
91
|
+
* usage are mapped to chat events.
|
|
92
|
+
* - When Loom asks the person something, the turn pauses. Answering posts to
|
|
93
|
+
* `/v1/clarifications/{session}/answer` and carries on reading the same
|
|
94
|
+
* stream.
|
|
95
|
+
* - A Loom agent draws UI by calling a `render_surface` tool (as the
|
|
96
|
+
* Surfaces MCP server provides) or by writing an `a2ui` fenced block.
|
|
97
|
+
*/
|
|
98
|
+
export declare function loomAgent(options: LoomAgentOptions): AgentBackend & DescribesAgents;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { create } from "@bufbuild/protobuf";
|
|
2
|
+
import { agentEvent, errorEvent, extractSurfaces, turnText } from "@surfaces-ui/agent";
|
|
3
|
+
import { AgentInfoSchema, ApprovalKind, DescribeAgentsResponseSchema, StepStatus } from "@surfaces-ui/proto";
|
|
4
|
+
const COMPLETED = 7;
|
|
5
|
+
const FAILED = 8;
|
|
6
|
+
/** Tools whose input is a list of A2UI messages to draw, not something to show as a step. */
|
|
7
|
+
const SURFACE_TOOLS = new Set(["render_surface"]);
|
|
8
|
+
export const newLoomTurn = () => ({ text: "", model: "", asked: new Set(), steps: 0 });
|
|
9
|
+
const words = (tool) => tool.replace(/[_-]+/g, " ").replace(/^./, (c) => c.toUpperCase());
|
|
10
|
+
const clip = (text, max = 4000) => (text.length > max ? `${text.slice(0, max)}…` : text);
|
|
11
|
+
/**
|
|
12
|
+
* Turns one Loom progress event into the events a chat shows. Pure: the
|
|
13
|
+
* turn's running state is passed in and updated, so a recorded stream can be
|
|
14
|
+
* replayed in tests.
|
|
15
|
+
*/
|
|
16
|
+
export function mapLoomProgress(frame, state, sessionId) {
|
|
17
|
+
const out = [];
|
|
18
|
+
if (frame.error)
|
|
19
|
+
return [agentEvent.error("FAILED", frame.error)];
|
|
20
|
+
if (typeof frame.partial_content === "string" && frame.partial_content !== "" && (frame.is_token_stream || frame.stage === COMPLETED)) {
|
|
21
|
+
const all = frame.partial_content;
|
|
22
|
+
// Loom sends the whole reply so far each time; only what is new is passed on.
|
|
23
|
+
const delta = all.startsWith(state.text) ? all.slice(state.text.length) : all;
|
|
24
|
+
if (delta)
|
|
25
|
+
out.push(agentEvent.text(delta));
|
|
26
|
+
state.text = all;
|
|
27
|
+
}
|
|
28
|
+
const tool = frame.tool_name ?? "";
|
|
29
|
+
const stepId = frame.tool_call_id || (tool ? `${tool}#${state.steps}` : "");
|
|
30
|
+
if (frame.is_tool_started && tool) {
|
|
31
|
+
const messages = SURFACE_TOOLS.has(tool) ? frame.tool_input?.messages : undefined;
|
|
32
|
+
if (Array.isArray(messages)) {
|
|
33
|
+
for (const message of messages)
|
|
34
|
+
if (message && typeof message === "object")
|
|
35
|
+
out.push(agentEvent.surface(message));
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const sql = typeof frame.tool_input?.sql === "string" ? frame.tool_input.sql : undefined;
|
|
39
|
+
out.push(agentEvent.step({ id: stepId, title: words(tool), status: StepStatus.RUNNING, tool, detail: clip(sql ?? (frame.tool_input ? JSON.stringify(frame.tool_input, null, 2) : "")) }));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (frame.is_tool_completed && tool && !SURFACE_TOOLS.has(tool)) {
|
|
43
|
+
const failed = Boolean(frame.tool_error) || frame.tool_success === false;
|
|
44
|
+
out.push(agentEvent.step({
|
|
45
|
+
id: stepId,
|
|
46
|
+
title: words(tool),
|
|
47
|
+
status: failed ? StepStatus.FAILED : StepStatus.DONE,
|
|
48
|
+
tool,
|
|
49
|
+
detail: frame.tool_error ? clip(frame.tool_error) : "",
|
|
50
|
+
durationMs: BigInt(Math.max(0, Math.round(Number(frame.tool_duration_ms ?? 0)))),
|
|
51
|
+
}));
|
|
52
|
+
if (!frame.tool_call_id)
|
|
53
|
+
state.steps++;
|
|
54
|
+
}
|
|
55
|
+
const ask = frame.hitl_request;
|
|
56
|
+
// An empty request_id is only a hint that a question is coming; the one that can be answered follows.
|
|
57
|
+
const askId = ask?.question_id || ask?.request_id || "";
|
|
58
|
+
if (ask && ask.request_id && !state.asked.has(askId)) {
|
|
59
|
+
state.asked.add(askId);
|
|
60
|
+
const options = ask.options ?? [];
|
|
61
|
+
const kind = options.length > 0 ? ApprovalKind.CHOICE : /approv|permission|confirm/i.test(`${ask.request_type ?? ""} ${ask.kind ?? ""}`) ? ApprovalKind.PERMISSION : ApprovalKind.INPUT;
|
|
62
|
+
let sql = "";
|
|
63
|
+
try {
|
|
64
|
+
const params = ask.params_json ? JSON.parse(ask.params_json) : {};
|
|
65
|
+
if (typeof params.sql === "string")
|
|
66
|
+
sql = params.sql;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// Parameters are optional context; a question without them is still a question.
|
|
70
|
+
}
|
|
71
|
+
out.push(agentEvent.approval({ id: askId, kind, title: ask.question ?? "The agent has a question.", detail: ask.summary ?? "", sql, options }));
|
|
72
|
+
}
|
|
73
|
+
if (frame.cost?.llm_cost?.model)
|
|
74
|
+
state.model = frame.cost.llm_cost.model;
|
|
75
|
+
if (frame.cost || frame.context_state) {
|
|
76
|
+
out.push(agentEvent.usage({
|
|
77
|
+
inputTokens: BigInt(frame.cost?.llm_cost?.input_tokens ?? 0),
|
|
78
|
+
outputTokens: BigInt(frame.cost?.llm_cost?.output_tokens ?? 0),
|
|
79
|
+
contextTokens: BigInt(Number(frame.context_state?.context_tokens_used ?? 0)),
|
|
80
|
+
contextLimit: BigInt(Number(frame.context_state?.context_tokens_max ?? 0)),
|
|
81
|
+
costUsd: frame.cost?.total_cost_usd,
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
if (frame.stage === FAILED || frame.stage === "EXECUTION_STAGE_FAILED")
|
|
85
|
+
out.push(agentEvent.error("FAILED", frame.message || "The agent could not finish."));
|
|
86
|
+
if (frame.stage === COMPLETED)
|
|
87
|
+
out.push(agentEvent.done(sessionId, state.model ? `Loom · ${state.model}` : "Loom"));
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** Reads `data:` lines from a server-sent event stream as JSON. Comment lines (heartbeats) are skipped. */
|
|
91
|
+
export async function* readSse(body) {
|
|
92
|
+
const reader = body.getReader();
|
|
93
|
+
const decoder = new TextDecoder();
|
|
94
|
+
let pending = "";
|
|
95
|
+
try {
|
|
96
|
+
for (;;) {
|
|
97
|
+
const { done, value } = await reader.read();
|
|
98
|
+
pending += done ? decoder.decode() : decoder.decode(value, { stream: true });
|
|
99
|
+
const lines = pending.split(/\r?\n/);
|
|
100
|
+
pending = done ? "" : (lines.pop() ?? "");
|
|
101
|
+
for (const line of lines) {
|
|
102
|
+
if (!line.startsWith("data:"))
|
|
103
|
+
continue;
|
|
104
|
+
const payload = line.slice(5).trim();
|
|
105
|
+
if (!payload)
|
|
106
|
+
continue;
|
|
107
|
+
try {
|
|
108
|
+
yield JSON.parse(payload);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
// A frame that is not JSON is skipped; the stream carries on.
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (done)
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
await reader.cancel().catch(() => { });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* A Loom model as a chat names it: `provider/model` (`anthropic/claude-opus-5-5`,
|
|
124
|
+
* `ollama/qwen3:8b`), since Loom switches a session by both. The provider
|
|
125
|
+
* part never holds a slash.
|
|
126
|
+
*/
|
|
127
|
+
export const loomModelId = (provider, model) => (provider ? `${provider}/${model}` : model);
|
|
128
|
+
export function splitLoomModel(id) {
|
|
129
|
+
const at = id.indexOf("/");
|
|
130
|
+
return at < 0 ? { provider: "", model: id } : { provider: id.slice(0, at), model: id.slice(at + 1) };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* An AgentBackend that talks to a Loom server. Loom stays a separate
|
|
134
|
+
* program: this adapter only calls its HTTP gateway, so nothing from Loom is
|
|
135
|
+
* built into or shipped with this library.
|
|
136
|
+
*
|
|
137
|
+
* - A turn is `POST /v1/weave:stream`; replies, tool calls, questions and
|
|
138
|
+
* usage are mapped to chat events.
|
|
139
|
+
* - When Loom asks the person something, the turn pauses. Answering posts to
|
|
140
|
+
* `/v1/clarifications/{session}/answer` and carries on reading the same
|
|
141
|
+
* stream.
|
|
142
|
+
* - A Loom agent draws UI by calling a `render_surface` tool (as the
|
|
143
|
+
* Surfaces MCP server provides) or by writing an `a2ui` fenced block.
|
|
144
|
+
*/
|
|
145
|
+
export function loomAgent(options) {
|
|
146
|
+
const call = options.fetch ?? fetch;
|
|
147
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
148
|
+
const open = new Map();
|
|
149
|
+
// The model each session was last switched to here, so a turn switches only when the choice changed.
|
|
150
|
+
const switched = new Map();
|
|
151
|
+
const headers = async (accept) => {
|
|
152
|
+
const token = await options.token?.();
|
|
153
|
+
return {
|
|
154
|
+
"Content-Type": "application/json",
|
|
155
|
+
Accept: accept,
|
|
156
|
+
// Marks the turn as started by a person, so Loom does not treat a retry as a duplicate background run.
|
|
157
|
+
"X-Loom-Slot-Origin": "interactive",
|
|
158
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
159
|
+
...options.headers,
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
const createSession = async (agentId, signal) => {
|
|
163
|
+
try {
|
|
164
|
+
const response = await call(`${base}/v1/sessions`, { method: "POST", headers: await headers("application/json"), body: JSON.stringify({ agent_id: agentId }), signal });
|
|
165
|
+
if (response.ok) {
|
|
166
|
+
const session = (await response.json());
|
|
167
|
+
if (session.id)
|
|
168
|
+
return session.id;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Fall through: Loom also accepts an ID chosen by the client.
|
|
173
|
+
}
|
|
174
|
+
return crypto.randomUUID();
|
|
175
|
+
};
|
|
176
|
+
async function* pump(turn, sessionId) {
|
|
177
|
+
for (;;) {
|
|
178
|
+
const next = await turn.frames.next();
|
|
179
|
+
if (next.done) {
|
|
180
|
+
open.delete(sessionId);
|
|
181
|
+
// The stream ended without a completed stage: still tell the chat the turn is over.
|
|
182
|
+
yield agentEvent.done(sessionId, turn.state.model ? `Loom · ${turn.state.model}` : "Loom");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const events = mapLoomProgress(next.value, turn.state, sessionId);
|
|
186
|
+
yield* events;
|
|
187
|
+
const last = events.at(-1)?.event.case;
|
|
188
|
+
if (last === "done" || last === "error") {
|
|
189
|
+
open.delete(sessionId);
|
|
190
|
+
// The reply is complete: close the reader. Aborting a finished request would raise in callers that share its body.
|
|
191
|
+
await turn.frames.return(undefined);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
// The agent is waiting for an answer: this turn pauses with the stream left open.
|
|
195
|
+
if (events.some((e) => e.event.case === "approval"))
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const getJson = async (path) => {
|
|
200
|
+
const response = await call(`${base}${path}`, { headers: await headers("application/json") });
|
|
201
|
+
if (!response.ok)
|
|
202
|
+
throw new Error(`Loom answered ${response.status} for ${path}.`);
|
|
203
|
+
return (await response.json());
|
|
204
|
+
};
|
|
205
|
+
return {
|
|
206
|
+
/**
|
|
207
|
+
* Loom's agents, each offering the models Loom can run (`GET /v1/agents`,
|
|
208
|
+
* `GET /v1/models`). A server that does not list models offers none, and a
|
|
209
|
+
* turn then runs on the agent's own.
|
|
210
|
+
*/
|
|
211
|
+
async describeAgents() {
|
|
212
|
+
const [agents, models] = await Promise.all([
|
|
213
|
+
getJson("/v1/agents").then((body) => body.agents ?? []),
|
|
214
|
+
getJson("/v1/models").then((body) => body.models ?? [], () => []),
|
|
215
|
+
]);
|
|
216
|
+
const options = models.filter((m) => m.id).map((m) => ({ id: loomModelId(m.provider ?? "", m.id), label: m.name || m.id, description: m.provider ?? "" }));
|
|
217
|
+
return create(DescribeAgentsResponseSchema, {
|
|
218
|
+
agents: agents.map((a, i) => create(AgentInfoSchema, { id: a.name || a.id || "", name: a.name || a.id || "", description: a.metadata?.description ?? "", isDefault: i === 0, models: options })),
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
async *send(request, callOptions) {
|
|
222
|
+
const signal = callOptions?.signal;
|
|
223
|
+
try {
|
|
224
|
+
const input = request.input;
|
|
225
|
+
const sessionId = request.sessionId || (await createSession(request.agentId ?? "", signal));
|
|
226
|
+
const waiting = open.get(sessionId);
|
|
227
|
+
if (input?.case === "approval" && waiting) {
|
|
228
|
+
const answer = input.value.answer || (input.value.allow ? "approved" : "denied");
|
|
229
|
+
const response = await call(`${base}/v1/clarifications/${encodeURIComponent(sessionId)}/answer`, {
|
|
230
|
+
method: "POST",
|
|
231
|
+
headers: await headers("application/json"),
|
|
232
|
+
body: JSON.stringify({ session_id: sessionId, question_id: input.value.id, answer, agent_id: request.agentId ?? "" }),
|
|
233
|
+
signal,
|
|
234
|
+
});
|
|
235
|
+
if (!response.ok)
|
|
236
|
+
throw new Error(`Loom did not accept the answer (${response.status}).`);
|
|
237
|
+
signal?.addEventListener("abort", () => (open.delete(sessionId), waiting.stop()), { once: true });
|
|
238
|
+
yield* extractSurfaces(pump(waiting, sessionId));
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
// Anything else starts a new turn; a paused one is dropped.
|
|
242
|
+
if (waiting) {
|
|
243
|
+
open.delete(sessionId);
|
|
244
|
+
waiting.stop();
|
|
245
|
+
}
|
|
246
|
+
// A model the person picked: Loom switches the session to it, keeping the conversation, before this turn.
|
|
247
|
+
const model = request.model ?? "";
|
|
248
|
+
if (model && switched.get(sessionId) !== model) {
|
|
249
|
+
const { provider, model: name } = splitLoomModel(model);
|
|
250
|
+
const switching = await call(`${base}/v1/sessions/${encodeURIComponent(sessionId)}:switch-model`, {
|
|
251
|
+
method: "POST",
|
|
252
|
+
headers: await headers("application/json"),
|
|
253
|
+
body: JSON.stringify({ session_id: sessionId, agent_id: request.agentId ?? "", provider, model: name, preserve_context: true }),
|
|
254
|
+
signal,
|
|
255
|
+
});
|
|
256
|
+
if (!switching.ok)
|
|
257
|
+
throw new Error(`Loom could not switch to ${model} (${switching.status}).`);
|
|
258
|
+
switched.set(sessionId, model);
|
|
259
|
+
}
|
|
260
|
+
// The event, the page's state, the agent's own contracts and any problems, as text Loom passes to the model.
|
|
261
|
+
const query = turnText(request);
|
|
262
|
+
const controller = new AbortController();
|
|
263
|
+
signal?.addEventListener("abort", () => controller.abort(), { once: true });
|
|
264
|
+
const response = await call(`${base}/v1/weave:stream`, {
|
|
265
|
+
method: "POST",
|
|
266
|
+
headers: await headers("text/event-stream"),
|
|
267
|
+
body: JSON.stringify({
|
|
268
|
+
query,
|
|
269
|
+
session_id: sessionId,
|
|
270
|
+
agent_id: request.agentId ?? "",
|
|
271
|
+
context: request.contextPackId ? { context_pack_id: request.contextPackId } : undefined,
|
|
272
|
+
}),
|
|
273
|
+
signal: controller.signal,
|
|
274
|
+
});
|
|
275
|
+
if (!response.ok || !response.body)
|
|
276
|
+
throw new Error(`Loom answered ${response.status}${response.statusText ? ` ${response.statusText}` : ""}.`);
|
|
277
|
+
const turn = { frames: readSse(response.body), state: newLoomTurn(), stop: () => controller.abort() };
|
|
278
|
+
open.set(sessionId, turn);
|
|
279
|
+
yield* extractSurfaces(pump(turn, sessionId));
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
yield signal?.aborted ? agentEvent.error("CANCELLED", "Stopped.") : errorEvent(error);
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAA4D,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACjJ,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,4BAA4B,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAuC7G,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,6FAA6F;AAC7F,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC;AAWlD,MAAM,CAAC,MAAM,WAAW,GAAG,GAAkB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;AAEtG,MAAM,KAAK,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAClG,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,GAAG,GAAG,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,GA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M,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC;gBAChH,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;gBAC1B,KAAK,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACxF,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { type JsonObject, create } from \"@bufbuild/protobuf\";\nimport { type AgentBackend, type AgentEvent, type DescribesAgents, agentEvent, errorEvent, extractSurfaces, turnText } from \"@surfaces-ui/agent\";\nimport { AgentInfoSchema, ApprovalKind, DescribeAgentsResponseSchema, StepStatus } from \"@surfaces-ui/proto\";\n\n/**\n * One event from Loom's `POST /v1/weave:stream`, as its HTTP gateway writes\n * it: the `WeaveProgress` message in JSON with snake_case names and numeric\n * enums. Only the fields this adapter reads are listed. Nothing from Loom is\n * vendored; this describes its public wire format.\n */\nexport interface LoomProgress {\n /** 7 is completed, 8 is failed. An error frame carries the text \"EXECUTION_STAGE_FAILED\". */\n stage?: number | string;\n message?: string;\n /** Set on a frame the gateway writes when the call itself fails. */\n error?: string;\n /** The reply so far (accumulated, not a delta) while `is_token_stream` is set. */\n partial_content?: string;\n is_token_stream?: boolean;\n tool_name?: string;\n tool_call_id?: string;\n is_tool_started?: boolean;\n is_tool_completed?: boolean;\n tool_input?: Record<string, unknown>;\n tool_error?: string;\n tool_success?: boolean;\n tool_duration_ms?: number | string;\n hitl_request?: {\n request_id?: string;\n question_id?: string;\n question?: string;\n request_type?: string;\n kind?: string;\n summary?: string;\n options?: string[];\n params_json?: string;\n };\n cost?: { total_cost_usd?: number; llm_cost?: { input_tokens?: number; output_tokens?: number; model?: string } };\n context_state?: { context_tokens_used?: number | string; context_tokens_max?: number | string };\n}\n\nconst COMPLETED = 7;\nconst FAILED = 8;\n/** Tools whose input is a list of A2UI messages to draw, not something to show as a step. */\nconst SURFACE_TOOLS = new Set([\"render_surface\"]);\n\nexport interface LoomTurnState {\n /** Reply text already passed on, to turn Loom's accumulated text into deltas. */\n text: string;\n model: string;\n /** Maps a Loom question to the tool step numbering, so repeated frames are not repeated here. */\n asked: Set<string>;\n steps: number;\n}\n\nexport const newLoomTurn = (): LoomTurnState => ({ text: \"\", model: \"\", asked: new Set(), steps: 0 });\n\nconst words = (tool: string) => tool.replace(/[_-]+/g, \" \").replace(/^./, (c) => c.toUpperCase());\nconst clip = (text: string, max = 4000) => (text.length > max ? `${text.slice(0, max)}…` : text);\n\n/**\n * Turns one Loom progress event into the events a chat shows. Pure: the\n * turn's running state is passed in and updated, so a recorded stream can be\n * replayed in tests.\n */\nexport function mapLoomProgress(frame: LoomProgress, state: LoomTurnState, sessionId: string): AgentEvent[] {\n const out: AgentEvent[] = [];\n if (frame.error) return [agentEvent.error(\"FAILED\", frame.error)];\n\n if (typeof frame.partial_content === \"string\" && frame.partial_content !== \"\" && (frame.is_token_stream || frame.stage === COMPLETED)) {\n const all = frame.partial_content;\n // Loom sends the whole reply so far each time; only what is new is passed on.\n const delta = all.startsWith(state.text) ? all.slice(state.text.length) : all;\n if (delta) out.push(agentEvent.text(delta));\n state.text = all;\n }\n\n const tool = frame.tool_name ?? \"\";\n const stepId = frame.tool_call_id || (tool ? `${tool}#${state.steps}` : \"\");\n if (frame.is_tool_started && tool) {\n const messages = SURFACE_TOOLS.has(tool) ? frame.tool_input?.messages : undefined;\n if (Array.isArray(messages)) {\n for (const message of messages) if (message && typeof message === \"object\") out.push(agentEvent.surface(message as JsonObject));\n } else {\n const sql = typeof frame.tool_input?.sql === \"string\" ? frame.tool_input.sql : undefined;\n out.push(agentEvent.step({ id: stepId, title: words(tool), status: StepStatus.RUNNING, tool, detail: clip(sql ?? (frame.tool_input ? JSON.stringify(frame.tool_input, null, 2) : \"\")) }));\n }\n }\n if (frame.is_tool_completed && tool && !SURFACE_TOOLS.has(tool)) {\n const failed = Boolean(frame.tool_error) || frame.tool_success === false;\n out.push(\n agentEvent.step({\n id: stepId,\n title: words(tool),\n status: failed ? StepStatus.FAILED : StepStatus.DONE,\n tool,\n detail: frame.tool_error ? clip(frame.tool_error) : \"\",\n durationMs: BigInt(Math.max(0, Math.round(Number(frame.tool_duration_ms ?? 0)))),\n }),\n );\n if (!frame.tool_call_id) state.steps++;\n }\n\n const ask = frame.hitl_request;\n // An empty request_id is only a hint that a question is coming; the one that can be answered follows.\n const askId = ask?.question_id || ask?.request_id || \"\";\n if (ask && ask.request_id && !state.asked.has(askId)) {\n state.asked.add(askId);\n const options = ask.options ?? [];\n const kind = options.length > 0 ? ApprovalKind.CHOICE : /approv|permission|confirm/i.test(`${ask.request_type ?? \"\"} ${ask.kind ?? \"\"}`) ? ApprovalKind.PERMISSION : ApprovalKind.INPUT;\n let sql = \"\";\n try {\n const params = ask.params_json ? (JSON.parse(ask.params_json) as Record<string, unknown>) : {};\n if (typeof params.sql === \"string\") sql = params.sql;\n } catch {\n // Parameters are optional context; a question without them is still a question.\n }\n out.push(agentEvent.approval({ id: askId, kind, title: ask.question ?? \"The agent has a question.\", detail: ask.summary ?? \"\", sql, options }));\n }\n\n if (frame.cost?.llm_cost?.model) state.model = frame.cost.llm_cost.model;\n if (frame.cost || frame.context_state) {\n out.push(\n agentEvent.usage({\n inputTokens: BigInt(frame.cost?.llm_cost?.input_tokens ?? 0),\n outputTokens: BigInt(frame.cost?.llm_cost?.output_tokens ?? 0),\n contextTokens: BigInt(Number(frame.context_state?.context_tokens_used ?? 0)),\n contextLimit: BigInt(Number(frame.context_state?.context_tokens_max ?? 0)),\n costUsd: frame.cost?.total_cost_usd,\n }),\n );\n }\n\n if (frame.stage === FAILED || frame.stage === \"EXECUTION_STAGE_FAILED\") out.push(agentEvent.error(\"FAILED\", frame.message || \"The agent could not finish.\"));\n if (frame.stage === COMPLETED) out.push(agentEvent.done(sessionId, state.model ? `Loom · ${state.model}` : \"Loom\"));\n return out;\n}\n\n/** Reads `data:` lines from a server-sent event stream as JSON. Comment lines (heartbeats) are skipped. */\nexport async function* readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<LoomProgress> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let pending = \"\";\n try {\n for (;;) {\n const { done, value } = await reader.read();\n pending += done ? decoder.decode() : decoder.decode(value, { stream: true });\n const lines = pending.split(/\\r?\\n/);\n pending = done ? \"\" : (lines.pop() ?? \"\");\n for (const line of lines) {\n if (!line.startsWith(\"data:\")) continue;\n const payload = line.slice(5).trim();\n if (!payload) continue;\n try {\n yield JSON.parse(payload) as LoomProgress;\n } catch {\n // A frame that is not JSON is skipped; the stream carries on.\n }\n }\n if (done) return;\n }\n } finally {\n await reader.cancel().catch(() => {});\n }\n}\n\nexport interface LoomAgentOptions {\n /** Where the Loom server's HTTP gateway is, e.g. http://localhost:5006. */\n baseUrl: string;\n /** Supplies a bearer token per request. The token is the host's to manage; it is never stored here. */\n token?(): string | Promise<string>;\n /** Extra headers, e.g. for a proxy. */\n headers?: Record<string, string>;\n /** Uses this instead of the global `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * A Loom model as a chat names it: `provider/model` (`anthropic/claude-opus-5-5`,\n * `ollama/qwen3:8b`), since Loom switches a session by both. The provider\n * part never holds a slash.\n */\nexport const loomModelId = (provider: string, model: string) => (provider ? `${provider}/${model}` : model);\nexport function splitLoomModel(id: string): { provider: string; model: string } {\n const at = id.indexOf(\"/\");\n return at < 0 ? { provider: \"\", model: id } : { provider: id.slice(0, at), model: id.slice(at + 1) };\n}\n\ninterface OpenTurn {\n frames: AsyncGenerator<LoomProgress>;\n state: LoomTurnState;\n stop(): void;\n}\n\n/**\n * An AgentBackend that talks to a Loom server. Loom stays a separate\n * program: this adapter only calls its HTTP gateway, so nothing from Loom is\n * built into or shipped with this library.\n *\n * - A turn is `POST /v1/weave:stream`; replies, tool calls, questions and\n * usage are mapped to chat events.\n * - When Loom asks the person something, the turn pauses. Answering posts to\n * `/v1/clarifications/{session}/answer` and carries on reading the same\n * stream.\n * - A Loom agent draws UI by calling a `render_surface` tool (as the\n * Surfaces MCP server provides) or by writing an `a2ui` fenced block.\n */\nexport function loomAgent(options: LoomAgentOptions): AgentBackend & DescribesAgents {\n const call = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const open = new Map<string, OpenTurn>();\n // The model each session was last switched to here, so a turn switches only when the choice changed.\n const switched = new Map<string, string>();\n\n const headers = async (accept: string) => {\n const token = await options.token?.();\n return {\n \"Content-Type\": \"application/json\",\n Accept: accept,\n // Marks the turn as started by a person, so Loom does not treat a retry as a duplicate background run.\n \"X-Loom-Slot-Origin\": \"interactive\",\n ...(token ? { Authorization: `Bearer ${token}` } : {}),\n ...options.headers,\n };\n };\n\n const createSession = async (agentId: string, signal?: AbortSignal): Promise<string> => {\n try {\n const response = await call(`${base}/v1/sessions`, { method: \"POST\", headers: await headers(\"application/json\"), body: JSON.stringify({ agent_id: agentId }), signal });\n if (response.ok) {\n const session = (await response.json()) as { id?: string };\n if (session.id) return session.id;\n }\n } catch {\n // Fall through: Loom also accepts an ID chosen by the client.\n }\n return crypto.randomUUID();\n };\n\n async function* pump(turn: OpenTurn, sessionId: string): AsyncGenerator<AgentEvent> {\n for (;;) {\n const next = await turn.frames.next();\n if (next.done) {\n open.delete(sessionId);\n // The stream ended without a completed stage: still tell the chat the turn is over.\n yield agentEvent.done(sessionId, turn.state.model ? `Loom · ${turn.state.model}` : \"Loom\");\n return;\n }\n const events = mapLoomProgress(next.value, turn.state, sessionId);\n yield* events;\n const last = events.at(-1)?.event.case;\n if (last === \"done\" || last === \"error\") {\n open.delete(sessionId);\n // The reply is complete: close the reader. Aborting a finished request would raise in callers that share its body.\n await turn.frames.return(undefined);\n return;\n }\n // The agent is waiting for an answer: this turn pauses with the stream left open.\n if (events.some((e) => e.event.case === \"approval\")) return;\n }\n }\n\n const getJson = async (path: string) => {\n const response = await call(`${base}${path}`, { headers: await headers(\"application/json\") });\n if (!response.ok) throw new Error(`Loom answered ${response.status} for ${path}.`);\n return (await response.json()) as unknown;\n };\n\n return {\n /**\n * Loom's agents, each offering the models Loom can run (`GET /v1/agents`,\n * `GET /v1/models`). A server that does not list models offers none, and a\n * turn then runs on the agent's own.\n */\n async describeAgents() {\n const [agents, models] = await Promise.all([\n getJson(\"/v1/agents\").then((body) => (body as { agents?: { id?: string; name?: string; metadata?: { description?: string } }[] }).agents ?? []),\n getJson(\"/v1/models\").then(\n (body) => (body as { models?: { id?: string; name?: string; provider?: string }[] }).models ?? [],\n () => [],\n ),\n ]);\n const options = models.filter((m) => m.id).map((m) => ({ id: loomModelId(m.provider ?? \"\", m.id!), label: m.name || m.id!, description: m.provider ?? \"\" }));\n return create(DescribeAgentsResponseSchema, {\n agents: agents.map((a, i) =>\n create(AgentInfoSchema, { id: a.name || a.id || \"\", name: a.name || a.id || \"\", description: a.metadata?.description ?? \"\", isDefault: i === 0, models: options }),\n ),\n });\n },\n async *send(request, callOptions) {\n const signal = callOptions?.signal;\n try {\n const input = request.input;\n const sessionId = request.sessionId || (await createSession(request.agentId ?? \"\", signal));\n const waiting = open.get(sessionId);\n\n if (input?.case === \"approval\" && waiting) {\n const answer = input.value.answer || (input.value.allow ? \"approved\" : \"denied\");\n const response = await call(`${base}/v1/clarifications/${encodeURIComponent(sessionId)}/answer`, {\n method: \"POST\",\n headers: await headers(\"application/json\"),\n body: JSON.stringify({ session_id: sessionId, question_id: input.value.id, answer, agent_id: request.agentId ?? \"\" }),\n signal,\n });\n if (!response.ok) throw new Error(`Loom did not accept the answer (${response.status}).`);\n signal?.addEventListener(\"abort\", () => (open.delete(sessionId), waiting.stop()), { once: true });\n yield* extractSurfaces(pump(waiting, sessionId));\n return;\n }\n // Anything else starts a new turn; a paused one is dropped.\n if (waiting) {\n open.delete(sessionId);\n waiting.stop();\n }\n\n // A model the person picked: Loom switches the session to it, keeping the conversation, before this turn.\n const model = request.model ?? \"\";\n if (model && switched.get(sessionId) !== model) {\n const { provider, model: name } = splitLoomModel(model);\n const switching = await call(`${base}/v1/sessions/${encodeURIComponent(sessionId)}:switch-model`, {\n method: \"POST\",\n headers: await headers(\"application/json\"),\n body: JSON.stringify({ session_id: sessionId, agent_id: request.agentId ?? \"\", provider, model: name, preserve_context: true }),\n signal,\n });\n if (!switching.ok) throw new Error(`Loom could not switch to ${model} (${switching.status}).`);\n switched.set(sessionId, model);\n }\n\n // The event, the page's state, the agent's own contracts and any problems, as text Loom passes to the model.\n const query = turnText(request);\n const controller = new AbortController();\n signal?.addEventListener(\"abort\", () => controller.abort(), { once: true });\n const response = await call(`${base}/v1/weave:stream`, {\n method: \"POST\",\n headers: await headers(\"text/event-stream\"),\n body: JSON.stringify({\n query,\n session_id: sessionId,\n agent_id: request.agentId ?? \"\",\n context: request.contextPackId ? { context_pack_id: request.contextPackId } : undefined,\n }),\n signal: controller.signal,\n });\n if (!response.ok || !response.body) throw new Error(`Loom answered ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}.`);\n const turn: OpenTurn = { frames: readSse(response.body), state: newLoomTurn(), stop: () => controller.abort() };\n open.set(sessionId, turn);\n yield* extractSurfaces(pump(turn, sessionId));\n } catch (error) {\n yield signal?.aborted ? agentEvent.error(\"CANCELLED\", \"Stopped.\") : errorEvent(error);\n }\n },\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@surfaces-ui/agent-loom",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Loom adapter for Surfaces UI chat: talks to a Loom server over its HTTP gateway",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"surfaces-ui",
|
|
7
|
+
"analytics",
|
|
8
|
+
"data",
|
|
9
|
+
"agent",
|
|
10
|
+
"loom"
|
|
11
|
+
],
|
|
12
|
+
"license": "Apache-2.0",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/teradata-labs/surfaces-ui.git",
|
|
16
|
+
"directory": "packages/agent-loom"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/teradata-labs/surfaces-ui#readme",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/teradata-labs/surfaces-ui/issues"
|
|
21
|
+
},
|
|
22
|
+
"type": "module",
|
|
23
|
+
"sideEffects": false,
|
|
24
|
+
"main": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist",
|
|
34
|
+
"NOTICE"
|
|
35
|
+
],
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@bufbuild/protobuf": "^2.17.0",
|
|
38
|
+
"@surfaces-ui/agent": "0.2.0",
|
|
39
|
+
"@surfaces-ui/proto": "0.2.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"provenance": true
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsc -p tsconfig.build.json",
|
|
47
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
48
|
+
"test": "vitest run --passWithNoTests"
|
|
49
|
+
}
|
|
6
50
|
}
|