@ably/ai-transport 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -47
- package/dist/ably-ai-transport.js +1006 -539
- package/dist/ably-ai-transport.js.map +1 -1
- package/dist/ably-ai-transport.umd.cjs +1 -1
- package/dist/ably-ai-transport.umd.cjs.map +1 -1
- package/dist/constants.d.ts +4 -0
- package/dist/core/codec/types.d.ts +19 -2
- package/dist/core/transport/decode-history.d.ts +8 -6
- package/dist/core/transport/headers.d.ts +4 -2
- package/dist/core/transport/index.d.ts +4 -1
- package/dist/core/transport/pipe-stream.d.ts +3 -2
- package/dist/core/transport/stream-router.d.ts +11 -1
- package/dist/core/transport/tree.d.ts +171 -0
- package/dist/core/transport/turn-manager.d.ts +4 -1
- package/dist/core/transport/types.d.ts +270 -119
- package/dist/core/transport/view.d.ts +166 -0
- package/dist/errors.d.ts +19 -2
- package/dist/index.d.ts +3 -1
- package/dist/react/ably-ai-transport-react.js +1019 -486
- package/dist/react/ably-ai-transport-react.js.map +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
- package/dist/react/contexts/transport-context.d.ts +31 -0
- package/dist/react/contexts/transport-provider.d.ts +49 -0
- package/dist/react/create-transport-hooks.d.ts +124 -0
- package/dist/react/index.d.ts +14 -8
- package/dist/react/use-ably-messages.d.ts +14 -8
- package/dist/react/use-active-turns.d.ts +7 -3
- package/dist/react/use-client-transport.d.ts +78 -5
- package/dist/react/use-create-view.d.ts +22 -0
- package/dist/react/use-tree.d.ts +20 -0
- package/dist/react/use-view.d.ts +79 -0
- package/dist/vercel/ably-ai-transport-vercel.js +1478 -842
- package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
- package/dist/vercel/codec/tool-transitions.d.ts +50 -0
- package/dist/vercel/index.d.ts +3 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +9099 -852
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +45 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
- package/dist/vercel/react/contexts/chat-transport-context.d.ts +32 -0
- package/dist/vercel/react/contexts/chat-transport-provider.d.ts +84 -0
- package/dist/vercel/react/index.d.ts +5 -0
- package/dist/vercel/react/use-chat-transport.d.ts +61 -20
- package/dist/vercel/react/use-message-sync.d.ts +41 -9
- package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +30 -0
- package/dist/vercel/tool-approvals.d.ts +124 -0
- package/dist/vercel/tool-events.d.ts +26 -0
- package/dist/vercel/transport/chat-transport.d.ts +33 -11
- package/dist/vercel/transport/index.d.ts +5 -2
- package/package.json +23 -17
- package/src/constants.ts +6 -0
- package/src/core/codec/encoder.ts +10 -1
- package/src/core/codec/types.ts +19 -3
- package/src/core/transport/client-transport.ts +382 -364
- package/src/core/transport/decode-history.ts +229 -81
- package/src/core/transport/headers.ts +6 -2
- package/src/core/transport/index.ts +13 -5
- package/src/core/transport/pipe-stream.ts +8 -5
- package/src/core/transport/server-transport.ts +212 -58
- package/src/core/transport/stream-router.ts +21 -3
- package/src/core/transport/{conversation-tree.ts → tree.ts} +192 -77
- package/src/core/transport/turn-manager.ts +28 -10
- package/src/core/transport/types.ts +318 -139
- package/src/core/transport/view.ts +840 -0
- package/src/errors.ts +21 -1
- package/src/index.ts +10 -5
- package/src/react/contexts/transport-context.ts +37 -0
- package/src/react/contexts/transport-provider.tsx +164 -0
- package/src/react/create-transport-hooks.ts +144 -0
- package/src/react/index.ts +15 -8
- package/src/react/use-ably-messages.ts +34 -16
- package/src/react/use-active-turns.ts +28 -17
- package/src/react/use-client-transport.ts +184 -24
- package/src/react/use-create-view.ts +68 -0
- package/src/react/use-tree.ts +53 -0
- package/src/react/use-view.ts +233 -0
- package/src/react/vite.config.ts +4 -1
- package/src/vercel/codec/accumulator.ts +64 -79
- package/src/vercel/codec/decoder.ts +11 -8
- package/src/vercel/codec/encoder.ts +68 -54
- package/src/vercel/codec/index.ts +0 -2
- package/src/vercel/codec/tool-transitions.ts +122 -0
- package/src/vercel/index.ts +17 -0
- package/src/vercel/react/contexts/chat-transport-context.ts +40 -0
- package/src/vercel/react/contexts/chat-transport-provider.tsx +122 -0
- package/src/vercel/react/index.ts +14 -0
- package/src/vercel/react/use-chat-transport.ts +164 -42
- package/src/vercel/react/use-message-sync.ts +77 -19
- package/src/vercel/react/use-staged-add-tool-approval-response.ts +87 -0
- package/src/vercel/react/vite.config.ts +4 -2
- package/src/vercel/tool-approvals.ts +380 -0
- package/src/vercel/tool-events.ts +53 -0
- package/src/vercel/transport/chat-transport.ts +225 -79
- package/src/vercel/transport/index.ts +14 -3
- package/dist/core/transport/conversation-tree.d.ts +0 -9
- package/dist/react/use-conversation-tree.d.ts +0 -20
- package/dist/react/use-edit.d.ts +0 -7
- package/dist/react/use-history.d.ts +0 -19
- package/dist/react/use-messages.d.ts +0 -7
- package/dist/react/use-regenerate.d.ts +0 -7
- package/dist/react/use-send.d.ts +0 -7
- package/src/react/use-conversation-tree.ts +0 -71
- package/src/react/use-edit.ts +0 -24
- package/src/react/use-history.ts +0 -111
- package/src/react/use-messages.ts +0 -32
- package/src/react/use-regenerate.ts +0 -24
- package/src/react/use-send.ts +0 -25
|
@@ -1,46 +1,78 @@
|
|
|
1
1
|
import * as e from "ably";
|
|
2
|
-
import {
|
|
2
|
+
import { convertToModelMessages as t, isDataUIPart as n } from "ai";
|
|
3
3
|
//#region src/constants.ts
|
|
4
|
-
var
|
|
4
|
+
var r = "x-ably-stream", i = "x-ably-status", a = "x-ably-stream-id", o = "x-ably-discrete", s = "x-ably-turn-id", c = "x-ably-msg-id", l = "x-ably-turn-client-id", u = "x-ably-role", d = "x-ably-amend", f = "x-ably-cancel-turn-id", p = "x-ably-cancel-own", m = "x-ably-cancel-all", h = "x-ably-cancel-client-id", g = "x-ably-parent", _ = "x-ably-fork-of", v = "x-ably-turn-reason", y = "x-ably-cancel", b = "x-ably-turn-start", x = "x-ably-turn-end", S = "x-domain-", C = (e) => {
|
|
5
5
|
let t = e.extras;
|
|
6
6
|
if (!t || typeof t != "object") return {};
|
|
7
7
|
let n = t.headers;
|
|
8
8
|
return !n || typeof n != "object" ? {} : n;
|
|
9
|
-
},
|
|
9
|
+
}, w = (e) => {
|
|
10
10
|
if (e !== void 0) try {
|
|
11
11
|
return JSON.parse(e);
|
|
12
12
|
} catch {
|
|
13
13
|
return;
|
|
14
14
|
}
|
|
15
|
-
},
|
|
15
|
+
}, T = (e, t) => ({
|
|
16
16
|
...e,
|
|
17
17
|
...t
|
|
18
|
-
}),
|
|
18
|
+
}), ee = (e) => {
|
|
19
19
|
if (e !== void 0) return e === "true";
|
|
20
|
-
},
|
|
20
|
+
}, E = (e, t) => e[S + t], D = (e) => {
|
|
21
21
|
let t = {};
|
|
22
22
|
for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
|
|
23
23
|
return t;
|
|
24
|
-
},
|
|
25
|
-
str: (t) =>
|
|
26
|
-
strOr: (t, n) =>
|
|
27
|
-
bool: (t) =>
|
|
28
|
-
json: (t) =>
|
|
29
|
-
}),
|
|
24
|
+
}, te = (e) => ({
|
|
25
|
+
str: (t) => E(e, t),
|
|
26
|
+
strOr: (t, n) => E(e, t) ?? n,
|
|
27
|
+
bool: (t) => ee(E(e, t)),
|
|
28
|
+
json: (t) => w(E(e, t))
|
|
29
|
+
}), O = () => {
|
|
30
30
|
let e = {}, t = {
|
|
31
|
-
str: (n, r) => (r !== void 0 && (e[
|
|
32
|
-
bool: (n, r) => (r !== void 0 && (e[
|
|
33
|
-
json: (n, r) => (r != null && (e[
|
|
31
|
+
str: (n, r) => (r !== void 0 && (e[S + n] = r), t),
|
|
32
|
+
bool: (n, r) => (r !== void 0 && (e[S + n] = String(r)), t),
|
|
33
|
+
json: (n, r) => (r != null && (e[S + n] = JSON.stringify(r)), t),
|
|
34
34
|
build: () => e
|
|
35
35
|
};
|
|
36
36
|
return t;
|
|
37
|
-
},
|
|
37
|
+
}, k = (e) => D({
|
|
38
38
|
type: "dynamic-tool",
|
|
39
39
|
toolCallId: e.toolCallId,
|
|
40
40
|
toolName: e.toolName,
|
|
41
41
|
title: e.title,
|
|
42
42
|
providerExecuted: e.providerExecuted
|
|
43
|
-
}),
|
|
43
|
+
}), ne = (e, t) => {
|
|
44
|
+
let n = k(e);
|
|
45
|
+
switch (t.type) {
|
|
46
|
+
case "tool-output-available": return D({
|
|
47
|
+
...n,
|
|
48
|
+
state: "output-available",
|
|
49
|
+
input: e.input,
|
|
50
|
+
output: t.output,
|
|
51
|
+
preliminary: t.preliminary
|
|
52
|
+
});
|
|
53
|
+
case "tool-output-error": return {
|
|
54
|
+
...n,
|
|
55
|
+
state: "output-error",
|
|
56
|
+
input: e.input,
|
|
57
|
+
errorText: t.errorText
|
|
58
|
+
};
|
|
59
|
+
case "tool-output-denied": return {
|
|
60
|
+
...n,
|
|
61
|
+
state: "output-denied",
|
|
62
|
+
input: e.input,
|
|
63
|
+
approval: {
|
|
64
|
+
id: "",
|
|
65
|
+
approved: !1
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
case "tool-approval-request": return {
|
|
69
|
+
...n,
|
|
70
|
+
state: "approval-requested",
|
|
71
|
+
input: e.input,
|
|
72
|
+
approval: { id: t.approvalId }
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
}, A = class {
|
|
44
76
|
constructor(e) {
|
|
45
77
|
this._activeIndex = /* @__PURE__ */ new Map(), this._partType = e;
|
|
46
78
|
}
|
|
@@ -62,7 +94,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
62
94
|
reset() {
|
|
63
95
|
this._activeIndex = /* @__PURE__ */ new Map();
|
|
64
96
|
}
|
|
65
|
-
},
|
|
97
|
+
}, re = class {
|
|
66
98
|
constructor() {
|
|
67
99
|
this._messageList = [], this._activeMessages = /* @__PURE__ */ new Map();
|
|
68
100
|
}
|
|
@@ -85,6 +117,42 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
85
117
|
let t = this._messageList.findIndex((t) => t.id === e.id);
|
|
86
118
|
t !== -1 && (this._messageList[t] = e);
|
|
87
119
|
}
|
|
120
|
+
initMessage(e, t) {
|
|
121
|
+
let n = this._activeMessages.get(e);
|
|
122
|
+
if (n) {
|
|
123
|
+
let e = structuredClone(t), r = this._messageList.indexOf(n.message);
|
|
124
|
+
n.message = e, r !== -1 && (this._messageList[r] = e), n.toolTrackers = {};
|
|
125
|
+
for (let t = 0; t < e.parts.length; t++) {
|
|
126
|
+
let r = e.parts[t];
|
|
127
|
+
r?.type === "dynamic-tool" && (n.toolTrackers[r.toolCallId] = {
|
|
128
|
+
partIndex: t,
|
|
129
|
+
inputText: ""
|
|
130
|
+
}, n.streamStatus.set(r.toolCallId, "finished"));
|
|
131
|
+
}
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
let r = structuredClone(t), i = {}, a = /* @__PURE__ */ new Map();
|
|
135
|
+
for (let e = 0; e < r.parts.length; e++) {
|
|
136
|
+
let t = r.parts[e];
|
|
137
|
+
t?.type === "dynamic-tool" && (i[t.toolCallId] = {
|
|
138
|
+
partIndex: e,
|
|
139
|
+
inputText: ""
|
|
140
|
+
}, a.set(t.toolCallId, "finished"));
|
|
141
|
+
}
|
|
142
|
+
let o = {
|
|
143
|
+
message: r,
|
|
144
|
+
textStreams: new A("text"),
|
|
145
|
+
reasoningStreams: new A("reasoning"),
|
|
146
|
+
toolTrackers: i,
|
|
147
|
+
streamStatus: a
|
|
148
|
+
};
|
|
149
|
+
this._activeMessages.set(e, o);
|
|
150
|
+
let s = this._messageList.findIndex((e) => e.id === t.id);
|
|
151
|
+
s === -1 ? this._messageList.push(o.message) : this._messageList[s] = o.message;
|
|
152
|
+
}
|
|
153
|
+
completeMessage(e) {
|
|
154
|
+
this._activeMessages.delete(e);
|
|
155
|
+
}
|
|
88
156
|
_ensureActiveMessage(e) {
|
|
89
157
|
let t = this._activeMessages.get(e);
|
|
90
158
|
if (t) return t;
|
|
@@ -94,8 +162,8 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
94
162
|
role: "assistant",
|
|
95
163
|
parts: []
|
|
96
164
|
},
|
|
97
|
-
textStreams: new
|
|
98
|
-
reasoningStreams: new
|
|
165
|
+
textStreams: new A("text"),
|
|
166
|
+
reasoningStreams: new A("reasoning"),
|
|
99
167
|
toolTrackers: {},
|
|
100
168
|
streamStatus: /* @__PURE__ */ new Map()
|
|
101
169
|
};
|
|
@@ -149,7 +217,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
149
217
|
default:
|
|
150
218
|
if (e.type.startsWith("data-")) {
|
|
151
219
|
if (e.transient) break;
|
|
152
|
-
let n = this._ensureActiveMessage(t), r =
|
|
220
|
+
let n = this._ensureActiveMessage(t), r = D({
|
|
153
221
|
type: e.type,
|
|
154
222
|
id: e.id,
|
|
155
223
|
data: e.data
|
|
@@ -228,7 +296,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
228
296
|
case "tool-input-start": {
|
|
229
297
|
let n = this._ensureActiveMessage(t), r = n.message.parts.length;
|
|
230
298
|
n.message.parts.push({
|
|
231
|
-
...
|
|
299
|
+
...k(e),
|
|
232
300
|
state: "input-streaming",
|
|
233
301
|
input: void 0
|
|
234
302
|
}), n.toolTrackers[e.toolCallId] = {
|
|
@@ -250,7 +318,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
250
318
|
let a = this._getToolPart(e.toolCallId, n);
|
|
251
319
|
if (!a) break;
|
|
252
320
|
n.message.parts[a.tracker.partIndex] = {
|
|
253
|
-
...
|
|
321
|
+
...k(a.part),
|
|
254
322
|
state: "input-streaming",
|
|
255
323
|
input: i
|
|
256
324
|
};
|
|
@@ -260,7 +328,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
260
328
|
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
261
329
|
if (!r) break;
|
|
262
330
|
n.message.parts[r.tracker.partIndex] = {
|
|
263
|
-
...
|
|
331
|
+
...k(r.part),
|
|
264
332
|
state: "input-available",
|
|
265
333
|
input: e.input
|
|
266
334
|
}, n.streamStatus.set(e.toolCallId, "finished");
|
|
@@ -269,7 +337,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
269
337
|
case "tool-input-error": {
|
|
270
338
|
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
271
339
|
if (r) n.message.parts[r.tracker.partIndex] = {
|
|
272
|
-
...
|
|
340
|
+
...k(r.part),
|
|
273
341
|
state: "output-error",
|
|
274
342
|
input: e.input,
|
|
275
343
|
errorText: e.errorText
|
|
@@ -277,7 +345,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
277
345
|
else {
|
|
278
346
|
let t = n.message.parts.length;
|
|
279
347
|
n.message.parts.push({
|
|
280
|
-
...
|
|
348
|
+
...k(e),
|
|
281
349
|
state: "output-error",
|
|
282
350
|
input: e.input,
|
|
283
351
|
errorText: e.errorText
|
|
@@ -293,44 +361,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
293
361
|
}
|
|
294
362
|
_processToolOutput(e, t) {
|
|
295
363
|
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
296
|
-
|
|
297
|
-
case "tool-output-available":
|
|
298
|
-
n.message.parts[r.tracker.partIndex] = C({
|
|
299
|
-
...T(r.part),
|
|
300
|
-
state: "output-available",
|
|
301
|
-
input: r.part.input,
|
|
302
|
-
output: e.output,
|
|
303
|
-
preliminary: e.preliminary
|
|
304
|
-
});
|
|
305
|
-
break;
|
|
306
|
-
case "tool-output-error":
|
|
307
|
-
n.message.parts[r.tracker.partIndex] = {
|
|
308
|
-
...T(r.part),
|
|
309
|
-
state: "output-error",
|
|
310
|
-
input: r.part.input,
|
|
311
|
-
errorText: e.errorText
|
|
312
|
-
};
|
|
313
|
-
break;
|
|
314
|
-
case "tool-output-denied":
|
|
315
|
-
n.message.parts[r.tracker.partIndex] = {
|
|
316
|
-
...T(r.part),
|
|
317
|
-
state: "output-denied",
|
|
318
|
-
input: r.part.input,
|
|
319
|
-
approval: {
|
|
320
|
-
id: "",
|
|
321
|
-
approved: !1
|
|
322
|
-
}
|
|
323
|
-
};
|
|
324
|
-
break;
|
|
325
|
-
case "tool-approval-request":
|
|
326
|
-
n.message.parts[r.tracker.partIndex] = {
|
|
327
|
-
...T(r.part),
|
|
328
|
-
state: "approval-requested",
|
|
329
|
-
input: r.part.input,
|
|
330
|
-
approval: { id: e.approvalId }
|
|
331
|
-
};
|
|
332
|
-
break;
|
|
333
|
-
}
|
|
364
|
+
r && (n.message.parts[r.tracker.partIndex] = ne(r.part, e));
|
|
334
365
|
}
|
|
335
366
|
_processContentPart(e, t) {
|
|
336
367
|
let n = this._ensureActiveMessage(t);
|
|
@@ -343,7 +374,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
343
374
|
});
|
|
344
375
|
break;
|
|
345
376
|
case "source-url":
|
|
346
|
-
n.message.parts.push(
|
|
377
|
+
n.message.parts.push(D({
|
|
347
378
|
type: "source-url",
|
|
348
379
|
sourceId: e.sourceId,
|
|
349
380
|
url: e.url,
|
|
@@ -351,7 +382,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
351
382
|
}));
|
|
352
383
|
break;
|
|
353
384
|
case "source-document":
|
|
354
|
-
n.message.parts.push(
|
|
385
|
+
n.message.parts.push(D({
|
|
355
386
|
type: "source-document",
|
|
356
387
|
sourceId: e.sourceId,
|
|
357
388
|
mediaType: e.mediaType,
|
|
@@ -361,7 +392,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
361
392
|
break;
|
|
362
393
|
}
|
|
363
394
|
}
|
|
364
|
-
},
|
|
395
|
+
}, j = () => new re(), ie = (e) => [{
|
|
365
396
|
kind: "event",
|
|
366
397
|
event: e
|
|
367
398
|
}], ae = class {
|
|
@@ -393,7 +424,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
393
424
|
break;
|
|
394
425
|
default: return [];
|
|
395
426
|
}
|
|
396
|
-
let r =
|
|
427
|
+
let r = C(e)[c];
|
|
397
428
|
if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
|
|
398
429
|
return n;
|
|
399
430
|
}
|
|
@@ -401,7 +432,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
401
432
|
return {
|
|
402
433
|
name: e.name ?? "",
|
|
403
434
|
data: e.data,
|
|
404
|
-
headers:
|
|
435
|
+
headers: C(e)
|
|
405
436
|
};
|
|
406
437
|
}
|
|
407
438
|
_stringData(e) {
|
|
@@ -441,14 +472,14 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
441
472
|
if (!t) return [];
|
|
442
473
|
let n = this._serialState.get(t);
|
|
443
474
|
if (!n) return this._decodeUpdate(e);
|
|
444
|
-
let
|
|
445
|
-
return a.length > 0 && (n.accumulated += a, s.push(...this._hooks.buildDeltaEvents(n, a))), o === "finished" && !n.closed ? (n.closed = !0, s.push(...this._hooks.buildEndEvents(n,
|
|
475
|
+
let r = C(e), a = typeof e.data == "string" ? e.data : "", o = r[i], s = [];
|
|
476
|
+
return a.length > 0 && (n.accumulated += a, s.push(...this._hooks.buildDeltaEvents(n, a))), o === "finished" && !n.closed ? (n.closed = !0, s.push(...this._hooks.buildEndEvents(n, r)), this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream finished", { streamId: n.streamId })) : o === "aborted" && !n.closed && (n.closed = !0, this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream aborted", { streamId: n.streamId })), s;
|
|
446
477
|
}
|
|
447
478
|
_decodeUpdate(e) {
|
|
448
479
|
let t = e.serial;
|
|
449
480
|
if (!t) return [];
|
|
450
|
-
let
|
|
451
|
-
if (!c) return this._decodeFirstContact(
|
|
481
|
+
let n = this._toPayload(e), a = n.headers ?? {}, o = a[r] === "true", s = a[i], c = this._serialState.get(t);
|
|
482
|
+
if (!c) return this._decodeFirstContact(n, o, s, t);
|
|
452
483
|
let l = this._stringData(e);
|
|
453
484
|
if (l.startsWith(c.accumulated)) {
|
|
454
485
|
let e = l.slice(c.accumulated.length), t = [];
|
|
@@ -503,32 +534,32 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
503
534
|
let t = this._emitted.get(e);
|
|
504
535
|
return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
|
|
505
536
|
}
|
|
506
|
-
}, ce = (e) => new se(e),
|
|
507
|
-
let t =
|
|
537
|
+
}, ce = (e) => new se(e), M = (e) => {
|
|
538
|
+
let t = te(e);
|
|
508
539
|
return {
|
|
509
540
|
...t,
|
|
510
541
|
providerMetadata: () => t.json("providerMetadata")
|
|
511
542
|
};
|
|
512
|
-
},
|
|
543
|
+
}, N = (e) => ie(e), le = (e, t) => e === "stop" || e === "length" || e === "content-filter" || e === "tool-calls" || e === "error" || e === "other" ? e : t, P = (e) => e.startsWith("data-"), ue = (e) => {
|
|
513
544
|
if (e) try {
|
|
514
545
|
return JSON.parse(e);
|
|
515
546
|
} catch {
|
|
516
547
|
return e;
|
|
517
548
|
}
|
|
518
|
-
},
|
|
519
|
-
let t =
|
|
549
|
+
}, de = (e) => {
|
|
550
|
+
let t = M(e.headers);
|
|
520
551
|
switch (e.name) {
|
|
521
|
-
case "text": return
|
|
552
|
+
case "text": return D({
|
|
522
553
|
type: "text-start",
|
|
523
554
|
id: e.streamId,
|
|
524
555
|
providerMetadata: t.providerMetadata()
|
|
525
556
|
});
|
|
526
|
-
case "reasoning": return
|
|
557
|
+
case "reasoning": return D({
|
|
527
558
|
type: "reasoning-start",
|
|
528
559
|
id: e.streamId,
|
|
529
560
|
providerMetadata: t.providerMetadata()
|
|
530
561
|
});
|
|
531
|
-
case "tool-input": return
|
|
562
|
+
case "tool-input": return D({
|
|
532
563
|
type: "tool-input-start",
|
|
533
564
|
toolCallId: e.streamId,
|
|
534
565
|
toolName: t.strOr("toolName", ""),
|
|
@@ -542,7 +573,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
542
573
|
id: e.streamId
|
|
543
574
|
};
|
|
544
575
|
}
|
|
545
|
-
},
|
|
576
|
+
}, fe = (e, t) => {
|
|
546
577
|
switch (e.name) {
|
|
547
578
|
case "text": return {
|
|
548
579
|
type: "text-delta",
|
|
@@ -565,23 +596,23 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
565
596
|
delta: t
|
|
566
597
|
};
|
|
567
598
|
}
|
|
568
|
-
},
|
|
569
|
-
let n =
|
|
599
|
+
}, pe = (e, t) => {
|
|
600
|
+
let n = M(t);
|
|
570
601
|
switch (e.name) {
|
|
571
|
-
case "text": return
|
|
602
|
+
case "text": return D({
|
|
572
603
|
type: "text-end",
|
|
573
604
|
id: e.streamId,
|
|
574
605
|
providerMetadata: n.providerMetadata()
|
|
575
606
|
});
|
|
576
|
-
case "reasoning": return
|
|
607
|
+
case "reasoning": return D({
|
|
577
608
|
type: "reasoning-end",
|
|
578
609
|
id: e.streamId,
|
|
579
610
|
providerMetadata: n.providerMetadata()
|
|
580
611
|
});
|
|
581
|
-
case "tool-input": return
|
|
612
|
+
case "tool-input": return D({
|
|
582
613
|
type: "tool-input-available",
|
|
583
614
|
toolCallId: e.streamId,
|
|
584
|
-
toolName: n.strOr("toolName",
|
|
615
|
+
toolName: n.strOr("toolName", M(e.headers).strOr("toolName", "")),
|
|
585
616
|
input: ue(e.accumulated),
|
|
586
617
|
providerMetadata: n.providerMetadata()
|
|
587
618
|
});
|
|
@@ -590,9 +621,9 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
590
621
|
id: e.streamId
|
|
591
622
|
};
|
|
592
623
|
}
|
|
593
|
-
},
|
|
624
|
+
}, me = () => ce([{
|
|
594
625
|
key: "start",
|
|
595
|
-
build: (e) => [
|
|
626
|
+
build: (e) => [D({
|
|
596
627
|
type: "start",
|
|
597
628
|
messageId: e.messageId
|
|
598
629
|
})]
|
|
@@ -602,44 +633,44 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
602
633
|
}]), F = (e, t, n) => e.ensurePhases(t, n).map((e) => ({
|
|
603
634
|
kind: "event",
|
|
604
635
|
event: e
|
|
605
|
-
})),
|
|
636
|
+
})), he = (e, t, n) => (n.markEmitted(t, "start"), N(D({
|
|
606
637
|
type: "start",
|
|
607
638
|
messageId: e.str("messageId"),
|
|
608
639
|
messageMetadata: e.json("messageMetadata")
|
|
609
|
-
}))),
|
|
640
|
+
}))), ge = (e, t) => (t.markEmitted(e, "start-step"), N({ type: "start-step" })), _e = (e, t) => (t.resetPhase(e, "start-step"), N({ type: "finish-step" })), I = (e, t, n) => (n.clearScope(t), N(D({
|
|
610
641
|
type: "finish",
|
|
611
642
|
finishReason: le(e.str("finishReason"), "stop"),
|
|
612
643
|
messageMetadata: e.json("messageMetadata")
|
|
613
|
-
}))),
|
|
644
|
+
}))), ve = (e, t, n) => (n.clearScope(t), N({
|
|
614
645
|
type: "error",
|
|
615
646
|
errorText: typeof e == "string" ? e : ""
|
|
616
|
-
}),
|
|
647
|
+
})), ye = (e, t, n) => (n.clearScope(t), N(D({
|
|
617
648
|
type: "abort",
|
|
618
649
|
reason: typeof e == "string" && e ? e : void 0
|
|
619
|
-
}))),
|
|
650
|
+
}))), be = (e) => N({
|
|
620
651
|
type: "message-metadata",
|
|
621
652
|
messageMetadata: e.json("messageMetadata")
|
|
622
|
-
}),
|
|
653
|
+
}), xe = (e, t) => N(D({
|
|
623
654
|
type: "file",
|
|
624
655
|
url: typeof t == "string" ? t : "",
|
|
625
656
|
mediaType: e.strOr("mediaType", ""),
|
|
626
657
|
providerMetadata: e.providerMetadata()
|
|
627
|
-
})),
|
|
658
|
+
})), Se = (e, t) => N(D({
|
|
628
659
|
type: "source-url",
|
|
629
660
|
sourceId: e.strOr("sourceId", ""),
|
|
630
661
|
url: typeof t == "string" ? t : "",
|
|
631
662
|
title: e.str("title"),
|
|
632
663
|
providerMetadata: e.providerMetadata()
|
|
633
|
-
})),
|
|
664
|
+
})), Ce = (e) => N(D({
|
|
634
665
|
type: "source-document",
|
|
635
666
|
sourceId: e.strOr("sourceId", ""),
|
|
636
667
|
mediaType: e.strOr("mediaType", ""),
|
|
637
668
|
title: e.strOr("title", ""),
|
|
638
669
|
filename: e.str("filename"),
|
|
639
670
|
providerMetadata: e.providerMetadata()
|
|
640
|
-
})),
|
|
671
|
+
})), we = (e, t) => {
|
|
641
672
|
let n = t;
|
|
642
|
-
return
|
|
673
|
+
return N(D({
|
|
643
674
|
type: "tool-input-error",
|
|
644
675
|
toolCallId: e.strOr("toolCallId", ""),
|
|
645
676
|
toolName: e.strOr("toolName", ""),
|
|
@@ -650,9 +681,9 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
650
681
|
providerExecuted: e.bool("providerExecuted"),
|
|
651
682
|
providerMetadata: e.providerMetadata()
|
|
652
683
|
}));
|
|
653
|
-
},
|
|
684
|
+
}, Te = (e, t) => {
|
|
654
685
|
let n = t;
|
|
655
|
-
return
|
|
686
|
+
return N(D({
|
|
656
687
|
type: "tool-output-available",
|
|
657
688
|
toolCallId: e.strOr("toolCallId", ""),
|
|
658
689
|
output: n?.output,
|
|
@@ -660,32 +691,32 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
660
691
|
providerExecuted: e.bool("providerExecuted"),
|
|
661
692
|
preliminary: e.bool("preliminary")
|
|
662
693
|
}));
|
|
663
|
-
},
|
|
694
|
+
}, Ee = (e, t) => {
|
|
664
695
|
let n = t;
|
|
665
|
-
return
|
|
696
|
+
return N(D({
|
|
666
697
|
type: "tool-output-error",
|
|
667
698
|
toolCallId: e.strOr("toolCallId", ""),
|
|
668
699
|
errorText: n?.errorText ?? "",
|
|
669
700
|
dynamic: e.bool("dynamic"),
|
|
670
701
|
providerExecuted: e.bool("providerExecuted")
|
|
671
702
|
}));
|
|
672
|
-
},
|
|
703
|
+
}, De = (e) => N({
|
|
673
704
|
type: "tool-approval-request",
|
|
674
705
|
toolCallId: e.strOr("toolCallId", ""),
|
|
675
706
|
approvalId: e.strOr("approvalId", "")
|
|
676
|
-
}),
|
|
707
|
+
}), Oe = (e) => N({
|
|
677
708
|
type: "tool-output-denied",
|
|
678
709
|
toolCallId: e.strOr("toolCallId", "")
|
|
679
|
-
}),
|
|
710
|
+
}), ke = (e, t, n) => N(D({
|
|
680
711
|
type: e,
|
|
681
712
|
data: n,
|
|
682
713
|
id: t.str("id"),
|
|
683
714
|
transient: t.bool("transient")
|
|
684
|
-
})),
|
|
715
|
+
})), Ae = (e, t, n, r) => {
|
|
685
716
|
let i = F(r, n, { messageId: e.str("messageId") });
|
|
686
717
|
return i.push({
|
|
687
718
|
kind: "event",
|
|
688
|
-
event:
|
|
719
|
+
event: D({
|
|
689
720
|
type: "tool-input-start",
|
|
690
721
|
toolCallId: e.strOr("toolCallId", ""),
|
|
691
722
|
toolName: e.strOr("toolName", ""),
|
|
@@ -696,7 +727,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
696
727
|
})
|
|
697
728
|
}, {
|
|
698
729
|
kind: "event",
|
|
699
|
-
event:
|
|
730
|
+
event: D({
|
|
700
731
|
type: "tool-input-available",
|
|
701
732
|
toolCallId: e.strOr("toolCallId", ""),
|
|
702
733
|
toolName: e.strOr("toolName", ""),
|
|
@@ -704,8 +735,8 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
704
735
|
providerMetadata: e.providerMetadata()
|
|
705
736
|
})
|
|
706
737
|
}), i;
|
|
707
|
-
},
|
|
708
|
-
let t = e.headers ?? {}, n =
|
|
738
|
+
}, je = (e) => {
|
|
739
|
+
let t = e.headers ?? {}, n = M(t), r = t["x-ably-role"] ?? "user", i = n.str("messageId") ?? "", a;
|
|
709
740
|
switch (e.name) {
|
|
710
741
|
case "text":
|
|
711
742
|
a = {
|
|
@@ -721,7 +752,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
721
752
|
};
|
|
722
753
|
break;
|
|
723
754
|
default:
|
|
724
|
-
|
|
755
|
+
P(e.name) && (a = D({
|
|
725
756
|
type: e.name,
|
|
726
757
|
id: n.str("id"),
|
|
727
758
|
data: e.data
|
|
@@ -736,49 +767,49 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
736
767
|
parts: [a]
|
|
737
768
|
}
|
|
738
769
|
}] : [];
|
|
739
|
-
},
|
|
740
|
-
let n = e.headers ?? {}, r =
|
|
741
|
-
if (
|
|
742
|
-
if (e.name === "tool-input") return
|
|
770
|
+
}, Me = (e, t) => (e === "text" || e === "file" || P(e)) && "x-ably-discrete" in t, Ne = (e, t) => {
|
|
771
|
+
let n = e.headers ?? {}, r = M(n), i = n["x-ably-turn-id"] ?? "";
|
|
772
|
+
if (Me(e.name, n)) return je(e);
|
|
773
|
+
if (e.name === "tool-input") return Ae(r, e.data, i, t);
|
|
743
774
|
switch (e.name) {
|
|
744
|
-
case "start": return
|
|
745
|
-
case "start-step": return
|
|
746
|
-
case "finish-step": return
|
|
747
|
-
case "finish": return
|
|
748
|
-
case "error": return
|
|
749
|
-
case "abort": return
|
|
750
|
-
case "message-metadata": return
|
|
751
|
-
case "file": return
|
|
752
|
-
case "source-url": return
|
|
753
|
-
case "source-document": return
|
|
754
|
-
case "tool-input-error": return
|
|
755
|
-
case "tool-output-available": return
|
|
756
|
-
case "tool-output-error": return
|
|
757
|
-
case "tool-approval-request": return
|
|
758
|
-
case "tool-output-denied": return
|
|
759
|
-
default: return
|
|
760
|
-
}
|
|
761
|
-
},
|
|
775
|
+
case "start": return he(r, i, t);
|
|
776
|
+
case "start-step": return ge(i, t);
|
|
777
|
+
case "finish-step": return _e(i, t);
|
|
778
|
+
case "finish": return I(r, i, t);
|
|
779
|
+
case "error": return ve(e.data, i, t);
|
|
780
|
+
case "abort": return ye(e.data, i, t);
|
|
781
|
+
case "message-metadata": return be(r);
|
|
782
|
+
case "file": return xe(r, e.data);
|
|
783
|
+
case "source-url": return Se(r, e.data);
|
|
784
|
+
case "source-document": return Ce(r);
|
|
785
|
+
case "tool-input-error": return we(r, e.data);
|
|
786
|
+
case "tool-output-available": return Te(r, e.data);
|
|
787
|
+
case "tool-output-error": return Ee(r, e.data);
|
|
788
|
+
case "tool-approval-request": return De(r);
|
|
789
|
+
case "tool-output-denied": return Oe(r);
|
|
790
|
+
default: return P(e.name) ? ke(e.name, r, e.data) : [];
|
|
791
|
+
}
|
|
792
|
+
}, Pe = (e) => ({
|
|
762
793
|
buildStartEvents: (t) => {
|
|
763
|
-
let n = F(e, t.headers["x-ably-turn-id"] ?? "", { messageId:
|
|
794
|
+
let n = F(e, t.headers["x-ably-turn-id"] ?? "", { messageId: M(t.headers).str("messageId") });
|
|
764
795
|
return n.push({
|
|
765
796
|
kind: "event",
|
|
766
|
-
event:
|
|
797
|
+
event: de(t)
|
|
767
798
|
}), n;
|
|
768
799
|
},
|
|
769
|
-
buildDeltaEvents: (e, t) =>
|
|
770
|
-
buildEndEvents: (e, t) =>
|
|
771
|
-
decodeDiscrete: (t) =>
|
|
772
|
-
}),
|
|
800
|
+
buildDeltaEvents: (e, t) => N(fe(e, t)),
|
|
801
|
+
buildEndEvents: (e, t) => N(pe(e, t)),
|
|
802
|
+
decodeDiscrete: (t) => Ne(t, e)
|
|
803
|
+
}), Fe = class {
|
|
773
804
|
constructor(e = {}) {
|
|
774
|
-
this._core = oe(
|
|
805
|
+
this._core = oe(Pe(me()), e);
|
|
775
806
|
}
|
|
776
807
|
decode(e) {
|
|
777
808
|
return this._core.decode(e);
|
|
778
809
|
}
|
|
779
|
-
},
|
|
780
|
-
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;
|
|
781
|
-
}({}),
|
|
810
|
+
}, Ie = (e = {}) => new Fe(e), L = /* @__PURE__ */ function(e) {
|
|
811
|
+
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[e.ChannelContinuityLost = 104006] = "ChannelContinuityLost", e[e.ChannelNotReady = 104007] = "ChannelNotReady", e[e.StreamError = 104008] = "StreamError", e;
|
|
812
|
+
}({}), Le = (e, t) => e.code === t, Re = class {
|
|
782
813
|
constructor(e, t = {}) {
|
|
783
814
|
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" });
|
|
784
815
|
}
|
|
@@ -790,33 +821,34 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
790
821
|
async publishDiscreteBatch(e, t) {
|
|
791
822
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
|
|
792
823
|
let n = e.map((e) => this._buildDiscreteMessage(e, t));
|
|
824
|
+
for (let e of n) e.extras.headers[o] = "true";
|
|
793
825
|
return this._writer.publish(n);
|
|
794
826
|
}
|
|
795
|
-
async startStream(t,
|
|
827
|
+
async startStream(t, n, o) {
|
|
796
828
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.startStream();", {
|
|
797
|
-
name:
|
|
829
|
+
name: n.name,
|
|
798
830
|
streamId: t
|
|
799
831
|
});
|
|
800
|
-
let s = this._buildHeaders(
|
|
801
|
-
s[
|
|
832
|
+
let s = this._buildHeaders(n.headers ?? {}, o);
|
|
833
|
+
s[r] = "true", s[i] = "streaming", s[a] = t;
|
|
802
834
|
let c = this._resolveClientId(o), l = {
|
|
803
|
-
name:
|
|
804
|
-
data:
|
|
835
|
+
name: n.name,
|
|
836
|
+
data: n.data,
|
|
805
837
|
extras: { headers: s },
|
|
806
838
|
...c ? { clientId: c } : {}
|
|
807
839
|
};
|
|
808
840
|
this._invokeOnMessage(l);
|
|
809
841
|
let u = (await this._writer.publish(l)).serials[0];
|
|
810
|
-
if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${
|
|
842
|
+
if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${n.name}' (streamId: ${t})`, L.BadRequest, 400);
|
|
811
843
|
this._trackers.set(t, {
|
|
812
844
|
serial: u,
|
|
813
|
-
name:
|
|
845
|
+
name: n.name,
|
|
814
846
|
streamId: t,
|
|
815
|
-
accumulated:
|
|
847
|
+
accumulated: n.data,
|
|
816
848
|
persistentHeaders: s,
|
|
817
849
|
aborted: !1
|
|
818
850
|
}), this._logger?.debug("DefaultEncoderCore.startStream(); stream started", {
|
|
819
|
-
name:
|
|
851
|
+
name: n.name,
|
|
820
852
|
streamId: t,
|
|
821
853
|
serial: u
|
|
822
854
|
});
|
|
@@ -824,7 +856,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
824
856
|
appendStream(t, n) {
|
|
825
857
|
this._assertNotClosed();
|
|
826
858
|
let r = this._trackers.get(t);
|
|
827
|
-
if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`,
|
|
859
|
+
if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, L.InvalidArgument, 400);
|
|
828
860
|
r.accumulated += n;
|
|
829
861
|
let i = {
|
|
830
862
|
serial: r.serial,
|
|
@@ -840,13 +872,13 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
840
872
|
}
|
|
841
873
|
async closeStream(t, n) {
|
|
842
874
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.closeStream();", { streamId: t });
|
|
843
|
-
let
|
|
844
|
-
if (!
|
|
845
|
-
|
|
846
|
-
let a = this._buildClosingHeaders(
|
|
847
|
-
a[
|
|
875
|
+
let r = this._trackers.get(t);
|
|
876
|
+
if (!r) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, L.InvalidArgument, 400);
|
|
877
|
+
r.accumulated += n.data;
|
|
878
|
+
let a = this._buildClosingHeaders(r, n.headers ?? {});
|
|
879
|
+
a[i] = "finished";
|
|
848
880
|
let o = {
|
|
849
|
-
serial:
|
|
881
|
+
serial: r.serial,
|
|
850
882
|
data: n.data,
|
|
851
883
|
extras: { headers: a }
|
|
852
884
|
};
|
|
@@ -859,13 +891,13 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
859
891
|
}
|
|
860
892
|
async abortStream(t, n) {
|
|
861
893
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortStream();", { streamId: t });
|
|
862
|
-
let
|
|
863
|
-
if (!
|
|
864
|
-
|
|
865
|
-
let a = this._buildClosingHeaders(
|
|
866
|
-
a[
|
|
894
|
+
let r = this._trackers.get(t);
|
|
895
|
+
if (!r) throw new e.ErrorInfo(`unable to abort stream; no active stream for streamId '${t}'`, L.InvalidArgument, 400);
|
|
896
|
+
r.aborted = !0;
|
|
897
|
+
let a = this._buildClosingHeaders(r, {}, n);
|
|
898
|
+
a[i] = "aborted";
|
|
867
899
|
let o = {
|
|
868
|
-
serial:
|
|
900
|
+
serial: r.serial,
|
|
869
901
|
data: "",
|
|
870
902
|
extras: { headers: a }
|
|
871
903
|
};
|
|
@@ -881,14 +913,14 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
881
913
|
for (let t of this._trackers.values()) {
|
|
882
914
|
t.aborted = !0;
|
|
883
915
|
let n = this._buildClosingHeaders(t, {}, e);
|
|
884
|
-
n[
|
|
885
|
-
let
|
|
916
|
+
n[i] = "aborted";
|
|
917
|
+
let r = {
|
|
886
918
|
serial: t.serial,
|
|
887
919
|
data: "",
|
|
888
920
|
extras: { headers: n }
|
|
889
921
|
};
|
|
890
|
-
this._invokeOnMessage(
|
|
891
|
-
let a = this._writer.appendMessage(
|
|
922
|
+
this._invokeOnMessage(r);
|
|
923
|
+
let a = this._writer.appendMessage(r);
|
|
892
924
|
this._pending.push({
|
|
893
925
|
promise: a,
|
|
894
926
|
streamId: t.streamId
|
|
@@ -909,30 +941,30 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
909
941
|
}
|
|
910
942
|
}
|
|
911
943
|
async _doFlush(t) {
|
|
912
|
-
let n = await Promise.allSettled(t.map(async (e) => e.promise)),
|
|
913
|
-
for (let [e,
|
|
944
|
+
let n = await Promise.allSettled(t.map(async (e) => e.promise)), r = /* @__PURE__ */ new Set();
|
|
945
|
+
for (let [e, i] of n.entries()) {
|
|
914
946
|
let n = t[e];
|
|
915
|
-
n &&
|
|
947
|
+
n && i.status === "rejected" && r.add(n.streamId);
|
|
916
948
|
}
|
|
917
|
-
if (
|
|
949
|
+
if (r.size === 0) {
|
|
918
950
|
this._logger?.debug("DefaultEncoderCore._flushPending(); all appends succeeded");
|
|
919
951
|
return;
|
|
920
952
|
}
|
|
921
|
-
this._logger?.warn("DefaultEncoderCore._flushPending(); recovering failed appends", { failedStreams: [...
|
|
953
|
+
this._logger?.warn("DefaultEncoderCore._flushPending(); recovering failed appends", { failedStreams: [...r] });
|
|
922
954
|
let a = [];
|
|
923
|
-
for (let e of
|
|
955
|
+
for (let e of r) {
|
|
924
956
|
let t = this._trackers.get(e);
|
|
925
957
|
if (!t) continue;
|
|
926
|
-
let n = t.aborted ? "aborted" : "finished",
|
|
958
|
+
let n = t.aborted ? "aborted" : "finished", r = {
|
|
927
959
|
serial: t.serial,
|
|
928
960
|
data: t.accumulated,
|
|
929
961
|
extras: { headers: {
|
|
930
962
|
...t.persistentHeaders,
|
|
931
|
-
[
|
|
963
|
+
[i]: n
|
|
932
964
|
} }
|
|
933
965
|
};
|
|
934
966
|
try {
|
|
935
|
-
await this._writer.updateMessage(
|
|
967
|
+
await this._writer.updateMessage(r);
|
|
936
968
|
} catch (t) {
|
|
937
969
|
a.push({
|
|
938
970
|
streamId: e,
|
|
@@ -942,7 +974,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
942
974
|
}
|
|
943
975
|
if (a.length > 0) {
|
|
944
976
|
let t = a.map((e) => e.streamId).join(", ");
|
|
945
|
-
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`,
|
|
977
|
+
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, L.EncoderRecoveryFailed, 500);
|
|
946
978
|
}
|
|
947
979
|
}
|
|
948
980
|
async close() {
|
|
@@ -964,26 +996,26 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
964
996
|
}
|
|
965
997
|
}
|
|
966
998
|
_assertNotClosed() {
|
|
967
|
-
if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed",
|
|
999
|
+
if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", L.InvalidArgument, 400);
|
|
968
1000
|
}
|
|
969
1001
|
_resolveClientId(e) {
|
|
970
1002
|
return e?.clientId ?? this._defaultClientId;
|
|
971
1003
|
}
|
|
972
1004
|
_buildHeaders(e, t) {
|
|
973
1005
|
let n = {
|
|
974
|
-
...
|
|
1006
|
+
...T(this._defaultExtras?.headers, t?.extras?.headers),
|
|
975
1007
|
...e
|
|
976
1008
|
};
|
|
977
|
-
return t?.messageId !== void 0 && (n[
|
|
1009
|
+
return t?.messageId !== void 0 && (n[c] = t.messageId), n;
|
|
978
1010
|
}
|
|
979
1011
|
_buildDiscreteMessage(e, t) {
|
|
980
|
-
let
|
|
981
|
-
r
|
|
1012
|
+
let n = this._buildHeaders(e.headers ?? {}, t);
|
|
1013
|
+
n[r] = "false";
|
|
982
1014
|
let i = this._resolveClientId(t), a = {
|
|
983
1015
|
name: e.name,
|
|
984
1016
|
data: e.data,
|
|
985
1017
|
extras: {
|
|
986
|
-
headers:
|
|
1018
|
+
headers: n,
|
|
987
1019
|
...e.ephemeral ? { ephemeral: !0 } : {}
|
|
988
1020
|
},
|
|
989
1021
|
...i ? { clientId: i } : {}
|
|
@@ -991,17 +1023,57 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
991
1023
|
return this._invokeOnMessage(a), a;
|
|
992
1024
|
}
|
|
993
1025
|
_buildClosingHeaders(e, t, n) {
|
|
994
|
-
let r = { ...e.persistentHeaders }, i =
|
|
1026
|
+
let r = { ...e.persistentHeaders }, i = T(this._defaultExtras?.headers, n?.extras?.headers);
|
|
995
1027
|
return Object.assign(r, i), Object.assign(r, t), r;
|
|
996
1028
|
}
|
|
997
|
-
},
|
|
1029
|
+
}, ze = (e, t = {}) => new Re(e, t), R = (t) => {
|
|
1030
|
+
switch (t.type) {
|
|
1031
|
+
case "tool-output-available": {
|
|
1032
|
+
let e = O().str("toolCallId", t.toolCallId).bool("dynamic", t.dynamic).bool("providerExecuted", t.providerExecuted).bool("preliminary", t.preliminary).build();
|
|
1033
|
+
return {
|
|
1034
|
+
name: "tool-output-available",
|
|
1035
|
+
data: { output: t.output },
|
|
1036
|
+
headers: e
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
case "tool-output-error": {
|
|
1040
|
+
let e = O().str("toolCallId", t.toolCallId).bool("dynamic", t.dynamic).bool("providerExecuted", t.providerExecuted).build();
|
|
1041
|
+
return {
|
|
1042
|
+
name: "tool-output-error",
|
|
1043
|
+
data: { errorText: t.errorText },
|
|
1044
|
+
headers: e
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
case "tool-approval-request": return {
|
|
1048
|
+
name: "tool-approval-request",
|
|
1049
|
+
data: "",
|
|
1050
|
+
headers: O().str("toolCallId", t.toolCallId).str("approvalId", t.approvalId).build()
|
|
1051
|
+
};
|
|
1052
|
+
case "tool-output-denied": return {
|
|
1053
|
+
name: "tool-output-denied",
|
|
1054
|
+
data: "",
|
|
1055
|
+
headers: O().str("toolCallId", t.toolCallId).build()
|
|
1056
|
+
};
|
|
1057
|
+
default:
|
|
1058
|
+
if (t.type.startsWith("data-")) {
|
|
1059
|
+
let e = t, n = O().str("id", e.id).bool("transient", e.transient).build(), r = e.transient === !0;
|
|
1060
|
+
return {
|
|
1061
|
+
name: t.type,
|
|
1062
|
+
data: e.data,
|
|
1063
|
+
headers: n,
|
|
1064
|
+
ephemeral: r
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
throw new e.ErrorInfo(`unable to write event; unsupported chunk type '${t.type}'`, L.InvalidArgument, 400);
|
|
1068
|
+
}
|
|
1069
|
+
}, Be = class {
|
|
998
1070
|
constructor(e, t = {}) {
|
|
999
|
-
this._aborted = !1, this._core =
|
|
1071
|
+
this._aborted = !1, this._core = ze(e, t), this._messageId = t.messageId;
|
|
1000
1072
|
}
|
|
1001
1073
|
async appendEvent(t, n) {
|
|
1002
1074
|
switch (t.type) {
|
|
1003
1075
|
case "text-start": {
|
|
1004
|
-
let e =
|
|
1076
|
+
let e = O().str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1005
1077
|
await this._core.startStream(t.id, {
|
|
1006
1078
|
name: "text",
|
|
1007
1079
|
data: "",
|
|
@@ -1010,7 +1082,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1010
1082
|
break;
|
|
1011
1083
|
}
|
|
1012
1084
|
case "reasoning-start": {
|
|
1013
|
-
let e =
|
|
1085
|
+
let e = O().str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1014
1086
|
await this._core.startStream(t.id, {
|
|
1015
1087
|
name: "reasoning",
|
|
1016
1088
|
data: "",
|
|
@@ -1019,7 +1091,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1019
1091
|
break;
|
|
1020
1092
|
}
|
|
1021
1093
|
case "tool-input-start": {
|
|
1022
|
-
let e =
|
|
1094
|
+
let e = O().str("toolCallId", t.toolCallId).str("toolName", t.toolName).bool("dynamic", t.dynamic).str("title", t.title).bool("providerExecuted", t.providerExecuted).json("providerMetadata", t.providerMetadata).build();
|
|
1023
1095
|
await this._core.startStream(t.toolCallId, {
|
|
1024
1096
|
name: "tool-input",
|
|
1025
1097
|
data: "",
|
|
@@ -1037,7 +1109,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1037
1109
|
this._core.appendStream(t.toolCallId, t.inputTextDelta);
|
|
1038
1110
|
break;
|
|
1039
1111
|
case "text-end": {
|
|
1040
|
-
let e =
|
|
1112
|
+
let e = O().str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1041
1113
|
await this._core.closeStream(t.id, {
|
|
1042
1114
|
name: "text",
|
|
1043
1115
|
data: "",
|
|
@@ -1046,7 +1118,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1046
1118
|
break;
|
|
1047
1119
|
}
|
|
1048
1120
|
case "reasoning-end": {
|
|
1049
|
-
let e =
|
|
1121
|
+
let e = O().str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1050
1122
|
await this._core.closeStream(t.id, {
|
|
1051
1123
|
name: "reasoning",
|
|
1052
1124
|
data: "",
|
|
@@ -1056,15 +1128,15 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1056
1128
|
}
|
|
1057
1129
|
case "tool-input-available":
|
|
1058
1130
|
try {
|
|
1059
|
-
let e =
|
|
1131
|
+
let e = O().str("toolCallId", t.toolCallId).str("toolName", t.toolName).json("providerMetadata", t.providerMetadata).build();
|
|
1060
1132
|
await this._core.closeStream(t.toolCallId, {
|
|
1061
1133
|
name: "tool-input",
|
|
1062
1134
|
data: "",
|
|
1063
1135
|
headers: e
|
|
1064
1136
|
});
|
|
1065
1137
|
} catch (n) {
|
|
1066
|
-
if (!(n instanceof e.ErrorInfo &&
|
|
1067
|
-
let r =
|
|
1138
|
+
if (!(n instanceof e.ErrorInfo && Le(n, L.InvalidArgument))) throw n;
|
|
1139
|
+
let r = O().str("toolCallId", t.toolCallId).str("toolName", t.toolName).bool("dynamic", t.dynamic).str("title", t.title).bool("providerExecuted", t.providerExecuted).json("providerMetadata", t.providerMetadata).build();
|
|
1068
1140
|
await this._core.publishDiscrete({
|
|
1069
1141
|
name: "tool-input",
|
|
1070
1142
|
data: t.input,
|
|
@@ -1073,7 +1145,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1073
1145
|
}
|
|
1074
1146
|
break;
|
|
1075
1147
|
case "start": {
|
|
1076
|
-
let e =
|
|
1148
|
+
let e = O().str("messageId", t.messageId ?? this._messageId).json("messageMetadata", t.messageMetadata).build();
|
|
1077
1149
|
await this._core.publishDiscrete({
|
|
1078
1150
|
name: "start",
|
|
1079
1151
|
data: "",
|
|
@@ -1094,7 +1166,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1094
1166
|
}, n);
|
|
1095
1167
|
break;
|
|
1096
1168
|
case "finish": {
|
|
1097
|
-
let e =
|
|
1169
|
+
let e = O().str("finishReason", t.finishReason).json("messageMetadata", t.messageMetadata).build();
|
|
1098
1170
|
await this._core.publishDiscrete({
|
|
1099
1171
|
name: "finish",
|
|
1100
1172
|
data: "",
|
|
@@ -1112,11 +1184,11 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1112
1184
|
this._aborted = !0, await this._core.abortAllStreams(n), await this._core.publishDiscrete({
|
|
1113
1185
|
name: "abort",
|
|
1114
1186
|
data: t.reason ?? "",
|
|
1115
|
-
headers: { [
|
|
1187
|
+
headers: { [i]: "aborted" }
|
|
1116
1188
|
}, n);
|
|
1117
1189
|
break;
|
|
1118
1190
|
case "tool-input-error": {
|
|
1119
|
-
let e =
|
|
1191
|
+
let e = O().str("toolCallId", t.toolCallId).str("toolName", t.toolName).bool("dynamic", t.dynamic).str("title", t.title).bool("providerExecuted", t.providerExecuted).json("providerMetadata", t.providerMetadata).build();
|
|
1120
1192
|
await this._core.publishDiscrete({
|
|
1121
1193
|
name: "tool-input-error",
|
|
1122
1194
|
data: {
|
|
@@ -1127,44 +1199,14 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1127
1199
|
});
|
|
1128
1200
|
break;
|
|
1129
1201
|
}
|
|
1130
|
-
case "tool-output-available":
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
headers: e
|
|
1136
|
-
});
|
|
1137
|
-
break;
|
|
1138
|
-
}
|
|
1139
|
-
case "tool-output-error": {
|
|
1140
|
-
let e = w().str("toolCallId", t.toolCallId).bool("dynamic", t.dynamic).bool("providerExecuted", t.providerExecuted).build();
|
|
1141
|
-
await this._core.publishDiscrete({
|
|
1142
|
-
name: "tool-output-error",
|
|
1143
|
-
data: { errorText: t.errorText },
|
|
1144
|
-
headers: e
|
|
1145
|
-
});
|
|
1146
|
-
break;
|
|
1147
|
-
}
|
|
1148
|
-
case "tool-approval-request": {
|
|
1149
|
-
let e = w().str("toolCallId", t.toolCallId).str("approvalId", t.approvalId).build();
|
|
1150
|
-
await this._core.publishDiscrete({
|
|
1151
|
-
name: "tool-approval-request",
|
|
1152
|
-
data: "",
|
|
1153
|
-
headers: e
|
|
1154
|
-
}, n);
|
|
1155
|
-
break;
|
|
1156
|
-
}
|
|
1157
|
-
case "tool-output-denied": {
|
|
1158
|
-
let e = w().str("toolCallId", t.toolCallId).build();
|
|
1159
|
-
await this._core.publishDiscrete({
|
|
1160
|
-
name: "tool-output-denied",
|
|
1161
|
-
data: "",
|
|
1162
|
-
headers: e
|
|
1163
|
-
}, n);
|
|
1202
|
+
case "tool-output-available":
|
|
1203
|
+
case "tool-output-error":
|
|
1204
|
+
case "tool-approval-request":
|
|
1205
|
+
case "tool-output-denied":
|
|
1206
|
+
await this._core.publishDiscrete(R(t), n);
|
|
1164
1207
|
break;
|
|
1165
|
-
}
|
|
1166
1208
|
case "file": {
|
|
1167
|
-
let e =
|
|
1209
|
+
let e = O().str("mediaType", t.mediaType).json("providerMetadata", t.providerMetadata).build();
|
|
1168
1210
|
await this._core.publishDiscrete({
|
|
1169
1211
|
name: "file",
|
|
1170
1212
|
data: t.url,
|
|
@@ -1173,7 +1215,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1173
1215
|
break;
|
|
1174
1216
|
}
|
|
1175
1217
|
case "source-url": {
|
|
1176
|
-
let e =
|
|
1218
|
+
let e = O().str("sourceId", t.sourceId).str("title", t.title).json("providerMetadata", t.providerMetadata).build();
|
|
1177
1219
|
await this._core.publishDiscrete({
|
|
1178
1220
|
name: "source-url",
|
|
1179
1221
|
data: t.url,
|
|
@@ -1182,7 +1224,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1182
1224
|
break;
|
|
1183
1225
|
}
|
|
1184
1226
|
case "source-document": {
|
|
1185
|
-
let e =
|
|
1227
|
+
let e = O().str("sourceId", t.sourceId).str("mediaType", t.mediaType).str("title", t.title).str("filename", t.filename).json("providerMetadata", t.providerMetadata).build();
|
|
1186
1228
|
await this._core.publishDiscrete({
|
|
1187
1229
|
name: "source-document",
|
|
1188
1230
|
data: "",
|
|
@@ -1191,7 +1233,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1191
1233
|
break;
|
|
1192
1234
|
}
|
|
1193
1235
|
case "message-metadata": {
|
|
1194
|
-
let e =
|
|
1236
|
+
let e = O().json("messageMetadata", t.messageMetadata).build();
|
|
1195
1237
|
await this._core.publishDiscrete({
|
|
1196
1238
|
name: "message-metadata",
|
|
1197
1239
|
data: "",
|
|
@@ -1201,7 +1243,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1201
1243
|
}
|
|
1202
1244
|
default:
|
|
1203
1245
|
if (t.type.startsWith("data-")) {
|
|
1204
|
-
let e =
|
|
1246
|
+
let e = O().str("id", t.id).bool("transient", t.transient).build(), r = t.transient === !0;
|
|
1205
1247
|
await this._core.publishDiscrete({
|
|
1206
1248
|
name: t.type,
|
|
1207
1249
|
data: t.data,
|
|
@@ -1212,186 +1254,197 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1212
1254
|
break;
|
|
1213
1255
|
}
|
|
1214
1256
|
}
|
|
1215
|
-
async writeEvent(
|
|
1216
|
-
|
|
1217
|
-
let r = w().str("id", "id" in t ? t.id : void 0).bool("transient", "transient" in t ? t.transient : void 0).build(), i = "transient" in t && t.transient === !0;
|
|
1218
|
-
return this._core.publishDiscrete({
|
|
1219
|
-
name: t.type,
|
|
1220
|
-
data: "data" in t ? t.data : void 0,
|
|
1221
|
-
headers: r,
|
|
1222
|
-
ephemeral: i
|
|
1223
|
-
}, n);
|
|
1257
|
+
async writeEvent(e, t) {
|
|
1258
|
+
return this._core.publishDiscrete(R(e), t);
|
|
1224
1259
|
}
|
|
1225
1260
|
async writeMessages(e, t) {
|
|
1226
|
-
let n = e.flatMap((e) =>
|
|
1261
|
+
let n = e.flatMap((e) => Ve(e));
|
|
1227
1262
|
return this._core.publishDiscreteBatch(n, t);
|
|
1228
1263
|
}
|
|
1229
1264
|
async abort(e) {
|
|
1230
1265
|
this._aborted || (this._aborted = !0, await this._core.abortAllStreams(), await this._core.publishDiscrete({
|
|
1231
1266
|
name: "abort",
|
|
1232
1267
|
data: e ?? "",
|
|
1233
|
-
headers: { [
|
|
1268
|
+
headers: { [i]: "aborted" }
|
|
1234
1269
|
}));
|
|
1235
1270
|
}
|
|
1236
1271
|
async close() {
|
|
1237
1272
|
await this._core.close();
|
|
1238
1273
|
}
|
|
1239
|
-
},
|
|
1240
|
-
let
|
|
1274
|
+
}, Ve = (e) => {
|
|
1275
|
+
let t = e.id, r = [];
|
|
1241
1276
|
for (let i of e.parts) switch (i.type) {
|
|
1242
1277
|
case "text":
|
|
1243
1278
|
r.push({
|
|
1244
1279
|
name: "text",
|
|
1245
1280
|
data: i.text,
|
|
1246
|
-
headers:
|
|
1281
|
+
headers: O().str("messageId", t).build()
|
|
1247
1282
|
});
|
|
1248
1283
|
break;
|
|
1249
1284
|
case "file":
|
|
1250
1285
|
r.push({
|
|
1251
1286
|
name: "file",
|
|
1252
1287
|
data: i.url,
|
|
1253
|
-
headers:
|
|
1288
|
+
headers: O().str("messageId", t).str("mediaType", i.mediaType).build()
|
|
1254
1289
|
});
|
|
1255
1290
|
break;
|
|
1256
1291
|
default:
|
|
1257
|
-
|
|
1292
|
+
n(i) && r.push({
|
|
1258
1293
|
name: i.type,
|
|
1259
1294
|
data: i.data,
|
|
1260
|
-
headers:
|
|
1295
|
+
headers: O().str("messageId", t).str("id", i.id).build()
|
|
1261
1296
|
});
|
|
1262
1297
|
break;
|
|
1263
1298
|
}
|
|
1264
1299
|
return r.length === 0 && r.push({
|
|
1265
1300
|
name: "text",
|
|
1266
1301
|
data: "",
|
|
1267
|
-
headers:
|
|
1302
|
+
headers: O().str("messageId", t).build()
|
|
1268
1303
|
}), r;
|
|
1269
|
-
},
|
|
1270
|
-
createEncoder: (e, t = {}) => new
|
|
1271
|
-
createDecoder:
|
|
1272
|
-
createAccumulator:
|
|
1273
|
-
getMessageKey: (e) => e.id,
|
|
1304
|
+
}, z = {
|
|
1305
|
+
createEncoder: (e, t = {}) => new Be(e, t),
|
|
1306
|
+
createDecoder: Ie,
|
|
1307
|
+
createAccumulator: j,
|
|
1274
1308
|
isTerminal: (e) => e.type === "finish" || e.type === "error" || e.type === "abort"
|
|
1275
|
-
},
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
} else f = {
|
|
1302
|
-
history: l.map((e) => ({
|
|
1303
|
-
message: e,
|
|
1304
|
-
headers: t.getMessageHeaders(e)
|
|
1305
|
-
})),
|
|
1306
|
-
id: r.chatId,
|
|
1307
|
-
trigger: o,
|
|
1308
|
-
...s !== void 0 && { messageId: s },
|
|
1309
|
-
...u !== void 0 && { forkOf: u },
|
|
1310
|
-
...d !== void 0 && { parent: d }
|
|
1311
|
-
}, p = void 0;
|
|
1312
|
-
let m = {
|
|
1313
|
-
body: f,
|
|
1314
|
-
headers: p
|
|
1315
|
-
};
|
|
1316
|
-
u !== void 0 && (m.forkOf = u), d !== void 0 && (m.parent = d);
|
|
1317
|
-
let h = await t.send(c, m);
|
|
1318
|
-
a && a.addEventListener("abort", () => void t.cancel({ all: !0 }), { once: !0 });
|
|
1319
|
-
let { readable: g, writable: _ } = new TransformStream(), v = _.getWriter();
|
|
1320
|
-
return h.stream.pipeTo(new WritableStream({
|
|
1321
|
-
close: () => {
|
|
1322
|
-
v.close().catch(() => {});
|
|
1323
|
-
},
|
|
1324
|
-
abort: () => {
|
|
1325
|
-
v.close().catch(() => {});
|
|
1309
|
+
}, He = (e) => {
|
|
1310
|
+
let t, n = new Promise((e) => {
|
|
1311
|
+
t = e;
|
|
1312
|
+
}), r = new TransformStream({ flush: () => {
|
|
1313
|
+
t();
|
|
1314
|
+
} });
|
|
1315
|
+
return e.pipeTo(r.writable).catch(() => {
|
|
1316
|
+
t();
|
|
1317
|
+
}), {
|
|
1318
|
+
stream: r.readable,
|
|
1319
|
+
done: n
|
|
1320
|
+
};
|
|
1321
|
+
}, Ue = (e) => e.role === "assistant" && e.parts.some((e) => e.type === "dynamic-tool" && (e.state === "input-streaming" || e.state === "input-available" || e.state === "approval-requested")), We = (t, n) => {
|
|
1322
|
+
let r = !1, i = /* @__PURE__ */ new Set(), a = (e) => {
|
|
1323
|
+
r = e;
|
|
1324
|
+
for (let t of i) try {
|
|
1325
|
+
t(e);
|
|
1326
|
+
} catch {}
|
|
1327
|
+
};
|
|
1328
|
+
return {
|
|
1329
|
+
sendMessages: async (r) => {
|
|
1330
|
+
let { messages: i, abortSignal: o, trigger: s, messageId: c } = r, l = t.view.flattenNodes(), u = i.at(-1), d = u ? l.find((e) => e.message.id === u.id) : void 0, f = s === "submit-message" && u?.role === "assistant" && !!d, p = s === "submit-message" && !c && u?.role === "user" ? i.at(-2) : void 0, m = p && Ue(p) ? l.find((e) => e.message.id === p.id) : void 0, h, g;
|
|
1331
|
+
if (s === "regenerate-message" || f) h = [], g = i;
|
|
1332
|
+
else {
|
|
1333
|
+
if (i.length === 0) throw new e.ErrorInfo("unable to send messages; messages array is empty for submit-message trigger", L.InvalidArgument, 400);
|
|
1334
|
+
h = [i.at(-1)], g = m ? i.slice(0, -2) : i.slice(0, -1);
|
|
1326
1335
|
}
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1336
|
+
let _, v;
|
|
1337
|
+
if (c && !f) {
|
|
1338
|
+
_ = c;
|
|
1339
|
+
let e = l.find((e) => e.message.id === c);
|
|
1340
|
+
e && (_ = e.msgId, v = e.parentId);
|
|
1341
|
+
} else f ? v = d.msgId : m && (_ = m.msgId, v = m.parentId);
|
|
1342
|
+
let y, b;
|
|
1343
|
+
if (n?.prepareSendMessagesRequest) {
|
|
1344
|
+
let e = n.prepareSendMessagesRequest({
|
|
1345
|
+
chatId: r.chatId,
|
|
1346
|
+
trigger: s,
|
|
1347
|
+
messageId: c,
|
|
1348
|
+
history: g,
|
|
1349
|
+
messages: h,
|
|
1350
|
+
forkOf: _,
|
|
1351
|
+
parent: v
|
|
1352
|
+
});
|
|
1353
|
+
y = e.body ?? {}, b = e.headers;
|
|
1354
|
+
} else {
|
|
1355
|
+
let e = new Set(g.map((e) => e.id));
|
|
1356
|
+
y = {
|
|
1357
|
+
history: l.filter((t) => e.has(t.message.id)),
|
|
1358
|
+
chatId: r.chatId,
|
|
1359
|
+
trigger: s,
|
|
1360
|
+
...c !== void 0 && { messageId: c },
|
|
1361
|
+
..._ !== void 0 && { forkOf: _ },
|
|
1362
|
+
...v !== void 0 && { parent: v }
|
|
1363
|
+
}, b = void 0;
|
|
1364
|
+
}
|
|
1365
|
+
let x = {
|
|
1366
|
+
body: y,
|
|
1367
|
+
headers: b
|
|
1368
|
+
};
|
|
1369
|
+
_ !== void 0 && (x.forkOf = _), v !== void 0 && (x.parent = v);
|
|
1370
|
+
let S = await t.view.send(h, x);
|
|
1371
|
+
o && o.addEventListener("abort", () => void t.cancel({ all: !0 }), { once: !0 });
|
|
1372
|
+
let { stream: C, done: w } = He(S.stream);
|
|
1373
|
+
return a(!0), w.then(() => {
|
|
1374
|
+
a(!1);
|
|
1375
|
+
}), C;
|
|
1376
|
+
},
|
|
1377
|
+
reconnectToStream: () => Promise.resolve(null),
|
|
1378
|
+
close: async (e) => t.close(e),
|
|
1379
|
+
get streaming() {
|
|
1380
|
+
return r;
|
|
1381
|
+
},
|
|
1382
|
+
onStreamingChange: (e) => (i.add(e), () => {
|
|
1383
|
+
i.delete(e);
|
|
1384
|
+
})
|
|
1385
|
+
};
|
|
1386
|
+
}, Ge = (e) => ({
|
|
1334
1387
|
logAction: (t, n, r) => {
|
|
1335
1388
|
e.error(n, { detail: r });
|
|
1336
1389
|
},
|
|
1337
1390
|
shouldLog: () => !0
|
|
1338
|
-
}),
|
|
1391
|
+
}), Ke = e.Realtime.EventEmitter, B = class extends Ke {
|
|
1339
1392
|
constructor(e) {
|
|
1340
|
-
super(
|
|
1393
|
+
super(Ge(e));
|
|
1341
1394
|
}
|
|
1342
|
-
},
|
|
1395
|
+
}, V = /* @__PURE__ */ function(e) {
|
|
1343
1396
|
return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
|
|
1344
|
-
}({}),
|
|
1397
|
+
}({}), qe = (e, t, n) => {
|
|
1345
1398
|
let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
|
|
1346
1399
|
switch (t) {
|
|
1347
|
-
case
|
|
1348
|
-
case
|
|
1400
|
+
case V.Trace:
|
|
1401
|
+
case V.Debug:
|
|
1349
1402
|
console.log(i);
|
|
1350
1403
|
break;
|
|
1351
|
-
case
|
|
1404
|
+
case V.Info:
|
|
1352
1405
|
console.info(i);
|
|
1353
1406
|
break;
|
|
1354
|
-
case
|
|
1407
|
+
case V.Warn:
|
|
1355
1408
|
console.warn(i);
|
|
1356
1409
|
break;
|
|
1357
|
-
case
|
|
1410
|
+
case V.Error:
|
|
1358
1411
|
console.error(i);
|
|
1359
1412
|
break;
|
|
1360
|
-
case
|
|
1413
|
+
case V.Silent: break;
|
|
1361
1414
|
}
|
|
1362
|
-
},
|
|
1415
|
+
}, Je = (e) => new Ye(e.logHandler ?? qe, e.logLevel), H = /* @__PURE__ */ function(e) {
|
|
1363
1416
|
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;
|
|
1364
|
-
}(
|
|
1365
|
-
[
|
|
1366
|
-
[
|
|
1367
|
-
[
|
|
1368
|
-
[
|
|
1369
|
-
[
|
|
1370
|
-
[
|
|
1371
|
-
]),
|
|
1417
|
+
}(H || {}), U = new Map([
|
|
1418
|
+
[V.Trace, H.Trace],
|
|
1419
|
+
[V.Debug, H.Debug],
|
|
1420
|
+
[V.Info, H.Info],
|
|
1421
|
+
[V.Warn, H.Warn],
|
|
1422
|
+
[V.Error, H.Error],
|
|
1423
|
+
[V.Silent, H.Silent]
|
|
1424
|
+
]), Ye = class t {
|
|
1372
1425
|
constructor(t, n, r) {
|
|
1373
1426
|
this._handler = t, this._context = r;
|
|
1374
|
-
let i =
|
|
1375
|
-
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`,
|
|
1427
|
+
let i = U.get(n);
|
|
1428
|
+
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, L.InvalidArgument, 400);
|
|
1376
1429
|
this._levelNumber = i;
|
|
1377
1430
|
}
|
|
1378
1431
|
trace(e, t) {
|
|
1379
|
-
this._write(e,
|
|
1432
|
+
this._write(e, V.Trace, H.Trace, t);
|
|
1380
1433
|
}
|
|
1381
1434
|
debug(e, t) {
|
|
1382
|
-
this._write(e,
|
|
1435
|
+
this._write(e, V.Debug, H.Debug, t);
|
|
1383
1436
|
}
|
|
1384
1437
|
info(e, t) {
|
|
1385
|
-
this._write(e,
|
|
1438
|
+
this._write(e, V.Info, H.Info, t);
|
|
1386
1439
|
}
|
|
1387
1440
|
warn(e, t) {
|
|
1388
|
-
this._write(e,
|
|
1441
|
+
this._write(e, V.Warn, H.Warn, t);
|
|
1389
1442
|
}
|
|
1390
1443
|
error(e, t) {
|
|
1391
|
-
this._write(e,
|
|
1444
|
+
this._write(e, V.Error, H.Error, t);
|
|
1392
1445
|
}
|
|
1393
1446
|
withContext(e) {
|
|
1394
|
-
let n = [...
|
|
1447
|
+
let n = [...U.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? V.Error;
|
|
1395
1448
|
return new t(this._handler, n, this._mergeContext(e));
|
|
1396
1449
|
}
|
|
1397
1450
|
_write(e, t, n, r) {
|
|
@@ -1403,9 +1456,65 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1403
1456
|
...e
|
|
1404
1457
|
} : this._context : e ?? void 0;
|
|
1405
1458
|
}
|
|
1406
|
-
},
|
|
1459
|
+
}, W = (e) => {
|
|
1460
|
+
let t = {
|
|
1461
|
+
[u]: e.role,
|
|
1462
|
+
[s]: e.turnId,
|
|
1463
|
+
[c]: e.msgId
|
|
1464
|
+
};
|
|
1465
|
+
return e.turnClientId !== void 0 && (t[l] = e.turnClientId), e.parent && (t[g] = e.parent), e.forkOf && (t[_] = e.forkOf), e.amend && (t[d] = e.amend), t;
|
|
1466
|
+
}, Xe = class {
|
|
1407
1467
|
constructor(e, t) {
|
|
1408
|
-
this.
|
|
1468
|
+
this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
|
|
1469
|
+
}
|
|
1470
|
+
createStream(t) {
|
|
1471
|
+
this._logger.trace("StreamRouter.createStream();", { turnId: t });
|
|
1472
|
+
let n = {}, r = new ReadableStream({ start(e) {
|
|
1473
|
+
n.controller = e;
|
|
1474
|
+
} });
|
|
1475
|
+
if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", L.TransportSubscriptionError, 500);
|
|
1476
|
+
return this._turns.set(t, {
|
|
1477
|
+
controller: n.controller,
|
|
1478
|
+
turnId: t
|
|
1479
|
+
}), r;
|
|
1480
|
+
}
|
|
1481
|
+
closeStream(e) {
|
|
1482
|
+
let t = this._turns.get(e);
|
|
1483
|
+
if (!t) return !1;
|
|
1484
|
+
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
1485
|
+
try {
|
|
1486
|
+
t.controller.close();
|
|
1487
|
+
} catch {}
|
|
1488
|
+
return this._turns.delete(e), !0;
|
|
1489
|
+
}
|
|
1490
|
+
errorStream(e, t) {
|
|
1491
|
+
let n = this._turns.get(e);
|
|
1492
|
+
if (!n) return !1;
|
|
1493
|
+
this._logger.debug("StreamRouter.errorStream(); erroring stream", { turnId: e });
|
|
1494
|
+
try {
|
|
1495
|
+
n.controller.error(t);
|
|
1496
|
+
} catch {}
|
|
1497
|
+
return this._turns.delete(e), !0;
|
|
1498
|
+
}
|
|
1499
|
+
route(e, t) {
|
|
1500
|
+
let n = this._turns.get(e);
|
|
1501
|
+
if (!n) return !1;
|
|
1502
|
+
try {
|
|
1503
|
+
n.controller.enqueue(t);
|
|
1504
|
+
} catch {
|
|
1505
|
+
return this._turns.delete(e), !1;
|
|
1506
|
+
}
|
|
1507
|
+
return this._isTerminal(t) && this.closeStream(e), !0;
|
|
1508
|
+
}
|
|
1509
|
+
has(e) {
|
|
1510
|
+
return this._turns.has(e);
|
|
1511
|
+
}
|
|
1512
|
+
}, Ze = (e, t) => new Xe(e, t), Qe = class {
|
|
1513
|
+
get structuralVersion() {
|
|
1514
|
+
return this._structuralVersion;
|
|
1515
|
+
}
|
|
1516
|
+
constructor(e) {
|
|
1517
|
+
this._nodeIndex = /* @__PURE__ */ new Map(), this._sortedList = [], this._parentIndex = /* @__PURE__ */ new Map(), this._turnClientIds = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._structuralVersion = 0, this._logger = e, this._emitter = new B(e);
|
|
1409
1518
|
}
|
|
1410
1519
|
_compareNodes(e, t) {
|
|
1411
1520
|
let n = e.node.serial, r = t.node.serial;
|
|
@@ -1464,7 +1573,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1464
1573
|
}
|
|
1465
1574
|
return !1;
|
|
1466
1575
|
}
|
|
1467
|
-
|
|
1576
|
+
getGroupRoot(e) {
|
|
1468
1577
|
let t = this._nodeIndex.get(e);
|
|
1469
1578
|
if (!t) return e;
|
|
1470
1579
|
let n = t.node, r = new Set([n.msgId]);
|
|
@@ -1475,75 +1584,63 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1475
1584
|
}
|
|
1476
1585
|
return n.msgId;
|
|
1477
1586
|
}
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1587
|
+
flattenNodes(e) {
|
|
1588
|
+
this._logger.trace("DefaultTree.flattenNodes();");
|
|
1589
|
+
let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
|
|
1590
|
+
for (let i of this._sortedList) {
|
|
1591
|
+
let a = i.node, { msgId: o, parentId: s } = a;
|
|
1592
|
+
if (s !== void 0 && !n.has(s)) continue;
|
|
1593
|
+
let c = this._getSiblingGroup(o);
|
|
1594
|
+
if (c.length > 1) {
|
|
1595
|
+
let t = this.getGroupRoot(o), n = r.get(t);
|
|
1596
|
+
if (n === void 0) {
|
|
1597
|
+
let i = e.get(t);
|
|
1598
|
+
if (i && c.some((e) => e.msgId === i)) n = i;
|
|
1599
|
+
else {
|
|
1600
|
+
let e = c.at(-1);
|
|
1601
|
+
if (!e) break;
|
|
1602
|
+
n = e.msgId;
|
|
1603
|
+
}
|
|
1604
|
+
r.set(t, n);
|
|
1490
1605
|
}
|
|
1491
|
-
if (
|
|
1606
|
+
if (o !== n) continue;
|
|
1492
1607
|
}
|
|
1493
|
-
|
|
1608
|
+
n.add(o), t.push(a);
|
|
1494
1609
|
}
|
|
1495
|
-
return
|
|
1610
|
+
return t;
|
|
1496
1611
|
}
|
|
1497
1612
|
getSiblings(e) {
|
|
1498
|
-
return this._getSiblingGroup(e).map((e) => e.message);
|
|
1613
|
+
return this._logger.trace("DefaultTree.getSiblings();", { msgId: e }), this._getSiblingGroup(e).map((e) => e.message);
|
|
1614
|
+
}
|
|
1615
|
+
getSiblingNodes(e) {
|
|
1616
|
+
return this._getSiblingGroup(e);
|
|
1499
1617
|
}
|
|
1500
1618
|
hasSiblings(e) {
|
|
1501
1619
|
return this._getSiblingGroup(e).length > 1;
|
|
1502
1620
|
}
|
|
1503
|
-
getSelectedIndex(e) {
|
|
1504
|
-
let t = this._getSiblingGroup(e);
|
|
1505
|
-
if (t.length <= 1) return 0;
|
|
1506
|
-
let n = this._getGroupRoot(e), r = this._selections.get(n);
|
|
1507
|
-
return r === void 0 ? t.length - 1 : Math.max(0, Math.min(r, t.length - 1));
|
|
1508
|
-
}
|
|
1509
|
-
select(e, t) {
|
|
1510
|
-
this._logger.debug("ConversationTree.select();", {
|
|
1511
|
-
msgId: e,
|
|
1512
|
-
index: t
|
|
1513
|
-
});
|
|
1514
|
-
let n = this._getSiblingGroup(e);
|
|
1515
|
-
if (n.length <= 1) return;
|
|
1516
|
-
let r = this._getGroupRoot(e);
|
|
1517
|
-
this._selections.set(r, Math.max(0, Math.min(t, n.length - 1)));
|
|
1518
|
-
}
|
|
1519
1621
|
getNode(e) {
|
|
1520
|
-
return this._nodeIndex.get(e)?.node;
|
|
1521
|
-
}
|
|
1522
|
-
getNodeByKey(e) {
|
|
1523
|
-
let t = this._codecKeyIndex.get(e);
|
|
1524
|
-
if (t) return this._nodeIndex.get(t)?.node;
|
|
1622
|
+
return this._logger.trace("DefaultTree.getNode();", { msgId: e }), this._nodeIndex.get(e)?.node;
|
|
1525
1623
|
}
|
|
1526
1624
|
getHeaders(e) {
|
|
1527
|
-
return this._nodeIndex.get(e)?.node.headers;
|
|
1625
|
+
return this._logger.trace("DefaultTree.getHeaders();", { msgId: e }), this._nodeIndex.get(e)?.node.headers;
|
|
1528
1626
|
}
|
|
1529
1627
|
upsert(e, t, n, r) {
|
|
1530
|
-
let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0;
|
|
1531
|
-
this._codecKeyIndex.set(this._getKey(t), e);
|
|
1532
|
-
let o = this._nodeIndex.get(e);
|
|
1628
|
+
let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0, o = this._nodeIndex.get(e);
|
|
1533
1629
|
if (o) {
|
|
1534
|
-
o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("
|
|
1630
|
+
o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("Tree.upsert(); promoting serial", {
|
|
1535
1631
|
msgId: e,
|
|
1536
1632
|
serial: r
|
|
1537
|
-
}), o.node.serial = r, this._removeSorted(o), this._insertSorted(o));
|
|
1633
|
+
}), o.node.serial = r, this._removeSorted(o), this._insertSorted(o), this._structuralVersion++), this._emitter.emit("update");
|
|
1538
1634
|
return;
|
|
1539
1635
|
}
|
|
1540
|
-
this._logger.trace("
|
|
1636
|
+
this._logger.trace("Tree.upsert(); inserting new node", {
|
|
1541
1637
|
msgId: e,
|
|
1542
1638
|
parentId: i,
|
|
1543
1639
|
forkOf: a
|
|
1544
1640
|
});
|
|
1545
1641
|
let s = {
|
|
1546
1642
|
node: {
|
|
1643
|
+
kind: "message",
|
|
1547
1644
|
message: t,
|
|
1548
1645
|
msgId: e,
|
|
1549
1646
|
parentId: i,
|
|
@@ -1553,224 +1650,580 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1553
1650
|
},
|
|
1554
1651
|
insertSeq: this._seqCounter++
|
|
1555
1652
|
};
|
|
1556
|
-
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s);
|
|
1653
|
+
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s), this._structuralVersion++, this._emitter.emit("update");
|
|
1557
1654
|
}
|
|
1558
1655
|
delete(e) {
|
|
1559
1656
|
let t = this._nodeIndex.get(e);
|
|
1560
1657
|
if (!t) return;
|
|
1561
|
-
this._logger.debug("
|
|
1562
|
-
let { node: n } = t
|
|
1563
|
-
this.
|
|
1564
|
-
}
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1658
|
+
this._logger.debug("Tree.delete();", { msgId: e });
|
|
1659
|
+
let { node: n } = t;
|
|
1660
|
+
this._removeFromParentIndex(n.parentId, e), this._removeSorted(t), this._nodeIndex.delete(e), this._structuralVersion++, this._emitter.emit("update");
|
|
1661
|
+
}
|
|
1662
|
+
getActiveTurnIds() {
|
|
1663
|
+
this._logger.trace("DefaultTree.getActiveTurnIds();");
|
|
1664
|
+
let e = /* @__PURE__ */ new Map();
|
|
1665
|
+
for (let [t, n] of this._turnClientIds) {
|
|
1666
|
+
let r = e.get(n);
|
|
1667
|
+
r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
|
|
1668
|
+
}
|
|
1669
|
+
return e;
|
|
1670
|
+
}
|
|
1671
|
+
on(e, t) {
|
|
1672
|
+
let n = t;
|
|
1673
|
+
return this._emitter.on(e, n), () => {
|
|
1674
|
+
this._emitter.off(e, n);
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
emitAblyMessage(e) {
|
|
1678
|
+
this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
|
|
1679
|
+
}
|
|
1680
|
+
emitTurn(e) {
|
|
1681
|
+
this._logger.trace("DefaultTree.emitTurn();", { turnId: e.turnId }), this._emitter.emit("turn", e);
|
|
1682
|
+
}
|
|
1683
|
+
trackTurn(e, t) {
|
|
1684
|
+
this._logger.trace("DefaultTree.trackTurn();", {
|
|
1685
|
+
turnId: e,
|
|
1686
|
+
clientId: t
|
|
1687
|
+
}), this._turnClientIds.set(e, t);
|
|
1688
|
+
}
|
|
1689
|
+
untrackTurn(e) {
|
|
1690
|
+
this._logger.trace("DefaultTree.untrackTurn();", { turnId: e }), this._turnClientIds.delete(e);
|
|
1691
|
+
}
|
|
1692
|
+
}, $e = (e) => new Qe(e), et = (e) => {
|
|
1693
|
+
let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), i = e.codec.createAccumulator(), a = 0, o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), u = [], f = [];
|
|
1694
|
+
for (let p of t) {
|
|
1695
|
+
let t = n.decode(p), m = C(p), h = m[s], g = m[c], _ = p.serial, v = m[d];
|
|
1696
|
+
if (v) {
|
|
1697
|
+
for (let e of r.values()) if (e.msgHeaders.has(v)) {
|
|
1698
|
+
let n = [...e.msgHeaders.keys()].indexOf(v), r = n === -1 ? void 0 : e.accumulator.messages[n];
|
|
1699
|
+
r && e.accumulator.initMessage(v, r), e.accumulator.processOutputs(t), f.push({
|
|
1700
|
+
accumulator: e.accumulator,
|
|
1701
|
+
messageId: v
|
|
1702
|
+
});
|
|
1703
|
+
break;
|
|
1704
|
+
}
|
|
1705
|
+
continue;
|
|
1706
|
+
}
|
|
1707
|
+
if (h) {
|
|
1708
|
+
let n = r.get(h);
|
|
1571
1709
|
if (n || (n = {
|
|
1572
1710
|
accumulator: e.codec.createAccumulator(),
|
|
1573
|
-
firstSeen:
|
|
1711
|
+
firstSeen: a++,
|
|
1574
1712
|
msgHeaders: /* @__PURE__ */ new Map(),
|
|
1575
1713
|
msgSerials: /* @__PURE__ */ new Map()
|
|
1576
|
-
}, r.set(
|
|
1577
|
-
let e = n.msgHeaders.get(
|
|
1578
|
-
e ? Object.keys(
|
|
1714
|
+
}, r.set(h, n)), g) {
|
|
1715
|
+
let e = n.msgHeaders.get(g);
|
|
1716
|
+
e ? Object.keys(m).length > 0 && Object.assign(e, m) : (n.msgHeaders.set(g, { ...m }), _ && n.msgSerials.set(g, _));
|
|
1579
1717
|
}
|
|
1580
1718
|
n.accumulator.processOutputs(t);
|
|
1581
|
-
} else
|
|
1582
|
-
|
|
1583
|
-
let t
|
|
1584
|
-
|
|
1719
|
+
} else {
|
|
1720
|
+
i.processOutputs(t);
|
|
1721
|
+
for (let e of t) if (e.kind === "message" && g) {
|
|
1722
|
+
u.push(g);
|
|
1723
|
+
let e = o.get(g);
|
|
1724
|
+
e ? Object.keys(m).length > 0 && Object.assign(e, m) : (o.set(g, { ...m }), _ && l.set(g, _));
|
|
1725
|
+
}
|
|
1585
1726
|
}
|
|
1586
1727
|
}
|
|
1587
|
-
let
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
u
|
|
1728
|
+
for (let { accumulator: e, messageId: t } of f) e.completeMessage(t);
|
|
1729
|
+
let p = [];
|
|
1730
|
+
for (let [e, t] of i.completedMessages.entries()) {
|
|
1731
|
+
let n = u[e];
|
|
1732
|
+
p.push({
|
|
1591
1733
|
message: t,
|
|
1592
|
-
headers:
|
|
1593
|
-
serial: l.get(n) ?? ""
|
|
1734
|
+
headers: n ? o.get(n) ?? {} : {},
|
|
1735
|
+
serial: n ? l.get(n) ?? "" : ""
|
|
1594
1736
|
});
|
|
1595
1737
|
}
|
|
1596
|
-
let
|
|
1597
|
-
for (let
|
|
1598
|
-
let
|
|
1599
|
-
for (let
|
|
1600
|
-
let
|
|
1601
|
-
if (
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
if (!r.has(o) && c) {
|
|
1613
|
-
let [e, n] = c;
|
|
1614
|
-
r.set(o, n);
|
|
1615
|
-
let a = t.msgSerials.get(e);
|
|
1616
|
-
a && i.set(o, a), s++;
|
|
1617
|
-
}
|
|
1618
|
-
}
|
|
1619
|
-
for (let n of t.accumulator.completedMessages) {
|
|
1620
|
-
let t = e.getMessageKey(n);
|
|
1621
|
-
u.push({
|
|
1622
|
-
message: n,
|
|
1623
|
-
headers: r.get(t) ?? {},
|
|
1624
|
-
serial: i.get(t) ?? ""
|
|
1738
|
+
let m = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
|
|
1739
|
+
for (let e of m) {
|
|
1740
|
+
let t = [...e.msgHeaders.entries()], n = 0;
|
|
1741
|
+
for (let r of e.accumulator.completedMessages) {
|
|
1742
|
+
let i = t[n];
|
|
1743
|
+
if (i) {
|
|
1744
|
+
let [t, a] = i;
|
|
1745
|
+
p.push({
|
|
1746
|
+
message: r,
|
|
1747
|
+
headers: a,
|
|
1748
|
+
serial: e.msgSerials.get(t) ?? ""
|
|
1749
|
+
}), n++;
|
|
1750
|
+
} else p.push({
|
|
1751
|
+
message: r,
|
|
1752
|
+
headers: {},
|
|
1753
|
+
serial: ""
|
|
1625
1754
|
});
|
|
1626
1755
|
}
|
|
1627
1756
|
}
|
|
1628
|
-
return
|
|
1629
|
-
},
|
|
1630
|
-
e.rawMessages.
|
|
1631
|
-
let
|
|
1632
|
-
|
|
1757
|
+
return p.toReversed();
|
|
1758
|
+
}, tt = (e) => {
|
|
1759
|
+
if (e.cachedDecode && e.cachedAtRawLength === e.rawMessages.length) return e.cachedDecode;
|
|
1760
|
+
let t = et(e);
|
|
1761
|
+
return e.cachedDecode = t, e.cachedAtRawLength = e.rawMessages.length, t;
|
|
1762
|
+
}, G = (e, t) => {
|
|
1763
|
+
for (let n of t) {
|
|
1764
|
+
let t = C(n), r = t[c];
|
|
1765
|
+
if (!r || t["x-ably-amend"]) continue;
|
|
1766
|
+
let a = n.action, o = a === "message.create" && "x-ably-discrete" in t, s = t["x-ably-stream"] === "true" && (a === "message.create" || a === "message.update" || a === "message.append"), l = t[i], u = l === "finished" || l === "aborted";
|
|
1767
|
+
(o || s) && e.startedMsgIds.add(r), (o || u) && e.terminatedMsgIds.add(r), e.startedMsgIds.has(r) && e.terminatedMsgIds.has(r) && e.completedMsgIds.add(r);
|
|
1768
|
+
}
|
|
1769
|
+
}, K = async (e, t, n) => {
|
|
1770
|
+
e.rawMessages.push(...t.items), e.lastAblyPage = t, G(e, t.items);
|
|
1771
|
+
let r = e.returnedCount + n;
|
|
1772
|
+
for (; e.completedMsgIds.size < r && t.hasNext();) {
|
|
1633
1773
|
e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
|
|
1634
1774
|
collected: e.rawMessages.length,
|
|
1635
|
-
|
|
1775
|
+
completed: e.completedMsgIds.size
|
|
1636
1776
|
});
|
|
1637
1777
|
let n = await t.next();
|
|
1638
1778
|
if (!n) break;
|
|
1639
|
-
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n,
|
|
1779
|
+
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, G(e, n.items);
|
|
1640
1780
|
}
|
|
1641
|
-
},
|
|
1642
|
-
let n =
|
|
1781
|
+
}, q = (e, t) => {
|
|
1782
|
+
let n = tt(e), r = n.slice(e.returnedCount, e.returnedCount + t), i = [...r].toReversed();
|
|
1643
1783
|
e.returnedCount += r.length;
|
|
1644
1784
|
let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
|
|
1645
1785
|
return e.returnedRawCount = e.rawMessages.length, {
|
|
1646
|
-
items: i.map((e) =>
|
|
1647
|
-
|
|
1648
|
-
|
|
1786
|
+
items: i.map((e) => ({
|
|
1787
|
+
message: e.message,
|
|
1788
|
+
headers: e.headers,
|
|
1789
|
+
serial: e.serial
|
|
1790
|
+
})),
|
|
1649
1791
|
rawMessages: s,
|
|
1650
1792
|
hasNext: () => a || o,
|
|
1651
1793
|
next: async () => {
|
|
1652
|
-
if (a) return
|
|
1794
|
+
if (a) return q(e, t);
|
|
1653
1795
|
if (!o || !e.lastAblyPage) return;
|
|
1654
1796
|
let n = await e.lastAblyPage.next();
|
|
1655
|
-
if (n) return await
|
|
1797
|
+
if (n) return await K(e, n, t), q(e, t);
|
|
1656
1798
|
}
|
|
1657
1799
|
};
|
|
1658
|
-
},
|
|
1800
|
+
}, nt = async (e, t, n, r) => {
|
|
1659
1801
|
let i = n?.limit ?? 100, a = {
|
|
1660
1802
|
codec: t,
|
|
1661
1803
|
rawMessages: [],
|
|
1662
1804
|
returnedCount: 0,
|
|
1663
1805
|
returnedRawCount: 0,
|
|
1664
1806
|
lastAblyPage: void 0,
|
|
1665
|
-
|
|
1807
|
+
cachedDecode: void 0,
|
|
1808
|
+
cachedAtRawLength: 0,
|
|
1809
|
+
startedMsgIds: /* @__PURE__ */ new Set(),
|
|
1810
|
+
terminatedMsgIds: /* @__PURE__ */ new Set(),
|
|
1811
|
+
completedMsgIds: /* @__PURE__ */ new Set(),
|
|
1666
1812
|
logger: r
|
|
1667
1813
|
};
|
|
1668
1814
|
r.trace("decodeHistory();", { limit: i });
|
|
1669
1815
|
let o = i * 10;
|
|
1670
|
-
return await e.attach(), await
|
|
1816
|
+
return await e.attach(), await K(a, await e.history({
|
|
1671
1817
|
untilAttach: !0,
|
|
1672
1818
|
limit: o
|
|
1673
|
-
}), i),
|
|
1674
|
-
},
|
|
1675
|
-
|
|
1676
|
-
[
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
|
|
1819
|
+
}), i), q(a, i);
|
|
1820
|
+
}, rt = class {
|
|
1821
|
+
constructor(e) {
|
|
1822
|
+
this._branchSelections = /* @__PURE__ */ new Map(), this._withheldMsgIds = /* @__PURE__ */ new Set(), this._lastVisibleIds = [], this._lastVisibleMessages = [], this._lastVisibleTurnIds = /* @__PURE__ */ new Set(), this._hasMoreHistory = !1, this._withheldBuffer = [], this._unsubs = [], this._cachedNodes = [], this._lastStructuralVersion = -1, this._loadingOlder = !1, this._processingHistory = !1, this._closed = !1, this._tree = e.tree, this._channel = e.channel, this._codec = e.codec, this._sendDelegate = e.sendDelegate, this._onClose = e.onClose, this._logger = e.logger.withContext({ component: "View" }), this._logger.trace("DefaultView();"), this._emitter = new B(this._logger), this._cachedNodes = this._computeFlatNodes(), this._lastStructuralVersion = this._tree.structuralVersion, this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
|
|
1823
|
+
this._onTreeUpdate();
|
|
1824
|
+
}), this._tree.on("ably-message", (e) => {
|
|
1825
|
+
this._onTreeAblyMessage(e);
|
|
1826
|
+
}), this._tree.on("turn", (e) => {
|
|
1827
|
+
this._onTreeTurn(e);
|
|
1828
|
+
}));
|
|
1684
1829
|
}
|
|
1685
|
-
|
|
1686
|
-
this.
|
|
1687
|
-
let n = {}, r = new ReadableStream({ start(e) {
|
|
1688
|
-
n.controller = e;
|
|
1689
|
-
} });
|
|
1690
|
-
if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", W.TransportSubscriptionError, 500);
|
|
1691
|
-
return this._turns.set(t, {
|
|
1692
|
-
controller: n.controller,
|
|
1693
|
-
turnId: t
|
|
1694
|
-
}), r;
|
|
1830
|
+
getMessages() {
|
|
1831
|
+
return this.flattenNodes().map((e) => e.message);
|
|
1695
1832
|
}
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
if (!t) return !1;
|
|
1699
|
-
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
1700
|
-
try {
|
|
1701
|
-
t.controller.close();
|
|
1702
|
-
} catch {}
|
|
1703
|
-
return this._turns.delete(e), !0;
|
|
1833
|
+
flattenNodes() {
|
|
1834
|
+
return this._cachedNodes;
|
|
1704
1835
|
}
|
|
1705
|
-
|
|
1706
|
-
let
|
|
1707
|
-
|
|
1836
|
+
_computeFlatNodes() {
|
|
1837
|
+
let e = this._tree.flattenNodes(this._resolveSelections());
|
|
1838
|
+
return this._withheldMsgIds.size === 0 ? e : e.filter((e) => !this._withheldMsgIds.has(e.msgId));
|
|
1839
|
+
}
|
|
1840
|
+
hasOlder() {
|
|
1841
|
+
return this._withheldBuffer.length > 0 || this._hasMoreHistory;
|
|
1842
|
+
}
|
|
1843
|
+
async loadOlder(e = 100) {
|
|
1844
|
+
if (!(this._closed || this._loadingOlder)) {
|
|
1845
|
+
this._loadingOlder = !0, this._logger.trace("DefaultView.loadOlder();", { limit: e });
|
|
1846
|
+
try {
|
|
1847
|
+
if (this._withheldBuffer.length > 0) {
|
|
1848
|
+
let t = this._withheldBuffer.splice(-e, e);
|
|
1849
|
+
this._releaseWithheld(t);
|
|
1850
|
+
return;
|
|
1851
|
+
}
|
|
1852
|
+
if (!this._hasMoreHistory && !this._lastHistoryPage) {
|
|
1853
|
+
await this._loadFirstPage(e);
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
if (!this._hasMoreHistory) return;
|
|
1857
|
+
if (!this._lastHistoryPage?.hasNext()) {
|
|
1858
|
+
this._hasMoreHistory = !1;
|
|
1859
|
+
return;
|
|
1860
|
+
}
|
|
1861
|
+
let t = await this._lastHistoryPage.next();
|
|
1862
|
+
if (this._closed || !t) {
|
|
1863
|
+
t || (this._hasMoreHistory = !1);
|
|
1864
|
+
return;
|
|
1865
|
+
}
|
|
1866
|
+
await this._loadAndReveal(t, e);
|
|
1867
|
+
} catch (e) {
|
|
1868
|
+
throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
|
|
1869
|
+
} finally {
|
|
1870
|
+
this._loadingOlder = !1;
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
select(e, t) {
|
|
1875
|
+
this._logger.trace("DefaultView.select();", {
|
|
1876
|
+
msgId: e,
|
|
1877
|
+
index: t
|
|
1878
|
+
});
|
|
1879
|
+
let n = this._tree.getSiblingNodes(e);
|
|
1880
|
+
if (n.length <= 1) return;
|
|
1881
|
+
let r = this._tree.getGroupRoot(e), i = Math.max(0, Math.min(t, n.length - 1)), a = n[i];
|
|
1882
|
+
a && (this._branchSelections.set(r, {
|
|
1883
|
+
kind: "user",
|
|
1884
|
+
selectedId: a.msgId
|
|
1885
|
+
}), this._logger.debug("DefaultView.select();", {
|
|
1886
|
+
msgId: e,
|
|
1887
|
+
index: i,
|
|
1888
|
+
selectedId: a.msgId
|
|
1889
|
+
}), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
|
|
1890
|
+
}
|
|
1891
|
+
getSelectedIndex(e) {
|
|
1892
|
+
this._logger.trace("DefaultView.getSelectedIndex();", { msgId: e });
|
|
1893
|
+
let t = this._tree.getSiblingNodes(e);
|
|
1894
|
+
if (t.length <= 1) return 0;
|
|
1895
|
+
let n = this._tree.getGroupRoot(e), r = this._branchSelections.get(n);
|
|
1896
|
+
if (!r || r.kind === "pending") return t.length - 1;
|
|
1897
|
+
let i = t.findIndex((e) => e.msgId === r.selectedId);
|
|
1898
|
+
return i === -1 ? t.length - 1 : i;
|
|
1899
|
+
}
|
|
1900
|
+
getSiblings(e) {
|
|
1901
|
+
return this._tree.getSiblings(e);
|
|
1902
|
+
}
|
|
1903
|
+
hasSiblings(e) {
|
|
1904
|
+
return this._tree.hasSiblings(e);
|
|
1905
|
+
}
|
|
1906
|
+
getNode(e) {
|
|
1907
|
+
return this._tree.getNode(e);
|
|
1908
|
+
}
|
|
1909
|
+
async send(t, n) {
|
|
1910
|
+
if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", L.InvalidArgument, 400);
|
|
1911
|
+
let r = this.flattenNodes(), i = await this._sendDelegate(t, n, r);
|
|
1912
|
+
if (n?.forkOf) {
|
|
1913
|
+
let e = this._tree.getGroupRoot(n.forkOf);
|
|
1914
|
+
if (i.optimisticMsgIds.length > 0) {
|
|
1915
|
+
let t = i.optimisticMsgIds.at(-1);
|
|
1916
|
+
t && (this._branchSelections.set(e, {
|
|
1917
|
+
kind: "auto",
|
|
1918
|
+
selectedId: t
|
|
1919
|
+
}), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
|
|
1920
|
+
} else {
|
|
1921
|
+
this._branchSelections.set(e, {
|
|
1922
|
+
kind: "pending",
|
|
1923
|
+
turnId: i.turnId
|
|
1924
|
+
}), this._logger.debug("DefaultView.send(); deferring fork auto-selection", {
|
|
1925
|
+
forkOf: n.forkOf,
|
|
1926
|
+
groupRoot: e,
|
|
1927
|
+
turnId: i.turnId
|
|
1928
|
+
});
|
|
1929
|
+
let t = this._tree.on("turn", (n) => {
|
|
1930
|
+
if (n.type !== "x-ably-turn-end" || n.turnId !== i.turnId) return;
|
|
1931
|
+
let r = this._branchSelections.get(e);
|
|
1932
|
+
r?.kind === "pending" && r.turnId === i.turnId && this._branchSelections.delete(e), t();
|
|
1933
|
+
let a = this._unsubs.indexOf(t);
|
|
1934
|
+
a !== -1 && this._unsubs.splice(a, 1);
|
|
1935
|
+
});
|
|
1936
|
+
this._unsubs.push(t);
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
return i;
|
|
1940
|
+
}
|
|
1941
|
+
async regenerate(t, n) {
|
|
1942
|
+
this._logger.trace("DefaultView.regenerate();", { messageId: t });
|
|
1943
|
+
let r = this._tree.getNode(t);
|
|
1944
|
+
if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, L.InvalidArgument, 400);
|
|
1945
|
+
let i = r.parentId;
|
|
1946
|
+
return this.send([], {
|
|
1947
|
+
...n,
|
|
1948
|
+
body: {
|
|
1949
|
+
history: this._getHistoryBefore(t),
|
|
1950
|
+
...n?.body
|
|
1951
|
+
},
|
|
1952
|
+
forkOf: t,
|
|
1953
|
+
parent: i
|
|
1954
|
+
});
|
|
1955
|
+
}
|
|
1956
|
+
async edit(t, n, r) {
|
|
1957
|
+
this._logger.trace("DefaultView.edit();", { messageId: t });
|
|
1958
|
+
let i = this._tree.getNode(t);
|
|
1959
|
+
if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, L.InvalidArgument, 400);
|
|
1960
|
+
let a = i.parentId;
|
|
1961
|
+
return this.send(n, {
|
|
1962
|
+
...r,
|
|
1963
|
+
body: {
|
|
1964
|
+
history: this._getHistoryBefore(t),
|
|
1965
|
+
...r?.body
|
|
1966
|
+
},
|
|
1967
|
+
forkOf: t,
|
|
1968
|
+
parent: a
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1971
|
+
async update(t, n, r) {
|
|
1972
|
+
if (this._closed) throw new e.ErrorInfo("unable to update; view is closed", L.InvalidArgument, 400);
|
|
1973
|
+
this._logger.trace("DefaultView.update();", {
|
|
1974
|
+
msgId: t,
|
|
1975
|
+
eventCount: n.length
|
|
1976
|
+
});
|
|
1977
|
+
let i = [{
|
|
1978
|
+
kind: "event",
|
|
1979
|
+
msgId: t,
|
|
1980
|
+
events: n
|
|
1981
|
+
}];
|
|
1982
|
+
return this._sendDelegate([], r, this.flattenNodes(), i);
|
|
1983
|
+
}
|
|
1984
|
+
_getHistoryBefore(e) {
|
|
1985
|
+
this._logger.trace("DefaultView._getHistoryBefore();", { messageId: e });
|
|
1986
|
+
let t = this.flattenNodes(), n = t.findIndex((t) => t.msgId === e);
|
|
1987
|
+
return n === -1 ? (this._logger.warn("DefaultView._getHistoryBefore(); target not in visible nodes, returning full list", { messageId: e }), t) : t.slice(0, n);
|
|
1988
|
+
}
|
|
1989
|
+
getActiveTurnIds() {
|
|
1990
|
+
this._logger.trace("DefaultView.getActiveTurnIds();");
|
|
1991
|
+
let e = this._tree.getActiveTurnIds();
|
|
1992
|
+
if (this._withheldMsgIds.size === 0) return e;
|
|
1993
|
+
let t = /* @__PURE__ */ new Map();
|
|
1994
|
+
for (let [n, r] of e) {
|
|
1995
|
+
let e = /* @__PURE__ */ new Set();
|
|
1996
|
+
for (let t of r) this._lastVisibleTurnIds.has(t) && e.add(t);
|
|
1997
|
+
e.size > 0 && t.set(n, e);
|
|
1998
|
+
}
|
|
1999
|
+
return t;
|
|
2000
|
+
}
|
|
2001
|
+
on(e, t) {
|
|
2002
|
+
let n = t;
|
|
2003
|
+
return this._emitter.on(e, n), () => {
|
|
2004
|
+
this._emitter.off(e, n);
|
|
2005
|
+
};
|
|
2006
|
+
}
|
|
2007
|
+
close() {
|
|
2008
|
+
this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
|
|
2009
|
+
for (let e of this._unsubs) e();
|
|
2010
|
+
this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._withheldMsgIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
|
|
2011
|
+
}
|
|
2012
|
+
async _loadFirstPage(e) {
|
|
2013
|
+
let t = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), n = await nt(this._channel, this._codec, { limit: e }, this._logger);
|
|
2014
|
+
if (this._closed) return;
|
|
2015
|
+
let { newVisible: r, lastPage: i } = await this._loadUntilVisible(n, e, t);
|
|
2016
|
+
if (this._closed) return;
|
|
2017
|
+
this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
|
|
2018
|
+
let a = r.slice(-e), o = r.slice(0, -e);
|
|
2019
|
+
for (let e of o) this._withheldMsgIds.add(e.msgId);
|
|
2020
|
+
this._withheldBuffer.push(...o), this._releaseWithheld(a);
|
|
2021
|
+
}
|
|
2022
|
+
async _loadAndReveal(e, t) {
|
|
2023
|
+
let n = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
|
|
2024
|
+
if (this._closed) return;
|
|
2025
|
+
this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
|
|
2026
|
+
let a = r.slice(-t), o = r.slice(0, -t);
|
|
2027
|
+
for (let e of o) this._withheldMsgIds.add(e.msgId);
|
|
2028
|
+
this._withheldBuffer.push(...o), this._releaseWithheld(a);
|
|
2029
|
+
}
|
|
2030
|
+
_processHistoryPage(e) {
|
|
2031
|
+
this._processingHistory = !0;
|
|
1708
2032
|
try {
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
2033
|
+
for (let t of e.items) {
|
|
2034
|
+
let e = t.headers[c];
|
|
2035
|
+
e && this._tree.upsert(e, t.message, t.headers, t.serial);
|
|
2036
|
+
}
|
|
2037
|
+
for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
|
|
2038
|
+
} finally {
|
|
2039
|
+
this._processingHistory = !1;
|
|
1712
2040
|
}
|
|
1713
|
-
return this._isTerminal(t) && this.closeStream(e), !0;
|
|
1714
2041
|
}
|
|
1715
|
-
|
|
1716
|
-
|
|
2042
|
+
async _loadUntilVisible(e, t, n) {
|
|
2043
|
+
this._processHistoryPage(e);
|
|
2044
|
+
let r = e, i = () => {
|
|
2045
|
+
let e = 0;
|
|
2046
|
+
for (let t of this._tree.flattenNodes(this._resolveSelections())) n.has(t.msgId) || e++;
|
|
2047
|
+
return e;
|
|
2048
|
+
};
|
|
2049
|
+
for (; i() < t && r.hasNext();) {
|
|
2050
|
+
let e = await r.next();
|
|
2051
|
+
if (!e || this._closed) break;
|
|
2052
|
+
this._processHistoryPage(e), r = e;
|
|
2053
|
+
}
|
|
2054
|
+
return {
|
|
2055
|
+
newVisible: this._tree.flattenNodes(this._resolveSelections()).filter((e) => !n.has(e.msgId)),
|
|
2056
|
+
lastPage: r
|
|
2057
|
+
};
|
|
1717
2058
|
}
|
|
1718
|
-
|
|
2059
|
+
_releaseWithheld(e) {
|
|
2060
|
+
for (let t of e) this._withheldMsgIds.delete(t.msgId);
|
|
2061
|
+
e.length > 0 && (this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
|
|
2062
|
+
}
|
|
2063
|
+
_updateVisibleSnapshot(e) {
|
|
2064
|
+
let t = e ?? this.flattenNodes();
|
|
2065
|
+
this._lastVisibleIds = t.map((e) => e.msgId), this._lastVisibleMessages = t.map((e) => e.message), this._lastVisibleTurnIds = /* @__PURE__ */ new Set();
|
|
2066
|
+
for (let e of t) {
|
|
2067
|
+
let t = e.headers[s];
|
|
2068
|
+
t && this._lastVisibleTurnIds.add(t);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
_onTreeUpdate() {
|
|
2072
|
+
if (this._processingHistory) return;
|
|
2073
|
+
let e = this._tree.structuralVersion;
|
|
2074
|
+
if (e === this._lastStructuralVersion) {
|
|
2075
|
+
this._cachedNodes.some((e, t) => e.message !== this._lastVisibleMessages[t]) && (this._lastVisibleMessages = this._cachedNodes.map((e) => e.message), this._cachedNodes = [...this._cachedNodes], this._emitter.emit("update"));
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
this._lastStructuralVersion = e, this._pinBranchSelections(), this._resolvePendingSelections();
|
|
2079
|
+
let t = this._computeFlatNodes(), n = t.map((e) => e.msgId), r = t.map((e) => e.message);
|
|
2080
|
+
this._visibleChanged(n, r) && (this._cachedNodes = t, this._updateVisibleSnapshot(t), this._emitter.emit("update"));
|
|
2081
|
+
}
|
|
2082
|
+
_resolveSelections() {
|
|
2083
|
+
let e = /* @__PURE__ */ new Map();
|
|
2084
|
+
for (let [t, n] of this._branchSelections) n.kind !== "pending" && e.set(t, n.selectedId);
|
|
2085
|
+
return e;
|
|
2086
|
+
}
|
|
2087
|
+
_pinBranchSelections() {
|
|
2088
|
+
for (let e of this._lastVisibleIds) {
|
|
2089
|
+
if (!this._tree.hasSiblings(e)) continue;
|
|
2090
|
+
let t = this._tree.getGroupRoot(e), n = this._branchSelections.get(t);
|
|
2091
|
+
if (n?.kind === "pending") {
|
|
2092
|
+
let r = this._tree.getSiblingNodes(e).at(-1);
|
|
2093
|
+
r && r.msgId !== e && r.headers["x-ably-turn-id"] === n.turnId && (this._logger.debug("DefaultView._pinBranchSelections(); auto-selecting pending fork", {
|
|
2094
|
+
msgId: e,
|
|
2095
|
+
newestId: r.msgId,
|
|
2096
|
+
turnId: n.turnId
|
|
2097
|
+
}), this._branchSelections.set(t, {
|
|
2098
|
+
kind: "auto",
|
|
2099
|
+
selectedId: r.msgId
|
|
2100
|
+
}));
|
|
2101
|
+
continue;
|
|
2102
|
+
}
|
|
2103
|
+
n || this._branchSelections.set(t, {
|
|
2104
|
+
kind: "pinned",
|
|
2105
|
+
selectedId: e
|
|
2106
|
+
});
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
_resolvePendingSelections() {
|
|
2110
|
+
for (let [e, t] of this._branchSelections) {
|
|
2111
|
+
if (t.kind !== "pending") continue;
|
|
2112
|
+
let n = this._tree.getSiblingNodes(e);
|
|
2113
|
+
if (n.length <= 1) continue;
|
|
2114
|
+
let r = n.at(-1);
|
|
2115
|
+
!r || r.msgId === e || r.headers["x-ably-turn-id"] === t.turnId && (this._logger.debug("DefaultView._resolvePendingSelections(); resolving off-branch pending", {
|
|
2116
|
+
groupRoot: e,
|
|
2117
|
+
newestId: r.msgId,
|
|
2118
|
+
turnId: t.turnId
|
|
2119
|
+
}), this._branchSelections.set(e, {
|
|
2120
|
+
kind: "auto",
|
|
2121
|
+
selectedId: r.msgId
|
|
2122
|
+
}));
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
_onTreeAblyMessage(e) {
|
|
2126
|
+
let t = C(e)[c];
|
|
2127
|
+
if (!t) {
|
|
2128
|
+
this._emitter.emit("ably-message", e);
|
|
2129
|
+
return;
|
|
2130
|
+
}
|
|
2131
|
+
this._lastVisibleIds.includes(t) && this._emitter.emit("ably-message", e);
|
|
2132
|
+
}
|
|
2133
|
+
_onTreeTurn(e) {
|
|
2134
|
+
if (this._lastVisibleTurnIds.has(e.turnId)) {
|
|
2135
|
+
this._emitter.emit("turn", e);
|
|
2136
|
+
return;
|
|
2137
|
+
}
|
|
2138
|
+
e.type === "x-ably-turn-start" && this._isTurnStartVisible(e) && (this._lastVisibleTurnIds.add(e.turnId), this._emitter.emit("turn", e));
|
|
2139
|
+
}
|
|
2140
|
+
_isTurnStartVisible(e) {
|
|
2141
|
+
let { parent: t } = e;
|
|
2142
|
+
return t === void 0 ? !0 : this._lastVisibleIds.includes(t);
|
|
2143
|
+
}
|
|
2144
|
+
_visibleChanged(e, t) {
|
|
2145
|
+
if (e.length !== this._lastVisibleIds.length) return !0;
|
|
2146
|
+
for (let [t, n] of e.entries()) if (n !== this._lastVisibleIds[t]) return !0;
|
|
2147
|
+
for (let [e, n] of t.entries()) if (n !== this._lastVisibleMessages[e]) return !0;
|
|
2148
|
+
return !1;
|
|
2149
|
+
}
|
|
2150
|
+
}, J = (e) => new rt(e), it = () => {}, Y = /* @__PURE__ */ function(e) {
|
|
2151
|
+
return e.READY = "ready", e.CLOSED = "closed", e;
|
|
2152
|
+
}(Y || {}), at = class {
|
|
1719
2153
|
constructor(e) {
|
|
1720
|
-
if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this.
|
|
2154
|
+
if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this._turnMsgIds = /* @__PURE__ */ new Map(), this._turnObservers = /* @__PURE__ */ new Map(), this._closeResolvers = [], this._views = /* @__PURE__ */ new Set(), this._state = Y.READY, this._pendingLocalEvents = [], this._channel = e.channel, this._codec = e.codec, this._clientId = e.clientId, this._api = e.api, 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 ?? Je({ logLevel: V.Silent })).withContext({ component: "ClientTransport" }), this._emitter = new B(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = $e(this._logger), this._view = J({
|
|
2155
|
+
tree: this._tree,
|
|
2156
|
+
channel: this._channel,
|
|
2157
|
+
codec: this._codec,
|
|
2158
|
+
sendDelegate: this._internalSend.bind(this),
|
|
2159
|
+
logger: this._logger,
|
|
2160
|
+
onClose: () => this._views.delete(this._view)
|
|
2161
|
+
}), this._router = Ze(this._codec.isTerminal.bind(this._codec), this._logger), this._decoder = this._codec.createDecoder(), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
|
|
1721
2162
|
let t;
|
|
1722
2163
|
for (let n of e.messages) {
|
|
1723
|
-
let e =
|
|
1724
|
-
t && (r[
|
|
2164
|
+
let e = crypto.randomUUID(), r = { [c]: e };
|
|
2165
|
+
t && (r[g] = t), this._tree.upsert(e, n, r), t = e;
|
|
1725
2166
|
}
|
|
1726
|
-
this._emitter.emit("message");
|
|
1727
2167
|
}
|
|
1728
2168
|
this._onMessage = (e) => {
|
|
1729
2169
|
this._handleMessage(e);
|
|
1730
|
-
}, this._attachPromise = this._channel.subscribe(this._onMessage)
|
|
2170
|
+
}, this._attachPromise = this._channel.subscribe(this._onMessage), this._onChannelStateChange = (e) => {
|
|
2171
|
+
this._handleChannelStateChange(e);
|
|
2172
|
+
}, this._channel.on(this._onChannelStateChange);
|
|
1731
2173
|
}
|
|
1732
2174
|
_handleMessage(t) {
|
|
1733
|
-
if (
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
if (
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
2175
|
+
if (this._state !== Y.CLOSED) try {
|
|
2176
|
+
if (t.name === "x-ably-turn-start") {
|
|
2177
|
+
let e = C(t), n = e[s], r = e["x-ably-turn-client-id"] ?? "";
|
|
2178
|
+
if (n) {
|
|
2179
|
+
this._tree.trackTurn(n, r);
|
|
2180
|
+
let t = e[g], i = e[_];
|
|
2181
|
+
this._tree.emitTurn({
|
|
2182
|
+
type: b,
|
|
1740
2183
|
turnId: n,
|
|
1741
|
-
clientId: r
|
|
1742
|
-
|
|
1743
|
-
|
|
2184
|
+
clientId: r,
|
|
2185
|
+
...t !== void 0 && { parent: t },
|
|
2186
|
+
...i !== void 0 && { forkOf: i }
|
|
2187
|
+
});
|
|
1744
2188
|
}
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
turnId: n,
|
|
1757
|
-
clientId: r,
|
|
1758
|
-
reason: i
|
|
1759
|
-
});
|
|
2189
|
+
this._tree.emitAblyMessage(t);
|
|
2190
|
+
return;
|
|
2191
|
+
}
|
|
2192
|
+
if (t.name === "x-ably-turn-end") {
|
|
2193
|
+
let e = C(t), n = e[s], r = e["x-ably-turn-client-id"] ?? "", i = e["x-ably-turn-reason"] ?? "complete";
|
|
2194
|
+
if (n) {
|
|
2195
|
+
this._router.closeStream(n), this._turnObservers.delete(n), this._tree.untrackTurn(n);
|
|
2196
|
+
let e = this._turnMsgIds.get(n);
|
|
2197
|
+
if (e) {
|
|
2198
|
+
for (let t of e) this._ownMsgIds.delete(t);
|
|
2199
|
+
this._turnMsgIds.delete(n);
|
|
1760
2200
|
}
|
|
1761
|
-
|
|
2201
|
+
this._ownTurnIds.delete(n), this._tree.emitTurn({
|
|
2202
|
+
type: x,
|
|
2203
|
+
turnId: n,
|
|
2204
|
+
clientId: r,
|
|
2205
|
+
reason: i
|
|
2206
|
+
});
|
|
1762
2207
|
}
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
2208
|
+
this._tree.emitAblyMessage(t);
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
let e = this._decoder.decode(t), n = C(t), r = t.serial, i = n[d];
|
|
2212
|
+
if (i) {
|
|
2213
|
+
for (let t of e) t.kind === "event" && this._handleAmendmentEvent(i, t);
|
|
2214
|
+
return;
|
|
1769
2215
|
}
|
|
2216
|
+
let a = n[s];
|
|
2217
|
+
a && this._updateTurnObserverHeaders(a, n, r);
|
|
2218
|
+
for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
|
|
2219
|
+
this._tree.emitAblyMessage(t);
|
|
2220
|
+
} catch (t) {
|
|
2221
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
2222
|
+
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, L.TransportSubscriptionError, 500, n));
|
|
1770
2223
|
}
|
|
1771
2224
|
}
|
|
1772
2225
|
_handleMessageOutput(e, t, n, r) {
|
|
1773
|
-
let i = t[
|
|
2226
|
+
let i = t[c];
|
|
1774
2227
|
if (i && this._ownMsgIds.has(i)) {
|
|
1775
2228
|
this._upsertAndNotify(e, t, n);
|
|
1776
2229
|
return;
|
|
@@ -1779,7 +2232,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1779
2232
|
}
|
|
1780
2233
|
_handleEventOutput(e, t) {
|
|
1781
2234
|
if (e.kind !== "event") return;
|
|
1782
|
-
let n = e.event, r = t[
|
|
2235
|
+
let n = e.event, r = t[s];
|
|
1783
2236
|
if (r) {
|
|
1784
2237
|
if (this._router.route(r, n)) {
|
|
1785
2238
|
this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
|
|
@@ -1788,9 +2241,38 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1788
2241
|
this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
|
|
1789
2242
|
}
|
|
1790
2243
|
}
|
|
2244
|
+
_handleAmendmentEvent(e, t) {
|
|
2245
|
+
this._logger.trace("ClientTransport._handleAmendmentEvent();", { targetMsgId: e });
|
|
2246
|
+
let n = this._tree.getNode(e);
|
|
2247
|
+
if (!n) {
|
|
2248
|
+
this._logger.debug("ClientTransport._handleAmendmentEvent(); target not found, dropping", { targetMsgId: e });
|
|
2249
|
+
return;
|
|
2250
|
+
}
|
|
2251
|
+
let r = this._codec.createAccumulator();
|
|
2252
|
+
r.initMessage(e, n.message), r.processOutputs([t]);
|
|
2253
|
+
let i = r.messages.at(-1);
|
|
2254
|
+
i && this._tree.upsert(e, i, n.headers, n.serial);
|
|
2255
|
+
}
|
|
2256
|
+
_handleChannelStateChange(t) {
|
|
2257
|
+
if (this._state === Y.CLOSED) return;
|
|
2258
|
+
let { current: n, resumed: r } = t;
|
|
2259
|
+
if (n === "attached" && !this._hasAttachedOnce) {
|
|
2260
|
+
this._hasAttachedOnce = !0;
|
|
2261
|
+
return;
|
|
2262
|
+
}
|
|
2263
|
+
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
2264
|
+
this._logger.error("ClientTransport._handleChannelStateChange(); channel continuity lost", {
|
|
2265
|
+
current: n,
|
|
2266
|
+
resumed: r,
|
|
2267
|
+
previous: t.previous
|
|
2268
|
+
});
|
|
2269
|
+
let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, L.ChannelContinuityLost, 500, t.reason);
|
|
2270
|
+
for (let e of this._ownTurnIds) this._router.errorStream(e, i);
|
|
2271
|
+
this._emitter.emit("error", i);
|
|
2272
|
+
}
|
|
1791
2273
|
_upsertAndNotify(e, t, n) {
|
|
1792
|
-
let r =
|
|
1793
|
-
this._tree.upsert(
|
|
2274
|
+
let r = t[c];
|
|
2275
|
+
r && this._tree.upsert(r, e, t, n);
|
|
1794
2276
|
}
|
|
1795
2277
|
_updateTurnObserverHeaders(e, t, n) {
|
|
1796
2278
|
let r = this._turnObservers.get(e);
|
|
@@ -1803,321 +2285,289 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1803
2285
|
_accumulateAndEmit(e, t) {
|
|
1804
2286
|
let n = this._turnObservers.get(e);
|
|
1805
2287
|
if (!n) return;
|
|
2288
|
+
let r = n.headers[c];
|
|
2289
|
+
if (r) {
|
|
2290
|
+
let e = this._tree.getNode(r);
|
|
2291
|
+
e && n.accumulator.initMessage(r, e.message);
|
|
2292
|
+
}
|
|
1806
2293
|
n.accumulator.processOutputs([t]);
|
|
1807
|
-
let
|
|
1808
|
-
if (
|
|
1809
|
-
let
|
|
2294
|
+
let i = n.accumulator.messages;
|
|
2295
|
+
if (i.length === 0) return;
|
|
2296
|
+
let a;
|
|
1810
2297
|
try {
|
|
1811
|
-
|
|
2298
|
+
a = structuredClone(i.at(-1));
|
|
1812
2299
|
} catch {
|
|
1813
|
-
|
|
2300
|
+
a = i.at(-1);
|
|
2301
|
+
}
|
|
2302
|
+
if (a) {
|
|
2303
|
+
let e = n.headers[c];
|
|
2304
|
+
e && this._tree.upsert(e, a, { ...n.headers }, n.serial);
|
|
1814
2305
|
}
|
|
1815
|
-
i && (this._tree.upsert(n.headers["x-ably-msg-id"] ?? this._codec.getMessageKey(i), i, { ...n.headers }, n.serial), this._emitter.emit("message"));
|
|
1816
2306
|
}
|
|
1817
2307
|
async _publishCancel(e) {
|
|
1818
2308
|
this._logger.trace("ClientTransport._publishCancel();", { filter: e });
|
|
1819
2309
|
let t = {};
|
|
1820
|
-
e.turnId ? t[
|
|
1821
|
-
name:
|
|
2310
|
+
e.turnId ? t[f] = e.turnId : e.own ? t[p] = "true" : e.clientId ? t[h] = e.clientId : e.all && (t[m] = "true"), await this._channel.publish({
|
|
2311
|
+
name: y,
|
|
1822
2312
|
extras: { headers: t }
|
|
1823
2313
|
});
|
|
1824
2314
|
}
|
|
1825
2315
|
_closeMatchingTurnStreams(e) {
|
|
1826
|
-
|
|
1827
|
-
else if (e.own) for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
1828
|
-
else if (e.clientId) for (let [t, n] of this._turnClientIds) n === e.clientId && this._router.closeStream(t);
|
|
1829
|
-
else e.turnId && this._router.closeStream(e.turnId);
|
|
2316
|
+
for (let t of this._getMatchingTurnIds(e)) this._router.closeStream(t);
|
|
1830
2317
|
}
|
|
1831
2318
|
_getMatchingTurnIds(e) {
|
|
1832
|
-
let t = /* @__PURE__ */ new Set();
|
|
1833
|
-
if (e.all) for (let e of
|
|
1834
|
-
else if (e.own)
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
_getHistoryBefore(e) {
|
|
1846
|
-
let t = this._getMessagesWithHeaders(), n = t.findIndex((t) => t.headers?.[o] === e);
|
|
1847
|
-
return n === -1 ? t : t.slice(0, n);
|
|
1848
|
-
}
|
|
1849
|
-
_processHistoryPage(e) {
|
|
1850
|
-
for (let [t, n] of e.items.entries()) {
|
|
1851
|
-
let r = e.itemHeaders?.[t] ?? {}, i = e.itemSerials?.[t], a = this._codec.getMessageKey(n), o = r["x-ably-msg-id"] ?? a;
|
|
1852
|
-
this._tree.upsert(o, n, r, i);
|
|
1853
|
-
}
|
|
1854
|
-
this._emitter.emit("message"), e.rawMessages && e.rawMessages.length > 0 && (this._ablyMessages.unshift(...e.rawMessages), this._emitter.emit("ably-message"));
|
|
1855
|
-
}
|
|
1856
|
-
async _loadUntilVisible(e, t, n) {
|
|
1857
|
-
this._processHistoryPage(e);
|
|
1858
|
-
let r = e, i = () => {
|
|
1859
|
-
let e = 0;
|
|
1860
|
-
for (let t of this._tree.flatten()) n.has(this._codec.getMessageKey(t)) || e++;
|
|
1861
|
-
return e;
|
|
1862
|
-
};
|
|
1863
|
-
for (; i() < t && r.hasNext();) {
|
|
1864
|
-
let e = await r.next();
|
|
1865
|
-
if (!e) break;
|
|
1866
|
-
this._processHistoryPage(e), r = e;
|
|
2319
|
+
let t = /* @__PURE__ */ new Set(), n = this._tree.getActiveTurnIds();
|
|
2320
|
+
if (e.all) for (let e of n.values()) for (let n of e) t.add(n);
|
|
2321
|
+
else if (e.own) {
|
|
2322
|
+
let e = n.get(this._clientId ?? "");
|
|
2323
|
+
if (e) for (let n of e) t.add(n);
|
|
2324
|
+
} else if (e.clientId) {
|
|
2325
|
+
let r = n.get(e.clientId);
|
|
2326
|
+
if (r) for (let e of r) t.add(e);
|
|
2327
|
+
} else if (e.turnId) {
|
|
2328
|
+
for (let r of n.values()) if (r.has(e.turnId)) {
|
|
2329
|
+
t.add(e.turnId);
|
|
2330
|
+
break;
|
|
2331
|
+
}
|
|
1867
2332
|
}
|
|
1868
|
-
return
|
|
1869
|
-
newVisible: this._tree.flatten().filter((e) => !n.has(this._codec.getMessageKey(e))),
|
|
1870
|
-
lastPage: r
|
|
1871
|
-
};
|
|
1872
|
-
}
|
|
1873
|
-
_releaseWithheld(e) {
|
|
1874
|
-
for (let t of e) this._withheldKeys.delete(this._codec.getMessageKey(t));
|
|
1875
|
-
e.length > 0 && this._emitter.emit("message");
|
|
2333
|
+
return t;
|
|
1876
2334
|
}
|
|
1877
|
-
|
|
1878
|
-
if (this.
|
|
1879
|
-
this._logger.trace("
|
|
1880
|
-
let
|
|
1881
|
-
|
|
1882
|
-
|
|
2335
|
+
createView() {
|
|
2336
|
+
if (this._state === Y.CLOSED) throw new e.ErrorInfo("unable to create view; transport is closed", L.TransportClosed, 400);
|
|
2337
|
+
this._logger.trace("DefaultClientTransport.createView();");
|
|
2338
|
+
let t = J({
|
|
2339
|
+
tree: this._tree,
|
|
2340
|
+
channel: this._channel,
|
|
2341
|
+
codec: this._codec,
|
|
2342
|
+
sendDelegate: this._internalSend.bind(this),
|
|
2343
|
+
logger: this._logger,
|
|
2344
|
+
onClose: () => this._views.delete(t)
|
|
2345
|
+
});
|
|
2346
|
+
return this._views.add(t), t;
|
|
2347
|
+
}
|
|
2348
|
+
async _internalSend(t, n, r, i) {
|
|
2349
|
+
if (this._state === Y.CLOSED || (await this._attachPromise, this._state === Y.CLOSED)) throw new e.ErrorInfo("unable to send; transport is closed", L.TransportClosed, 400);
|
|
2350
|
+
let a = this._channel.state;
|
|
2351
|
+
if (a !== "attached" && a !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${a}`, L.ChannelNotReady, 400);
|
|
2352
|
+
this._logger.trace("ClientTransport._internalSend();");
|
|
2353
|
+
let o = Array.isArray(t) ? t : [t], s = crypto.randomUUID();
|
|
2354
|
+
this._ownTurnIds.add(s), this._tree.trackTurn(s, this._clientId ?? "");
|
|
2355
|
+
let c = this._pendingLocalEvents;
|
|
2356
|
+
this._pendingLocalEvents = [], i && i.length > 0 && this._applyEventsToTree(i);
|
|
2357
|
+
let l = [...c, ...i ?? []], u = /* @__PURE__ */ new Set(), d = [], f = r, p;
|
|
1883
2358
|
if (n?.parent === void 0 && !n?.forkOf) {
|
|
1884
|
-
let e =
|
|
1885
|
-
|
|
1886
|
-
let t = e.at(-1);
|
|
1887
|
-
if (t) {
|
|
1888
|
-
let e = this._codec.getMessageKey(t);
|
|
1889
|
-
u = this._tree.getNodeByKey(e)?.msgId ?? e;
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
2359
|
+
let e = f.at(-1);
|
|
2360
|
+
e && (p = e.msgId);
|
|
1892
2361
|
}
|
|
1893
|
-
let
|
|
1894
|
-
for (let e of
|
|
2362
|
+
let m = n?.parent === void 0 ? p : n.parent;
|
|
2363
|
+
for (let e of o) {
|
|
1895
2364
|
let t = crypto.randomUUID();
|
|
1896
|
-
this._ownMsgIds.add(t),
|
|
1897
|
-
let r = n?.parent === void 0 ?
|
|
2365
|
+
this._ownMsgIds.add(t), u.add(t);
|
|
2366
|
+
let r = n?.parent === void 0 ? p : n.parent, i = W({
|
|
1898
2367
|
role: "user",
|
|
1899
|
-
turnId:
|
|
2368
|
+
turnId: s,
|
|
1900
2369
|
msgId: t,
|
|
1901
2370
|
turnClientId: this._clientId,
|
|
1902
2371
|
parent: r,
|
|
1903
2372
|
forkOf: n?.forkOf
|
|
1904
2373
|
});
|
|
1905
|
-
this._upsertAndNotify(e,
|
|
1906
|
-
|
|
1907
|
-
[o]: t,
|
|
1908
|
-
[c]: "user"
|
|
1909
|
-
};
|
|
1910
|
-
r && (d[p] = r), s.push({
|
|
2374
|
+
this._upsertAndNotify(e, i), d.push({
|
|
2375
|
+
kind: "message",
|
|
1911
2376
|
message: e,
|
|
1912
|
-
|
|
1913
|
-
|
|
2377
|
+
msgId: t,
|
|
2378
|
+
parentId: r,
|
|
2379
|
+
forkOf: n?.forkOf,
|
|
2380
|
+
headers: i,
|
|
2381
|
+
serial: void 0
|
|
2382
|
+
}), n?.parent === void 0 && !n?.forkOf && (p = t);
|
|
1914
2383
|
}
|
|
1915
|
-
this._turnMsgIds.set(
|
|
1916
|
-
let
|
|
2384
|
+
this._turnMsgIds.set(s, u);
|
|
2385
|
+
let h = this._router.createStream(s), g = this._headersFn?.() ?? {}, _ = {
|
|
1917
2386
|
...this._bodyFn?.() ?? {},
|
|
1918
|
-
history:
|
|
2387
|
+
history: f,
|
|
1919
2388
|
...n?.body,
|
|
1920
|
-
turnId:
|
|
2389
|
+
turnId: s,
|
|
1921
2390
|
clientId: this._clientId,
|
|
1922
|
-
messages:
|
|
2391
|
+
messages: d,
|
|
1923
2392
|
...n?.forkOf !== void 0 && { forkOf: n.forkOf },
|
|
1924
|
-
...
|
|
1925
|
-
|
|
1926
|
-
|
|
2393
|
+
...m !== void 0 && { parent: m },
|
|
2394
|
+
...l.length > 0 && { events: l }
|
|
2395
|
+
}, v = {
|
|
2396
|
+
...g,
|
|
1927
2397
|
...n?.headers
|
|
1928
2398
|
};
|
|
1929
2399
|
return this._fetchFn(this._api, {
|
|
1930
2400
|
method: "POST",
|
|
1931
2401
|
headers: {
|
|
1932
2402
|
"Content-Type": "application/json",
|
|
1933
|
-
...
|
|
2403
|
+
...v
|
|
1934
2404
|
},
|
|
1935
|
-
body: JSON.stringify(
|
|
2405
|
+
body: JSON.stringify(_),
|
|
1936
2406
|
...this._credentials ? { credentials: this._credentials } : {}
|
|
1937
2407
|
}).then((t) => {
|
|
1938
|
-
|
|
2408
|
+
if (!t.ok) {
|
|
2409
|
+
let n = new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(t.status)} ${t.statusText}`, L.TransportSendFailed, t.status);
|
|
2410
|
+
this._emitter.emit("error", n), this._router.errorStream(s, n);
|
|
2411
|
+
}
|
|
1939
2412
|
}).catch((t) => {
|
|
1940
|
-
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
1941
|
-
this._emitter.emit("error",
|
|
2413
|
+
let n = t instanceof e.ErrorInfo ? t : void 0, r = new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${t instanceof Error ? t.message : String(t)}`, L.TransportSendFailed, 500, n);
|
|
2414
|
+
this._emitter.emit("error", r), this._router.errorStream(s, r);
|
|
1942
2415
|
}), {
|
|
1943
|
-
stream:
|
|
1944
|
-
turnId:
|
|
1945
|
-
cancel: async () => this.cancel({ turnId:
|
|
2416
|
+
stream: h,
|
|
2417
|
+
turnId: s,
|
|
2418
|
+
cancel: async () => this.cancel({ turnId: s }),
|
|
2419
|
+
optimisticMsgIds: [...u]
|
|
1946
2420
|
};
|
|
1947
2421
|
}
|
|
1948
|
-
async regenerate(e, t) {
|
|
1949
|
-
this._logger.trace("ClientTransport.regenerate();", { messageId: e });
|
|
1950
|
-
let n = this._tree.getNode(e)?.parentId;
|
|
1951
|
-
return this.send([], {
|
|
1952
|
-
...t,
|
|
1953
|
-
body: {
|
|
1954
|
-
history: this._getHistoryBefore(e),
|
|
1955
|
-
...t?.body
|
|
1956
|
-
},
|
|
1957
|
-
forkOf: e,
|
|
1958
|
-
parent: n
|
|
1959
|
-
});
|
|
1960
|
-
}
|
|
1961
|
-
async edit(e, t, n) {
|
|
1962
|
-
this._logger.trace("ClientTransport.edit();", { messageId: e });
|
|
1963
|
-
let r = this._tree.getNode(e)?.parentId;
|
|
1964
|
-
return this.send(t, {
|
|
1965
|
-
...n,
|
|
1966
|
-
body: {
|
|
1967
|
-
history: this._getHistoryBefore(e),
|
|
1968
|
-
...n?.body
|
|
1969
|
-
},
|
|
1970
|
-
forkOf: e,
|
|
1971
|
-
parent: r
|
|
1972
|
-
});
|
|
1973
|
-
}
|
|
1974
2422
|
async cancel(e) {
|
|
1975
|
-
if (this.
|
|
2423
|
+
if (this._state === Y.CLOSED) return;
|
|
1976
2424
|
let t = e ?? { own: !0 };
|
|
1977
2425
|
this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
|
|
1978
2426
|
}
|
|
2427
|
+
stageEvents(e, t) {
|
|
2428
|
+
if (this._logger.trace("ClientTransport.stageEvents();", {
|
|
2429
|
+
msgId: e,
|
|
2430
|
+
eventCount: t.length
|
|
2431
|
+
}), this._state === Y.CLOSED) {
|
|
2432
|
+
this._logger.warn("ClientTransport.stageEvents(); transport is closed", { msgId: e });
|
|
2433
|
+
return;
|
|
2434
|
+
}
|
|
2435
|
+
if (!this._tree.getNode(e)) {
|
|
2436
|
+
this._logger.warn("ClientTransport.stageEvents(); msgId not found in tree", { msgId: e });
|
|
2437
|
+
return;
|
|
2438
|
+
}
|
|
2439
|
+
if (t.length === 0) return;
|
|
2440
|
+
let n = {
|
|
2441
|
+
kind: "event",
|
|
2442
|
+
msgId: e,
|
|
2443
|
+
events: t
|
|
2444
|
+
};
|
|
2445
|
+
this._applyEventsToTree([n]), this._pendingLocalEvents.push(n);
|
|
2446
|
+
}
|
|
2447
|
+
stageMessage(e, t) {
|
|
2448
|
+
if (this._logger.trace("ClientTransport.stageMessage();", { msgId: e }), this._state === Y.CLOSED) {
|
|
2449
|
+
this._logger.warn("ClientTransport.stageMessage(); transport is closed", { msgId: e });
|
|
2450
|
+
return;
|
|
2451
|
+
}
|
|
2452
|
+
let n = this._tree.getNode(e);
|
|
2453
|
+
if (!n) {
|
|
2454
|
+
this._logger.warn("ClientTransport.stageMessage(); msgId not found in tree", { msgId: e });
|
|
2455
|
+
return;
|
|
2456
|
+
}
|
|
2457
|
+
this._tree.upsert(e, t, n.headers, n.serial);
|
|
2458
|
+
}
|
|
2459
|
+
_applyEventsToTree(e) {
|
|
2460
|
+
for (let t of e) {
|
|
2461
|
+
let e = this._tree.getNode(t.msgId);
|
|
2462
|
+
if (!e) continue;
|
|
2463
|
+
let n = t.events.map((e) => ({
|
|
2464
|
+
kind: "event",
|
|
2465
|
+
event: e,
|
|
2466
|
+
messageId: t.msgId
|
|
2467
|
+
})), r = this._codec.createAccumulator();
|
|
2468
|
+
r.initMessage(t.msgId, e.message), r.processOutputs(n);
|
|
2469
|
+
let i = r.messages.at(-1);
|
|
2470
|
+
i && this._tree.upsert(t.msgId, i, e.headers, e.serial);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
1979
2473
|
async waitForTurn(e) {
|
|
1980
|
-
if (this.
|
|
2474
|
+
if (this._state === Y.CLOSED) return;
|
|
1981
2475
|
let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
|
|
1982
2476
|
if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
|
|
1983
|
-
let t = (
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
2477
|
+
let t = !1, r = () => {
|
|
2478
|
+
if (t) return;
|
|
2479
|
+
t = !0, i();
|
|
2480
|
+
let n = this._closeResolvers.indexOf(r);
|
|
2481
|
+
n !== -1 && this._closeResolvers.splice(n, 1), e();
|
|
2482
|
+
}, i = this._tree.on("turn", (e) => {
|
|
2483
|
+
e.type === "x-ably-turn-end" && (n.delete(e.turnId), n.size === 0 && r());
|
|
2484
|
+
});
|
|
2485
|
+
this._closeResolvers.push(r);
|
|
1987
2486
|
});
|
|
1988
2487
|
}
|
|
1989
2488
|
on(e, t) {
|
|
1990
|
-
if (this.
|
|
2489
|
+
if (this._state === Y.CLOSED) return it;
|
|
1991
2490
|
let n = t;
|
|
1992
2491
|
return this._emitter.on(e, n), () => {
|
|
1993
2492
|
this._emitter.off(e, n);
|
|
1994
2493
|
};
|
|
1995
2494
|
}
|
|
1996
|
-
getTree() {
|
|
1997
|
-
return this._tree;
|
|
1998
|
-
}
|
|
1999
|
-
getActiveTurnIds() {
|
|
2000
|
-
let e = /* @__PURE__ */ new Map();
|
|
2001
|
-
for (let [t, n] of this._turnClientIds) {
|
|
2002
|
-
let r = e.get(n);
|
|
2003
|
-
r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
|
|
2004
|
-
}
|
|
2005
|
-
return e;
|
|
2006
|
-
}
|
|
2007
|
-
getMessageHeaders(e) {
|
|
2008
|
-
let t = this._codec.getMessageKey(e);
|
|
2009
|
-
return this._tree.getNodeByKey(t)?.headers;
|
|
2010
|
-
}
|
|
2011
|
-
getMessages() {
|
|
2012
|
-
return this._withheldKeys.size === 0 ? this._tree.flatten() : this._tree.flatten().filter((e) => !this._withheldKeys.has(this._codec.getMessageKey(e)));
|
|
2013
|
-
}
|
|
2014
|
-
getMessagesWithHeaders() {
|
|
2015
|
-
return this._getMessagesWithHeaders();
|
|
2016
|
-
}
|
|
2017
|
-
getAblyMessages() {
|
|
2018
|
-
return [...this._ablyMessages];
|
|
2019
|
-
}
|
|
2020
|
-
async history(t) {
|
|
2021
|
-
if (this._closed) throw new e.ErrorInfo("unable to load history; transport is closed", W.TransportClosed, 400);
|
|
2022
|
-
this._logger.trace("ClientTransport.history();", { limit: t?.limit });
|
|
2023
|
-
let n = t?.limit ?? 100, r = new Set(this._tree.flatten().map((e) => this._codec.getMessageKey(e))), i = await Be(this._channel, this._codec, t, this._logger), a = await this._loadUntilVisible(i, n, r);
|
|
2024
|
-
i = a.lastPage;
|
|
2025
|
-
let o = a.newVisible;
|
|
2026
|
-
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
2027
|
-
let s = o.slice(-n), c = o.slice(0, -n);
|
|
2028
|
-
this._releaseWithheld(s);
|
|
2029
|
-
let l = (e) => ({
|
|
2030
|
-
items: e,
|
|
2031
|
-
hasNext: () => c.length > 0 || i.hasNext(),
|
|
2032
|
-
next: async () => {
|
|
2033
|
-
if (c.length > 0) {
|
|
2034
|
-
let e = c.splice(-n, n);
|
|
2035
|
-
return this._releaseWithheld(e), l(e);
|
|
2036
|
-
}
|
|
2037
|
-
if (!i.hasNext()) return;
|
|
2038
|
-
let e = await i.next();
|
|
2039
|
-
if (!e) return;
|
|
2040
|
-
let t = new Set(r);
|
|
2041
|
-
for (let e of this._tree.flatten()) t.add(this._codec.getMessageKey(e));
|
|
2042
|
-
let a = await this._loadUntilVisible(e, n, t);
|
|
2043
|
-
i = a.lastPage;
|
|
2044
|
-
let o = a.newVisible;
|
|
2045
|
-
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
2046
|
-
let s = o.splice(-n, n);
|
|
2047
|
-
if (c.push(...o), this._releaseWithheld(s), s.length !== 0) return l(s);
|
|
2048
|
-
}
|
|
2049
|
-
});
|
|
2050
|
-
return l(s);
|
|
2051
|
-
}
|
|
2052
2495
|
async close(e) {
|
|
2053
|
-
if (
|
|
2054
|
-
if (this.
|
|
2496
|
+
if (this._state !== Y.CLOSED) {
|
|
2497
|
+
if (this._state = Y.CLOSED, this._logger.info("ClientTransport.close();"), e?.cancel) {
|
|
2055
2498
|
try {
|
|
2056
2499
|
await this._publishCancel(e.cancel);
|
|
2057
2500
|
} catch {}
|
|
2058
2501
|
this._closeMatchingTurnStreams(e.cancel);
|
|
2059
2502
|
}
|
|
2060
|
-
this._channel.unsubscribe(this._onMessage);
|
|
2503
|
+
this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange);
|
|
2061
2504
|
for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
2062
|
-
this._turnObservers.clear(), this._emitter.off()
|
|
2505
|
+
this._turnObservers.clear(), this._emitter.off();
|
|
2506
|
+
for (let e of this._views) e.close();
|
|
2507
|
+
this._views.clear();
|
|
2508
|
+
for (let e of this._closeResolvers) e();
|
|
2509
|
+
this._closeResolvers.length = 0, this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear();
|
|
2063
2510
|
}
|
|
2064
2511
|
}
|
|
2065
|
-
},
|
|
2066
|
-
|
|
2067
|
-
let
|
|
2512
|
+
}, ot = (e) => new at(e), st = async (e, t, n, r, i, a) => {
|
|
2513
|
+
a?.trace("pipeStream();");
|
|
2514
|
+
let o = e.getReader(), s, c = n ? new Promise((e) => {
|
|
2068
2515
|
if (n.aborted) {
|
|
2069
2516
|
e();
|
|
2070
2517
|
return;
|
|
2071
2518
|
}
|
|
2072
|
-
|
|
2519
|
+
s = () => {
|
|
2073
2520
|
e();
|
|
2074
|
-
}, n.addEventListener("abort",
|
|
2075
|
-
}) : new Promise(() => {}),
|
|
2521
|
+
}, n.addEventListener("abort", s, { once: !0 });
|
|
2522
|
+
}) : new Promise(() => {}), l = "complete", u;
|
|
2076
2523
|
try {
|
|
2077
2524
|
for (;;) {
|
|
2078
|
-
let e = await Promise.race([
|
|
2525
|
+
let e = await Promise.race([o.read(), c.then(() => "aborted")]);
|
|
2079
2526
|
if (e === "aborted") {
|
|
2080
|
-
|
|
2527
|
+
l = "cancelled", a?.debug("pipeStream(); stream cancelled by abort signal"), r && await r(async (e) => t.appendEvent(e)), await t.abort("cancelled");
|
|
2081
2528
|
break;
|
|
2082
2529
|
}
|
|
2083
|
-
let { done: n, value:
|
|
2530
|
+
let { done: n, value: s } = e;
|
|
2084
2531
|
if (n) {
|
|
2085
|
-
await t.close(),
|
|
2532
|
+
await t.close(), a?.debug("pipeStream(); stream completed");
|
|
2086
2533
|
break;
|
|
2087
2534
|
}
|
|
2088
|
-
await t.appendEvent(
|
|
2535
|
+
await t.appendEvent(s, i?.(s));
|
|
2089
2536
|
}
|
|
2090
2537
|
} catch (e) {
|
|
2091
|
-
|
|
2092
|
-
let n = e instanceof Error ? e.message : String(e);
|
|
2093
|
-
i?.error("pipeStream(); stream error", { error: n });
|
|
2538
|
+
l = "error", u = e instanceof Error ? e : Error(String(e)), a?.error("pipeStream(); stream error", { error: u.message });
|
|
2094
2539
|
try {
|
|
2095
2540
|
await t.close();
|
|
2096
2541
|
} catch {}
|
|
2097
2542
|
} finally {
|
|
2098
|
-
|
|
2543
|
+
s && n?.removeEventListener("abort", s), o.releaseLock();
|
|
2099
2544
|
}
|
|
2100
|
-
return {
|
|
2101
|
-
|
|
2545
|
+
return {
|
|
2546
|
+
reason: l,
|
|
2547
|
+
error: u
|
|
2548
|
+
};
|
|
2549
|
+
}, ct = class {
|
|
2102
2550
|
constructor(e, t) {
|
|
2103
2551
|
this._activeTurns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "TurnManager" });
|
|
2104
2552
|
}
|
|
2105
|
-
async startTurn(e, t, n) {
|
|
2553
|
+
async startTurn(e, t, n, r) {
|
|
2106
2554
|
this._logger?.trace("DefaultTurnManager.startTurn();", {
|
|
2107
2555
|
turnId: e,
|
|
2108
2556
|
clientId: t
|
|
2109
2557
|
});
|
|
2110
|
-
let
|
|
2111
|
-
|
|
2112
|
-
controller:
|
|
2113
|
-
clientId:
|
|
2114
|
-
})
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2558
|
+
let i = n ?? new AbortController(), a = t ?? "";
|
|
2559
|
+
this._activeTurns.set(e, {
|
|
2560
|
+
controller: i,
|
|
2561
|
+
clientId: a
|
|
2562
|
+
});
|
|
2563
|
+
let o = {
|
|
2564
|
+
[s]: e,
|
|
2565
|
+
[l]: a
|
|
2566
|
+
};
|
|
2567
|
+
return r?.parent !== void 0 && (o[g] = r.parent), r?.forkOf !== void 0 && (o[_] = r.forkOf), await this._channel.publish({
|
|
2568
|
+
name: b,
|
|
2569
|
+
extras: { headers: o }
|
|
2570
|
+
}), this._logger?.debug("DefaultTurnManager.startTurn(); turn started", { turnId: e }), i.signal;
|
|
2121
2571
|
}
|
|
2122
2572
|
async endTurn(e, t) {
|
|
2123
2573
|
this._logger?.trace("DefaultTurnManager.endTurn();", {
|
|
@@ -2126,11 +2576,11 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
2126
2576
|
});
|
|
2127
2577
|
let n = this._activeTurns.get(e)?.clientId ?? "";
|
|
2128
2578
|
await this._channel.publish({
|
|
2129
|
-
name:
|
|
2579
|
+
name: x,
|
|
2130
2580
|
extras: { headers: {
|
|
2131
|
-
[
|
|
2132
|
-
[
|
|
2133
|
-
[
|
|
2581
|
+
[s]: e,
|
|
2582
|
+
[l]: n,
|
|
2583
|
+
[v]: t
|
|
2134
2584
|
} }
|
|
2135
2585
|
}), this._activeTurns.delete(e), this._logger?.debug("DefaultTurnManager.endTurn(); turn ended", {
|
|
2136
2586
|
turnId: e,
|
|
@@ -2154,30 +2604,38 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
2154
2604
|
for (let e of this._activeTurns.values()) e.controller.abort();
|
|
2155
2605
|
this._activeTurns.clear();
|
|
2156
2606
|
}
|
|
2157
|
-
},
|
|
2607
|
+
}, lt = (e, t) => new ct(e, t), X = /* @__PURE__ */ function(e) {
|
|
2608
|
+
return e.READY = "ready", e.CLOSED = "closed", e;
|
|
2609
|
+
}(X || {}), Z = /* @__PURE__ */ function(e) {
|
|
2610
|
+
return e.INITIALIZED = "initialized", e.STARTED = "started", e.ENDED = "ended", e;
|
|
2611
|
+
}(Z || {}), ut = class {
|
|
2158
2612
|
constructor(t) {
|
|
2159
|
-
this._registeredTurns = /* @__PURE__ */ new Map(), this._channel = t.channel, this._codec = t.codec, this._logger = t.logger?.withContext({ component: "ServerTransport" }), this._onError = t.onError, this._turnManager =
|
|
2613
|
+
this._registeredTurns = /* @__PURE__ */ new Map(), this._state = X.READY, this._channel = t.channel, this._codec = t.codec, this._logger = t.logger?.withContext({ component: "ServerTransport" }), this._onError = t.onError, this._turnManager = lt(this._channel, this._logger), this._channelListener = (e) => {
|
|
2160
2614
|
this._handleChannelMessage(e);
|
|
2161
|
-
}, this._attachPromise = this._channel.subscribe(
|
|
2162
|
-
let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`,
|
|
2615
|
+
}, this._attachPromise = this._channel.subscribe(y, this._channelListener).then(() => {}, (t) => {
|
|
2616
|
+
let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`, L.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2163
2617
|
this._logger?.error("DefaultServerTransport(); subscribe failed"), this._onError?.(n);
|
|
2164
|
-
}), this.
|
|
2618
|
+
}), this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
|
|
2619
|
+
this._handleChannelStateChange(e);
|
|
2620
|
+
}, this._channel.on(this._onChannelStateChange), this._logger?.debug("DefaultServerTransport(); transport created");
|
|
2165
2621
|
}
|
|
2166
2622
|
newTurn(e) {
|
|
2167
2623
|
return this._logger?.trace("DefaultServerTransport.newTurn();", { turnId: e.turnId }), this._createTurn(e);
|
|
2168
2624
|
}
|
|
2169
2625
|
close() {
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2626
|
+
if (this._state !== X.CLOSED) {
|
|
2627
|
+
this._state = X.CLOSED, this._logger?.trace("DefaultServerTransport.close();"), this._channel.unsubscribe(y, this._channelListener), this._channel.off(this._onChannelStateChange);
|
|
2628
|
+
for (let e of this._registeredTurns.values()) e.controller.abort();
|
|
2629
|
+
this._registeredTurns.clear(), this._turnManager.close(), this._logger?.debug("DefaultServerTransport.close(); transport closed");
|
|
2630
|
+
}
|
|
2173
2631
|
}
|
|
2174
2632
|
_resolveFilter(e, t) {
|
|
2175
2633
|
let n = [...this._registeredTurns.keys()];
|
|
2176
2634
|
return e.all ? n : e.own && t ? n.filter((e) => this._registeredTurns.get(e)?.clientId === t) : e.clientId ? n.filter((t) => this._registeredTurns.get(t)?.clientId === e.clientId) : e.turnId && this._registeredTurns.has(e.turnId) ? [e.turnId] : [];
|
|
2177
2635
|
}
|
|
2178
2636
|
async _handleCancelMessage(t) {
|
|
2179
|
-
let n =
|
|
2180
|
-
n["x-ably-cancel-turn-id"] ? r.turnId = n[
|
|
2637
|
+
let n = C(t), r = {};
|
|
2638
|
+
n["x-ably-cancel-turn-id"] ? r.turnId = n[f] : n["x-ably-cancel-own"] === "true" ? r.own = !0 : n["x-ably-cancel-client-id"] ? r.clientId = n[h] : n["x-ably-cancel-all"] === "true" && (r.all = !0);
|
|
2181
2639
|
let i = this._resolveFilter(r, t.clientId);
|
|
2182
2640
|
if (i.length === 0) return;
|
|
2183
2641
|
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); matched turns", {
|
|
@@ -2204,113 +2662,174 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
2204
2662
|
}
|
|
2205
2663
|
n.controller.abort(), this._logger?.debug("DefaultServerTransport._handleCancelMessage(); turn aborted", { turnId: t });
|
|
2206
2664
|
} catch (r) {
|
|
2207
|
-
let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`,
|
|
2665
|
+
let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`, L.CancelListenerError, 500, r instanceof e.ErrorInfo ? r : void 0);
|
|
2208
2666
|
this._logger?.error("DefaultServerTransport._handleCancelMessage(); onCancel threw", { turnId: t }), (n.onError ?? this._onError)?.(i);
|
|
2209
2667
|
}
|
|
2210
2668
|
}
|
|
2211
2669
|
}
|
|
2670
|
+
_handleChannelStateChange(t) {
|
|
2671
|
+
if (this._state === X.CLOSED) return;
|
|
2672
|
+
let { current: n, resumed: r } = t;
|
|
2673
|
+
if (n === "attached" && !this._hasAttachedOnce) {
|
|
2674
|
+
this._hasAttachedOnce = !0;
|
|
2675
|
+
return;
|
|
2676
|
+
}
|
|
2677
|
+
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
2678
|
+
this._logger?.error("DefaultServerTransport._handleChannelStateChange(); channel continuity lost", {
|
|
2679
|
+
current: n,
|
|
2680
|
+
resumed: r,
|
|
2681
|
+
previous: t.previous
|
|
2682
|
+
});
|
|
2683
|
+
let i = new e.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, L.ChannelContinuityLost, 500, t.reason);
|
|
2684
|
+
this._onError?.(i);
|
|
2685
|
+
}
|
|
2212
2686
|
_handleChannelMessage(t) {
|
|
2213
2687
|
try {
|
|
2214
2688
|
t.name === "x-ably-cancel" && this._handleCancelMessage(t).catch((t) => {
|
|
2215
|
-
let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`,
|
|
2689
|
+
let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, L.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2216
2690
|
this._logger?.error("DefaultServerTransport._handleChannelMessage(); cancel routing error"), this._onError?.(n);
|
|
2217
2691
|
});
|
|
2218
2692
|
} catch (t) {
|
|
2219
|
-
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`,
|
|
2693
|
+
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, L.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2220
2694
|
this._logger?.error("DefaultServerTransport._handleChannelMessage(); subscription error"), this._onError?.(n);
|
|
2221
2695
|
}
|
|
2222
2696
|
}
|
|
2223
2697
|
_createTurn(t) {
|
|
2224
|
-
let { turnId: n, clientId: r, onMessage: i, onAbort: a, onCancel: o, onError: s, parent: c, forkOf: l } = t,
|
|
2698
|
+
let { turnId: n, clientId: r, onMessage: i, onAbort: a, onCancel: o, onError: s, parent: c, forkOf: l, signal: u } = t, d = new AbortController(), f = Z.INITIALIZED, p = u ? AbortSignal.any([d.signal, u]) : d.signal, m = {
|
|
2225
2699
|
turnId: n,
|
|
2226
2700
|
clientId: r ?? "",
|
|
2227
|
-
controller:
|
|
2701
|
+
controller: d,
|
|
2702
|
+
signal: p,
|
|
2228
2703
|
onCancel: o,
|
|
2229
2704
|
onError: s
|
|
2230
2705
|
};
|
|
2231
|
-
this._registeredTurns.set(n,
|
|
2232
|
-
let
|
|
2706
|
+
this._registeredTurns.set(n, m);
|
|
2707
|
+
let h = this._logger, g = this._turnManager, _ = this._attachPromise, v = this._codec, y = this._channel, b = this._registeredTurns;
|
|
2233
2708
|
return {
|
|
2234
2709
|
get turnId() {
|
|
2235
2710
|
return n;
|
|
2236
2711
|
},
|
|
2237
2712
|
get abortSignal() {
|
|
2238
|
-
return
|
|
2713
|
+
return p;
|
|
2239
2714
|
},
|
|
2240
2715
|
start: async () => {
|
|
2241
|
-
if (
|
|
2242
|
-
if (
|
|
2243
|
-
|
|
2716
|
+
if (h?.trace("Turn.start();", { turnId: n }), p.aborted) throw new e.ErrorInfo(`unable to start turn; turn ${n} was cancelled before start()`, L.InvalidArgument, 400);
|
|
2717
|
+
if (f === Z.INITIALIZED) {
|
|
2718
|
+
f = Z.STARTED;
|
|
2244
2719
|
try {
|
|
2245
|
-
await
|
|
2720
|
+
await g.startTurn(n, r, d, {
|
|
2721
|
+
parent: c,
|
|
2722
|
+
forkOf: l
|
|
2723
|
+
});
|
|
2246
2724
|
} catch (t) {
|
|
2247
|
-
let r = new e.ErrorInfo(`unable to publish turn-start for turn ${n}; ${t instanceof Error ? t.message : String(t)}`,
|
|
2248
|
-
throw
|
|
2725
|
+
let r = new e.ErrorInfo(`unable to publish turn-start for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, L.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2726
|
+
throw h?.error("Turn.start(); failed to publish turn-start", { turnId: n }), r;
|
|
2249
2727
|
}
|
|
2250
|
-
|
|
2728
|
+
h?.debug("Turn.start(); turn started", { turnId: n });
|
|
2251
2729
|
}
|
|
2252
2730
|
},
|
|
2253
2731
|
addMessages: async (t, r) => {
|
|
2254
|
-
if (
|
|
2732
|
+
if (h?.trace("Turn.addMessages();", {
|
|
2255
2733
|
turnId: n,
|
|
2256
2734
|
count: t.length
|
|
2257
|
-
}),
|
|
2258
|
-
await
|
|
2735
|
+
}), f === Z.INITIALIZED) throw new e.ErrorInfo(`unable to add messages; start() must be called before addMessages() (turn ${n})`, L.InvalidArgument, 400);
|
|
2736
|
+
await _;
|
|
2259
2737
|
let a = [];
|
|
2260
|
-
|
|
2261
|
-
let
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2738
|
+
try {
|
|
2739
|
+
for (let e of t) {
|
|
2740
|
+
let t = T(W({
|
|
2741
|
+
role: "user",
|
|
2742
|
+
turnId: n,
|
|
2743
|
+
msgId: e.msgId,
|
|
2744
|
+
turnClientId: r?.clientId,
|
|
2745
|
+
parent: e.parentId ?? c,
|
|
2746
|
+
forkOf: e.forkOf ?? l
|
|
2747
|
+
}), e.headers);
|
|
2748
|
+
await v.createEncoder(y, {
|
|
2749
|
+
extras: { headers: t },
|
|
2750
|
+
onMessage: i
|
|
2751
|
+
}).writeMessages([e.message], r?.clientId ? { clientId: r.clientId } : void 0), a.push(e.msgId);
|
|
2752
|
+
}
|
|
2753
|
+
} catch (t) {
|
|
2754
|
+
let r = new e.ErrorInfo(`unable to publish messages for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, L.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2755
|
+
throw h?.error("Turn.addMessages(); publish failed", { turnId: n }), r;
|
|
2273
2756
|
}
|
|
2274
|
-
return
|
|
2757
|
+
return h?.debug("Turn.addMessages(); messages published", {
|
|
2275
2758
|
turnId: n,
|
|
2276
2759
|
count: t.length
|
|
2277
2760
|
}), { msgIds: a };
|
|
2278
2761
|
},
|
|
2762
|
+
addEvents: async (t) => {
|
|
2763
|
+
if (h?.trace("Turn.addEvents();", {
|
|
2764
|
+
turnId: n,
|
|
2765
|
+
count: t.length
|
|
2766
|
+
}), f === Z.INITIALIZED) throw new e.ErrorInfo(`unable to add events; start() must be called before addEvents() (turn ${n})`, L.InvalidArgument, 400);
|
|
2767
|
+
await _;
|
|
2768
|
+
let r = g.getClientId(n);
|
|
2769
|
+
try {
|
|
2770
|
+
for (let e of t) {
|
|
2771
|
+
let t = W({
|
|
2772
|
+
role: "assistant",
|
|
2773
|
+
turnId: n,
|
|
2774
|
+
msgId: e.msgId,
|
|
2775
|
+
turnClientId: r,
|
|
2776
|
+
amend: e.msgId
|
|
2777
|
+
}), a = v.createEncoder(y, {
|
|
2778
|
+
extras: { headers: t },
|
|
2779
|
+
onMessage: i
|
|
2780
|
+
});
|
|
2781
|
+
for (let t of e.events) await a.writeEvent(t);
|
|
2782
|
+
await a.close();
|
|
2783
|
+
}
|
|
2784
|
+
} catch (t) {
|
|
2785
|
+
let r = new e.ErrorInfo(`unable to publish events for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, L.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2786
|
+
throw h?.error("Turn.addEvents(); publish failed", { turnId: n }), r;
|
|
2787
|
+
}
|
|
2788
|
+
h?.debug("Turn.addEvents(); events published", {
|
|
2789
|
+
turnId: n,
|
|
2790
|
+
count: t.length
|
|
2791
|
+
});
|
|
2792
|
+
},
|
|
2279
2793
|
streamResponse: async (t, r) => {
|
|
2280
|
-
if (
|
|
2281
|
-
await
|
|
2282
|
-
let o =
|
|
2794
|
+
if (h?.trace("Turn.streamResponse();", { turnId: n }), f === Z.INITIALIZED) throw new e.ErrorInfo(`unable to stream response; start() must be called before streamResponse() (turn ${n})`, L.InvalidArgument, 400);
|
|
2795
|
+
await _;
|
|
2796
|
+
let o = g.getClientId(n), u = r?.parent === void 0 ? c : r.parent, d = crypto.randomUUID(), m = W({
|
|
2283
2797
|
role: "assistant",
|
|
2284
2798
|
turnId: n,
|
|
2285
|
-
msgId:
|
|
2286
|
-
turnClientId:
|
|
2799
|
+
msgId: d,
|
|
2800
|
+
turnClientId: o,
|
|
2287
2801
|
parent: u,
|
|
2288
2802
|
forkOf: r?.forkOf ?? l
|
|
2289
|
-
}),
|
|
2290
|
-
extras: { headers:
|
|
2291
|
-
onMessage: i
|
|
2292
|
-
|
|
2293
|
-
|
|
2803
|
+
}), b = await st(t, v.createEncoder(y, {
|
|
2804
|
+
extras: { headers: m },
|
|
2805
|
+
onMessage: i,
|
|
2806
|
+
messageId: d
|
|
2807
|
+
}), p, a, r?.resolveWriteOptions, h);
|
|
2808
|
+
if (b.error) {
|
|
2809
|
+
let t = new e.ErrorInfo(`unable to stream response for turn ${n}; ${b.error.message}`, L.StreamError, 500, b.error instanceof e.ErrorInfo ? b.error : void 0);
|
|
2810
|
+
h?.error("Turn.streamResponse(); stream error", { turnId: n }), s?.(t);
|
|
2811
|
+
}
|
|
2812
|
+
return h?.debug("Turn.streamResponse(); stream finished", {
|
|
2294
2813
|
turnId: n,
|
|
2295
|
-
reason:
|
|
2296
|
-
}),
|
|
2814
|
+
reason: b.reason
|
|
2815
|
+
}), b;
|
|
2297
2816
|
},
|
|
2298
2817
|
end: async (t) => {
|
|
2299
|
-
if (
|
|
2818
|
+
if (h?.trace("Turn.end();", {
|
|
2300
2819
|
turnId: n,
|
|
2301
2820
|
reason: t
|
|
2302
|
-
}),
|
|
2303
|
-
if (
|
|
2304
|
-
f =
|
|
2821
|
+
}), f === Z.INITIALIZED) throw new e.ErrorInfo(`unable to end turn; start() must be called before end() (turn ${n})`, L.InvalidArgument, 400);
|
|
2822
|
+
if (f !== Z.ENDED) {
|
|
2823
|
+
f = Z.ENDED;
|
|
2305
2824
|
try {
|
|
2306
|
-
await
|
|
2825
|
+
await g.endTurn(n, t);
|
|
2307
2826
|
} catch (t) {
|
|
2308
|
-
let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`,
|
|
2309
|
-
throw
|
|
2827
|
+
let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, L.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2828
|
+
throw h?.error("Turn.end(); failed to publish turn-end", { turnId: n }), r;
|
|
2310
2829
|
} finally {
|
|
2311
|
-
|
|
2830
|
+
b.delete(n);
|
|
2312
2831
|
}
|
|
2313
|
-
|
|
2832
|
+
h?.debug("Turn.end(); turn ended", {
|
|
2314
2833
|
turnId: n,
|
|
2315
2834
|
reason: t
|
|
2316
2835
|
});
|
|
@@ -2318,14 +2837,131 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
2318
2837
|
}
|
|
2319
2838
|
};
|
|
2320
2839
|
}
|
|
2321
|
-
},
|
|
2840
|
+
}, dt = (e) => new ut(e), ft = (e) => ot({
|
|
2322
2841
|
...e,
|
|
2323
|
-
codec:
|
|
2324
|
-
|
|
2842
|
+
codec: z,
|
|
2843
|
+
api: e.api ?? "/api/chat"
|
|
2844
|
+
}), pt = (e) => dt({
|
|
2325
2845
|
...e,
|
|
2326
|
-
codec:
|
|
2327
|
-
})
|
|
2846
|
+
codec: z
|
|
2847
|
+
}), Q = (e, t) => {
|
|
2848
|
+
if (e.length === 0) return t;
|
|
2849
|
+
let n = new Map(e.map((e) => [e.msgId, e]));
|
|
2850
|
+
return t.map((e) => {
|
|
2851
|
+
let t = n.get(e.msgId);
|
|
2852
|
+
if (!t) return e;
|
|
2853
|
+
let r = j();
|
|
2854
|
+
r.initMessage(e.msgId, e.message), r.processOutputs(t.events.map((t) => ({
|
|
2855
|
+
kind: "event",
|
|
2856
|
+
event: t,
|
|
2857
|
+
messageId: e.msgId
|
|
2858
|
+
})));
|
|
2859
|
+
let i = r.messages.at(-1);
|
|
2860
|
+
return i ? {
|
|
2861
|
+
...e,
|
|
2862
|
+
message: i
|
|
2863
|
+
} : e;
|
|
2864
|
+
});
|
|
2865
|
+
}, mt = (e, t, n, r) => D({
|
|
2866
|
+
...k(e),
|
|
2867
|
+
state: "approval-responded",
|
|
2868
|
+
input: e.input,
|
|
2869
|
+
approval: D({
|
|
2870
|
+
id: t,
|
|
2871
|
+
approved: n,
|
|
2872
|
+
reason: r
|
|
2873
|
+
})
|
|
2874
|
+
}), ht = (e, t) => ({
|
|
2875
|
+
...k(e),
|
|
2876
|
+
state: "output-denied",
|
|
2877
|
+
input: e.input,
|
|
2878
|
+
approval: {
|
|
2879
|
+
id: t,
|
|
2880
|
+
approved: !1
|
|
2881
|
+
}
|
|
2882
|
+
}), $ = (e, t) => {
|
|
2883
|
+
if (t.length === 0) return e;
|
|
2884
|
+
let n = new Map(t.map((e) => [e.toolCallId, e]));
|
|
2885
|
+
return e.map((e) => {
|
|
2886
|
+
let t;
|
|
2887
|
+
for (let [r, i] of e.parts.entries()) {
|
|
2888
|
+
if (i.type !== "dynamic-tool") continue;
|
|
2889
|
+
let a = n.get(i.toolCallId);
|
|
2890
|
+
if (!a) continue;
|
|
2891
|
+
let o = i.approval?.id ?? crypto.randomUUID(), s = a.approved ? mt(i, o, !0, a.reason) : ht(i, o);
|
|
2892
|
+
t ??= [...e.parts], t[r] = s;
|
|
2893
|
+
}
|
|
2894
|
+
return t ? {
|
|
2895
|
+
...e,
|
|
2896
|
+
parts: t
|
|
2897
|
+
} : e;
|
|
2898
|
+
});
|
|
2899
|
+
}, gt = (e, t) => {
|
|
2900
|
+
let n = new Set(t.filter((e) => e.approved).map((e) => e.toolCallId));
|
|
2901
|
+
if (n.size === 0) return /* @__PURE__ */ new Set();
|
|
2902
|
+
let r = /* @__PURE__ */ new Set();
|
|
2903
|
+
for (let t of e) for (let e of t.parts) e.type === "dynamic-tool" && n.has(e.toolCallId) && r.add(e.toolName);
|
|
2904
|
+
return r;
|
|
2905
|
+
}, _t = (e, t) => {
|
|
2906
|
+
if (t.size === 0) return e;
|
|
2907
|
+
let n = Object.entries(e).map(([e, n]) => t.has(e) ? [e, {
|
|
2908
|
+
...n,
|
|
2909
|
+
needsApproval: !1
|
|
2910
|
+
}] : [e, n]);
|
|
2911
|
+
return Object.fromEntries(n);
|
|
2912
|
+
}, vt = async (e) => {
|
|
2913
|
+
let { messages: n, decisions: r, tools: i } = e;
|
|
2914
|
+
if (!r || r.length === 0) return {
|
|
2915
|
+
modelMessages: await t(n),
|
|
2916
|
+
tools: i
|
|
2917
|
+
};
|
|
2918
|
+
let a = await t($(n, r));
|
|
2919
|
+
return {
|
|
2920
|
+
modelMessages: a.at(-1)?.role === "user" ? a.slice(0, -1) : a,
|
|
2921
|
+
tools: _t(i, gt(n, r))
|
|
2922
|
+
};
|
|
2923
|
+
}, yt = (e, t, n) => {
|
|
2924
|
+
let { decisions: r, ...i } = n, a = /* @__PURE__ */ new Map();
|
|
2925
|
+
for (let e of r ?? []) e.approved && a.set(e.toolCallId, e.targetMsgId);
|
|
2926
|
+
if (a.size === 0) return e.streamResponse(t, i);
|
|
2927
|
+
let o = (e) => (e.type === "tool-output-available" || e.type === "tool-output-error") && a.has(e.toolCallId), s = [], c = t.pipeThrough(new TransformStream({
|
|
2928
|
+
transform: (e, t) => {
|
|
2929
|
+
if (o(e)) {
|
|
2930
|
+
s.push(e);
|
|
2931
|
+
return;
|
|
2932
|
+
}
|
|
2933
|
+
t.enqueue(e);
|
|
2934
|
+
},
|
|
2935
|
+
flush: (t) => {
|
|
2936
|
+
if (!e.abortSignal.aborted) for (let e of s) t.enqueue(e);
|
|
2937
|
+
}
|
|
2938
|
+
}));
|
|
2939
|
+
return e.streamResponse(c, {
|
|
2940
|
+
...i,
|
|
2941
|
+
resolveWriteOptions: (e) => {
|
|
2942
|
+
if (!o(e)) return;
|
|
2943
|
+
let t = a.get(e.toolCallId);
|
|
2944
|
+
if (t !== void 0) return {
|
|
2945
|
+
messageId: t,
|
|
2946
|
+
extras: { headers: { [d]: t } }
|
|
2947
|
+
};
|
|
2948
|
+
}
|
|
2949
|
+
});
|
|
2950
|
+
}, bt = (e) => {
|
|
2951
|
+
let t = [];
|
|
2952
|
+
for (let n of e) for (let e of n.message.parts) e.type === "dynamic-tool" && (e.state === "approval-responded" ? t.push({
|
|
2953
|
+
toolCallId: e.toolCallId,
|
|
2954
|
+
approved: !0,
|
|
2955
|
+
targetMsgId: n.msgId,
|
|
2956
|
+
...e.approval.reason === void 0 ? {} : { reason: e.approval.reason }
|
|
2957
|
+
}) : e.state === "output-denied" && t.push({
|
|
2958
|
+
toolCallId: e.toolCallId,
|
|
2959
|
+
approved: !1,
|
|
2960
|
+
targetMsgId: n.msgId
|
|
2961
|
+
}));
|
|
2962
|
+
return t;
|
|
2963
|
+
};
|
|
2328
2964
|
//#endregion
|
|
2329
|
-
export {
|
|
2965
|
+
export { z as UIMessageCodec, $ as applyToolApprovalsToHistory, Q as applyToolEventsToHistory, We as createChatTransport, ft as createClientTransport, pt as createServerTransport, bt as extractApprovalDecisionsFromHistory, vt as prepareApprovalTurn, yt as streamResponseWithApprovalRedirect };
|
|
2330
2966
|
|
|
2331
2967
|
//# sourceMappingURL=ably-ai-transport-vercel.js.map
|