@ably/ai-transport 0.0.1
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 +176 -0
- package/README.md +426 -0
- package/dist/ably-ai-transport.js +1388 -0
- package/dist/ably-ai-transport.js.map +1 -0
- package/dist/ably-ai-transport.umd.cjs +2 -0
- package/dist/ably-ai-transport.umd.cjs.map +1 -0
- package/dist/constants.d.ts +50 -0
- package/dist/core/codec/decoder.d.ts +62 -0
- package/dist/core/codec/encoder.d.ts +56 -0
- package/dist/core/codec/index.d.ts +8 -0
- package/dist/core/codec/lifecycle-tracker.d.ts +74 -0
- package/dist/core/codec/types.d.ts +188 -0
- package/dist/core/transport/client-transport.d.ts +10 -0
- package/dist/core/transport/conversation-tree.d.ts +9 -0
- package/dist/core/transport/decode-history.d.ts +41 -0
- package/dist/core/transport/headers.d.ts +26 -0
- package/dist/core/transport/index.d.ts +4 -0
- package/dist/core/transport/pipe-stream.d.ts +16 -0
- package/dist/core/transport/server-transport.d.ts +7 -0
- package/dist/core/transport/stream-router.d.ts +19 -0
- package/dist/core/transport/turn-manager.d.ts +34 -0
- package/dist/core/transport/types.d.ts +407 -0
- package/dist/errors.d.ts +46 -0
- package/dist/event-emitter.d.ts +65 -0
- package/dist/index.d.ts +11 -0
- package/dist/logger.d.ts +103 -0
- package/dist/react/ably-ai-transport-react.js +823 -0
- package/dist/react/ably-ai-transport-react.js.map +1 -0
- package/dist/react/ably-ai-transport-react.umd.cjs +2 -0
- package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -0
- package/dist/react/index.d.ts +11 -0
- package/dist/react/use-ably-messages.d.ts +18 -0
- package/dist/react/use-active-turns.d.ts +8 -0
- package/dist/react/use-client-transport.d.ts +7 -0
- package/dist/react/use-conversation-tree.d.ts +20 -0
- package/dist/react/use-edit.d.ts +7 -0
- package/dist/react/use-history.d.ts +19 -0
- package/dist/react/use-messages.d.ts +7 -0
- package/dist/react/use-regenerate.d.ts +7 -0
- package/dist/react/use-send.d.ts +7 -0
- package/dist/utils.d.ts +127 -0
- package/dist/vercel/ably-ai-transport-vercel.js +2331 -0
- package/dist/vercel/ably-ai-transport-vercel.js.map +1 -0
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs +2 -0
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -0
- package/dist/vercel/codec/accumulator.d.ts +21 -0
- package/dist/vercel/codec/decoder.d.ts +22 -0
- package/dist/vercel/codec/encoder.d.ts +41 -0
- package/dist/vercel/codec/index.d.ts +22 -0
- package/dist/vercel/index.d.ts +3 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +2082 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +2 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -0
- package/dist/vercel/react/index.d.ts +3 -0
- package/dist/vercel/react/use-chat-transport.d.ts +29 -0
- package/dist/vercel/react/use-message-sync.d.ts +19 -0
- package/dist/vercel/transport/chat-transport.d.ts +118 -0
- package/dist/vercel/transport/index.d.ts +36 -0
- package/package.json +123 -0
- package/react/README.md +3 -0
- package/react/index.d.ts +1 -0
- package/react/index.js +1 -0
- package/react/index.umd.cjs +1 -0
- package/src/constants.ts +98 -0
- package/src/core/codec/decoder.ts +402 -0
- package/src/core/codec/encoder.ts +470 -0
- package/src/core/codec/index.ts +28 -0
- package/src/core/codec/lifecycle-tracker.ts +140 -0
- package/src/core/codec/types.ts +249 -0
- package/src/core/transport/client-transport.ts +959 -0
- package/src/core/transport/conversation-tree.ts +434 -0
- package/src/core/transport/decode-history.ts +337 -0
- package/src/core/transport/headers.ts +46 -0
- package/src/core/transport/index.ts +34 -0
- package/src/core/transport/pipe-stream.ts +95 -0
- package/src/core/transport/server-transport.ts +458 -0
- package/src/core/transport/stream-router.ts +118 -0
- package/src/core/transport/turn-manager.ts +147 -0
- package/src/core/transport/types.ts +533 -0
- package/src/errors.ts +58 -0
- package/src/event-emitter.ts +103 -0
- package/src/index.ts +89 -0
- package/src/logger.ts +241 -0
- package/src/react/index.ts +11 -0
- package/src/react/use-ably-messages.ts +37 -0
- package/src/react/use-active-turns.ts +61 -0
- package/src/react/use-client-transport.ts +37 -0
- package/src/react/use-conversation-tree.ts +71 -0
- package/src/react/use-edit.ts +24 -0
- package/src/react/use-history.ts +111 -0
- package/src/react/use-messages.ts +32 -0
- package/src/react/use-regenerate.ts +24 -0
- package/src/react/use-send.ts +25 -0
- package/src/react/vite.config.ts +32 -0
- package/src/tsconfig.json +25 -0
- package/src/utils.ts +230 -0
- package/src/vercel/codec/accumulator.ts +603 -0
- package/src/vercel/codec/decoder.ts +615 -0
- package/src/vercel/codec/encoder.ts +396 -0
- package/src/vercel/codec/index.ts +37 -0
- package/src/vercel/index.ts +12 -0
- package/src/vercel/react/index.ts +4 -0
- package/src/vercel/react/use-chat-transport.ts +60 -0
- package/src/vercel/react/use-message-sync.ts +34 -0
- package/src/vercel/react/vite.config.ts +33 -0
- package/src/vercel/transport/chat-transport.ts +278 -0
- package/src/vercel/transport/index.ts +56 -0
- package/src/vercel/vite.config.ts +33 -0
- package/src/vite.config.ts +31 -0
- package/vercel/README.md +3 -0
- package/vercel/index.d.ts +1 -0
- package/vercel/index.js +1 -0
- package/vercel/index.umd.cjs +1 -0
- package/vercel/react/README.md +3 -0
- package/vercel/react/index.d.ts +1 -0
- package/vercel/react/index.js +1 -0
- package/vercel/react/index.umd.cjs +1 -0
|
@@ -0,0 +1,2082 @@
|
|
|
1
|
+
import { useEffect as e, useRef as t } from "react";
|
|
2
|
+
import * as n from "ably";
|
|
3
|
+
import { isDataUIPart as r } from "ai";
|
|
4
|
+
//#region src/errors.ts
|
|
5
|
+
var i = /* @__PURE__ */ function(e) {
|
|
6
|
+
return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.TransportSubscriptionError = 104001] = "TransportSubscriptionError", e[e.CancelListenerError = 104002] = "CancelListenerError", e[e.TurnLifecycleError = 104003] = "TurnLifecycleError", e[e.TransportClosed = 104004] = "TransportClosed", e[e.TransportSendFailed = 104005] = "TransportSendFailed", e;
|
|
7
|
+
}({}), a = (e, t) => e.code === t, o = (e, t) => ({
|
|
8
|
+
sendMessages: async (r) => {
|
|
9
|
+
let { messages: a, abortSignal: o, trigger: s, messageId: c } = r, l, u;
|
|
10
|
+
if (s === "regenerate-message") l = [], u = a;
|
|
11
|
+
else {
|
|
12
|
+
if (a.length === 0) throw new n.ErrorInfo("unable to send messages; messages array is empty for submit-message trigger", i.InvalidArgument, 400);
|
|
13
|
+
l = [a.at(-1)], u = a.slice(0, -1);
|
|
14
|
+
}
|
|
15
|
+
let d, f;
|
|
16
|
+
if (s === "regenerate-message" && c) {
|
|
17
|
+
d = c;
|
|
18
|
+
let t = e.getTree().getNodeByKey(c);
|
|
19
|
+
t && (d = t.msgId, f = t.parentId);
|
|
20
|
+
}
|
|
21
|
+
let p, m;
|
|
22
|
+
if (t?.prepareSendMessagesRequest) {
|
|
23
|
+
let e = t.prepareSendMessagesRequest({
|
|
24
|
+
id: r.chatId,
|
|
25
|
+
trigger: s,
|
|
26
|
+
messageId: c,
|
|
27
|
+
history: u,
|
|
28
|
+
messages: l,
|
|
29
|
+
forkOf: d,
|
|
30
|
+
parent: f
|
|
31
|
+
});
|
|
32
|
+
p = e.body ?? {}, m = e.headers;
|
|
33
|
+
} else p = {
|
|
34
|
+
history: u.map((t) => ({
|
|
35
|
+
message: t,
|
|
36
|
+
headers: e.getMessageHeaders(t)
|
|
37
|
+
})),
|
|
38
|
+
id: r.chatId,
|
|
39
|
+
trigger: s,
|
|
40
|
+
...c !== void 0 && { messageId: c },
|
|
41
|
+
...d !== void 0 && { forkOf: d },
|
|
42
|
+
...f !== void 0 && { parent: f }
|
|
43
|
+
}, m = void 0;
|
|
44
|
+
let h = {
|
|
45
|
+
body: p,
|
|
46
|
+
headers: m
|
|
47
|
+
};
|
|
48
|
+
d !== void 0 && (h.forkOf = d), f !== void 0 && (h.parent = f);
|
|
49
|
+
let g = await e.send(l, h);
|
|
50
|
+
o && o.addEventListener("abort", () => void e.cancel({ all: !0 }), { once: !0 });
|
|
51
|
+
let { readable: _, writable: v } = new TransformStream(), y = v.getWriter();
|
|
52
|
+
return g.stream.pipeTo(new WritableStream({
|
|
53
|
+
close: () => {
|
|
54
|
+
y.close().catch(() => {});
|
|
55
|
+
},
|
|
56
|
+
abort: () => {
|
|
57
|
+
y.close().catch(() => {});
|
|
58
|
+
}
|
|
59
|
+
})).catch(() => {
|
|
60
|
+
y.close().catch(() => {});
|
|
61
|
+
}), _;
|
|
62
|
+
},
|
|
63
|
+
reconnectToStream: () => Promise.resolve(null),
|
|
64
|
+
close: async (t) => e.close(t)
|
|
65
|
+
}), s = "x-ably-stream", c = "x-ably-status", l = "x-ably-stream-id", u = "x-ably-turn-id", d = "x-ably-msg-id", f = "x-ably-turn-client-id", p = "x-ably-role", m = "x-ably-cancel-turn-id", h = "x-ably-cancel-own", g = "x-ably-cancel-all", _ = "x-ably-cancel-client-id", v = "x-ably-parent", y = "x-ably-fork-of", b = "x-ably-cancel", ee = "x-ably-turn-start", x = "x-ably-turn-end", S = "x-domain-", C = (e) => ({
|
|
66
|
+
logAction: (t, n, r) => {
|
|
67
|
+
e.error(n, { detail: r });
|
|
68
|
+
},
|
|
69
|
+
shouldLog: () => !0
|
|
70
|
+
}), te = n.Realtime.EventEmitter, ne = class extends te {
|
|
71
|
+
constructor(e) {
|
|
72
|
+
super(C(e));
|
|
73
|
+
}
|
|
74
|
+
}, w = /* @__PURE__ */ function(e) {
|
|
75
|
+
return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
|
|
76
|
+
}({}), T = (e, t, n) => {
|
|
77
|
+
let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
|
|
78
|
+
switch (t) {
|
|
79
|
+
case w.Trace:
|
|
80
|
+
case w.Debug:
|
|
81
|
+
console.log(i);
|
|
82
|
+
break;
|
|
83
|
+
case w.Info:
|
|
84
|
+
console.info(i);
|
|
85
|
+
break;
|
|
86
|
+
case w.Warn:
|
|
87
|
+
console.warn(i);
|
|
88
|
+
break;
|
|
89
|
+
case w.Error:
|
|
90
|
+
console.error(i);
|
|
91
|
+
break;
|
|
92
|
+
case w.Silent: break;
|
|
93
|
+
}
|
|
94
|
+
}, E = (e) => new k(e.logHandler ?? T, e.logLevel), D = /* @__PURE__ */ function(e) {
|
|
95
|
+
return e[e.Trace = 0] = "Trace", e[e.Debug = 1] = "Debug", e[e.Info = 2] = "Info", e[e.Warn = 3] = "Warn", e[e.Error = 4] = "Error", e[e.Silent = 5] = "Silent", e;
|
|
96
|
+
}(D || {}), O = new Map([
|
|
97
|
+
[w.Trace, D.Trace],
|
|
98
|
+
[w.Debug, D.Debug],
|
|
99
|
+
[w.Info, D.Info],
|
|
100
|
+
[w.Warn, D.Warn],
|
|
101
|
+
[w.Error, D.Error],
|
|
102
|
+
[w.Silent, D.Silent]
|
|
103
|
+
]), k = class e {
|
|
104
|
+
constructor(e, t, r) {
|
|
105
|
+
this._handler = e, this._context = r;
|
|
106
|
+
let a = O.get(t);
|
|
107
|
+
if (a === void 0) throw new n.ErrorInfo(`unable to create logger; invalid log level: ${t}`, i.InvalidArgument, 400);
|
|
108
|
+
this._levelNumber = a;
|
|
109
|
+
}
|
|
110
|
+
trace(e, t) {
|
|
111
|
+
this._write(e, w.Trace, D.Trace, t);
|
|
112
|
+
}
|
|
113
|
+
debug(e, t) {
|
|
114
|
+
this._write(e, w.Debug, D.Debug, t);
|
|
115
|
+
}
|
|
116
|
+
info(e, t) {
|
|
117
|
+
this._write(e, w.Info, D.Info, t);
|
|
118
|
+
}
|
|
119
|
+
warn(e, t) {
|
|
120
|
+
this._write(e, w.Warn, D.Warn, t);
|
|
121
|
+
}
|
|
122
|
+
error(e, t) {
|
|
123
|
+
this._write(e, w.Error, D.Error, t);
|
|
124
|
+
}
|
|
125
|
+
withContext(t) {
|
|
126
|
+
let n = [...O.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? w.Error;
|
|
127
|
+
return new e(this._handler, n, this._mergeContext(t));
|
|
128
|
+
}
|
|
129
|
+
_write(e, t, n, r) {
|
|
130
|
+
n >= this._levelNumber && this._handler(e, t, this._mergeContext(r));
|
|
131
|
+
}
|
|
132
|
+
_mergeContext(e) {
|
|
133
|
+
return this._context ? e ? {
|
|
134
|
+
...this._context,
|
|
135
|
+
...e
|
|
136
|
+
} : this._context : e ?? void 0;
|
|
137
|
+
}
|
|
138
|
+
}, A = (e) => {
|
|
139
|
+
let t = e.extras;
|
|
140
|
+
if (!t || typeof t != "object") return {};
|
|
141
|
+
let n = t.headers;
|
|
142
|
+
return !n || typeof n != "object" ? {} : n;
|
|
143
|
+
}, re = (e) => {
|
|
144
|
+
if (e !== void 0) try {
|
|
145
|
+
return JSON.parse(e);
|
|
146
|
+
} catch {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
}, j = (e, t) => ({
|
|
150
|
+
...e,
|
|
151
|
+
...t
|
|
152
|
+
}), ie = (e) => {
|
|
153
|
+
if (e !== void 0) return e === "true";
|
|
154
|
+
}, M = (e, t) => e[S + t], N = (e) => {
|
|
155
|
+
let t = {};
|
|
156
|
+
for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
|
|
157
|
+
return t;
|
|
158
|
+
}, ae = (e) => ({
|
|
159
|
+
str: (t) => M(e, t),
|
|
160
|
+
strOr: (t, n) => M(e, t) ?? n,
|
|
161
|
+
bool: (t) => ie(M(e, t)),
|
|
162
|
+
json: (t) => re(M(e, t))
|
|
163
|
+
}), P = () => {
|
|
164
|
+
let e = {}, t = {
|
|
165
|
+
str: (n, r) => (r !== void 0 && (e[S + n] = r), t),
|
|
166
|
+
bool: (n, r) => (r !== void 0 && (e[S + n] = String(r)), t),
|
|
167
|
+
json: (n, r) => (r != null && (e[S + n] = JSON.stringify(r)), t),
|
|
168
|
+
build: () => e
|
|
169
|
+
};
|
|
170
|
+
return t;
|
|
171
|
+
}, F = class {
|
|
172
|
+
constructor(e, t) {
|
|
173
|
+
this._nodeIndex = /* @__PURE__ */ new Map(), this._codecKeyIndex = /* @__PURE__ */ new Map(), this._sortedList = [], this._parentIndex = /* @__PURE__ */ new Map(), this._selections = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._getKey = e, this._logger = t;
|
|
174
|
+
}
|
|
175
|
+
_compareNodes(e, t) {
|
|
176
|
+
let n = e.node.serial, r = t.node.serial;
|
|
177
|
+
return n === void 0 && r === void 0 ? e.insertSeq - t.insertSeq : n === void 0 ? 1 : r === void 0 || n < r ? -1 : n > r ? 1 : e.insertSeq - t.insertSeq;
|
|
178
|
+
}
|
|
179
|
+
_insertSorted(e) {
|
|
180
|
+
if (e.node.serial === void 0) {
|
|
181
|
+
this._sortedList.push(e);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
let t = 0, n = this._sortedList.length;
|
|
185
|
+
for (; t < n;) {
|
|
186
|
+
let r = t + n >>> 1, i = this._sortedList[r];
|
|
187
|
+
if (!i) break;
|
|
188
|
+
this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
|
|
189
|
+
}
|
|
190
|
+
this._sortedList.splice(t, 0, e);
|
|
191
|
+
}
|
|
192
|
+
_removeSorted(e) {
|
|
193
|
+
let t = this._sortedList.indexOf(e);
|
|
194
|
+
t !== -1 && this._sortedList.splice(t, 1);
|
|
195
|
+
}
|
|
196
|
+
_addToParentIndex(e, t) {
|
|
197
|
+
let n = this._parentIndex.get(e);
|
|
198
|
+
n || (n = /* @__PURE__ */ new Set(), this._parentIndex.set(e, n)), n.add(t);
|
|
199
|
+
}
|
|
200
|
+
_removeFromParentIndex(e, t) {
|
|
201
|
+
let n = this._parentIndex.get(e);
|
|
202
|
+
n && (n.delete(t), n.size === 0 && this._parentIndex.delete(e));
|
|
203
|
+
}
|
|
204
|
+
_getSiblingGroup(e) {
|
|
205
|
+
let t = this._nodeIndex.get(e);
|
|
206
|
+
if (!t) return [];
|
|
207
|
+
let n = t.node, r = new Set([n.msgId]);
|
|
208
|
+
for (; n.forkOf && !r.has(n.forkOf);) {
|
|
209
|
+
let e = this._nodeIndex.get(n.forkOf);
|
|
210
|
+
if (!e || e.node.parentId !== n.parentId) break;
|
|
211
|
+
n = e.node, r.add(n.msgId);
|
|
212
|
+
}
|
|
213
|
+
let i = n.parentId, a = n.msgId, o = [], s = this._parentIndex.get(i);
|
|
214
|
+
if (s) for (let e of s) {
|
|
215
|
+
let t = this._nodeIndex.get(e);
|
|
216
|
+
t && this._isSiblingOf(t.node, a) && o.push(t);
|
|
217
|
+
}
|
|
218
|
+
return o.sort((e, t) => this._compareNodes(e, t)), o.map((e) => e.node);
|
|
219
|
+
}
|
|
220
|
+
_isSiblingOf(e, t) {
|
|
221
|
+
if (e.msgId === t) return !0;
|
|
222
|
+
let n = e, r = new Set([n.msgId]);
|
|
223
|
+
for (; n.forkOf;) {
|
|
224
|
+
if (n.forkOf === t) return !0;
|
|
225
|
+
if (r.has(n.forkOf)) break;
|
|
226
|
+
let e = this._nodeIndex.get(n.forkOf);
|
|
227
|
+
if (!e) break;
|
|
228
|
+
n = e.node, r.add(n.msgId);
|
|
229
|
+
}
|
|
230
|
+
return !1;
|
|
231
|
+
}
|
|
232
|
+
_getGroupRoot(e) {
|
|
233
|
+
let t = this._nodeIndex.get(e);
|
|
234
|
+
if (!t) return e;
|
|
235
|
+
let n = t.node, r = new Set([n.msgId]);
|
|
236
|
+
for (; n.forkOf && !r.has(n.forkOf);) {
|
|
237
|
+
let e = this._nodeIndex.get(n.forkOf);
|
|
238
|
+
if (!e || e.node.parentId !== n.parentId) break;
|
|
239
|
+
n = e.node, r.add(n.msgId);
|
|
240
|
+
}
|
|
241
|
+
return n.msgId;
|
|
242
|
+
}
|
|
243
|
+
flatten() {
|
|
244
|
+
let e = [], t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Map();
|
|
245
|
+
for (let r of this._sortedList) {
|
|
246
|
+
let i = r.node, { msgId: a, parentId: o } = i;
|
|
247
|
+
if (o !== void 0 && !t.has(o)) continue;
|
|
248
|
+
let s = this._getSiblingGroup(a);
|
|
249
|
+
if (s.length > 1) {
|
|
250
|
+
let e = this._getGroupRoot(a), t = n.get(e);
|
|
251
|
+
if (t === void 0) {
|
|
252
|
+
let r = this._selections.get(e) ?? s.length - 1, i = s[Math.max(0, Math.min(r, s.length - 1))];
|
|
253
|
+
if (!i) break;
|
|
254
|
+
t = i.msgId, n.set(e, t);
|
|
255
|
+
}
|
|
256
|
+
if (a !== t) continue;
|
|
257
|
+
}
|
|
258
|
+
t.add(a), e.push(i.message);
|
|
259
|
+
}
|
|
260
|
+
return e;
|
|
261
|
+
}
|
|
262
|
+
getSiblings(e) {
|
|
263
|
+
return this._getSiblingGroup(e).map((e) => e.message);
|
|
264
|
+
}
|
|
265
|
+
hasSiblings(e) {
|
|
266
|
+
return this._getSiblingGroup(e).length > 1;
|
|
267
|
+
}
|
|
268
|
+
getSelectedIndex(e) {
|
|
269
|
+
let t = this._getSiblingGroup(e);
|
|
270
|
+
if (t.length <= 1) return 0;
|
|
271
|
+
let n = this._getGroupRoot(e), r = this._selections.get(n);
|
|
272
|
+
return r === void 0 ? t.length - 1 : Math.max(0, Math.min(r, t.length - 1));
|
|
273
|
+
}
|
|
274
|
+
select(e, t) {
|
|
275
|
+
this._logger.debug("ConversationTree.select();", {
|
|
276
|
+
msgId: e,
|
|
277
|
+
index: t
|
|
278
|
+
});
|
|
279
|
+
let n = this._getSiblingGroup(e);
|
|
280
|
+
if (n.length <= 1) return;
|
|
281
|
+
let r = this._getGroupRoot(e);
|
|
282
|
+
this._selections.set(r, Math.max(0, Math.min(t, n.length - 1)));
|
|
283
|
+
}
|
|
284
|
+
getNode(e) {
|
|
285
|
+
return this._nodeIndex.get(e)?.node;
|
|
286
|
+
}
|
|
287
|
+
getNodeByKey(e) {
|
|
288
|
+
let t = this._codecKeyIndex.get(e);
|
|
289
|
+
if (t) return this._nodeIndex.get(t)?.node;
|
|
290
|
+
}
|
|
291
|
+
getHeaders(e) {
|
|
292
|
+
return this._nodeIndex.get(e)?.node.headers;
|
|
293
|
+
}
|
|
294
|
+
upsert(e, t, n, r) {
|
|
295
|
+
let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0;
|
|
296
|
+
this._codecKeyIndex.set(this._getKey(t), e);
|
|
297
|
+
let o = this._nodeIndex.get(e);
|
|
298
|
+
if (o) {
|
|
299
|
+
o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("ConversationTree.upsert(); promoting serial", {
|
|
300
|
+
msgId: e,
|
|
301
|
+
serial: r
|
|
302
|
+
}), o.node.serial = r, this._removeSorted(o), this._insertSorted(o));
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
this._logger.trace("ConversationTree.upsert(); inserting new node", {
|
|
306
|
+
msgId: e,
|
|
307
|
+
parentId: i,
|
|
308
|
+
forkOf: a
|
|
309
|
+
});
|
|
310
|
+
let s = {
|
|
311
|
+
node: {
|
|
312
|
+
message: t,
|
|
313
|
+
msgId: e,
|
|
314
|
+
parentId: i,
|
|
315
|
+
forkOf: a,
|
|
316
|
+
headers: { ...n },
|
|
317
|
+
serial: r
|
|
318
|
+
},
|
|
319
|
+
insertSeq: this._seqCounter++
|
|
320
|
+
};
|
|
321
|
+
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s);
|
|
322
|
+
}
|
|
323
|
+
delete(e) {
|
|
324
|
+
let t = this._nodeIndex.get(e);
|
|
325
|
+
if (!t) return;
|
|
326
|
+
this._logger.debug("ConversationTree.delete();", { msgId: e });
|
|
327
|
+
let { node: n } = t, r = this._getKey(n.message);
|
|
328
|
+
this._codecKeyIndex.get(r) === e && this._codecKeyIndex.delete(r), this._removeFromParentIndex(n.parentId, e), this._removeSorted(t), this._nodeIndex.delete(e), this._selections.delete(e);
|
|
329
|
+
}
|
|
330
|
+
}, I = (e, t) => new F(e, t), L = (e) => {
|
|
331
|
+
let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), i = e.codec.createAccumulator(), a = 0, o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
|
|
332
|
+
for (let c of t) {
|
|
333
|
+
let t = n.decode(c), l = A(c), f = l[u], p = l[d], m = c.serial;
|
|
334
|
+
if (f) {
|
|
335
|
+
let n = r.get(f);
|
|
336
|
+
if (n || (n = {
|
|
337
|
+
accumulator: e.codec.createAccumulator(),
|
|
338
|
+
firstSeen: a++,
|
|
339
|
+
msgHeaders: /* @__PURE__ */ new Map(),
|
|
340
|
+
msgSerials: /* @__PURE__ */ new Map()
|
|
341
|
+
}, r.set(f, n)), p) {
|
|
342
|
+
let e = n.msgHeaders.get(p);
|
|
343
|
+
e ? Object.keys(l).length > 0 && Object.assign(e, l) : (n.msgHeaders.set(p, { ...l }), m && n.msgSerials.set(p, m));
|
|
344
|
+
}
|
|
345
|
+
n.accumulator.processOutputs(t);
|
|
346
|
+
} else i.processOutputs(t);
|
|
347
|
+
for (let n of t) if (n.kind === "message") {
|
|
348
|
+
let t = e.getMessageKey(n.message), r = o.get(t);
|
|
349
|
+
r ? Object.keys(l).length > 0 && Object.assign(r, l) : (o.set(t, { ...l }), m && s.set(t, m));
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
let c = [];
|
|
353
|
+
for (let t of i.completedMessages) {
|
|
354
|
+
let n = e.getMessageKey(t);
|
|
355
|
+
c.push({
|
|
356
|
+
message: t,
|
|
357
|
+
headers: o.get(n) ?? {},
|
|
358
|
+
serial: s.get(n) ?? ""
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
let l = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
|
|
362
|
+
for (let t of l) {
|
|
363
|
+
let n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map();
|
|
364
|
+
for (let a of t.accumulator.completedMessages) {
|
|
365
|
+
let t = e.getMessageKey(a), c = o.get(t);
|
|
366
|
+
if (c) {
|
|
367
|
+
r.set(t, c);
|
|
368
|
+
let e = s.get(t);
|
|
369
|
+
e && i.set(t, e);
|
|
370
|
+
let a = c[d];
|
|
371
|
+
a && n.add(a);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
let a = [...t.msgHeaders.entries()].filter(([e]) => !n.has(e)), l = 0;
|
|
375
|
+
for (let n of t.accumulator.completedMessages) {
|
|
376
|
+
let o = e.getMessageKey(n), s = a[l];
|
|
377
|
+
if (!r.has(o) && s) {
|
|
378
|
+
let [e, n] = s;
|
|
379
|
+
r.set(o, n);
|
|
380
|
+
let a = t.msgSerials.get(e);
|
|
381
|
+
a && i.set(o, a), l++;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
for (let n of t.accumulator.completedMessages) {
|
|
385
|
+
let t = e.getMessageKey(n);
|
|
386
|
+
c.push({
|
|
387
|
+
message: n,
|
|
388
|
+
headers: r.get(t) ?? {},
|
|
389
|
+
serial: i.get(t) ?? ""
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return c.toReversed();
|
|
394
|
+
}, R = async (e, t, n) => {
|
|
395
|
+
e.rawMessages.push(...t.items), e.lastAblyPage = t;
|
|
396
|
+
let r = L(e).length;
|
|
397
|
+
for (; r < e.returnedCount + n && t.hasNext();) {
|
|
398
|
+
e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
|
|
399
|
+
collected: e.rawMessages.length,
|
|
400
|
+
decoded: r
|
|
401
|
+
});
|
|
402
|
+
let n = await t.next();
|
|
403
|
+
if (!n) break;
|
|
404
|
+
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, r = L(e).length;
|
|
405
|
+
}
|
|
406
|
+
}, z = (e, t) => {
|
|
407
|
+
let n = L(e), r = n.slice(e.returnedCount, e.returnedCount + t), i = [...r].toReversed();
|
|
408
|
+
e.returnedCount += r.length;
|
|
409
|
+
let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
|
|
410
|
+
return e.returnedRawCount = e.rawMessages.length, {
|
|
411
|
+
items: i.map((e) => e.message),
|
|
412
|
+
itemHeaders: i.map((e) => e.headers),
|
|
413
|
+
itemSerials: i.map((e) => e.serial),
|
|
414
|
+
rawMessages: s,
|
|
415
|
+
hasNext: () => a || o,
|
|
416
|
+
next: async () => {
|
|
417
|
+
if (a) return z(e, t);
|
|
418
|
+
if (!o || !e.lastAblyPage) return;
|
|
419
|
+
let n = await e.lastAblyPage.next();
|
|
420
|
+
if (n) return await R(e, n, t), z(e, t);
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
}, B = async (e, t, n, r) => {
|
|
424
|
+
let i = n?.limit ?? 100, a = {
|
|
425
|
+
codec: t,
|
|
426
|
+
rawMessages: [],
|
|
427
|
+
returnedCount: 0,
|
|
428
|
+
returnedRawCount: 0,
|
|
429
|
+
lastAblyPage: void 0,
|
|
430
|
+
getMessageKey: t.getMessageKey.bind(t),
|
|
431
|
+
logger: r
|
|
432
|
+
};
|
|
433
|
+
r.trace("decodeHistory();", { limit: i });
|
|
434
|
+
let o = i * 10;
|
|
435
|
+
return await e.attach(), await R(a, await e.history({
|
|
436
|
+
untilAttach: !0,
|
|
437
|
+
limit: o
|
|
438
|
+
}), i), z(a, i);
|
|
439
|
+
}, V = (e) => {
|
|
440
|
+
let t = {
|
|
441
|
+
[p]: e.role,
|
|
442
|
+
[u]: e.turnId,
|
|
443
|
+
[d]: e.msgId
|
|
444
|
+
};
|
|
445
|
+
return e.turnClientId !== void 0 && (t[f] = e.turnClientId), e.parent && (t[v] = e.parent), e.forkOf && (t[y] = e.forkOf), t;
|
|
446
|
+
}, H = class {
|
|
447
|
+
constructor(e, t) {
|
|
448
|
+
this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
|
|
449
|
+
}
|
|
450
|
+
createStream(e) {
|
|
451
|
+
this._logger.trace("StreamRouter.createStream();", { turnId: e });
|
|
452
|
+
let t = {}, r = new ReadableStream({ start(e) {
|
|
453
|
+
t.controller = e;
|
|
454
|
+
} });
|
|
455
|
+
if (!t.controller) throw new n.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", i.TransportSubscriptionError, 500);
|
|
456
|
+
return this._turns.set(e, {
|
|
457
|
+
controller: t.controller,
|
|
458
|
+
turnId: e
|
|
459
|
+
}), r;
|
|
460
|
+
}
|
|
461
|
+
closeStream(e) {
|
|
462
|
+
let t = this._turns.get(e);
|
|
463
|
+
if (!t) return !1;
|
|
464
|
+
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
465
|
+
try {
|
|
466
|
+
t.controller.close();
|
|
467
|
+
} catch {}
|
|
468
|
+
return this._turns.delete(e), !0;
|
|
469
|
+
}
|
|
470
|
+
route(e, t) {
|
|
471
|
+
let n = this._turns.get(e);
|
|
472
|
+
if (!n) return !1;
|
|
473
|
+
try {
|
|
474
|
+
n.controller.enqueue(t);
|
|
475
|
+
} catch {
|
|
476
|
+
return this._turns.delete(e), !1;
|
|
477
|
+
}
|
|
478
|
+
return this._isTerminal(t) && this.closeStream(e), !0;
|
|
479
|
+
}
|
|
480
|
+
has(e) {
|
|
481
|
+
return this._turns.has(e);
|
|
482
|
+
}
|
|
483
|
+
}, U = (e, t) => new H(e, t), W = () => {}, G = class {
|
|
484
|
+
constructor(e) {
|
|
485
|
+
if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this._turnClientIds = /* @__PURE__ */ new Map(), this._turnMsgIds = /* @__PURE__ */ new Map(), this._turnObservers = /* @__PURE__ */ new Map(), this._ablyMessages = [], this._withheldKeys = /* @__PURE__ */ new Set(), this._closed = !1, this._channel = e.channel, this._codec = e.codec, this._clientId = e.clientId, this._api = e.api ?? "/api/chat", this._credentials = e.credentials, this._headersFn = typeof e.headers == "function" ? e.headers : e.headers ? () => e.headers : void 0, this._bodyFn = typeof e.body == "function" ? e.body : e.body ? () => e.body : void 0, this._fetchFn = e.fetch ?? globalThis.fetch.bind(globalThis), this._logger = (e.logger ?? E({ logLevel: w.Silent })).withContext({ component: "ClientTransport" }), this._emitter = new ne(this._logger), this._tree = I(this._codec.getMessageKey.bind(this._codec), this._logger), this._router = U(this._codec.isTerminal.bind(this._codec), this._logger), this._decoder = this._codec.createDecoder(), e.messages) {
|
|
486
|
+
let t;
|
|
487
|
+
for (let n of e.messages) {
|
|
488
|
+
let e = this._codec.getMessageKey(n), r = {};
|
|
489
|
+
t && (r[v] = t), this._tree.upsert(e, n, r), t = e;
|
|
490
|
+
}
|
|
491
|
+
this._emitter.emit("message");
|
|
492
|
+
}
|
|
493
|
+
this._onMessage = (e) => {
|
|
494
|
+
this._handleMessage(e);
|
|
495
|
+
}, this._attachPromise = this._channel.subscribe(this._onMessage);
|
|
496
|
+
}
|
|
497
|
+
_handleMessage(e) {
|
|
498
|
+
if (!this._closed) {
|
|
499
|
+
this._ablyMessages.push(e), this._emitter.emit("ably-message");
|
|
500
|
+
try {
|
|
501
|
+
if (e.name === "x-ably-turn-start") {
|
|
502
|
+
let t = A(e), n = t[u], r = t["x-ably-turn-client-id"] ?? "";
|
|
503
|
+
n && (this._turnClientIds.set(n, r), this._emitter.emit("turn", {
|
|
504
|
+
type: ee,
|
|
505
|
+
turnId: n,
|
|
506
|
+
clientId: r
|
|
507
|
+
}));
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (e.name === "x-ably-turn-end") {
|
|
511
|
+
let t = A(e), n = t[u], r = t["x-ably-turn-client-id"] ?? "", i = t["x-ably-turn-reason"] ?? "complete";
|
|
512
|
+
if (n) {
|
|
513
|
+
this._router.closeStream(n), this._turnObservers.delete(n), this._turnClientIds.delete(n);
|
|
514
|
+
let e = this._turnMsgIds.get(n);
|
|
515
|
+
if (e) {
|
|
516
|
+
for (let t of e) this._ownMsgIds.delete(t);
|
|
517
|
+
this._turnMsgIds.delete(n);
|
|
518
|
+
}
|
|
519
|
+
this._ownTurnIds.delete(n), this._emitter.emit("turn", {
|
|
520
|
+
type: x,
|
|
521
|
+
turnId: n,
|
|
522
|
+
clientId: r,
|
|
523
|
+
reason: i
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
let t = this._decoder.decode(e), n = A(e), r = e.serial, i = n[u];
|
|
529
|
+
i && this._updateTurnObserverHeaders(i, n, r);
|
|
530
|
+
for (let i of t) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, e.action) : this._handleEventOutput(i, n);
|
|
531
|
+
} catch (e) {
|
|
532
|
+
let t = e instanceof n.ErrorInfo ? e : void 0;
|
|
533
|
+
this._emitter.emit("error", new n.ErrorInfo(`unable to process channel message; ${e instanceof Error ? e.message : String(e)}`, i.TransportSubscriptionError, 500, t));
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
_handleMessageOutput(e, t, n, r) {
|
|
538
|
+
let i = t[d];
|
|
539
|
+
if (i && this._ownMsgIds.has(i)) {
|
|
540
|
+
this._upsertAndNotify(e, t, n);
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
r === "message.create" && this._upsertAndNotify(e, t, n);
|
|
544
|
+
}
|
|
545
|
+
_handleEventOutput(e, t) {
|
|
546
|
+
if (e.kind !== "event") return;
|
|
547
|
+
let n = e.event, r = t[u];
|
|
548
|
+
if (r) {
|
|
549
|
+
if (this._router.route(r, n)) {
|
|
550
|
+
this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
_upsertAndNotify(e, t, n) {
|
|
557
|
+
let r = this._codec.getMessageKey(e), i = t["x-ably-msg-id"] ?? r;
|
|
558
|
+
this._tree.upsert(i, e, t, n), this._emitter.emit("message");
|
|
559
|
+
}
|
|
560
|
+
_updateTurnObserverHeaders(e, t, n) {
|
|
561
|
+
let r = this._turnObservers.get(e);
|
|
562
|
+
r ? (Object.keys(t).length > 0 && Object.assign(r.headers, t), n !== void 0 && (r.serial = n)) : this._turnObservers.set(e, {
|
|
563
|
+
headers: { ...t },
|
|
564
|
+
serial: n,
|
|
565
|
+
accumulator: this._codec.createAccumulator()
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
_accumulateAndEmit(e, t) {
|
|
569
|
+
let n = this._turnObservers.get(e);
|
|
570
|
+
if (!n) return;
|
|
571
|
+
n.accumulator.processOutputs([t]);
|
|
572
|
+
let r = n.accumulator.messages;
|
|
573
|
+
if (r.length === 0) return;
|
|
574
|
+
let i;
|
|
575
|
+
try {
|
|
576
|
+
i = structuredClone(r.at(-1));
|
|
577
|
+
} catch {
|
|
578
|
+
i = r.at(-1);
|
|
579
|
+
}
|
|
580
|
+
i && (this._tree.upsert(n.headers["x-ably-msg-id"] ?? this._codec.getMessageKey(i), i, { ...n.headers }, n.serial), this._emitter.emit("message"));
|
|
581
|
+
}
|
|
582
|
+
async _publishCancel(e) {
|
|
583
|
+
this._logger.trace("ClientTransport._publishCancel();", { filter: e });
|
|
584
|
+
let t = {};
|
|
585
|
+
e.turnId ? t[m] = e.turnId : e.own ? t[h] = "true" : e.clientId ? t[_] = e.clientId : e.all && (t[g] = "true"), await this._channel.publish({
|
|
586
|
+
name: b,
|
|
587
|
+
extras: { headers: t }
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
_closeMatchingTurnStreams(e) {
|
|
591
|
+
if (e.all) for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
592
|
+
else if (e.own) for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
593
|
+
else if (e.clientId) for (let [t, n] of this._turnClientIds) n === e.clientId && this._router.closeStream(t);
|
|
594
|
+
else e.turnId && this._router.closeStream(e.turnId);
|
|
595
|
+
}
|
|
596
|
+
_getMatchingTurnIds(e) {
|
|
597
|
+
let t = /* @__PURE__ */ new Set();
|
|
598
|
+
if (e.all) for (let e of this._turnClientIds.keys()) t.add(e);
|
|
599
|
+
else if (e.own) for (let [e, n] of this._turnClientIds) n === this._clientId && t.add(e);
|
|
600
|
+
else if (e.clientId) for (let [n, r] of this._turnClientIds) r === e.clientId && t.add(n);
|
|
601
|
+
else e.turnId && this._turnClientIds.has(e.turnId) && t.add(e.turnId);
|
|
602
|
+
return t;
|
|
603
|
+
}
|
|
604
|
+
_getMessagesWithHeaders() {
|
|
605
|
+
return this._tree.flatten().map((e) => ({
|
|
606
|
+
message: e,
|
|
607
|
+
headers: this.getMessageHeaders(e)
|
|
608
|
+
}));
|
|
609
|
+
}
|
|
610
|
+
_getHistoryBefore(e) {
|
|
611
|
+
let t = this._getMessagesWithHeaders(), n = t.findIndex((t) => t.headers?.[d] === e);
|
|
612
|
+
return n === -1 ? t : t.slice(0, n);
|
|
613
|
+
}
|
|
614
|
+
_processHistoryPage(e) {
|
|
615
|
+
for (let [t, n] of e.items.entries()) {
|
|
616
|
+
let r = e.itemHeaders?.[t] ?? {}, i = e.itemSerials?.[t], a = this._codec.getMessageKey(n), o = r["x-ably-msg-id"] ?? a;
|
|
617
|
+
this._tree.upsert(o, n, r, i);
|
|
618
|
+
}
|
|
619
|
+
this._emitter.emit("message"), e.rawMessages && e.rawMessages.length > 0 && (this._ablyMessages.unshift(...e.rawMessages), this._emitter.emit("ably-message"));
|
|
620
|
+
}
|
|
621
|
+
async _loadUntilVisible(e, t, n) {
|
|
622
|
+
this._processHistoryPage(e);
|
|
623
|
+
let r = e, i = () => {
|
|
624
|
+
let e = 0;
|
|
625
|
+
for (let t of this._tree.flatten()) n.has(this._codec.getMessageKey(t)) || e++;
|
|
626
|
+
return e;
|
|
627
|
+
};
|
|
628
|
+
for (; i() < t && r.hasNext();) {
|
|
629
|
+
let e = await r.next();
|
|
630
|
+
if (!e) break;
|
|
631
|
+
this._processHistoryPage(e), r = e;
|
|
632
|
+
}
|
|
633
|
+
return {
|
|
634
|
+
newVisible: this._tree.flatten().filter((e) => !n.has(this._codec.getMessageKey(e))),
|
|
635
|
+
lastPage: r
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
_releaseWithheld(e) {
|
|
639
|
+
for (let t of e) this._withheldKeys.delete(this._codec.getMessageKey(t));
|
|
640
|
+
e.length > 0 && this._emitter.emit("message");
|
|
641
|
+
}
|
|
642
|
+
async send(e, t) {
|
|
643
|
+
if (this._closed || (await this._attachPromise, this._closed)) throw new n.ErrorInfo("unable to send; transport is closed", i.TransportClosed, 400);
|
|
644
|
+
this._logger.trace("ClientTransport.send();");
|
|
645
|
+
let r = Array.isArray(e) ? e : [e], a = crypto.randomUUID();
|
|
646
|
+
this._ownTurnIds.add(a);
|
|
647
|
+
let o = /* @__PURE__ */ new Set(), s = [], c = this._getMessagesWithHeaders(), l;
|
|
648
|
+
if (t?.parent === void 0 && !t?.forkOf) {
|
|
649
|
+
let e = this._tree.flatten();
|
|
650
|
+
if (e.length > 0) {
|
|
651
|
+
let t = e.at(-1);
|
|
652
|
+
if (t) {
|
|
653
|
+
let e = this._codec.getMessageKey(t);
|
|
654
|
+
l = this._tree.getNodeByKey(e)?.msgId ?? e;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
let u = t?.parent === void 0 ? l : t.parent;
|
|
659
|
+
for (let e of r) {
|
|
660
|
+
let n = crypto.randomUUID();
|
|
661
|
+
this._ownMsgIds.add(n), o.add(n);
|
|
662
|
+
let r = t?.parent === void 0 ? l : t.parent ?? void 0, i = V({
|
|
663
|
+
role: "user",
|
|
664
|
+
turnId: a,
|
|
665
|
+
msgId: n,
|
|
666
|
+
turnClientId: this._clientId,
|
|
667
|
+
parent: r,
|
|
668
|
+
forkOf: t?.forkOf
|
|
669
|
+
});
|
|
670
|
+
this._upsertAndNotify(e, i);
|
|
671
|
+
let c = {
|
|
672
|
+
[d]: n,
|
|
673
|
+
[p]: "user"
|
|
674
|
+
};
|
|
675
|
+
r && (c[v] = r), s.push({
|
|
676
|
+
message: e,
|
|
677
|
+
headers: c
|
|
678
|
+
}), t?.parent === void 0 && !t?.forkOf && (l = n);
|
|
679
|
+
}
|
|
680
|
+
this._turnMsgIds.set(a, o);
|
|
681
|
+
let f = this._router.createStream(a), m = this._headersFn?.() ?? {}, h = {
|
|
682
|
+
...this._bodyFn?.() ?? {},
|
|
683
|
+
history: c,
|
|
684
|
+
...t?.body,
|
|
685
|
+
turnId: a,
|
|
686
|
+
clientId: this._clientId,
|
|
687
|
+
messages: s,
|
|
688
|
+
...t?.forkOf !== void 0 && { forkOf: t.forkOf },
|
|
689
|
+
...u !== void 0 && { parent: u }
|
|
690
|
+
}, g = {
|
|
691
|
+
...m,
|
|
692
|
+
...t?.headers
|
|
693
|
+
};
|
|
694
|
+
return this._fetchFn(this._api, {
|
|
695
|
+
method: "POST",
|
|
696
|
+
headers: {
|
|
697
|
+
"Content-Type": "application/json",
|
|
698
|
+
...g
|
|
699
|
+
},
|
|
700
|
+
body: JSON.stringify(h),
|
|
701
|
+
...this._credentials ? { credentials: this._credentials } : {}
|
|
702
|
+
}).then((e) => {
|
|
703
|
+
e.ok || (this._emitter.emit("error", new n.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(e.status)} ${e.statusText}`, i.TransportSendFailed, e.status)), this._router.closeStream(a));
|
|
704
|
+
}).catch((e) => {
|
|
705
|
+
let t = e instanceof n.ErrorInfo ? e : void 0;
|
|
706
|
+
this._emitter.emit("error", new n.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${e instanceof Error ? e.message : String(e)}`, i.TransportSendFailed, 500, t)), this._router.closeStream(a);
|
|
707
|
+
}), {
|
|
708
|
+
stream: f,
|
|
709
|
+
turnId: a,
|
|
710
|
+
cancel: async () => this.cancel({ turnId: a })
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
async regenerate(e, t) {
|
|
714
|
+
this._logger.trace("ClientTransport.regenerate();", { messageId: e });
|
|
715
|
+
let n = this._tree.getNode(e)?.parentId;
|
|
716
|
+
return this.send([], {
|
|
717
|
+
...t,
|
|
718
|
+
body: {
|
|
719
|
+
history: this._getHistoryBefore(e),
|
|
720
|
+
...t?.body
|
|
721
|
+
},
|
|
722
|
+
forkOf: e,
|
|
723
|
+
parent: n
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
async edit(e, t, n) {
|
|
727
|
+
this._logger.trace("ClientTransport.edit();", { messageId: e });
|
|
728
|
+
let r = this._tree.getNode(e)?.parentId;
|
|
729
|
+
return this.send(t, {
|
|
730
|
+
...n,
|
|
731
|
+
body: {
|
|
732
|
+
history: this._getHistoryBefore(e),
|
|
733
|
+
...n?.body
|
|
734
|
+
},
|
|
735
|
+
forkOf: e,
|
|
736
|
+
parent: r
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
async cancel(e) {
|
|
740
|
+
if (this._closed) return;
|
|
741
|
+
let t = e ?? { own: !0 };
|
|
742
|
+
this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
|
|
743
|
+
}
|
|
744
|
+
async waitForTurn(e) {
|
|
745
|
+
if (this._closed) return;
|
|
746
|
+
let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
|
|
747
|
+
if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
|
|
748
|
+
let t = (r) => {
|
|
749
|
+
r.type === "x-ably-turn-end" && (n.delete(r.turnId), n.size === 0 && (this._emitter.off("turn", t), e()));
|
|
750
|
+
};
|
|
751
|
+
this._emitter.on("turn", t);
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
on(e, t) {
|
|
755
|
+
if (this._closed) return W;
|
|
756
|
+
let n = t;
|
|
757
|
+
return this._emitter.on(e, n), () => {
|
|
758
|
+
this._emitter.off(e, n);
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
getTree() {
|
|
762
|
+
return this._tree;
|
|
763
|
+
}
|
|
764
|
+
getActiveTurnIds() {
|
|
765
|
+
let e = /* @__PURE__ */ new Map();
|
|
766
|
+
for (let [t, n] of this._turnClientIds) {
|
|
767
|
+
let r = e.get(n);
|
|
768
|
+
r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
|
|
769
|
+
}
|
|
770
|
+
return e;
|
|
771
|
+
}
|
|
772
|
+
getMessageHeaders(e) {
|
|
773
|
+
let t = this._codec.getMessageKey(e);
|
|
774
|
+
return this._tree.getNodeByKey(t)?.headers;
|
|
775
|
+
}
|
|
776
|
+
getMessages() {
|
|
777
|
+
return this._withheldKeys.size === 0 ? this._tree.flatten() : this._tree.flatten().filter((e) => !this._withheldKeys.has(this._codec.getMessageKey(e)));
|
|
778
|
+
}
|
|
779
|
+
getMessagesWithHeaders() {
|
|
780
|
+
return this._getMessagesWithHeaders();
|
|
781
|
+
}
|
|
782
|
+
getAblyMessages() {
|
|
783
|
+
return [...this._ablyMessages];
|
|
784
|
+
}
|
|
785
|
+
async history(e) {
|
|
786
|
+
if (this._closed) throw new n.ErrorInfo("unable to load history; transport is closed", i.TransportClosed, 400);
|
|
787
|
+
this._logger.trace("ClientTransport.history();", { limit: e?.limit });
|
|
788
|
+
let t = e?.limit ?? 100, r = new Set(this._tree.flatten().map((e) => this._codec.getMessageKey(e))), a = await B(this._channel, this._codec, e, this._logger), o = await this._loadUntilVisible(a, t, r);
|
|
789
|
+
a = o.lastPage;
|
|
790
|
+
let s = o.newVisible;
|
|
791
|
+
for (let e of s) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
792
|
+
let c = s.slice(-t), l = s.slice(0, -t);
|
|
793
|
+
this._releaseWithheld(c);
|
|
794
|
+
let u = (e) => ({
|
|
795
|
+
items: e,
|
|
796
|
+
hasNext: () => l.length > 0 || a.hasNext(),
|
|
797
|
+
next: async () => {
|
|
798
|
+
if (l.length > 0) {
|
|
799
|
+
let e = l.splice(-t, t);
|
|
800
|
+
return this._releaseWithheld(e), u(e);
|
|
801
|
+
}
|
|
802
|
+
if (!a.hasNext()) return;
|
|
803
|
+
let e = await a.next();
|
|
804
|
+
if (!e) return;
|
|
805
|
+
let n = new Set(r);
|
|
806
|
+
for (let e of this._tree.flatten()) n.add(this._codec.getMessageKey(e));
|
|
807
|
+
let i = await this._loadUntilVisible(e, t, n);
|
|
808
|
+
a = i.lastPage;
|
|
809
|
+
let o = i.newVisible;
|
|
810
|
+
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
811
|
+
let s = o.splice(-t, t);
|
|
812
|
+
if (l.push(...o), this._releaseWithheld(s), s.length !== 0) return u(s);
|
|
813
|
+
}
|
|
814
|
+
});
|
|
815
|
+
return u(c);
|
|
816
|
+
}
|
|
817
|
+
async close(e) {
|
|
818
|
+
if (!this._closed) {
|
|
819
|
+
if (this._closed = !0, this._logger.info("ClientTransport.close();"), e?.cancel) {
|
|
820
|
+
try {
|
|
821
|
+
await this._publishCancel(e.cancel);
|
|
822
|
+
} catch {}
|
|
823
|
+
this._closeMatchingTurnStreams(e.cancel);
|
|
824
|
+
}
|
|
825
|
+
this._channel.unsubscribe(this._onMessage);
|
|
826
|
+
for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
827
|
+
this._turnObservers.clear(), this._emitter.off(), this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear(), this._turnClientIds.clear(), this._withheldKeys.clear(), this._ablyMessages.length = 0;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
}, K = (e) => new G(e), q = (e) => N({
|
|
831
|
+
type: "dynamic-tool",
|
|
832
|
+
toolCallId: e.toolCallId,
|
|
833
|
+
toolName: e.toolName,
|
|
834
|
+
title: e.title,
|
|
835
|
+
providerExecuted: e.providerExecuted
|
|
836
|
+
}), J = class {
|
|
837
|
+
constructor(e) {
|
|
838
|
+
this._activeIndex = /* @__PURE__ */ new Map(), this._partType = e;
|
|
839
|
+
}
|
|
840
|
+
start(e, t, n) {
|
|
841
|
+
this._activeIndex.set(e, t.parts.length), t.parts.push({
|
|
842
|
+
type: this._partType,
|
|
843
|
+
text: ""
|
|
844
|
+
}), n.set(e, "streaming");
|
|
845
|
+
}
|
|
846
|
+
delta(e, t, n) {
|
|
847
|
+
let r = this._activeIndex.get(e);
|
|
848
|
+
if (r === void 0) return;
|
|
849
|
+
let i = t.parts[r];
|
|
850
|
+
i?.type === this._partType && (i.text += n);
|
|
851
|
+
}
|
|
852
|
+
end(e, t) {
|
|
853
|
+
t.set(e, "finished"), this._activeIndex.delete(e);
|
|
854
|
+
}
|
|
855
|
+
reset() {
|
|
856
|
+
this._activeIndex = /* @__PURE__ */ new Map();
|
|
857
|
+
}
|
|
858
|
+
}, oe = class {
|
|
859
|
+
constructor() {
|
|
860
|
+
this._messageList = [], this._activeMessages = /* @__PURE__ */ new Map();
|
|
861
|
+
}
|
|
862
|
+
get messages() {
|
|
863
|
+
return this._messageList;
|
|
864
|
+
}
|
|
865
|
+
get completedMessages() {
|
|
866
|
+
let e = /* @__PURE__ */ new Set();
|
|
867
|
+
for (let t of this._activeMessages.values()) e.add(t.message);
|
|
868
|
+
return this._messageList.filter((t) => !e.has(t));
|
|
869
|
+
}
|
|
870
|
+
get hasActiveStream() {
|
|
871
|
+
for (let e of this._activeMessages.values()) for (let t of e.streamStatus.values()) if (t === "streaming") return !0;
|
|
872
|
+
return !1;
|
|
873
|
+
}
|
|
874
|
+
processOutputs(e) {
|
|
875
|
+
for (let t of e) t.kind === "message" ? this._messageList.push(t.message) : t.messageId !== void 0 && this._processEvent(t.event, t.messageId);
|
|
876
|
+
}
|
|
877
|
+
updateMessage(e) {
|
|
878
|
+
let t = this._messageList.findIndex((t) => t.id === e.id);
|
|
879
|
+
t !== -1 && (this._messageList[t] = e);
|
|
880
|
+
}
|
|
881
|
+
_ensureActiveMessage(e) {
|
|
882
|
+
let t = this._activeMessages.get(e);
|
|
883
|
+
if (t) return t;
|
|
884
|
+
let n = {
|
|
885
|
+
message: {
|
|
886
|
+
id: e,
|
|
887
|
+
role: "assistant",
|
|
888
|
+
parts: []
|
|
889
|
+
},
|
|
890
|
+
textStreams: new J("text"),
|
|
891
|
+
reasoningStreams: new J("reasoning"),
|
|
892
|
+
toolTrackers: {},
|
|
893
|
+
streamStatus: /* @__PURE__ */ new Map()
|
|
894
|
+
};
|
|
895
|
+
return this._activeMessages.set(e, n), this._messageList.push(n.message), n;
|
|
896
|
+
}
|
|
897
|
+
_getToolPart(e, t) {
|
|
898
|
+
let n = t.toolTrackers[e];
|
|
899
|
+
if (!n) return;
|
|
900
|
+
let r = t.message.parts[n.partIndex];
|
|
901
|
+
if (r?.type === "dynamic-tool") return {
|
|
902
|
+
tracker: n,
|
|
903
|
+
part: r
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
_processEvent(e, t) {
|
|
907
|
+
switch (e.type) {
|
|
908
|
+
case "start":
|
|
909
|
+
case "start-step":
|
|
910
|
+
case "finish-step":
|
|
911
|
+
case "finish":
|
|
912
|
+
case "abort":
|
|
913
|
+
case "error":
|
|
914
|
+
case "message-metadata":
|
|
915
|
+
this._processLifecycle(e, t);
|
|
916
|
+
break;
|
|
917
|
+
case "text-start":
|
|
918
|
+
case "text-delta":
|
|
919
|
+
case "text-end":
|
|
920
|
+
case "reasoning-start":
|
|
921
|
+
case "reasoning-delta":
|
|
922
|
+
case "reasoning-end":
|
|
923
|
+
this._processTextOrReasoning(e, t);
|
|
924
|
+
break;
|
|
925
|
+
case "tool-input-start":
|
|
926
|
+
case "tool-input-delta":
|
|
927
|
+
case "tool-input-available":
|
|
928
|
+
case "tool-input-error":
|
|
929
|
+
this._processToolInput(e, t);
|
|
930
|
+
break;
|
|
931
|
+
case "tool-output-available":
|
|
932
|
+
case "tool-output-error":
|
|
933
|
+
case "tool-output-denied":
|
|
934
|
+
case "tool-approval-request":
|
|
935
|
+
this._processToolOutput(e, t);
|
|
936
|
+
break;
|
|
937
|
+
case "file":
|
|
938
|
+
case "source-url":
|
|
939
|
+
case "source-document":
|
|
940
|
+
this._processContentPart(e, t);
|
|
941
|
+
break;
|
|
942
|
+
default:
|
|
943
|
+
if (e.type.startsWith("data-")) {
|
|
944
|
+
if (e.transient) break;
|
|
945
|
+
let n = this._ensureActiveMessage(t), r = N({
|
|
946
|
+
type: e.type,
|
|
947
|
+
id: e.id,
|
|
948
|
+
data: e.data
|
|
949
|
+
});
|
|
950
|
+
if (e.id !== void 0) {
|
|
951
|
+
let t = n.message.parts.findIndex((t) => t.type === e.type && "id" in t && t.id === e.id);
|
|
952
|
+
if (t !== -1) {
|
|
953
|
+
n.message.parts[t] = r;
|
|
954
|
+
break;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
n.message.parts.push(r);
|
|
958
|
+
}
|
|
959
|
+
break;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
_processLifecycle(e, t) {
|
|
963
|
+
switch (e.type) {
|
|
964
|
+
case "start": {
|
|
965
|
+
let n = this._ensureActiveMessage(t);
|
|
966
|
+
e.messageId && (n.message.id = e.messageId), e.messageMetadata !== void 0 && (n.message.metadata = e.messageMetadata);
|
|
967
|
+
break;
|
|
968
|
+
}
|
|
969
|
+
case "start-step":
|
|
970
|
+
this._ensureActiveMessage(t).message.parts.push({ type: "step-start" });
|
|
971
|
+
break;
|
|
972
|
+
case "finish-step": {
|
|
973
|
+
let e = this._activeMessages.get(t);
|
|
974
|
+
e && (e.textStreams.reset(), e.reasoningStreams.reset());
|
|
975
|
+
break;
|
|
976
|
+
}
|
|
977
|
+
case "finish": {
|
|
978
|
+
let n = this._activeMessages.get(t);
|
|
979
|
+
n && e.messageMetadata !== void 0 && (n.message.metadata = e.messageMetadata), this._activeMessages.delete(t);
|
|
980
|
+
break;
|
|
981
|
+
}
|
|
982
|
+
case "abort": {
|
|
983
|
+
let e = this._activeMessages.get(t);
|
|
984
|
+
if (e) for (let [t, n] of e.streamStatus) n === "streaming" && e.streamStatus.set(t, "aborted");
|
|
985
|
+
this._activeMessages.delete(t);
|
|
986
|
+
break;
|
|
987
|
+
}
|
|
988
|
+
case "error": break;
|
|
989
|
+
case "message-metadata": {
|
|
990
|
+
let n = this._activeMessages.get(t);
|
|
991
|
+
n && e.messageMetadata !== void 0 && (n.message.metadata = e.messageMetadata);
|
|
992
|
+
break;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
_processTextOrReasoning(e, t) {
|
|
997
|
+
let n = this._ensureActiveMessage(t);
|
|
998
|
+
switch (e.type) {
|
|
999
|
+
case "text-start":
|
|
1000
|
+
n.textStreams.start(e.id, n.message, n.streamStatus);
|
|
1001
|
+
break;
|
|
1002
|
+
case "text-delta":
|
|
1003
|
+
n.textStreams.delta(e.id, n.message, e.delta);
|
|
1004
|
+
break;
|
|
1005
|
+
case "text-end":
|
|
1006
|
+
n.textStreams.end(e.id, n.streamStatus);
|
|
1007
|
+
break;
|
|
1008
|
+
case "reasoning-start":
|
|
1009
|
+
n.reasoningStreams.start(e.id, n.message, n.streamStatus);
|
|
1010
|
+
break;
|
|
1011
|
+
case "reasoning-delta":
|
|
1012
|
+
n.reasoningStreams.delta(e.id, n.message, e.delta);
|
|
1013
|
+
break;
|
|
1014
|
+
case "reasoning-end":
|
|
1015
|
+
n.reasoningStreams.end(e.id, n.streamStatus);
|
|
1016
|
+
break;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
_processToolInput(e, t) {
|
|
1020
|
+
switch (e.type) {
|
|
1021
|
+
case "tool-input-start": {
|
|
1022
|
+
let n = this._ensureActiveMessage(t), r = n.message.parts.length;
|
|
1023
|
+
n.message.parts.push({
|
|
1024
|
+
...q(e),
|
|
1025
|
+
state: "input-streaming",
|
|
1026
|
+
input: void 0
|
|
1027
|
+
}), n.toolTrackers[e.toolCallId] = {
|
|
1028
|
+
partIndex: r,
|
|
1029
|
+
inputText: ""
|
|
1030
|
+
}, n.streamStatus.set(e.toolCallId, "streaming");
|
|
1031
|
+
break;
|
|
1032
|
+
}
|
|
1033
|
+
case "tool-input-delta": {
|
|
1034
|
+
let n = this._ensureActiveMessage(t), r = n.toolTrackers[e.toolCallId];
|
|
1035
|
+
if (!r) break;
|
|
1036
|
+
r.inputText += e.inputTextDelta;
|
|
1037
|
+
let i;
|
|
1038
|
+
try {
|
|
1039
|
+
i = JSON.parse(r.inputText);
|
|
1040
|
+
} catch {
|
|
1041
|
+
i = void 0;
|
|
1042
|
+
}
|
|
1043
|
+
let a = this._getToolPart(e.toolCallId, n);
|
|
1044
|
+
if (!a) break;
|
|
1045
|
+
n.message.parts[a.tracker.partIndex] = {
|
|
1046
|
+
...q(a.part),
|
|
1047
|
+
state: "input-streaming",
|
|
1048
|
+
input: i
|
|
1049
|
+
};
|
|
1050
|
+
break;
|
|
1051
|
+
}
|
|
1052
|
+
case "tool-input-available": {
|
|
1053
|
+
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
1054
|
+
if (!r) break;
|
|
1055
|
+
n.message.parts[r.tracker.partIndex] = {
|
|
1056
|
+
...q(r.part),
|
|
1057
|
+
state: "input-available",
|
|
1058
|
+
input: e.input
|
|
1059
|
+
}, n.streamStatus.set(e.toolCallId, "finished");
|
|
1060
|
+
break;
|
|
1061
|
+
}
|
|
1062
|
+
case "tool-input-error": {
|
|
1063
|
+
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
1064
|
+
if (r) n.message.parts[r.tracker.partIndex] = {
|
|
1065
|
+
...q(r.part),
|
|
1066
|
+
state: "output-error",
|
|
1067
|
+
input: e.input,
|
|
1068
|
+
errorText: e.errorText
|
|
1069
|
+
};
|
|
1070
|
+
else {
|
|
1071
|
+
let t = n.message.parts.length;
|
|
1072
|
+
n.message.parts.push({
|
|
1073
|
+
...q(e),
|
|
1074
|
+
state: "output-error",
|
|
1075
|
+
input: e.input,
|
|
1076
|
+
errorText: e.errorText
|
|
1077
|
+
}), n.toolTrackers[e.toolCallId] = {
|
|
1078
|
+
partIndex: t,
|
|
1079
|
+
inputText: ""
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
n.streamStatus.set(e.toolCallId, "finished");
|
|
1083
|
+
break;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
_processToolOutput(e, t) {
|
|
1088
|
+
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
1089
|
+
if (r) switch (e.type) {
|
|
1090
|
+
case "tool-output-available":
|
|
1091
|
+
n.message.parts[r.tracker.partIndex] = N({
|
|
1092
|
+
...q(r.part),
|
|
1093
|
+
state: "output-available",
|
|
1094
|
+
input: r.part.input,
|
|
1095
|
+
output: e.output,
|
|
1096
|
+
preliminary: e.preliminary
|
|
1097
|
+
});
|
|
1098
|
+
break;
|
|
1099
|
+
case "tool-output-error":
|
|
1100
|
+
n.message.parts[r.tracker.partIndex] = {
|
|
1101
|
+
...q(r.part),
|
|
1102
|
+
state: "output-error",
|
|
1103
|
+
input: r.part.input,
|
|
1104
|
+
errorText: e.errorText
|
|
1105
|
+
};
|
|
1106
|
+
break;
|
|
1107
|
+
case "tool-output-denied":
|
|
1108
|
+
n.message.parts[r.tracker.partIndex] = {
|
|
1109
|
+
...q(r.part),
|
|
1110
|
+
state: "output-denied",
|
|
1111
|
+
input: r.part.input,
|
|
1112
|
+
approval: {
|
|
1113
|
+
id: "",
|
|
1114
|
+
approved: !1
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
break;
|
|
1118
|
+
case "tool-approval-request":
|
|
1119
|
+
n.message.parts[r.tracker.partIndex] = {
|
|
1120
|
+
...q(r.part),
|
|
1121
|
+
state: "approval-requested",
|
|
1122
|
+
input: r.part.input,
|
|
1123
|
+
approval: { id: e.approvalId }
|
|
1124
|
+
};
|
|
1125
|
+
break;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
_processContentPart(e, t) {
|
|
1129
|
+
let n = this._ensureActiveMessage(t);
|
|
1130
|
+
switch (e.type) {
|
|
1131
|
+
case "file":
|
|
1132
|
+
n.message.parts.push({
|
|
1133
|
+
type: "file",
|
|
1134
|
+
mediaType: e.mediaType,
|
|
1135
|
+
url: e.url
|
|
1136
|
+
});
|
|
1137
|
+
break;
|
|
1138
|
+
case "source-url":
|
|
1139
|
+
n.message.parts.push(N({
|
|
1140
|
+
type: "source-url",
|
|
1141
|
+
sourceId: e.sourceId,
|
|
1142
|
+
url: e.url,
|
|
1143
|
+
title: e.title
|
|
1144
|
+
}));
|
|
1145
|
+
break;
|
|
1146
|
+
case "source-document":
|
|
1147
|
+
n.message.parts.push(N({
|
|
1148
|
+
type: "source-document",
|
|
1149
|
+
sourceId: e.sourceId,
|
|
1150
|
+
mediaType: e.mediaType,
|
|
1151
|
+
title: e.title,
|
|
1152
|
+
filename: e.filename
|
|
1153
|
+
}));
|
|
1154
|
+
break;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}, se = () => new oe(), ce = (e) => [{
|
|
1158
|
+
kind: "event",
|
|
1159
|
+
event: e
|
|
1160
|
+
}], le = class {
|
|
1161
|
+
constructor(e, t = {}) {
|
|
1162
|
+
this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
|
|
1163
|
+
}
|
|
1164
|
+
decode(e) {
|
|
1165
|
+
let t = e.action;
|
|
1166
|
+
this._logger?.trace("DefaultDecoderCore.decode();", {
|
|
1167
|
+
action: t,
|
|
1168
|
+
serial: e.serial,
|
|
1169
|
+
name: e.name
|
|
1170
|
+
});
|
|
1171
|
+
let n;
|
|
1172
|
+
switch (t) {
|
|
1173
|
+
case "message.create": {
|
|
1174
|
+
let t = this._toPayload(e);
|
|
1175
|
+
n = t.headers?.["x-ably-stream"] === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
|
|
1176
|
+
break;
|
|
1177
|
+
}
|
|
1178
|
+
case "message.append":
|
|
1179
|
+
n = this._decodeAppend(e);
|
|
1180
|
+
break;
|
|
1181
|
+
case "message.update":
|
|
1182
|
+
n = this._decodeUpdate(e);
|
|
1183
|
+
break;
|
|
1184
|
+
case "message.delete":
|
|
1185
|
+
n = this._decodeDelete(e);
|
|
1186
|
+
break;
|
|
1187
|
+
default: return [];
|
|
1188
|
+
}
|
|
1189
|
+
let r = A(e)[d];
|
|
1190
|
+
if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
|
|
1191
|
+
return n;
|
|
1192
|
+
}
|
|
1193
|
+
_toPayload(e) {
|
|
1194
|
+
return {
|
|
1195
|
+
name: e.name ?? "",
|
|
1196
|
+
data: e.data,
|
|
1197
|
+
headers: A(e)
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
_stringData(e) {
|
|
1201
|
+
return typeof e.data == "string" ? e.data : "";
|
|
1202
|
+
}
|
|
1203
|
+
_invokeOnStreamUpdate(e) {
|
|
1204
|
+
if (this._onStreamUpdate) try {
|
|
1205
|
+
this._onStreamUpdate(e);
|
|
1206
|
+
} catch (e) {
|
|
1207
|
+
this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
_invokeOnStreamDelete(e, t) {
|
|
1211
|
+
if (this._onStreamDelete) try {
|
|
1212
|
+
this._onStreamDelete(e, t);
|
|
1213
|
+
} catch (e) {
|
|
1214
|
+
this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
_decodeStreamedCreate(e, t) {
|
|
1218
|
+
if (!t) return [];
|
|
1219
|
+
let n = e.headers?.["x-ably-stream-id"] ?? "", r = e.headers ?? {}, i = {
|
|
1220
|
+
name: e.name,
|
|
1221
|
+
streamId: n,
|
|
1222
|
+
accumulated: "",
|
|
1223
|
+
headers: { ...r },
|
|
1224
|
+
closed: !1
|
|
1225
|
+
};
|
|
1226
|
+
return this._serialState.set(t, i), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
|
|
1227
|
+
name: e.name,
|
|
1228
|
+
streamId: n,
|
|
1229
|
+
serial: t
|
|
1230
|
+
}), this._hooks.buildStartEvents(i);
|
|
1231
|
+
}
|
|
1232
|
+
_decodeAppend(e) {
|
|
1233
|
+
let t = e.serial;
|
|
1234
|
+
if (!t) return [];
|
|
1235
|
+
let n = this._serialState.get(t);
|
|
1236
|
+
if (!n) return this._decodeUpdate(e);
|
|
1237
|
+
let r = A(e), i = typeof e.data == "string" ? e.data : "", a = r[c], o = [];
|
|
1238
|
+
return i.length > 0 && (n.accumulated += i, o.push(...this._hooks.buildDeltaEvents(n, i))), a === "finished" && !n.closed ? (n.closed = !0, o.push(...this._hooks.buildEndEvents(n, r)), this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream finished", { streamId: n.streamId })) : a === "aborted" && !n.closed && (n.closed = !0, this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream aborted", { streamId: n.streamId })), o;
|
|
1239
|
+
}
|
|
1240
|
+
_decodeUpdate(e) {
|
|
1241
|
+
let t = e.serial;
|
|
1242
|
+
if (!t) return [];
|
|
1243
|
+
let n = this._toPayload(e), r = n.headers ?? {}, i = r[s] === "true", a = r[c], o = this._serialState.get(t);
|
|
1244
|
+
if (!o) return this._decodeFirstContact(n, i, a, t);
|
|
1245
|
+
let l = this._stringData(e);
|
|
1246
|
+
if (l.startsWith(o.accumulated)) {
|
|
1247
|
+
let e = l.slice(o.accumulated.length), t = [];
|
|
1248
|
+
return e.length > 0 && (o.accumulated = l, t.push(...this._hooks.buildDeltaEvents(o, e))), a === "finished" && !o.closed ? (o.closed = !0, t.push(...this._hooks.buildEndEvents(o, r))) : a === "aborted" && !o.closed && (o.closed = !0), t;
|
|
1249
|
+
}
|
|
1250
|
+
return o.accumulated = l, o.headers = { ...r }, this._invokeOnStreamUpdate(o), [];
|
|
1251
|
+
}
|
|
1252
|
+
_decodeFirstContact(e, t, n, r) {
|
|
1253
|
+
if (!t) return this._hooks.decodeDiscrete(e);
|
|
1254
|
+
let i = e.headers?.["x-ably-stream-id"] ?? "", a = e.headers ?? {}, o = typeof e.data == "string" ? e.data : "";
|
|
1255
|
+
this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
|
|
1256
|
+
name: e.name,
|
|
1257
|
+
streamId: i,
|
|
1258
|
+
serial: r
|
|
1259
|
+
});
|
|
1260
|
+
let s = {
|
|
1261
|
+
name: e.name,
|
|
1262
|
+
streamId: i,
|
|
1263
|
+
accumulated: o,
|
|
1264
|
+
headers: { ...a },
|
|
1265
|
+
closed: n === "finished" || n === "aborted"
|
|
1266
|
+
};
|
|
1267
|
+
this._serialState.set(r, s);
|
|
1268
|
+
let c = this._hooks.buildStartEvents(s);
|
|
1269
|
+
return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "finished" && c.push(...this._hooks.buildEndEvents(s, a)), c;
|
|
1270
|
+
}
|
|
1271
|
+
_decodeDelete(e) {
|
|
1272
|
+
let t = e.serial;
|
|
1273
|
+
if (!t) return [];
|
|
1274
|
+
let n = this._serialState.get(t);
|
|
1275
|
+
return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
|
|
1276
|
+
}
|
|
1277
|
+
}, ue = (e, t = {}) => new le(e, t), de = class {
|
|
1278
|
+
constructor(e) {
|
|
1279
|
+
this._emitted = /* @__PURE__ */ new Map(), this._phases = e;
|
|
1280
|
+
}
|
|
1281
|
+
ensurePhases(e, t) {
|
|
1282
|
+
let n = this._getOrCreate(e), r = [];
|
|
1283
|
+
for (let e of this._phases) n.has(e.key) || (n.add(e.key), r.push(...e.build(t)));
|
|
1284
|
+
return r;
|
|
1285
|
+
}
|
|
1286
|
+
markEmitted(e, t) {
|
|
1287
|
+
this._getOrCreate(e).add(t);
|
|
1288
|
+
}
|
|
1289
|
+
resetPhase(e, t) {
|
|
1290
|
+
this._emitted.get(e)?.delete(t);
|
|
1291
|
+
}
|
|
1292
|
+
clearScope(e) {
|
|
1293
|
+
this._emitted.delete(e);
|
|
1294
|
+
}
|
|
1295
|
+
_getOrCreate(e) {
|
|
1296
|
+
let t = this._emitted.get(e);
|
|
1297
|
+
return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
|
|
1298
|
+
}
|
|
1299
|
+
}, fe = (e) => new de(e), Y = (e) => {
|
|
1300
|
+
let t = ae(e);
|
|
1301
|
+
return {
|
|
1302
|
+
...t,
|
|
1303
|
+
providerMetadata: () => t.json("providerMetadata")
|
|
1304
|
+
};
|
|
1305
|
+
}, X = (e) => ce(e), pe = (e, t) => e === "stop" || e === "length" || e === "content-filter" || e === "tool-calls" || e === "error" || e === "other" ? e : t, Z = (e) => e.startsWith("data-"), me = (e) => {
|
|
1306
|
+
if (e) try {
|
|
1307
|
+
return JSON.parse(e);
|
|
1308
|
+
} catch {
|
|
1309
|
+
return e;
|
|
1310
|
+
}
|
|
1311
|
+
}, he = (e) => {
|
|
1312
|
+
let t = Y(e.headers);
|
|
1313
|
+
switch (e.name) {
|
|
1314
|
+
case "text": return N({
|
|
1315
|
+
type: "text-start",
|
|
1316
|
+
id: e.streamId,
|
|
1317
|
+
providerMetadata: t.providerMetadata()
|
|
1318
|
+
});
|
|
1319
|
+
case "reasoning": return N({
|
|
1320
|
+
type: "reasoning-start",
|
|
1321
|
+
id: e.streamId,
|
|
1322
|
+
providerMetadata: t.providerMetadata()
|
|
1323
|
+
});
|
|
1324
|
+
case "tool-input": return N({
|
|
1325
|
+
type: "tool-input-start",
|
|
1326
|
+
toolCallId: e.streamId,
|
|
1327
|
+
toolName: t.strOr("toolName", ""),
|
|
1328
|
+
dynamic: t.bool("dynamic"),
|
|
1329
|
+
title: t.str("title"),
|
|
1330
|
+
providerExecuted: t.bool("providerExecuted"),
|
|
1331
|
+
providerMetadata: t.providerMetadata()
|
|
1332
|
+
});
|
|
1333
|
+
default: return {
|
|
1334
|
+
type: "text-start",
|
|
1335
|
+
id: e.streamId
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
}, ge = (e, t) => {
|
|
1339
|
+
switch (e.name) {
|
|
1340
|
+
case "text": return {
|
|
1341
|
+
type: "text-delta",
|
|
1342
|
+
id: e.streamId,
|
|
1343
|
+
delta: t
|
|
1344
|
+
};
|
|
1345
|
+
case "reasoning": return {
|
|
1346
|
+
type: "reasoning-delta",
|
|
1347
|
+
id: e.streamId,
|
|
1348
|
+
delta: t
|
|
1349
|
+
};
|
|
1350
|
+
case "tool-input": return {
|
|
1351
|
+
type: "tool-input-delta",
|
|
1352
|
+
toolCallId: e.streamId,
|
|
1353
|
+
inputTextDelta: t
|
|
1354
|
+
};
|
|
1355
|
+
default: return {
|
|
1356
|
+
type: "text-delta",
|
|
1357
|
+
id: e.streamId,
|
|
1358
|
+
delta: t
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
}, _e = (e, t) => {
|
|
1362
|
+
let n = Y(t);
|
|
1363
|
+
switch (e.name) {
|
|
1364
|
+
case "text": return N({
|
|
1365
|
+
type: "text-end",
|
|
1366
|
+
id: e.streamId,
|
|
1367
|
+
providerMetadata: n.providerMetadata()
|
|
1368
|
+
});
|
|
1369
|
+
case "reasoning": return N({
|
|
1370
|
+
type: "reasoning-end",
|
|
1371
|
+
id: e.streamId,
|
|
1372
|
+
providerMetadata: n.providerMetadata()
|
|
1373
|
+
});
|
|
1374
|
+
case "tool-input": return N({
|
|
1375
|
+
type: "tool-input-available",
|
|
1376
|
+
toolCallId: e.streamId,
|
|
1377
|
+
toolName: n.strOr("toolName", Y(e.headers).strOr("toolName", "")),
|
|
1378
|
+
input: me(e.accumulated),
|
|
1379
|
+
providerMetadata: n.providerMetadata()
|
|
1380
|
+
});
|
|
1381
|
+
default: return {
|
|
1382
|
+
type: "text-end",
|
|
1383
|
+
id: e.streamId
|
|
1384
|
+
};
|
|
1385
|
+
}
|
|
1386
|
+
}, ve = () => fe([{
|
|
1387
|
+
key: "start",
|
|
1388
|
+
build: (e) => [N({
|
|
1389
|
+
type: "start",
|
|
1390
|
+
messageId: e.messageId
|
|
1391
|
+
})]
|
|
1392
|
+
}, {
|
|
1393
|
+
key: "start-step",
|
|
1394
|
+
build: () => [{ type: "start-step" }]
|
|
1395
|
+
}]), Q = (e, t, n) => e.ensurePhases(t, n).map((e) => ({
|
|
1396
|
+
kind: "event",
|
|
1397
|
+
event: e
|
|
1398
|
+
})), ye = (e, t, n) => (n.markEmitted(t, "start"), X(N({
|
|
1399
|
+
type: "start",
|
|
1400
|
+
messageId: e.str("messageId"),
|
|
1401
|
+
messageMetadata: e.json("messageMetadata")
|
|
1402
|
+
}))), be = (e, t) => (t.markEmitted(e, "start-step"), X({ type: "start-step" })), xe = (e, t) => (t.resetPhase(e, "start-step"), X({ type: "finish-step" })), Se = (e, t, n) => (n.clearScope(t), X(N({
|
|
1403
|
+
type: "finish",
|
|
1404
|
+
finishReason: pe(e.str("finishReason"), "stop"),
|
|
1405
|
+
messageMetadata: e.json("messageMetadata")
|
|
1406
|
+
}))), Ce = (e) => X({
|
|
1407
|
+
type: "error",
|
|
1408
|
+
errorText: typeof e == "string" ? e : ""
|
|
1409
|
+
}), we = (e, t, n) => (n.clearScope(t), X(N({
|
|
1410
|
+
type: "abort",
|
|
1411
|
+
reason: typeof e == "string" && e ? e : void 0
|
|
1412
|
+
}))), Te = (e) => X({
|
|
1413
|
+
type: "message-metadata",
|
|
1414
|
+
messageMetadata: e.json("messageMetadata")
|
|
1415
|
+
}), Ee = (e, t) => X(N({
|
|
1416
|
+
type: "file",
|
|
1417
|
+
url: typeof t == "string" ? t : "",
|
|
1418
|
+
mediaType: e.strOr("mediaType", ""),
|
|
1419
|
+
providerMetadata: e.providerMetadata()
|
|
1420
|
+
})), De = (e, t) => X(N({
|
|
1421
|
+
type: "source-url",
|
|
1422
|
+
sourceId: e.strOr("sourceId", ""),
|
|
1423
|
+
url: typeof t == "string" ? t : "",
|
|
1424
|
+
title: e.str("title"),
|
|
1425
|
+
providerMetadata: e.providerMetadata()
|
|
1426
|
+
})), Oe = (e) => X(N({
|
|
1427
|
+
type: "source-document",
|
|
1428
|
+
sourceId: e.strOr("sourceId", ""),
|
|
1429
|
+
mediaType: e.strOr("mediaType", ""),
|
|
1430
|
+
title: e.strOr("title", ""),
|
|
1431
|
+
filename: e.str("filename"),
|
|
1432
|
+
providerMetadata: e.providerMetadata()
|
|
1433
|
+
})), ke = (e, t) => {
|
|
1434
|
+
let n = t;
|
|
1435
|
+
return X(N({
|
|
1436
|
+
type: "tool-input-error",
|
|
1437
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
1438
|
+
toolName: e.strOr("toolName", ""),
|
|
1439
|
+
errorText: n?.errorText ?? "",
|
|
1440
|
+
input: n?.input,
|
|
1441
|
+
dynamic: e.bool("dynamic"),
|
|
1442
|
+
title: e.str("title"),
|
|
1443
|
+
providerExecuted: e.bool("providerExecuted"),
|
|
1444
|
+
providerMetadata: e.providerMetadata()
|
|
1445
|
+
}));
|
|
1446
|
+
}, Ae = (e, t) => {
|
|
1447
|
+
let n = t;
|
|
1448
|
+
return X(N({
|
|
1449
|
+
type: "tool-output-available",
|
|
1450
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
1451
|
+
output: n?.output,
|
|
1452
|
+
dynamic: e.bool("dynamic"),
|
|
1453
|
+
providerExecuted: e.bool("providerExecuted"),
|
|
1454
|
+
preliminary: e.bool("preliminary")
|
|
1455
|
+
}));
|
|
1456
|
+
}, je = (e, t) => {
|
|
1457
|
+
let n = t;
|
|
1458
|
+
return X(N({
|
|
1459
|
+
type: "tool-output-error",
|
|
1460
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
1461
|
+
errorText: n?.errorText ?? "",
|
|
1462
|
+
dynamic: e.bool("dynamic"),
|
|
1463
|
+
providerExecuted: e.bool("providerExecuted")
|
|
1464
|
+
}));
|
|
1465
|
+
}, Me = (e) => X({
|
|
1466
|
+
type: "tool-approval-request",
|
|
1467
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
1468
|
+
approvalId: e.strOr("approvalId", "")
|
|
1469
|
+
}), Ne = (e) => X({
|
|
1470
|
+
type: "tool-output-denied",
|
|
1471
|
+
toolCallId: e.strOr("toolCallId", "")
|
|
1472
|
+
}), Pe = (e, t, n) => X(N({
|
|
1473
|
+
type: e,
|
|
1474
|
+
data: n,
|
|
1475
|
+
id: t.str("id"),
|
|
1476
|
+
transient: t.bool("transient")
|
|
1477
|
+
})), Fe = (e, t, n, r) => {
|
|
1478
|
+
let i = Q(r, n, { messageId: e.str("messageId") });
|
|
1479
|
+
return i.push({
|
|
1480
|
+
kind: "event",
|
|
1481
|
+
event: N({
|
|
1482
|
+
type: "tool-input-start",
|
|
1483
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
1484
|
+
toolName: e.strOr("toolName", ""),
|
|
1485
|
+
dynamic: e.bool("dynamic"),
|
|
1486
|
+
title: e.str("title"),
|
|
1487
|
+
providerExecuted: e.bool("providerExecuted"),
|
|
1488
|
+
providerMetadata: e.providerMetadata()
|
|
1489
|
+
})
|
|
1490
|
+
}, {
|
|
1491
|
+
kind: "event",
|
|
1492
|
+
event: N({
|
|
1493
|
+
type: "tool-input-available",
|
|
1494
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
1495
|
+
toolName: e.strOr("toolName", ""),
|
|
1496
|
+
input: t,
|
|
1497
|
+
providerMetadata: e.providerMetadata()
|
|
1498
|
+
})
|
|
1499
|
+
}), i;
|
|
1500
|
+
}, Ie = (e) => {
|
|
1501
|
+
let t = e.headers ?? {}, n = Y(t), r = t["x-ably-role"] ?? "user", i = n.str("messageId") ?? "", a;
|
|
1502
|
+
switch (e.name) {
|
|
1503
|
+
case "text":
|
|
1504
|
+
a = {
|
|
1505
|
+
type: "text",
|
|
1506
|
+
text: typeof e.data == "string" ? e.data : ""
|
|
1507
|
+
};
|
|
1508
|
+
break;
|
|
1509
|
+
case "file":
|
|
1510
|
+
a = {
|
|
1511
|
+
type: "file",
|
|
1512
|
+
mediaType: n.strOr("mediaType", ""),
|
|
1513
|
+
url: typeof e.data == "string" ? e.data : ""
|
|
1514
|
+
};
|
|
1515
|
+
break;
|
|
1516
|
+
default:
|
|
1517
|
+
Z(e.name) && (a = N({
|
|
1518
|
+
type: e.name,
|
|
1519
|
+
id: n.str("id"),
|
|
1520
|
+
data: e.data
|
|
1521
|
+
}));
|
|
1522
|
+
break;
|
|
1523
|
+
}
|
|
1524
|
+
return a ? [{
|
|
1525
|
+
kind: "message",
|
|
1526
|
+
message: {
|
|
1527
|
+
id: i,
|
|
1528
|
+
role: r,
|
|
1529
|
+
parts: [a]
|
|
1530
|
+
}
|
|
1531
|
+
}] : [];
|
|
1532
|
+
}, Le = (e, t) => (e === "text" || e === "file" || Z(e)) && "x-ably-role" in t, Re = (e, t) => {
|
|
1533
|
+
let n = e.headers ?? {}, r = Y(n), i = n["x-ably-turn-id"] ?? "";
|
|
1534
|
+
if (Le(e.name, n)) return Ie(e);
|
|
1535
|
+
if (e.name === "tool-input") return Fe(r, e.data, i, t);
|
|
1536
|
+
switch (e.name) {
|
|
1537
|
+
case "start": return ye(r, i, t);
|
|
1538
|
+
case "start-step": return be(i, t);
|
|
1539
|
+
case "finish-step": return xe(i, t);
|
|
1540
|
+
case "finish": return Se(r, i, t);
|
|
1541
|
+
case "error": return Ce(e.data);
|
|
1542
|
+
case "abort": return we(e.data, i, t);
|
|
1543
|
+
case "message-metadata": return Te(r);
|
|
1544
|
+
case "file": return Ee(r, e.data);
|
|
1545
|
+
case "source-url": return De(r, e.data);
|
|
1546
|
+
case "source-document": return Oe(r);
|
|
1547
|
+
case "tool-input-error": return ke(r, e.data);
|
|
1548
|
+
case "tool-output-available": return Ae(r, e.data);
|
|
1549
|
+
case "tool-output-error": return je(r, e.data);
|
|
1550
|
+
case "tool-approval-request": return Me(r);
|
|
1551
|
+
case "tool-output-denied": return Ne(r);
|
|
1552
|
+
default: return Z(e.name) ? Pe(e.name, r, e.data) : [];
|
|
1553
|
+
}
|
|
1554
|
+
}, ze = (e) => ({
|
|
1555
|
+
buildStartEvents: (t) => {
|
|
1556
|
+
let n = Q(e, t.headers["x-ably-turn-id"] ?? "", { messageId: Y(t.headers).str("messageId") });
|
|
1557
|
+
return n.push({
|
|
1558
|
+
kind: "event",
|
|
1559
|
+
event: he(t)
|
|
1560
|
+
}), n;
|
|
1561
|
+
},
|
|
1562
|
+
buildDeltaEvents: (e, t) => X(ge(e, t)),
|
|
1563
|
+
buildEndEvents: (e, t) => X(_e(e, t)),
|
|
1564
|
+
decodeDiscrete: (t) => Re(t, e)
|
|
1565
|
+
}), Be = class {
|
|
1566
|
+
constructor(e = {}) {
|
|
1567
|
+
this._core = ue(ze(ve()), e);
|
|
1568
|
+
}
|
|
1569
|
+
decode(e) {
|
|
1570
|
+
return this._core.decode(e);
|
|
1571
|
+
}
|
|
1572
|
+
}, Ve = (e = {}) => new Be(e), $ = class {
|
|
1573
|
+
constructor(e, t = {}) {
|
|
1574
|
+
this._trackers = /* @__PURE__ */ new Map(), this._pending = [], this._closed = !1, this._writer = e, this._defaultClientId = t.clientId, this._defaultExtras = t.extras, this._onMessageHook = t.onMessage ?? (() => {}), this._logger = t.logger?.withContext({ component: "EncoderCore" });
|
|
1575
|
+
}
|
|
1576
|
+
async publishDiscrete(e, t) {
|
|
1577
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscrete();", { name: e.name });
|
|
1578
|
+
let n = this._buildDiscreteMessage(e, t);
|
|
1579
|
+
return this._writer.publish(n);
|
|
1580
|
+
}
|
|
1581
|
+
async publishDiscreteBatch(e, t) {
|
|
1582
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
|
|
1583
|
+
let n = e.map((e) => this._buildDiscreteMessage(e, t));
|
|
1584
|
+
return this._writer.publish(n);
|
|
1585
|
+
}
|
|
1586
|
+
async startStream(e, t, r) {
|
|
1587
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.startStream();", {
|
|
1588
|
+
name: t.name,
|
|
1589
|
+
streamId: e
|
|
1590
|
+
});
|
|
1591
|
+
let a = this._buildHeaders(t.headers ?? {}, r);
|
|
1592
|
+
a[s] = "true", a[c] = "streaming", a[l] = e;
|
|
1593
|
+
let o = this._resolveClientId(r), u = {
|
|
1594
|
+
name: t.name,
|
|
1595
|
+
data: t.data,
|
|
1596
|
+
extras: { headers: a },
|
|
1597
|
+
...o ? { clientId: o } : {}
|
|
1598
|
+
};
|
|
1599
|
+
this._invokeOnMessage(u);
|
|
1600
|
+
let d = (await this._writer.publish(u)).serials[0];
|
|
1601
|
+
if (!d) throw new n.ErrorInfo(`unable to start stream; no serial returned for stream '${t.name}' (streamId: ${e})`, i.BadRequest, 400);
|
|
1602
|
+
this._trackers.set(e, {
|
|
1603
|
+
serial: d,
|
|
1604
|
+
name: t.name,
|
|
1605
|
+
streamId: e,
|
|
1606
|
+
accumulated: t.data,
|
|
1607
|
+
persistentHeaders: a,
|
|
1608
|
+
aborted: !1
|
|
1609
|
+
}), this._logger?.debug("DefaultEncoderCore.startStream(); stream started", {
|
|
1610
|
+
name: t.name,
|
|
1611
|
+
streamId: e,
|
|
1612
|
+
serial: d
|
|
1613
|
+
});
|
|
1614
|
+
}
|
|
1615
|
+
appendStream(e, t) {
|
|
1616
|
+
this._assertNotClosed();
|
|
1617
|
+
let r = this._trackers.get(e);
|
|
1618
|
+
if (!r) throw new n.ErrorInfo(`unable to append to stream; no active stream for streamId '${e}'`, i.InvalidArgument, 400);
|
|
1619
|
+
r.accumulated += t;
|
|
1620
|
+
let a = {
|
|
1621
|
+
serial: r.serial,
|
|
1622
|
+
data: t,
|
|
1623
|
+
extras: { headers: { ...r.persistentHeaders } }
|
|
1624
|
+
};
|
|
1625
|
+
this._invokeOnMessage(a);
|
|
1626
|
+
let o = this._writer.appendMessage(a);
|
|
1627
|
+
this._pending.push({
|
|
1628
|
+
promise: o,
|
|
1629
|
+
streamId: e
|
|
1630
|
+
});
|
|
1631
|
+
}
|
|
1632
|
+
async closeStream(e, t) {
|
|
1633
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.closeStream();", { streamId: e });
|
|
1634
|
+
let r = this._trackers.get(e);
|
|
1635
|
+
if (!r) throw new n.ErrorInfo(`unable to close stream; no active stream for streamId '${e}'`, i.InvalidArgument, 400);
|
|
1636
|
+
r.accumulated += t.data;
|
|
1637
|
+
let a = this._buildClosingHeaders(r, t.headers ?? {});
|
|
1638
|
+
a[c] = "finished";
|
|
1639
|
+
let o = {
|
|
1640
|
+
serial: r.serial,
|
|
1641
|
+
data: t.data,
|
|
1642
|
+
extras: { headers: a }
|
|
1643
|
+
};
|
|
1644
|
+
this._invokeOnMessage(o);
|
|
1645
|
+
let s = this._writer.appendMessage(o);
|
|
1646
|
+
this._pending.push({
|
|
1647
|
+
promise: s,
|
|
1648
|
+
streamId: e
|
|
1649
|
+
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.closeStream(); stream closed", { streamId: e });
|
|
1650
|
+
}
|
|
1651
|
+
async abortStream(e, t) {
|
|
1652
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortStream();", { streamId: e });
|
|
1653
|
+
let r = this._trackers.get(e);
|
|
1654
|
+
if (!r) throw new n.ErrorInfo(`unable to abort stream; no active stream for streamId '${e}'`, i.InvalidArgument, 400);
|
|
1655
|
+
r.aborted = !0;
|
|
1656
|
+
let a = this._buildClosingHeaders(r, {}, t);
|
|
1657
|
+
a[c] = "aborted";
|
|
1658
|
+
let o = {
|
|
1659
|
+
serial: r.serial,
|
|
1660
|
+
data: "",
|
|
1661
|
+
extras: { headers: a }
|
|
1662
|
+
};
|
|
1663
|
+
this._invokeOnMessage(o);
|
|
1664
|
+
let s = this._writer.appendMessage(o);
|
|
1665
|
+
this._pending.push({
|
|
1666
|
+
promise: s,
|
|
1667
|
+
streamId: e
|
|
1668
|
+
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.abortStream(); stream aborted", { streamId: e });
|
|
1669
|
+
}
|
|
1670
|
+
async abortAllStreams(e) {
|
|
1671
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortAllStreams();", { streamCount: this._trackers.size });
|
|
1672
|
+
for (let t of this._trackers.values()) {
|
|
1673
|
+
t.aborted = !0;
|
|
1674
|
+
let n = this._buildClosingHeaders(t, {}, e);
|
|
1675
|
+
n[c] = "aborted";
|
|
1676
|
+
let r = {
|
|
1677
|
+
serial: t.serial,
|
|
1678
|
+
data: "",
|
|
1679
|
+
extras: { headers: n }
|
|
1680
|
+
};
|
|
1681
|
+
this._invokeOnMessage(r);
|
|
1682
|
+
let i = this._writer.appendMessage(r);
|
|
1683
|
+
this._pending.push({
|
|
1684
|
+
promise: i,
|
|
1685
|
+
streamId: t.streamId
|
|
1686
|
+
});
|
|
1687
|
+
}
|
|
1688
|
+
await this._flushPending();
|
|
1689
|
+
}
|
|
1690
|
+
async _flushPending() {
|
|
1691
|
+
if (this._flushPromise) return this._flushPromise;
|
|
1692
|
+
let e = this._pending;
|
|
1693
|
+
if (this._pending = [], e.length !== 0) {
|
|
1694
|
+
this._logger?.trace("DefaultEncoderCore._flushPending();", { count: e.length }), this._flushPromise = this._doFlush(e);
|
|
1695
|
+
try {
|
|
1696
|
+
await this._flushPromise;
|
|
1697
|
+
} finally {
|
|
1698
|
+
this._flushPromise = void 0;
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
async _doFlush(e) {
|
|
1703
|
+
let t = await Promise.allSettled(e.map(async (e) => e.promise)), r = /* @__PURE__ */ new Set();
|
|
1704
|
+
for (let [n, i] of t.entries()) {
|
|
1705
|
+
let t = e[n];
|
|
1706
|
+
t && i.status === "rejected" && r.add(t.streamId);
|
|
1707
|
+
}
|
|
1708
|
+
if (r.size === 0) {
|
|
1709
|
+
this._logger?.debug("DefaultEncoderCore._flushPending(); all appends succeeded");
|
|
1710
|
+
return;
|
|
1711
|
+
}
|
|
1712
|
+
this._logger?.warn("DefaultEncoderCore._flushPending(); recovering failed appends", { failedStreams: [...r] });
|
|
1713
|
+
let a = [];
|
|
1714
|
+
for (let e of r) {
|
|
1715
|
+
let t = this._trackers.get(e);
|
|
1716
|
+
if (!t) continue;
|
|
1717
|
+
let n = t.aborted ? "aborted" : "finished", r = {
|
|
1718
|
+
serial: t.serial,
|
|
1719
|
+
data: t.accumulated,
|
|
1720
|
+
extras: { headers: {
|
|
1721
|
+
...t.persistentHeaders,
|
|
1722
|
+
[c]: n
|
|
1723
|
+
} }
|
|
1724
|
+
};
|
|
1725
|
+
try {
|
|
1726
|
+
await this._writer.updateMessage(r);
|
|
1727
|
+
} catch (t) {
|
|
1728
|
+
a.push({
|
|
1729
|
+
streamId: e,
|
|
1730
|
+
error: t
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
if (a.length > 0) {
|
|
1735
|
+
let e = a.map((e) => e.streamId).join(", ");
|
|
1736
|
+
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: e }), new n.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${e}`, i.EncoderRecoveryFailed, 500);
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
async close() {
|
|
1740
|
+
if (!this._closed) {
|
|
1741
|
+
this._logger?.trace("DefaultEncoderCore.close();"), this._closed = !0;
|
|
1742
|
+
try {
|
|
1743
|
+
await this._flushPending();
|
|
1744
|
+
} finally {
|
|
1745
|
+
this._trackers.clear();
|
|
1746
|
+
}
|
|
1747
|
+
this._logger?.debug("DefaultEncoderCore.close(); encoder closed");
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
_invokeOnMessage(e) {
|
|
1751
|
+
try {
|
|
1752
|
+
this._onMessageHook(e);
|
|
1753
|
+
} catch (e) {
|
|
1754
|
+
this._logger?.error("DefaultEncoderCore._invokeOnMessage(); hook threw", { error: e });
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
_assertNotClosed() {
|
|
1758
|
+
if (this._closed) throw new n.ErrorInfo("unable to write to encoder; encoder has been closed", i.InvalidArgument, 400);
|
|
1759
|
+
}
|
|
1760
|
+
_resolveClientId(e) {
|
|
1761
|
+
return e?.clientId ?? this._defaultClientId;
|
|
1762
|
+
}
|
|
1763
|
+
_buildHeaders(e, t) {
|
|
1764
|
+
let n = {
|
|
1765
|
+
...j(this._defaultExtras?.headers, t?.extras?.headers),
|
|
1766
|
+
...e
|
|
1767
|
+
};
|
|
1768
|
+
return t?.messageId !== void 0 && (n[d] = t.messageId), n;
|
|
1769
|
+
}
|
|
1770
|
+
_buildDiscreteMessage(e, t) {
|
|
1771
|
+
let n = this._buildHeaders(e.headers ?? {}, t);
|
|
1772
|
+
n[s] = "false";
|
|
1773
|
+
let r = this._resolveClientId(t), i = {
|
|
1774
|
+
name: e.name,
|
|
1775
|
+
data: e.data,
|
|
1776
|
+
extras: {
|
|
1777
|
+
headers: n,
|
|
1778
|
+
...e.ephemeral ? { ephemeral: !0 } : {}
|
|
1779
|
+
},
|
|
1780
|
+
...r ? { clientId: r } : {}
|
|
1781
|
+
};
|
|
1782
|
+
return this._invokeOnMessage(i), i;
|
|
1783
|
+
}
|
|
1784
|
+
_buildClosingHeaders(e, t, n) {
|
|
1785
|
+
let r = { ...e.persistentHeaders }, i = j(this._defaultExtras?.headers, n?.extras?.headers);
|
|
1786
|
+
return Object.assign(r, i), Object.assign(r, t), r;
|
|
1787
|
+
}
|
|
1788
|
+
}, He = (e, t = {}) => new $(e, t), Ue = class {
|
|
1789
|
+
constructor(e, t = {}) {
|
|
1790
|
+
this._aborted = !1, this._core = He(e, t);
|
|
1791
|
+
}
|
|
1792
|
+
async appendEvent(e, t) {
|
|
1793
|
+
switch (e.type) {
|
|
1794
|
+
case "text-start": {
|
|
1795
|
+
let n = P().str("id", e.id).json("providerMetadata", e.providerMetadata).build();
|
|
1796
|
+
await this._core.startStream(e.id, {
|
|
1797
|
+
name: "text",
|
|
1798
|
+
data: "",
|
|
1799
|
+
headers: n
|
|
1800
|
+
}, t);
|
|
1801
|
+
break;
|
|
1802
|
+
}
|
|
1803
|
+
case "reasoning-start": {
|
|
1804
|
+
let n = P().str("id", e.id).json("providerMetadata", e.providerMetadata).build();
|
|
1805
|
+
await this._core.startStream(e.id, {
|
|
1806
|
+
name: "reasoning",
|
|
1807
|
+
data: "",
|
|
1808
|
+
headers: n
|
|
1809
|
+
}, t);
|
|
1810
|
+
break;
|
|
1811
|
+
}
|
|
1812
|
+
case "tool-input-start": {
|
|
1813
|
+
let n = P().str("toolCallId", e.toolCallId).str("toolName", e.toolName).bool("dynamic", e.dynamic).str("title", e.title).bool("providerExecuted", e.providerExecuted).json("providerMetadata", e.providerMetadata).build();
|
|
1814
|
+
await this._core.startStream(e.toolCallId, {
|
|
1815
|
+
name: "tool-input",
|
|
1816
|
+
data: "",
|
|
1817
|
+
headers: n
|
|
1818
|
+
}, t);
|
|
1819
|
+
break;
|
|
1820
|
+
}
|
|
1821
|
+
case "text-delta":
|
|
1822
|
+
this._core.appendStream(e.id, e.delta);
|
|
1823
|
+
break;
|
|
1824
|
+
case "reasoning-delta":
|
|
1825
|
+
this._core.appendStream(e.id, e.delta);
|
|
1826
|
+
break;
|
|
1827
|
+
case "tool-input-delta":
|
|
1828
|
+
this._core.appendStream(e.toolCallId, e.inputTextDelta);
|
|
1829
|
+
break;
|
|
1830
|
+
case "text-end": {
|
|
1831
|
+
let t = P().str("id", e.id).json("providerMetadata", e.providerMetadata).build();
|
|
1832
|
+
await this._core.closeStream(e.id, {
|
|
1833
|
+
name: "text",
|
|
1834
|
+
data: "",
|
|
1835
|
+
headers: t
|
|
1836
|
+
});
|
|
1837
|
+
break;
|
|
1838
|
+
}
|
|
1839
|
+
case "reasoning-end": {
|
|
1840
|
+
let t = P().str("id", e.id).json("providerMetadata", e.providerMetadata).build();
|
|
1841
|
+
await this._core.closeStream(e.id, {
|
|
1842
|
+
name: "reasoning",
|
|
1843
|
+
data: "",
|
|
1844
|
+
headers: t
|
|
1845
|
+
});
|
|
1846
|
+
break;
|
|
1847
|
+
}
|
|
1848
|
+
case "tool-input-available":
|
|
1849
|
+
try {
|
|
1850
|
+
let t = P().str("toolCallId", e.toolCallId).str("toolName", e.toolName).json("providerMetadata", e.providerMetadata).build();
|
|
1851
|
+
await this._core.closeStream(e.toolCallId, {
|
|
1852
|
+
name: "tool-input",
|
|
1853
|
+
data: "",
|
|
1854
|
+
headers: t
|
|
1855
|
+
});
|
|
1856
|
+
} catch (t) {
|
|
1857
|
+
if (!(t instanceof n.ErrorInfo && a(t, i.InvalidArgument))) throw t;
|
|
1858
|
+
let r = P().str("toolCallId", e.toolCallId).str("toolName", e.toolName).bool("dynamic", e.dynamic).str("title", e.title).bool("providerExecuted", e.providerExecuted).json("providerMetadata", e.providerMetadata).build();
|
|
1859
|
+
await this._core.publishDiscrete({
|
|
1860
|
+
name: "tool-input",
|
|
1861
|
+
data: e.input,
|
|
1862
|
+
headers: r
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
break;
|
|
1866
|
+
case "start": {
|
|
1867
|
+
let n = P().str("messageId", e.messageId).json("messageMetadata", e.messageMetadata).build();
|
|
1868
|
+
await this._core.publishDiscrete({
|
|
1869
|
+
name: "start",
|
|
1870
|
+
data: "",
|
|
1871
|
+
headers: n
|
|
1872
|
+
}, t);
|
|
1873
|
+
break;
|
|
1874
|
+
}
|
|
1875
|
+
case "start-step":
|
|
1876
|
+
await this._core.publishDiscrete({
|
|
1877
|
+
name: "start-step",
|
|
1878
|
+
data: ""
|
|
1879
|
+
}, t);
|
|
1880
|
+
break;
|
|
1881
|
+
case "finish-step":
|
|
1882
|
+
await this._core.publishDiscrete({
|
|
1883
|
+
name: "finish-step",
|
|
1884
|
+
data: ""
|
|
1885
|
+
}, t);
|
|
1886
|
+
break;
|
|
1887
|
+
case "finish": {
|
|
1888
|
+
let n = P().str("finishReason", e.finishReason).json("messageMetadata", e.messageMetadata).build();
|
|
1889
|
+
await this._core.publishDiscrete({
|
|
1890
|
+
name: "finish",
|
|
1891
|
+
data: "",
|
|
1892
|
+
headers: n
|
|
1893
|
+
}, t);
|
|
1894
|
+
break;
|
|
1895
|
+
}
|
|
1896
|
+
case "error":
|
|
1897
|
+
await this._core.publishDiscrete({
|
|
1898
|
+
name: "error",
|
|
1899
|
+
data: e.errorText
|
|
1900
|
+
}, t);
|
|
1901
|
+
break;
|
|
1902
|
+
case "abort":
|
|
1903
|
+
this._aborted = !0, await this._core.abortAllStreams(t), await this._core.publishDiscrete({
|
|
1904
|
+
name: "abort",
|
|
1905
|
+
data: e.reason ?? "",
|
|
1906
|
+
headers: { [c]: "aborted" }
|
|
1907
|
+
}, t);
|
|
1908
|
+
break;
|
|
1909
|
+
case "tool-input-error": {
|
|
1910
|
+
let t = P().str("toolCallId", e.toolCallId).str("toolName", e.toolName).bool("dynamic", e.dynamic).str("title", e.title).bool("providerExecuted", e.providerExecuted).json("providerMetadata", e.providerMetadata).build();
|
|
1911
|
+
await this._core.publishDiscrete({
|
|
1912
|
+
name: "tool-input-error",
|
|
1913
|
+
data: {
|
|
1914
|
+
errorText: e.errorText,
|
|
1915
|
+
input: e.input
|
|
1916
|
+
},
|
|
1917
|
+
headers: t
|
|
1918
|
+
});
|
|
1919
|
+
break;
|
|
1920
|
+
}
|
|
1921
|
+
case "tool-output-available": {
|
|
1922
|
+
let t = P().str("toolCallId", e.toolCallId).bool("dynamic", e.dynamic).bool("providerExecuted", e.providerExecuted).bool("preliminary", e.preliminary).build();
|
|
1923
|
+
await this._core.publishDiscrete({
|
|
1924
|
+
name: "tool-output-available",
|
|
1925
|
+
data: { output: e.output },
|
|
1926
|
+
headers: t
|
|
1927
|
+
});
|
|
1928
|
+
break;
|
|
1929
|
+
}
|
|
1930
|
+
case "tool-output-error": {
|
|
1931
|
+
let t = P().str("toolCallId", e.toolCallId).bool("dynamic", e.dynamic).bool("providerExecuted", e.providerExecuted).build();
|
|
1932
|
+
await this._core.publishDiscrete({
|
|
1933
|
+
name: "tool-output-error",
|
|
1934
|
+
data: { errorText: e.errorText },
|
|
1935
|
+
headers: t
|
|
1936
|
+
});
|
|
1937
|
+
break;
|
|
1938
|
+
}
|
|
1939
|
+
case "tool-approval-request": {
|
|
1940
|
+
let n = P().str("toolCallId", e.toolCallId).str("approvalId", e.approvalId).build();
|
|
1941
|
+
await this._core.publishDiscrete({
|
|
1942
|
+
name: "tool-approval-request",
|
|
1943
|
+
data: "",
|
|
1944
|
+
headers: n
|
|
1945
|
+
}, t);
|
|
1946
|
+
break;
|
|
1947
|
+
}
|
|
1948
|
+
case "tool-output-denied": {
|
|
1949
|
+
let n = P().str("toolCallId", e.toolCallId).build();
|
|
1950
|
+
await this._core.publishDiscrete({
|
|
1951
|
+
name: "tool-output-denied",
|
|
1952
|
+
data: "",
|
|
1953
|
+
headers: n
|
|
1954
|
+
}, t);
|
|
1955
|
+
break;
|
|
1956
|
+
}
|
|
1957
|
+
case "file": {
|
|
1958
|
+
let n = P().str("mediaType", e.mediaType).json("providerMetadata", e.providerMetadata).build();
|
|
1959
|
+
await this._core.publishDiscrete({
|
|
1960
|
+
name: "file",
|
|
1961
|
+
data: e.url,
|
|
1962
|
+
headers: n
|
|
1963
|
+
}, t);
|
|
1964
|
+
break;
|
|
1965
|
+
}
|
|
1966
|
+
case "source-url": {
|
|
1967
|
+
let n = P().str("sourceId", e.sourceId).str("title", e.title).json("providerMetadata", e.providerMetadata).build();
|
|
1968
|
+
await this._core.publishDiscrete({
|
|
1969
|
+
name: "source-url",
|
|
1970
|
+
data: e.url,
|
|
1971
|
+
headers: n
|
|
1972
|
+
}, t);
|
|
1973
|
+
break;
|
|
1974
|
+
}
|
|
1975
|
+
case "source-document": {
|
|
1976
|
+
let n = P().str("sourceId", e.sourceId).str("mediaType", e.mediaType).str("title", e.title).str("filename", e.filename).json("providerMetadata", e.providerMetadata).build();
|
|
1977
|
+
await this._core.publishDiscrete({
|
|
1978
|
+
name: "source-document",
|
|
1979
|
+
data: "",
|
|
1980
|
+
headers: n
|
|
1981
|
+
}, t);
|
|
1982
|
+
break;
|
|
1983
|
+
}
|
|
1984
|
+
case "message-metadata": {
|
|
1985
|
+
let n = P().json("messageMetadata", e.messageMetadata).build();
|
|
1986
|
+
await this._core.publishDiscrete({
|
|
1987
|
+
name: "message-metadata",
|
|
1988
|
+
data: "",
|
|
1989
|
+
headers: n
|
|
1990
|
+
}, t);
|
|
1991
|
+
break;
|
|
1992
|
+
}
|
|
1993
|
+
default:
|
|
1994
|
+
if (e.type.startsWith("data-")) {
|
|
1995
|
+
let n = P().str("id", e.id).bool("transient", e.transient).build(), r = e.transient === !0;
|
|
1996
|
+
await this._core.publishDiscrete({
|
|
1997
|
+
name: e.type,
|
|
1998
|
+
data: e.data,
|
|
1999
|
+
headers: n,
|
|
2000
|
+
ephemeral: r
|
|
2001
|
+
}, t);
|
|
2002
|
+
}
|
|
2003
|
+
break;
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
async writeEvent(e, t) {
|
|
2007
|
+
if (!e.type.startsWith("data-")) throw new n.ErrorInfo(`unable to write event; only data-* chunk types are supported, got '${e.type}'`, i.InvalidArgument, 400);
|
|
2008
|
+
let r = P().str("id", "id" in e ? e.id : void 0).bool("transient", "transient" in e ? e.transient : void 0).build(), a = "transient" in e && e.transient === !0;
|
|
2009
|
+
return this._core.publishDiscrete({
|
|
2010
|
+
name: e.type,
|
|
2011
|
+
data: "data" in e ? e.data : void 0,
|
|
2012
|
+
headers: r,
|
|
2013
|
+
ephemeral: a
|
|
2014
|
+
}, t);
|
|
2015
|
+
}
|
|
2016
|
+
async writeMessages(e, t) {
|
|
2017
|
+
let n = e.flatMap((e) => We(e));
|
|
2018
|
+
return this._core.publishDiscreteBatch(n, t);
|
|
2019
|
+
}
|
|
2020
|
+
async abort(e) {
|
|
2021
|
+
this._aborted || (this._aborted = !0, await this._core.abortAllStreams(), await this._core.publishDiscrete({
|
|
2022
|
+
name: "abort",
|
|
2023
|
+
data: e ?? "",
|
|
2024
|
+
headers: { [c]: "aborted" }
|
|
2025
|
+
}));
|
|
2026
|
+
}
|
|
2027
|
+
async close() {
|
|
2028
|
+
await this._core.close();
|
|
2029
|
+
}
|
|
2030
|
+
}, We = (e) => {
|
|
2031
|
+
let t = e.id, n = [];
|
|
2032
|
+
for (let i of e.parts) switch (i.type) {
|
|
2033
|
+
case "text":
|
|
2034
|
+
n.push({
|
|
2035
|
+
name: "text",
|
|
2036
|
+
data: i.text,
|
|
2037
|
+
headers: P().str("messageId", t).build()
|
|
2038
|
+
});
|
|
2039
|
+
break;
|
|
2040
|
+
case "file":
|
|
2041
|
+
n.push({
|
|
2042
|
+
name: "file",
|
|
2043
|
+
data: i.url,
|
|
2044
|
+
headers: P().str("messageId", t).str("mediaType", i.mediaType).build()
|
|
2045
|
+
});
|
|
2046
|
+
break;
|
|
2047
|
+
default:
|
|
2048
|
+
r(i) && n.push({
|
|
2049
|
+
name: i.type,
|
|
2050
|
+
data: i.data,
|
|
2051
|
+
headers: P().str("messageId", t).str("id", i.id).build()
|
|
2052
|
+
});
|
|
2053
|
+
break;
|
|
2054
|
+
}
|
|
2055
|
+
return n.length === 0 && n.push({
|
|
2056
|
+
name: "text",
|
|
2057
|
+
data: "",
|
|
2058
|
+
headers: P().str("messageId", t).build()
|
|
2059
|
+
}), n;
|
|
2060
|
+
}, Ge = {
|
|
2061
|
+
createEncoder: (e, t = {}) => new Ue(e, t),
|
|
2062
|
+
createDecoder: Ve,
|
|
2063
|
+
createAccumulator: se,
|
|
2064
|
+
getMessageKey: (e) => e.id,
|
|
2065
|
+
isTerminal: (e) => e.type === "finish" || e.type === "error" || e.type === "abort"
|
|
2066
|
+
}, Ke = (e) => K({
|
|
2067
|
+
...e,
|
|
2068
|
+
codec: Ge
|
|
2069
|
+
}), qe = (e) => "send" in e && typeof e.send == "function", Je = (e, n) => {
|
|
2070
|
+
let r = t(null);
|
|
2071
|
+
return r.current === null && (qe(e) ? r.current = o(e, n) : r.current = o(Ke(e), n)), r.current;
|
|
2072
|
+
}, Ye = (t, n) => {
|
|
2073
|
+
e(() => {
|
|
2074
|
+
if (t) return t.on("message", () => {
|
|
2075
|
+
n(() => t.getMessages());
|
|
2076
|
+
});
|
|
2077
|
+
}, [t, n]);
|
|
2078
|
+
};
|
|
2079
|
+
//#endregion
|
|
2080
|
+
export { Je as useChatTransport, Ye as useMessageSync };
|
|
2081
|
+
|
|
2082
|
+
//# sourceMappingURL=ably-ai-transport-vercel-react.js.map
|