@ably/ai-transport 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +176 -0
- package/README.md +426 -0
- package/dist/ably-ai-transport.js +1388 -0
- package/dist/ably-ai-transport.js.map +1 -0
- package/dist/ably-ai-transport.umd.cjs +2 -0
- package/dist/ably-ai-transport.umd.cjs.map +1 -0
- package/dist/constants.d.ts +50 -0
- package/dist/core/codec/decoder.d.ts +62 -0
- package/dist/core/codec/encoder.d.ts +56 -0
- package/dist/core/codec/index.d.ts +8 -0
- package/dist/core/codec/lifecycle-tracker.d.ts +74 -0
- package/dist/core/codec/types.d.ts +188 -0
- package/dist/core/transport/client-transport.d.ts +10 -0
- package/dist/core/transport/conversation-tree.d.ts +9 -0
- package/dist/core/transport/decode-history.d.ts +41 -0
- package/dist/core/transport/headers.d.ts +26 -0
- package/dist/core/transport/index.d.ts +4 -0
- package/dist/core/transport/pipe-stream.d.ts +16 -0
- package/dist/core/transport/server-transport.d.ts +7 -0
- package/dist/core/transport/stream-router.d.ts +19 -0
- package/dist/core/transport/turn-manager.d.ts +34 -0
- package/dist/core/transport/types.d.ts +407 -0
- package/dist/errors.d.ts +46 -0
- package/dist/event-emitter.d.ts +65 -0
- package/dist/index.d.ts +11 -0
- package/dist/logger.d.ts +103 -0
- package/dist/react/ably-ai-transport-react.js +823 -0
- package/dist/react/ably-ai-transport-react.js.map +1 -0
- package/dist/react/ably-ai-transport-react.umd.cjs +2 -0
- package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -0
- package/dist/react/index.d.ts +11 -0
- package/dist/react/use-ably-messages.d.ts +18 -0
- package/dist/react/use-active-turns.d.ts +8 -0
- package/dist/react/use-client-transport.d.ts +7 -0
- package/dist/react/use-conversation-tree.d.ts +20 -0
- package/dist/react/use-edit.d.ts +7 -0
- package/dist/react/use-history.d.ts +19 -0
- package/dist/react/use-messages.d.ts +7 -0
- package/dist/react/use-regenerate.d.ts +7 -0
- package/dist/react/use-send.d.ts +7 -0
- package/dist/utils.d.ts +127 -0
- package/dist/vercel/ably-ai-transport-vercel.js +2331 -0
- package/dist/vercel/ably-ai-transport-vercel.js.map +1 -0
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs +2 -0
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -0
- package/dist/vercel/codec/accumulator.d.ts +21 -0
- package/dist/vercel/codec/decoder.d.ts +22 -0
- package/dist/vercel/codec/encoder.d.ts +41 -0
- package/dist/vercel/codec/index.d.ts +22 -0
- package/dist/vercel/index.d.ts +3 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +2082 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +2 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -0
- package/dist/vercel/react/index.d.ts +3 -0
- package/dist/vercel/react/use-chat-transport.d.ts +29 -0
- package/dist/vercel/react/use-message-sync.d.ts +19 -0
- package/dist/vercel/transport/chat-transport.d.ts +118 -0
- package/dist/vercel/transport/index.d.ts +36 -0
- package/package.json +123 -0
- package/react/README.md +3 -0
- package/react/index.d.ts +1 -0
- package/react/index.js +1 -0
- package/react/index.umd.cjs +1 -0
- package/src/constants.ts +98 -0
- package/src/core/codec/decoder.ts +402 -0
- package/src/core/codec/encoder.ts +470 -0
- package/src/core/codec/index.ts +28 -0
- package/src/core/codec/lifecycle-tracker.ts +140 -0
- package/src/core/codec/types.ts +249 -0
- package/src/core/transport/client-transport.ts +959 -0
- package/src/core/transport/conversation-tree.ts +434 -0
- package/src/core/transport/decode-history.ts +337 -0
- package/src/core/transport/headers.ts +46 -0
- package/src/core/transport/index.ts +34 -0
- package/src/core/transport/pipe-stream.ts +95 -0
- package/src/core/transport/server-transport.ts +458 -0
- package/src/core/transport/stream-router.ts +118 -0
- package/src/core/transport/turn-manager.ts +147 -0
- package/src/core/transport/types.ts +533 -0
- package/src/errors.ts +58 -0
- package/src/event-emitter.ts +103 -0
- package/src/index.ts +89 -0
- package/src/logger.ts +241 -0
- package/src/react/index.ts +11 -0
- package/src/react/use-ably-messages.ts +37 -0
- package/src/react/use-active-turns.ts +61 -0
- package/src/react/use-client-transport.ts +37 -0
- package/src/react/use-conversation-tree.ts +71 -0
- package/src/react/use-edit.ts +24 -0
- package/src/react/use-history.ts +111 -0
- package/src/react/use-messages.ts +32 -0
- package/src/react/use-regenerate.ts +24 -0
- package/src/react/use-send.ts +25 -0
- package/src/react/vite.config.ts +32 -0
- package/src/tsconfig.json +25 -0
- package/src/utils.ts +230 -0
- package/src/vercel/codec/accumulator.ts +603 -0
- package/src/vercel/codec/decoder.ts +615 -0
- package/src/vercel/codec/encoder.ts +396 -0
- package/src/vercel/codec/index.ts +37 -0
- package/src/vercel/index.ts +12 -0
- package/src/vercel/react/index.ts +4 -0
- package/src/vercel/react/use-chat-transport.ts +60 -0
- package/src/vercel/react/use-message-sync.ts +34 -0
- package/src/vercel/react/vite.config.ts +33 -0
- package/src/vercel/transport/chat-transport.ts +278 -0
- package/src/vercel/transport/index.ts +56 -0
- package/src/vercel/vite.config.ts +33 -0
- package/src/vite.config.ts +31 -0
- package/vercel/README.md +3 -0
- package/vercel/index.d.ts +1 -0
- package/vercel/index.js +1 -0
- package/vercel/index.umd.cjs +1 -0
- package/vercel/react/README.md +3 -0
- package/vercel/react/index.d.ts +1 -0
- package/vercel/react/index.js +1 -0
- package/vercel/react/index.umd.cjs +1 -0
|
@@ -0,0 +1,1388 @@
|
|
|
1
|
+
import * as e from "ably";
|
|
2
|
+
//#region src/constants.ts
|
|
3
|
+
var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-ably-turn-id", a = "x-ably-msg-id", o = "x-ably-turn-client-id", s = "x-ably-role", c = "x-ably-cancel-turn-id", l = "x-ably-cancel-own", u = "x-ably-cancel-all", d = "x-ably-cancel-client-id", f = "x-ably-parent", p = "x-ably-fork-of", m = "x-ably-turn-reason", h = "x-ably-cancel", g = "x-ably-turn-start", _ = "x-ably-turn-end", v = "x-ably-abort", y = "x-ably-error", b = "x-domain-", x = /* @__PURE__ */ function(e) {
|
|
4
|
+
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;
|
|
5
|
+
}({}), S = (e, t) => e.code === t, C = (e) => {
|
|
6
|
+
let t = e.extras;
|
|
7
|
+
if (!t || typeof t != "object") return {};
|
|
8
|
+
let n = t.headers;
|
|
9
|
+
return !n || typeof n != "object" ? {} : n;
|
|
10
|
+
}, w = (e) => {
|
|
11
|
+
if (e !== void 0) try {
|
|
12
|
+
return JSON.parse(e);
|
|
13
|
+
} catch {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
}, T = (e, t) => ({
|
|
17
|
+
...e,
|
|
18
|
+
...t
|
|
19
|
+
}), E = (e) => {
|
|
20
|
+
if (e !== void 0) return e === "true";
|
|
21
|
+
}, D = (e, t) => e[b + t], O = (e) => {
|
|
22
|
+
let t = {};
|
|
23
|
+
for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
|
|
24
|
+
return t;
|
|
25
|
+
}, k = (e) => ({
|
|
26
|
+
str: (t) => D(e, t),
|
|
27
|
+
strOr: (t, n) => D(e, t) ?? n,
|
|
28
|
+
bool: (t) => E(D(e, t)),
|
|
29
|
+
json: (t) => w(D(e, t))
|
|
30
|
+
}), A = () => {
|
|
31
|
+
let e = {}, t = {
|
|
32
|
+
str: (n, r) => (r !== void 0 && (e[b + n] = r), t),
|
|
33
|
+
bool: (n, r) => (r !== void 0 && (e[b + n] = String(r)), t),
|
|
34
|
+
json: (n, r) => (r != null && (e[b + n] = JSON.stringify(r)), t),
|
|
35
|
+
build: () => e
|
|
36
|
+
};
|
|
37
|
+
return t;
|
|
38
|
+
}, j = (e) => {
|
|
39
|
+
let t = {
|
|
40
|
+
[s]: e.role,
|
|
41
|
+
[i]: e.turnId,
|
|
42
|
+
[a]: e.msgId
|
|
43
|
+
};
|
|
44
|
+
return e.turnClientId !== void 0 && (t[o] = e.turnClientId), e.parent && (t[f] = e.parent), e.forkOf && (t[p] = e.forkOf), t;
|
|
45
|
+
}, M = async (e, t, n, r, i) => {
|
|
46
|
+
i?.trace("pipeStream();");
|
|
47
|
+
let a = e.getReader(), o, s = n ? new Promise((e) => {
|
|
48
|
+
if (n.aborted) {
|
|
49
|
+
e();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
o = () => {
|
|
53
|
+
e();
|
|
54
|
+
}, n.addEventListener("abort", o, { once: !0 });
|
|
55
|
+
}) : new Promise(() => {}), c = "complete";
|
|
56
|
+
try {
|
|
57
|
+
for (;;) {
|
|
58
|
+
let e = await Promise.race([a.read(), s.then(() => "aborted")]);
|
|
59
|
+
if (e === "aborted") {
|
|
60
|
+
c = "cancelled", i?.debug("pipeStream(); stream cancelled by abort signal"), r && await r(async (e) => t.appendEvent(e)), await t.abort("cancelled");
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
let { done: n, value: o } = e;
|
|
64
|
+
if (n) {
|
|
65
|
+
await t.close(), i?.debug("pipeStream(); stream completed");
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
await t.appendEvent(o);
|
|
69
|
+
}
|
|
70
|
+
} catch (e) {
|
|
71
|
+
c = "error";
|
|
72
|
+
let n = e instanceof Error ? e.message : String(e);
|
|
73
|
+
i?.error("pipeStream(); stream error", { error: n });
|
|
74
|
+
try {
|
|
75
|
+
await t.close();
|
|
76
|
+
} catch {}
|
|
77
|
+
} finally {
|
|
78
|
+
o && n?.removeEventListener("abort", o), a.releaseLock();
|
|
79
|
+
}
|
|
80
|
+
return { reason: c };
|
|
81
|
+
}, N = class {
|
|
82
|
+
constructor(e, t) {
|
|
83
|
+
this._activeTurns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "TurnManager" });
|
|
84
|
+
}
|
|
85
|
+
async startTurn(e, t, n) {
|
|
86
|
+
this._logger?.trace("DefaultTurnManager.startTurn();", {
|
|
87
|
+
turnId: e,
|
|
88
|
+
clientId: t
|
|
89
|
+
});
|
|
90
|
+
let r = n ?? new AbortController(), a = t ?? "";
|
|
91
|
+
return this._activeTurns.set(e, {
|
|
92
|
+
controller: r,
|
|
93
|
+
clientId: a
|
|
94
|
+
}), await this._channel.publish({
|
|
95
|
+
name: g,
|
|
96
|
+
extras: { headers: {
|
|
97
|
+
[i]: e,
|
|
98
|
+
[o]: a
|
|
99
|
+
} }
|
|
100
|
+
}), this._logger?.debug("DefaultTurnManager.startTurn(); turn started", { turnId: e }), r.signal;
|
|
101
|
+
}
|
|
102
|
+
async endTurn(e, t) {
|
|
103
|
+
this._logger?.trace("DefaultTurnManager.endTurn();", {
|
|
104
|
+
turnId: e,
|
|
105
|
+
reason: t
|
|
106
|
+
});
|
|
107
|
+
let n = this._activeTurns.get(e)?.clientId ?? "";
|
|
108
|
+
await this._channel.publish({
|
|
109
|
+
name: _,
|
|
110
|
+
extras: { headers: {
|
|
111
|
+
[i]: e,
|
|
112
|
+
[o]: n,
|
|
113
|
+
[m]: t
|
|
114
|
+
} }
|
|
115
|
+
}), this._activeTurns.delete(e), this._logger?.debug("DefaultTurnManager.endTurn(); turn ended", {
|
|
116
|
+
turnId: e,
|
|
117
|
+
reason: t
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
getSignal(e) {
|
|
121
|
+
return this._activeTurns.get(e)?.controller.signal;
|
|
122
|
+
}
|
|
123
|
+
getClientId(e) {
|
|
124
|
+
return this._activeTurns.get(e)?.clientId;
|
|
125
|
+
}
|
|
126
|
+
abort(e) {
|
|
127
|
+
this._logger?.debug("DefaultTurnManager.abort();", { turnId: e }), this._activeTurns.get(e)?.controller.abort();
|
|
128
|
+
}
|
|
129
|
+
getActiveTurnIds() {
|
|
130
|
+
return [...this._activeTurns.keys()];
|
|
131
|
+
}
|
|
132
|
+
close() {
|
|
133
|
+
this._logger?.trace("DefaultTurnManager.close();", { activeTurns: this._activeTurns.size });
|
|
134
|
+
for (let e of this._activeTurns.values()) e.controller.abort();
|
|
135
|
+
this._activeTurns.clear();
|
|
136
|
+
}
|
|
137
|
+
}, P = (e, t) => new N(e, t), ee = class {
|
|
138
|
+
constructor(t) {
|
|
139
|
+
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 = P(this._channel, this._logger), this._channelListener = (e) => {
|
|
140
|
+
this._handleChannelMessage(e);
|
|
141
|
+
}, this._attachPromise = this._channel.subscribe(h, this._channelListener).then(() => {}, (t) => {
|
|
142
|
+
let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`, x.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
143
|
+
this._logger?.error("DefaultServerTransport(); subscribe failed"), this._onError?.(n);
|
|
144
|
+
}), this._logger?.debug("DefaultServerTransport(); transport created");
|
|
145
|
+
}
|
|
146
|
+
newTurn(e) {
|
|
147
|
+
return this._logger?.trace("DefaultServerTransport.newTurn();", { turnId: e.turnId }), this._createTurn(e);
|
|
148
|
+
}
|
|
149
|
+
close() {
|
|
150
|
+
this._logger?.trace("DefaultServerTransport.close();"), this._channel.unsubscribe(h, this._channelListener);
|
|
151
|
+
for (let e of this._registeredTurns.values()) e.controller.abort();
|
|
152
|
+
this._registeredTurns.clear(), this._turnManager.close(), this._logger?.debug("DefaultServerTransport.close(); transport closed");
|
|
153
|
+
}
|
|
154
|
+
_resolveFilter(e, t) {
|
|
155
|
+
let n = [...this._registeredTurns.keys()];
|
|
156
|
+
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] : [];
|
|
157
|
+
}
|
|
158
|
+
async _handleCancelMessage(t) {
|
|
159
|
+
let n = C(t), r = {};
|
|
160
|
+
n["x-ably-cancel-turn-id"] ? r.turnId = n[c] : n["x-ably-cancel-own"] === "true" ? r.own = !0 : n["x-ably-cancel-client-id"] ? r.clientId = n[d] : n["x-ably-cancel-all"] === "true" && (r.all = !0);
|
|
161
|
+
let i = this._resolveFilter(r, t.clientId);
|
|
162
|
+
if (i.length === 0) return;
|
|
163
|
+
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); matched turns", {
|
|
164
|
+
matchedTurnIds: i,
|
|
165
|
+
filter: r
|
|
166
|
+
});
|
|
167
|
+
let a = /* @__PURE__ */ new Map();
|
|
168
|
+
for (let e of i) {
|
|
169
|
+
let t = this._registeredTurns.get(e);
|
|
170
|
+
a.set(e, t?.clientId ?? "");
|
|
171
|
+
}
|
|
172
|
+
let o = {
|
|
173
|
+
message: t,
|
|
174
|
+
filter: r,
|
|
175
|
+
matchedTurnIds: i,
|
|
176
|
+
turnOwners: a
|
|
177
|
+
};
|
|
178
|
+
for (let t of i) {
|
|
179
|
+
let n = this._registeredTurns.get(t);
|
|
180
|
+
if (n) try {
|
|
181
|
+
if (n.onCancel && !await n.onCancel(o)) {
|
|
182
|
+
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); cancel rejected by onCancel", { turnId: t });
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
n.controller.abort(), this._logger?.debug("DefaultServerTransport._handleCancelMessage(); turn aborted", { turnId: t });
|
|
186
|
+
} catch (r) {
|
|
187
|
+
let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`, x.CancelListenerError, 500, r instanceof e.ErrorInfo ? r : void 0);
|
|
188
|
+
this._logger?.error("DefaultServerTransport._handleCancelMessage(); onCancel threw", { turnId: t }), (n.onError ?? this._onError)?.(i);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
_handleChannelMessage(t) {
|
|
193
|
+
try {
|
|
194
|
+
t.name === "x-ably-cancel" && this._handleCancelMessage(t).catch((t) => {
|
|
195
|
+
let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, x.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
196
|
+
this._logger?.error("DefaultServerTransport._handleChannelMessage(); cancel routing error"), this._onError?.(n);
|
|
197
|
+
});
|
|
198
|
+
} catch (t) {
|
|
199
|
+
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, x.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
200
|
+
this._logger?.error("DefaultServerTransport._handleChannelMessage(); subscription error"), this._onError?.(n);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
_createTurn(t) {
|
|
204
|
+
let { turnId: n, clientId: r, onMessage: i, onAbort: a, onCancel: o, onError: s, parent: c, forkOf: l } = t, u = new AbortController(), d = !1, f = !1, p = {
|
|
205
|
+
turnId: n,
|
|
206
|
+
clientId: r ?? "",
|
|
207
|
+
controller: u,
|
|
208
|
+
onCancel: o,
|
|
209
|
+
onError: s
|
|
210
|
+
};
|
|
211
|
+
this._registeredTurns.set(n, p);
|
|
212
|
+
let m = this._logger, h = this._turnManager, g = this._attachPromise, _ = this._codec, v = this._channel, y = this._registeredTurns;
|
|
213
|
+
return {
|
|
214
|
+
get turnId() {
|
|
215
|
+
return n;
|
|
216
|
+
},
|
|
217
|
+
get abortSignal() {
|
|
218
|
+
return u.signal;
|
|
219
|
+
},
|
|
220
|
+
start: async () => {
|
|
221
|
+
if (m?.trace("Turn.start();", { turnId: n }), u.signal.aborted) throw new e.ErrorInfo(`unable to start turn; turn ${n} was cancelled before start()`, x.InvalidArgument, 400);
|
|
222
|
+
if (!d) {
|
|
223
|
+
d = !0;
|
|
224
|
+
try {
|
|
225
|
+
await h.startTurn(n, r, u);
|
|
226
|
+
} catch (t) {
|
|
227
|
+
let r = new e.ErrorInfo(`unable to publish turn-start for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, x.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
228
|
+
throw m?.error("Turn.start(); failed to publish turn-start", { turnId: n }), s?.(r), r;
|
|
229
|
+
}
|
|
230
|
+
m?.debug("Turn.start(); turn started", { turnId: n });
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
addMessages: async (t, r) => {
|
|
234
|
+
if (m?.trace("Turn.addMessages();", {
|
|
235
|
+
turnId: n,
|
|
236
|
+
count: t.length
|
|
237
|
+
}), !d) throw new e.ErrorInfo(`unable to add messages; start() must be called before addMessages() (turn ${n})`, x.InvalidArgument, 400);
|
|
238
|
+
await g;
|
|
239
|
+
let a = [];
|
|
240
|
+
for (let e of t) {
|
|
241
|
+
let t = crypto.randomUUID(), o = T(j({
|
|
242
|
+
role: "user",
|
|
243
|
+
turnId: n,
|
|
244
|
+
msgId: t,
|
|
245
|
+
turnClientId: r?.clientId,
|
|
246
|
+
parent: r?.parent === void 0 ? c ?? void 0 : r.parent ?? void 0,
|
|
247
|
+
forkOf: r?.forkOf ?? l
|
|
248
|
+
}), e.headers);
|
|
249
|
+
await _.createEncoder(v, {
|
|
250
|
+
extras: { headers: o },
|
|
251
|
+
onMessage: i
|
|
252
|
+
}).writeMessages([e.message], r?.clientId ? { clientId: r.clientId } : void 0), a.push(o["x-ably-msg-id"] ?? t);
|
|
253
|
+
}
|
|
254
|
+
return m?.debug("Turn.addMessages(); messages published", {
|
|
255
|
+
turnId: n,
|
|
256
|
+
count: t.length
|
|
257
|
+
}), { msgIds: a };
|
|
258
|
+
},
|
|
259
|
+
streamResponse: async (t, r) => {
|
|
260
|
+
if (m?.trace("Turn.streamResponse();", { turnId: n }), !d) throw new e.ErrorInfo(`unable to stream response; start() must be called before streamResponse() (turn ${n})`, x.InvalidArgument, 400);
|
|
261
|
+
await g;
|
|
262
|
+
let o = h.getSignal(n), s = h.getClientId(n), u = r?.parent === void 0 ? c ?? void 0 : r.parent ?? void 0, f = j({
|
|
263
|
+
role: "assistant",
|
|
264
|
+
turnId: n,
|
|
265
|
+
msgId: crypto.randomUUID(),
|
|
266
|
+
turnClientId: s,
|
|
267
|
+
parent: u,
|
|
268
|
+
forkOf: r?.forkOf ?? l
|
|
269
|
+
}), p = await M(t, _.createEncoder(v, {
|
|
270
|
+
extras: { headers: f },
|
|
271
|
+
onMessage: i
|
|
272
|
+
}), o, a, m);
|
|
273
|
+
return m?.debug("Turn.streamResponse(); stream finished", {
|
|
274
|
+
turnId: n,
|
|
275
|
+
reason: p.reason
|
|
276
|
+
}), p;
|
|
277
|
+
},
|
|
278
|
+
end: async (t) => {
|
|
279
|
+
if (m?.trace("Turn.end();", {
|
|
280
|
+
turnId: n,
|
|
281
|
+
reason: t
|
|
282
|
+
}), !d) throw new e.ErrorInfo(`unable to end turn; start() must be called before end() (turn ${n})`, x.InvalidArgument, 400);
|
|
283
|
+
if (!f) {
|
|
284
|
+
f = !0;
|
|
285
|
+
try {
|
|
286
|
+
await h.endTurn(n, t);
|
|
287
|
+
} catch (t) {
|
|
288
|
+
let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, x.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
289
|
+
throw m?.error("Turn.end(); failed to publish turn-end", { turnId: n }), s?.(r), r;
|
|
290
|
+
} finally {
|
|
291
|
+
y.delete(n);
|
|
292
|
+
}
|
|
293
|
+
m?.debug("Turn.end(); turn ended", {
|
|
294
|
+
turnId: n,
|
|
295
|
+
reason: t
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
}, F = (e) => new ee(e), I = (e) => ({
|
|
302
|
+
logAction: (t, n, r) => {
|
|
303
|
+
e.error(n, { detail: r });
|
|
304
|
+
},
|
|
305
|
+
shouldLog: () => !0
|
|
306
|
+
}), L = e.Realtime.EventEmitter, R = class extends L {
|
|
307
|
+
constructor(e) {
|
|
308
|
+
super(I(e));
|
|
309
|
+
}
|
|
310
|
+
}, z = /* @__PURE__ */ function(e) {
|
|
311
|
+
return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
|
|
312
|
+
}({}), B = (e, t, n) => {
|
|
313
|
+
let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
|
|
314
|
+
switch (t) {
|
|
315
|
+
case z.Trace:
|
|
316
|
+
case z.Debug:
|
|
317
|
+
console.log(i);
|
|
318
|
+
break;
|
|
319
|
+
case z.Info:
|
|
320
|
+
console.info(i);
|
|
321
|
+
break;
|
|
322
|
+
case z.Warn:
|
|
323
|
+
console.warn(i);
|
|
324
|
+
break;
|
|
325
|
+
case z.Error:
|
|
326
|
+
console.error(i);
|
|
327
|
+
break;
|
|
328
|
+
case z.Silent: break;
|
|
329
|
+
}
|
|
330
|
+
}, V = (e) => new W(e.logHandler ?? B, e.logLevel), H = /* @__PURE__ */ function(e) {
|
|
331
|
+
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;
|
|
332
|
+
}(H || {}), U = new Map([
|
|
333
|
+
[z.Trace, H.Trace],
|
|
334
|
+
[z.Debug, H.Debug],
|
|
335
|
+
[z.Info, H.Info],
|
|
336
|
+
[z.Warn, H.Warn],
|
|
337
|
+
[z.Error, H.Error],
|
|
338
|
+
[z.Silent, H.Silent]
|
|
339
|
+
]), W = class t {
|
|
340
|
+
constructor(t, n, r) {
|
|
341
|
+
this._handler = t, this._context = r;
|
|
342
|
+
let i = U.get(n);
|
|
343
|
+
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, x.InvalidArgument, 400);
|
|
344
|
+
this._levelNumber = i;
|
|
345
|
+
}
|
|
346
|
+
trace(e, t) {
|
|
347
|
+
this._write(e, z.Trace, H.Trace, t);
|
|
348
|
+
}
|
|
349
|
+
debug(e, t) {
|
|
350
|
+
this._write(e, z.Debug, H.Debug, t);
|
|
351
|
+
}
|
|
352
|
+
info(e, t) {
|
|
353
|
+
this._write(e, z.Info, H.Info, t);
|
|
354
|
+
}
|
|
355
|
+
warn(e, t) {
|
|
356
|
+
this._write(e, z.Warn, H.Warn, t);
|
|
357
|
+
}
|
|
358
|
+
error(e, t) {
|
|
359
|
+
this._write(e, z.Error, H.Error, t);
|
|
360
|
+
}
|
|
361
|
+
withContext(e) {
|
|
362
|
+
let n = [...U.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? z.Error;
|
|
363
|
+
return new t(this._handler, n, this._mergeContext(e));
|
|
364
|
+
}
|
|
365
|
+
_write(e, t, n, r) {
|
|
366
|
+
n >= this._levelNumber && this._handler(e, t, this._mergeContext(r));
|
|
367
|
+
}
|
|
368
|
+
_mergeContext(e) {
|
|
369
|
+
return this._context ? e ? {
|
|
370
|
+
...this._context,
|
|
371
|
+
...e
|
|
372
|
+
} : this._context : e ?? void 0;
|
|
373
|
+
}
|
|
374
|
+
}, G = class {
|
|
375
|
+
constructor(e, t) {
|
|
376
|
+
this._nodeIndex = /* @__PURE__ */ new Map(), this._codecKeyIndex = /* @__PURE__ */ new Map(), this._sortedList = [], this._parentIndex = /* @__PURE__ */ new Map(), this._selections = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._getKey = e, this._logger = t;
|
|
377
|
+
}
|
|
378
|
+
_compareNodes(e, t) {
|
|
379
|
+
let n = e.node.serial, r = t.node.serial;
|
|
380
|
+
return n === void 0 && r === void 0 ? e.insertSeq - t.insertSeq : n === void 0 ? 1 : r === void 0 || n < r ? -1 : n > r ? 1 : e.insertSeq - t.insertSeq;
|
|
381
|
+
}
|
|
382
|
+
_insertSorted(e) {
|
|
383
|
+
if (e.node.serial === void 0) {
|
|
384
|
+
this._sortedList.push(e);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
let t = 0, n = this._sortedList.length;
|
|
388
|
+
for (; t < n;) {
|
|
389
|
+
let r = t + n >>> 1, i = this._sortedList[r];
|
|
390
|
+
if (!i) break;
|
|
391
|
+
this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
|
|
392
|
+
}
|
|
393
|
+
this._sortedList.splice(t, 0, e);
|
|
394
|
+
}
|
|
395
|
+
_removeSorted(e) {
|
|
396
|
+
let t = this._sortedList.indexOf(e);
|
|
397
|
+
t !== -1 && this._sortedList.splice(t, 1);
|
|
398
|
+
}
|
|
399
|
+
_addToParentIndex(e, t) {
|
|
400
|
+
let n = this._parentIndex.get(e);
|
|
401
|
+
n || (n = /* @__PURE__ */ new Set(), this._parentIndex.set(e, n)), n.add(t);
|
|
402
|
+
}
|
|
403
|
+
_removeFromParentIndex(e, t) {
|
|
404
|
+
let n = this._parentIndex.get(e);
|
|
405
|
+
n && (n.delete(t), n.size === 0 && this._parentIndex.delete(e));
|
|
406
|
+
}
|
|
407
|
+
_getSiblingGroup(e) {
|
|
408
|
+
let t = this._nodeIndex.get(e);
|
|
409
|
+
if (!t) return [];
|
|
410
|
+
let n = t.node, r = new Set([n.msgId]);
|
|
411
|
+
for (; n.forkOf && !r.has(n.forkOf);) {
|
|
412
|
+
let e = this._nodeIndex.get(n.forkOf);
|
|
413
|
+
if (!e || e.node.parentId !== n.parentId) break;
|
|
414
|
+
n = e.node, r.add(n.msgId);
|
|
415
|
+
}
|
|
416
|
+
let i = n.parentId, a = n.msgId, o = [], s = this._parentIndex.get(i);
|
|
417
|
+
if (s) for (let e of s) {
|
|
418
|
+
let t = this._nodeIndex.get(e);
|
|
419
|
+
t && this._isSiblingOf(t.node, a) && o.push(t);
|
|
420
|
+
}
|
|
421
|
+
return o.sort((e, t) => this._compareNodes(e, t)), o.map((e) => e.node);
|
|
422
|
+
}
|
|
423
|
+
_isSiblingOf(e, t) {
|
|
424
|
+
if (e.msgId === t) return !0;
|
|
425
|
+
let n = e, r = new Set([n.msgId]);
|
|
426
|
+
for (; n.forkOf;) {
|
|
427
|
+
if (n.forkOf === t) return !0;
|
|
428
|
+
if (r.has(n.forkOf)) break;
|
|
429
|
+
let e = this._nodeIndex.get(n.forkOf);
|
|
430
|
+
if (!e) break;
|
|
431
|
+
n = e.node, r.add(n.msgId);
|
|
432
|
+
}
|
|
433
|
+
return !1;
|
|
434
|
+
}
|
|
435
|
+
_getGroupRoot(e) {
|
|
436
|
+
let t = this._nodeIndex.get(e);
|
|
437
|
+
if (!t) return e;
|
|
438
|
+
let n = t.node, r = new Set([n.msgId]);
|
|
439
|
+
for (; n.forkOf && !r.has(n.forkOf);) {
|
|
440
|
+
let e = this._nodeIndex.get(n.forkOf);
|
|
441
|
+
if (!e || e.node.parentId !== n.parentId) break;
|
|
442
|
+
n = e.node, r.add(n.msgId);
|
|
443
|
+
}
|
|
444
|
+
return n.msgId;
|
|
445
|
+
}
|
|
446
|
+
flatten() {
|
|
447
|
+
let e = [], t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Map();
|
|
448
|
+
for (let r of this._sortedList) {
|
|
449
|
+
let i = r.node, { msgId: a, parentId: o } = i;
|
|
450
|
+
if (o !== void 0 && !t.has(o)) continue;
|
|
451
|
+
let s = this._getSiblingGroup(a);
|
|
452
|
+
if (s.length > 1) {
|
|
453
|
+
let e = this._getGroupRoot(a), t = n.get(e);
|
|
454
|
+
if (t === void 0) {
|
|
455
|
+
let r = this._selections.get(e) ?? s.length - 1, i = s[Math.max(0, Math.min(r, s.length - 1))];
|
|
456
|
+
if (!i) break;
|
|
457
|
+
t = i.msgId, n.set(e, t);
|
|
458
|
+
}
|
|
459
|
+
if (a !== t) continue;
|
|
460
|
+
}
|
|
461
|
+
t.add(a), e.push(i.message);
|
|
462
|
+
}
|
|
463
|
+
return e;
|
|
464
|
+
}
|
|
465
|
+
getSiblings(e) {
|
|
466
|
+
return this._getSiblingGroup(e).map((e) => e.message);
|
|
467
|
+
}
|
|
468
|
+
hasSiblings(e) {
|
|
469
|
+
return this._getSiblingGroup(e).length > 1;
|
|
470
|
+
}
|
|
471
|
+
getSelectedIndex(e) {
|
|
472
|
+
let t = this._getSiblingGroup(e);
|
|
473
|
+
if (t.length <= 1) return 0;
|
|
474
|
+
let n = this._getGroupRoot(e), r = this._selections.get(n);
|
|
475
|
+
return r === void 0 ? t.length - 1 : Math.max(0, Math.min(r, t.length - 1));
|
|
476
|
+
}
|
|
477
|
+
select(e, t) {
|
|
478
|
+
this._logger.debug("ConversationTree.select();", {
|
|
479
|
+
msgId: e,
|
|
480
|
+
index: t
|
|
481
|
+
});
|
|
482
|
+
let n = this._getSiblingGroup(e);
|
|
483
|
+
if (n.length <= 1) return;
|
|
484
|
+
let r = this._getGroupRoot(e);
|
|
485
|
+
this._selections.set(r, Math.max(0, Math.min(t, n.length - 1)));
|
|
486
|
+
}
|
|
487
|
+
getNode(e) {
|
|
488
|
+
return this._nodeIndex.get(e)?.node;
|
|
489
|
+
}
|
|
490
|
+
getNodeByKey(e) {
|
|
491
|
+
let t = this._codecKeyIndex.get(e);
|
|
492
|
+
if (t) return this._nodeIndex.get(t)?.node;
|
|
493
|
+
}
|
|
494
|
+
getHeaders(e) {
|
|
495
|
+
return this._nodeIndex.get(e)?.node.headers;
|
|
496
|
+
}
|
|
497
|
+
upsert(e, t, n, r) {
|
|
498
|
+
let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0;
|
|
499
|
+
this._codecKeyIndex.set(this._getKey(t), e);
|
|
500
|
+
let o = this._nodeIndex.get(e);
|
|
501
|
+
if (o) {
|
|
502
|
+
o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("ConversationTree.upsert(); promoting serial", {
|
|
503
|
+
msgId: e,
|
|
504
|
+
serial: r
|
|
505
|
+
}), o.node.serial = r, this._removeSorted(o), this._insertSorted(o));
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
this._logger.trace("ConversationTree.upsert(); inserting new node", {
|
|
509
|
+
msgId: e,
|
|
510
|
+
parentId: i,
|
|
511
|
+
forkOf: a
|
|
512
|
+
});
|
|
513
|
+
let s = {
|
|
514
|
+
node: {
|
|
515
|
+
message: t,
|
|
516
|
+
msgId: e,
|
|
517
|
+
parentId: i,
|
|
518
|
+
forkOf: a,
|
|
519
|
+
headers: { ...n },
|
|
520
|
+
serial: r
|
|
521
|
+
},
|
|
522
|
+
insertSeq: this._seqCounter++
|
|
523
|
+
};
|
|
524
|
+
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s);
|
|
525
|
+
}
|
|
526
|
+
delete(e) {
|
|
527
|
+
let t = this._nodeIndex.get(e);
|
|
528
|
+
if (!t) return;
|
|
529
|
+
this._logger.debug("ConversationTree.delete();", { msgId: e });
|
|
530
|
+
let { node: n } = t, r = this._getKey(n.message);
|
|
531
|
+
this._codecKeyIndex.get(r) === e && this._codecKeyIndex.delete(r), this._removeFromParentIndex(n.parentId, e), this._removeSorted(t), this._nodeIndex.delete(e), this._selections.delete(e);
|
|
532
|
+
}
|
|
533
|
+
}, K = (e, t) => new G(e, t), q = (e) => {
|
|
534
|
+
let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), o = e.codec.createAccumulator(), s = 0, c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map();
|
|
535
|
+
for (let u of t) {
|
|
536
|
+
let t = n.decode(u), d = C(u), f = d[i], p = d[a], m = u.serial;
|
|
537
|
+
if (f) {
|
|
538
|
+
let n = r.get(f);
|
|
539
|
+
if (n || (n = {
|
|
540
|
+
accumulator: e.codec.createAccumulator(),
|
|
541
|
+
firstSeen: s++,
|
|
542
|
+
msgHeaders: /* @__PURE__ */ new Map(),
|
|
543
|
+
msgSerials: /* @__PURE__ */ new Map()
|
|
544
|
+
}, r.set(f, n)), p) {
|
|
545
|
+
let e = n.msgHeaders.get(p);
|
|
546
|
+
e ? Object.keys(d).length > 0 && Object.assign(e, d) : (n.msgHeaders.set(p, { ...d }), m && n.msgSerials.set(p, m));
|
|
547
|
+
}
|
|
548
|
+
n.accumulator.processOutputs(t);
|
|
549
|
+
} else o.processOutputs(t);
|
|
550
|
+
for (let n of t) if (n.kind === "message") {
|
|
551
|
+
let t = e.getMessageKey(n.message), r = c.get(t);
|
|
552
|
+
r ? Object.keys(d).length > 0 && Object.assign(r, d) : (c.set(t, { ...d }), m && l.set(t, m));
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
let u = [];
|
|
556
|
+
for (let t of o.completedMessages) {
|
|
557
|
+
let n = e.getMessageKey(t);
|
|
558
|
+
u.push({
|
|
559
|
+
message: t,
|
|
560
|
+
headers: c.get(n) ?? {},
|
|
561
|
+
serial: l.get(n) ?? ""
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
let d = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
|
|
565
|
+
for (let t of d) {
|
|
566
|
+
let n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map();
|
|
567
|
+
for (let o of t.accumulator.completedMessages) {
|
|
568
|
+
let t = e.getMessageKey(o), s = c.get(t);
|
|
569
|
+
if (s) {
|
|
570
|
+
r.set(t, s);
|
|
571
|
+
let e = l.get(t);
|
|
572
|
+
e && i.set(t, e);
|
|
573
|
+
let o = s[a];
|
|
574
|
+
o && n.add(o);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
let o = [...t.msgHeaders.entries()].filter(([e]) => !n.has(e)), s = 0;
|
|
578
|
+
for (let n of t.accumulator.completedMessages) {
|
|
579
|
+
let a = e.getMessageKey(n), c = o[s];
|
|
580
|
+
if (!r.has(a) && c) {
|
|
581
|
+
let [e, n] = c;
|
|
582
|
+
r.set(a, n);
|
|
583
|
+
let o = t.msgSerials.get(e);
|
|
584
|
+
o && i.set(a, o), s++;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
for (let n of t.accumulator.completedMessages) {
|
|
588
|
+
let t = e.getMessageKey(n);
|
|
589
|
+
u.push({
|
|
590
|
+
message: n,
|
|
591
|
+
headers: r.get(t) ?? {},
|
|
592
|
+
serial: i.get(t) ?? ""
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return u.toReversed();
|
|
597
|
+
}, J = async (e, t, n) => {
|
|
598
|
+
e.rawMessages.push(...t.items), e.lastAblyPage = t;
|
|
599
|
+
let r = q(e).length;
|
|
600
|
+
for (; r < e.returnedCount + n && t.hasNext();) {
|
|
601
|
+
e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
|
|
602
|
+
collected: e.rawMessages.length,
|
|
603
|
+
decoded: r
|
|
604
|
+
});
|
|
605
|
+
let n = await t.next();
|
|
606
|
+
if (!n) break;
|
|
607
|
+
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, r = q(e).length;
|
|
608
|
+
}
|
|
609
|
+
}, Y = (e, t) => {
|
|
610
|
+
let n = q(e), r = n.slice(e.returnedCount, e.returnedCount + t), i = [...r].toReversed();
|
|
611
|
+
e.returnedCount += r.length;
|
|
612
|
+
let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
|
|
613
|
+
return e.returnedRawCount = e.rawMessages.length, {
|
|
614
|
+
items: i.map((e) => e.message),
|
|
615
|
+
itemHeaders: i.map((e) => e.headers),
|
|
616
|
+
itemSerials: i.map((e) => e.serial),
|
|
617
|
+
rawMessages: s,
|
|
618
|
+
hasNext: () => a || o,
|
|
619
|
+
next: async () => {
|
|
620
|
+
if (a) return Y(e, t);
|
|
621
|
+
if (!o || !e.lastAblyPage) return;
|
|
622
|
+
let n = await e.lastAblyPage.next();
|
|
623
|
+
if (n) return await J(e, n, t), Y(e, t);
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
}, X = async (e, t, n, r) => {
|
|
627
|
+
let i = n?.limit ?? 100, a = {
|
|
628
|
+
codec: t,
|
|
629
|
+
rawMessages: [],
|
|
630
|
+
returnedCount: 0,
|
|
631
|
+
returnedRawCount: 0,
|
|
632
|
+
lastAblyPage: void 0,
|
|
633
|
+
getMessageKey: t.getMessageKey.bind(t),
|
|
634
|
+
logger: r
|
|
635
|
+
};
|
|
636
|
+
r.trace("decodeHistory();", { limit: i });
|
|
637
|
+
let o = i * 10;
|
|
638
|
+
return await e.attach(), await J(a, await e.history({
|
|
639
|
+
untilAttach: !0,
|
|
640
|
+
limit: o
|
|
641
|
+
}), i), Y(a, i);
|
|
642
|
+
}, Z = class {
|
|
643
|
+
constructor(e, t) {
|
|
644
|
+
this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
|
|
645
|
+
}
|
|
646
|
+
createStream(t) {
|
|
647
|
+
this._logger.trace("StreamRouter.createStream();", { turnId: t });
|
|
648
|
+
let n = {}, r = new ReadableStream({ start(e) {
|
|
649
|
+
n.controller = e;
|
|
650
|
+
} });
|
|
651
|
+
if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", x.TransportSubscriptionError, 500);
|
|
652
|
+
return this._turns.set(t, {
|
|
653
|
+
controller: n.controller,
|
|
654
|
+
turnId: t
|
|
655
|
+
}), r;
|
|
656
|
+
}
|
|
657
|
+
closeStream(e) {
|
|
658
|
+
let t = this._turns.get(e);
|
|
659
|
+
if (!t) return !1;
|
|
660
|
+
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
661
|
+
try {
|
|
662
|
+
t.controller.close();
|
|
663
|
+
} catch {}
|
|
664
|
+
return this._turns.delete(e), !0;
|
|
665
|
+
}
|
|
666
|
+
route(e, t) {
|
|
667
|
+
let n = this._turns.get(e);
|
|
668
|
+
if (!n) return !1;
|
|
669
|
+
try {
|
|
670
|
+
n.controller.enqueue(t);
|
|
671
|
+
} catch {
|
|
672
|
+
return this._turns.delete(e), !1;
|
|
673
|
+
}
|
|
674
|
+
return this._isTerminal(t) && this.closeStream(e), !0;
|
|
675
|
+
}
|
|
676
|
+
has(e) {
|
|
677
|
+
return this._turns.has(e);
|
|
678
|
+
}
|
|
679
|
+
}, Q = (e, t) => new Z(e, t), te = () => {}, ne = class {
|
|
680
|
+
constructor(e) {
|
|
681
|
+
if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this._turnClientIds = /* @__PURE__ */ new Map(), this._turnMsgIds = /* @__PURE__ */ new Map(), this._turnObservers = /* @__PURE__ */ new Map(), this._ablyMessages = [], this._withheldKeys = /* @__PURE__ */ new Set(), this._closed = !1, this._channel = e.channel, this._codec = e.codec, this._clientId = e.clientId, this._api = e.api ?? "/api/chat", this._credentials = e.credentials, this._headersFn = typeof e.headers == "function" ? e.headers : e.headers ? () => e.headers : void 0, this._bodyFn = typeof e.body == "function" ? e.body : e.body ? () => e.body : void 0, this._fetchFn = e.fetch ?? globalThis.fetch.bind(globalThis), this._logger = (e.logger ?? V({ logLevel: z.Silent })).withContext({ component: "ClientTransport" }), this._emitter = new R(this._logger), this._tree = K(this._codec.getMessageKey.bind(this._codec), this._logger), this._router = Q(this._codec.isTerminal.bind(this._codec), this._logger), this._decoder = this._codec.createDecoder(), e.messages) {
|
|
682
|
+
let t;
|
|
683
|
+
for (let n of e.messages) {
|
|
684
|
+
let e = this._codec.getMessageKey(n), r = {};
|
|
685
|
+
t && (r[f] = t), this._tree.upsert(e, n, r), t = e;
|
|
686
|
+
}
|
|
687
|
+
this._emitter.emit("message");
|
|
688
|
+
}
|
|
689
|
+
this._onMessage = (e) => {
|
|
690
|
+
this._handleMessage(e);
|
|
691
|
+
}, this._attachPromise = this._channel.subscribe(this._onMessage);
|
|
692
|
+
}
|
|
693
|
+
_handleMessage(t) {
|
|
694
|
+
if (!this._closed) {
|
|
695
|
+
this._ablyMessages.push(t), this._emitter.emit("ably-message");
|
|
696
|
+
try {
|
|
697
|
+
if (t.name === "x-ably-turn-start") {
|
|
698
|
+
let e = C(t), n = e[i], r = e["x-ably-turn-client-id"] ?? "";
|
|
699
|
+
n && (this._turnClientIds.set(n, r), this._emitter.emit("turn", {
|
|
700
|
+
type: g,
|
|
701
|
+
turnId: n,
|
|
702
|
+
clientId: r
|
|
703
|
+
}));
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
if (t.name === "x-ably-turn-end") {
|
|
707
|
+
let e = C(t), n = e[i], r = e["x-ably-turn-client-id"] ?? "", a = e["x-ably-turn-reason"] ?? "complete";
|
|
708
|
+
if (n) {
|
|
709
|
+
this._router.closeStream(n), this._turnObservers.delete(n), this._turnClientIds.delete(n);
|
|
710
|
+
let e = this._turnMsgIds.get(n);
|
|
711
|
+
if (e) {
|
|
712
|
+
for (let t of e) this._ownMsgIds.delete(t);
|
|
713
|
+
this._turnMsgIds.delete(n);
|
|
714
|
+
}
|
|
715
|
+
this._ownTurnIds.delete(n), this._emitter.emit("turn", {
|
|
716
|
+
type: _,
|
|
717
|
+
turnId: n,
|
|
718
|
+
clientId: r,
|
|
719
|
+
reason: a
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
let e = this._decoder.decode(t), n = C(t), r = t.serial, a = n[i];
|
|
725
|
+
a && this._updateTurnObserverHeaders(a, n, r);
|
|
726
|
+
for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
|
|
727
|
+
} catch (t) {
|
|
728
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
729
|
+
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, x.TransportSubscriptionError, 500, n));
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
_handleMessageOutput(e, t, n, r) {
|
|
734
|
+
let i = t[a];
|
|
735
|
+
if (i && this._ownMsgIds.has(i)) {
|
|
736
|
+
this._upsertAndNotify(e, t, n);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
r === "message.create" && this._upsertAndNotify(e, t, n);
|
|
740
|
+
}
|
|
741
|
+
_handleEventOutput(e, t) {
|
|
742
|
+
if (e.kind !== "event") return;
|
|
743
|
+
let n = e.event, r = t[i];
|
|
744
|
+
if (r) {
|
|
745
|
+
if (this._router.route(r, n)) {
|
|
746
|
+
this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
_upsertAndNotify(e, t, n) {
|
|
753
|
+
let r = this._codec.getMessageKey(e), i = t["x-ably-msg-id"] ?? r;
|
|
754
|
+
this._tree.upsert(i, e, t, n), this._emitter.emit("message");
|
|
755
|
+
}
|
|
756
|
+
_updateTurnObserverHeaders(e, t, n) {
|
|
757
|
+
let r = this._turnObservers.get(e);
|
|
758
|
+
r ? (Object.keys(t).length > 0 && Object.assign(r.headers, t), n !== void 0 && (r.serial = n)) : this._turnObservers.set(e, {
|
|
759
|
+
headers: { ...t },
|
|
760
|
+
serial: n,
|
|
761
|
+
accumulator: this._codec.createAccumulator()
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
_accumulateAndEmit(e, t) {
|
|
765
|
+
let n = this._turnObservers.get(e);
|
|
766
|
+
if (!n) return;
|
|
767
|
+
n.accumulator.processOutputs([t]);
|
|
768
|
+
let r = n.accumulator.messages;
|
|
769
|
+
if (r.length === 0) return;
|
|
770
|
+
let i;
|
|
771
|
+
try {
|
|
772
|
+
i = structuredClone(r.at(-1));
|
|
773
|
+
} catch {
|
|
774
|
+
i = r.at(-1);
|
|
775
|
+
}
|
|
776
|
+
i && (this._tree.upsert(n.headers["x-ably-msg-id"] ?? this._codec.getMessageKey(i), i, { ...n.headers }, n.serial), this._emitter.emit("message"));
|
|
777
|
+
}
|
|
778
|
+
async _publishCancel(e) {
|
|
779
|
+
this._logger.trace("ClientTransport._publishCancel();", { filter: e });
|
|
780
|
+
let t = {};
|
|
781
|
+
e.turnId ? t[c] = e.turnId : e.own ? t[l] = "true" : e.clientId ? t[d] = e.clientId : e.all && (t[u] = "true"), await this._channel.publish({
|
|
782
|
+
name: h,
|
|
783
|
+
extras: { headers: t }
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
_closeMatchingTurnStreams(e) {
|
|
787
|
+
if (e.all) for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
788
|
+
else if (e.own) for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
789
|
+
else if (e.clientId) for (let [t, n] of this._turnClientIds) n === e.clientId && this._router.closeStream(t);
|
|
790
|
+
else e.turnId && this._router.closeStream(e.turnId);
|
|
791
|
+
}
|
|
792
|
+
_getMatchingTurnIds(e) {
|
|
793
|
+
let t = /* @__PURE__ */ new Set();
|
|
794
|
+
if (e.all) for (let e of this._turnClientIds.keys()) t.add(e);
|
|
795
|
+
else if (e.own) for (let [e, n] of this._turnClientIds) n === this._clientId && t.add(e);
|
|
796
|
+
else if (e.clientId) for (let [n, r] of this._turnClientIds) r === e.clientId && t.add(n);
|
|
797
|
+
else e.turnId && this._turnClientIds.has(e.turnId) && t.add(e.turnId);
|
|
798
|
+
return t;
|
|
799
|
+
}
|
|
800
|
+
_getMessagesWithHeaders() {
|
|
801
|
+
return this._tree.flatten().map((e) => ({
|
|
802
|
+
message: e,
|
|
803
|
+
headers: this.getMessageHeaders(e)
|
|
804
|
+
}));
|
|
805
|
+
}
|
|
806
|
+
_getHistoryBefore(e) {
|
|
807
|
+
let t = this._getMessagesWithHeaders(), n = t.findIndex((t) => t.headers?.[a] === e);
|
|
808
|
+
return n === -1 ? t : t.slice(0, n);
|
|
809
|
+
}
|
|
810
|
+
_processHistoryPage(e) {
|
|
811
|
+
for (let [t, n] of e.items.entries()) {
|
|
812
|
+
let r = e.itemHeaders?.[t] ?? {}, i = e.itemSerials?.[t], a = this._codec.getMessageKey(n), o = r["x-ably-msg-id"] ?? a;
|
|
813
|
+
this._tree.upsert(o, n, r, i);
|
|
814
|
+
}
|
|
815
|
+
this._emitter.emit("message"), e.rawMessages && e.rawMessages.length > 0 && (this._ablyMessages.unshift(...e.rawMessages), this._emitter.emit("ably-message"));
|
|
816
|
+
}
|
|
817
|
+
async _loadUntilVisible(e, t, n) {
|
|
818
|
+
this._processHistoryPage(e);
|
|
819
|
+
let r = e, i = () => {
|
|
820
|
+
let e = 0;
|
|
821
|
+
for (let t of this._tree.flatten()) n.has(this._codec.getMessageKey(t)) || e++;
|
|
822
|
+
return e;
|
|
823
|
+
};
|
|
824
|
+
for (; i() < t && r.hasNext();) {
|
|
825
|
+
let e = await r.next();
|
|
826
|
+
if (!e) break;
|
|
827
|
+
this._processHistoryPage(e), r = e;
|
|
828
|
+
}
|
|
829
|
+
return {
|
|
830
|
+
newVisible: this._tree.flatten().filter((e) => !n.has(this._codec.getMessageKey(e))),
|
|
831
|
+
lastPage: r
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
_releaseWithheld(e) {
|
|
835
|
+
for (let t of e) this._withheldKeys.delete(this._codec.getMessageKey(t));
|
|
836
|
+
e.length > 0 && this._emitter.emit("message");
|
|
837
|
+
}
|
|
838
|
+
async send(t, n) {
|
|
839
|
+
if (this._closed || (await this._attachPromise, this._closed)) throw new e.ErrorInfo("unable to send; transport is closed", x.TransportClosed, 400);
|
|
840
|
+
this._logger.trace("ClientTransport.send();");
|
|
841
|
+
let r = Array.isArray(t) ? t : [t], i = crypto.randomUUID();
|
|
842
|
+
this._ownTurnIds.add(i);
|
|
843
|
+
let o = /* @__PURE__ */ new Set(), c = [], l = this._getMessagesWithHeaders(), u;
|
|
844
|
+
if (n?.parent === void 0 && !n?.forkOf) {
|
|
845
|
+
let e = this._tree.flatten();
|
|
846
|
+
if (e.length > 0) {
|
|
847
|
+
let t = e.at(-1);
|
|
848
|
+
if (t) {
|
|
849
|
+
let e = this._codec.getMessageKey(t);
|
|
850
|
+
u = this._tree.getNodeByKey(e)?.msgId ?? e;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
let d = n?.parent === void 0 ? u : n.parent;
|
|
855
|
+
for (let e of r) {
|
|
856
|
+
let t = crypto.randomUUID();
|
|
857
|
+
this._ownMsgIds.add(t), o.add(t);
|
|
858
|
+
let r = n?.parent === void 0 ? u : n.parent ?? void 0, l = j({
|
|
859
|
+
role: "user",
|
|
860
|
+
turnId: i,
|
|
861
|
+
msgId: t,
|
|
862
|
+
turnClientId: this._clientId,
|
|
863
|
+
parent: r,
|
|
864
|
+
forkOf: n?.forkOf
|
|
865
|
+
});
|
|
866
|
+
this._upsertAndNotify(e, l);
|
|
867
|
+
let d = {
|
|
868
|
+
[a]: t,
|
|
869
|
+
[s]: "user"
|
|
870
|
+
};
|
|
871
|
+
r && (d[f] = r), c.push({
|
|
872
|
+
message: e,
|
|
873
|
+
headers: d
|
|
874
|
+
}), n?.parent === void 0 && !n?.forkOf && (u = t);
|
|
875
|
+
}
|
|
876
|
+
this._turnMsgIds.set(i, o);
|
|
877
|
+
let p = this._router.createStream(i), m = this._headersFn?.() ?? {}, h = {
|
|
878
|
+
...this._bodyFn?.() ?? {},
|
|
879
|
+
history: l,
|
|
880
|
+
...n?.body,
|
|
881
|
+
turnId: i,
|
|
882
|
+
clientId: this._clientId,
|
|
883
|
+
messages: c,
|
|
884
|
+
...n?.forkOf !== void 0 && { forkOf: n.forkOf },
|
|
885
|
+
...d !== void 0 && { parent: d }
|
|
886
|
+
}, g = {
|
|
887
|
+
...m,
|
|
888
|
+
...n?.headers
|
|
889
|
+
};
|
|
890
|
+
return this._fetchFn(this._api, {
|
|
891
|
+
method: "POST",
|
|
892
|
+
headers: {
|
|
893
|
+
"Content-Type": "application/json",
|
|
894
|
+
...g
|
|
895
|
+
},
|
|
896
|
+
body: JSON.stringify(h),
|
|
897
|
+
...this._credentials ? { credentials: this._credentials } : {}
|
|
898
|
+
}).then((t) => {
|
|
899
|
+
t.ok || (this._emitter.emit("error", new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(t.status)} ${t.statusText}`, x.TransportSendFailed, t.status)), this._router.closeStream(i));
|
|
900
|
+
}).catch((t) => {
|
|
901
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
902
|
+
this._emitter.emit("error", new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${t instanceof Error ? t.message : String(t)}`, x.TransportSendFailed, 500, n)), this._router.closeStream(i);
|
|
903
|
+
}), {
|
|
904
|
+
stream: p,
|
|
905
|
+
turnId: i,
|
|
906
|
+
cancel: async () => this.cancel({ turnId: i })
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
async regenerate(e, t) {
|
|
910
|
+
this._logger.trace("ClientTransport.regenerate();", { messageId: e });
|
|
911
|
+
let n = this._tree.getNode(e)?.parentId;
|
|
912
|
+
return this.send([], {
|
|
913
|
+
...t,
|
|
914
|
+
body: {
|
|
915
|
+
history: this._getHistoryBefore(e),
|
|
916
|
+
...t?.body
|
|
917
|
+
},
|
|
918
|
+
forkOf: e,
|
|
919
|
+
parent: n
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
async edit(e, t, n) {
|
|
923
|
+
this._logger.trace("ClientTransport.edit();", { messageId: e });
|
|
924
|
+
let r = this._tree.getNode(e)?.parentId;
|
|
925
|
+
return this.send(t, {
|
|
926
|
+
...n,
|
|
927
|
+
body: {
|
|
928
|
+
history: this._getHistoryBefore(e),
|
|
929
|
+
...n?.body
|
|
930
|
+
},
|
|
931
|
+
forkOf: e,
|
|
932
|
+
parent: r
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
async cancel(e) {
|
|
936
|
+
if (this._closed) return;
|
|
937
|
+
let t = e ?? { own: !0 };
|
|
938
|
+
this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
|
|
939
|
+
}
|
|
940
|
+
async waitForTurn(e) {
|
|
941
|
+
if (this._closed) return;
|
|
942
|
+
let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
|
|
943
|
+
if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
|
|
944
|
+
let t = (r) => {
|
|
945
|
+
r.type === "x-ably-turn-end" && (n.delete(r.turnId), n.size === 0 && (this._emitter.off("turn", t), e()));
|
|
946
|
+
};
|
|
947
|
+
this._emitter.on("turn", t);
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
on(e, t) {
|
|
951
|
+
if (this._closed) return te;
|
|
952
|
+
let n = t;
|
|
953
|
+
return this._emitter.on(e, n), () => {
|
|
954
|
+
this._emitter.off(e, n);
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
getTree() {
|
|
958
|
+
return this._tree;
|
|
959
|
+
}
|
|
960
|
+
getActiveTurnIds() {
|
|
961
|
+
let e = /* @__PURE__ */ new Map();
|
|
962
|
+
for (let [t, n] of this._turnClientIds) {
|
|
963
|
+
let r = e.get(n);
|
|
964
|
+
r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
|
|
965
|
+
}
|
|
966
|
+
return e;
|
|
967
|
+
}
|
|
968
|
+
getMessageHeaders(e) {
|
|
969
|
+
let t = this._codec.getMessageKey(e);
|
|
970
|
+
return this._tree.getNodeByKey(t)?.headers;
|
|
971
|
+
}
|
|
972
|
+
getMessages() {
|
|
973
|
+
return this._withheldKeys.size === 0 ? this._tree.flatten() : this._tree.flatten().filter((e) => !this._withheldKeys.has(this._codec.getMessageKey(e)));
|
|
974
|
+
}
|
|
975
|
+
getMessagesWithHeaders() {
|
|
976
|
+
return this._getMessagesWithHeaders();
|
|
977
|
+
}
|
|
978
|
+
getAblyMessages() {
|
|
979
|
+
return [...this._ablyMessages];
|
|
980
|
+
}
|
|
981
|
+
async history(t) {
|
|
982
|
+
if (this._closed) throw new e.ErrorInfo("unable to load history; transport is closed", x.TransportClosed, 400);
|
|
983
|
+
this._logger.trace("ClientTransport.history();", { limit: t?.limit });
|
|
984
|
+
let n = t?.limit ?? 100, r = new Set(this._tree.flatten().map((e) => this._codec.getMessageKey(e))), i = await X(this._channel, this._codec, t, this._logger), a = await this._loadUntilVisible(i, n, r);
|
|
985
|
+
i = a.lastPage;
|
|
986
|
+
let o = a.newVisible;
|
|
987
|
+
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
988
|
+
let s = o.slice(-n), c = o.slice(0, -n);
|
|
989
|
+
this._releaseWithheld(s);
|
|
990
|
+
let l = (e) => ({
|
|
991
|
+
items: e,
|
|
992
|
+
hasNext: () => c.length > 0 || i.hasNext(),
|
|
993
|
+
next: async () => {
|
|
994
|
+
if (c.length > 0) {
|
|
995
|
+
let e = c.splice(-n, n);
|
|
996
|
+
return this._releaseWithheld(e), l(e);
|
|
997
|
+
}
|
|
998
|
+
if (!i.hasNext()) return;
|
|
999
|
+
let e = await i.next();
|
|
1000
|
+
if (!e) return;
|
|
1001
|
+
let t = new Set(r);
|
|
1002
|
+
for (let e of this._tree.flatten()) t.add(this._codec.getMessageKey(e));
|
|
1003
|
+
let a = await this._loadUntilVisible(e, n, t);
|
|
1004
|
+
i = a.lastPage;
|
|
1005
|
+
let o = a.newVisible;
|
|
1006
|
+
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
1007
|
+
let s = o.splice(-n, n);
|
|
1008
|
+
if (c.push(...o), this._releaseWithheld(s), s.length !== 0) return l(s);
|
|
1009
|
+
}
|
|
1010
|
+
});
|
|
1011
|
+
return l(s);
|
|
1012
|
+
}
|
|
1013
|
+
async close(e) {
|
|
1014
|
+
if (!this._closed) {
|
|
1015
|
+
if (this._closed = !0, this._logger.info("ClientTransport.close();"), e?.cancel) {
|
|
1016
|
+
try {
|
|
1017
|
+
await this._publishCancel(e.cancel);
|
|
1018
|
+
} catch {}
|
|
1019
|
+
this._closeMatchingTurnStreams(e.cancel);
|
|
1020
|
+
}
|
|
1021
|
+
this._channel.unsubscribe(this._onMessage);
|
|
1022
|
+
for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
1023
|
+
this._turnObservers.clear(), this._emitter.off(), this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear(), this._turnClientIds.clear(), this._withheldKeys.clear(), this._ablyMessages.length = 0;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
}, re = (e) => new ne(e), ie = (e) => [{
|
|
1027
|
+
kind: "event",
|
|
1028
|
+
event: e
|
|
1029
|
+
}], ae = class {
|
|
1030
|
+
constructor(e, t = {}) {
|
|
1031
|
+
this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
|
|
1032
|
+
}
|
|
1033
|
+
decode(e) {
|
|
1034
|
+
let t = e.action;
|
|
1035
|
+
this._logger?.trace("DefaultDecoderCore.decode();", {
|
|
1036
|
+
action: t,
|
|
1037
|
+
serial: e.serial,
|
|
1038
|
+
name: e.name
|
|
1039
|
+
});
|
|
1040
|
+
let n;
|
|
1041
|
+
switch (t) {
|
|
1042
|
+
case "message.create": {
|
|
1043
|
+
let t = this._toPayload(e);
|
|
1044
|
+
n = t.headers?.["x-ably-stream"] === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
|
|
1045
|
+
break;
|
|
1046
|
+
}
|
|
1047
|
+
case "message.append":
|
|
1048
|
+
n = this._decodeAppend(e);
|
|
1049
|
+
break;
|
|
1050
|
+
case "message.update":
|
|
1051
|
+
n = this._decodeUpdate(e);
|
|
1052
|
+
break;
|
|
1053
|
+
case "message.delete":
|
|
1054
|
+
n = this._decodeDelete(e);
|
|
1055
|
+
break;
|
|
1056
|
+
default: return [];
|
|
1057
|
+
}
|
|
1058
|
+
let r = C(e)[a];
|
|
1059
|
+
if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
|
|
1060
|
+
return n;
|
|
1061
|
+
}
|
|
1062
|
+
_toPayload(e) {
|
|
1063
|
+
return {
|
|
1064
|
+
name: e.name ?? "",
|
|
1065
|
+
data: e.data,
|
|
1066
|
+
headers: C(e)
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
_stringData(e) {
|
|
1070
|
+
return typeof e.data == "string" ? e.data : "";
|
|
1071
|
+
}
|
|
1072
|
+
_invokeOnStreamUpdate(e) {
|
|
1073
|
+
if (this._onStreamUpdate) try {
|
|
1074
|
+
this._onStreamUpdate(e);
|
|
1075
|
+
} catch (e) {
|
|
1076
|
+
this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
_invokeOnStreamDelete(e, t) {
|
|
1080
|
+
if (this._onStreamDelete) try {
|
|
1081
|
+
this._onStreamDelete(e, t);
|
|
1082
|
+
} catch (e) {
|
|
1083
|
+
this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
_decodeStreamedCreate(e, t) {
|
|
1087
|
+
if (!t) return [];
|
|
1088
|
+
let n = e.headers?.["x-ably-stream-id"] ?? "", r = e.headers ?? {}, i = {
|
|
1089
|
+
name: e.name,
|
|
1090
|
+
streamId: n,
|
|
1091
|
+
accumulated: "",
|
|
1092
|
+
headers: { ...r },
|
|
1093
|
+
closed: !1
|
|
1094
|
+
};
|
|
1095
|
+
return this._serialState.set(t, i), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
|
|
1096
|
+
name: e.name,
|
|
1097
|
+
streamId: n,
|
|
1098
|
+
serial: t
|
|
1099
|
+
}), this._hooks.buildStartEvents(i);
|
|
1100
|
+
}
|
|
1101
|
+
_decodeAppend(e) {
|
|
1102
|
+
let t = e.serial;
|
|
1103
|
+
if (!t) return [];
|
|
1104
|
+
let r = this._serialState.get(t);
|
|
1105
|
+
if (!r) return this._decodeUpdate(e);
|
|
1106
|
+
let i = C(e), a = typeof e.data == "string" ? e.data : "", o = i[n], s = [];
|
|
1107
|
+
return a.length > 0 && (r.accumulated += a, s.push(...this._hooks.buildDeltaEvents(r, a))), o === "finished" && !r.closed ? (r.closed = !0, s.push(...this._hooks.buildEndEvents(r, i)), this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream finished", { streamId: r.streamId })) : o === "aborted" && !r.closed && (r.closed = !0, this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream aborted", { streamId: r.streamId })), s;
|
|
1108
|
+
}
|
|
1109
|
+
_decodeUpdate(e) {
|
|
1110
|
+
let r = e.serial;
|
|
1111
|
+
if (!r) return [];
|
|
1112
|
+
let i = this._toPayload(e), a = i.headers ?? {}, o = a[t] === "true", s = a[n], c = this._serialState.get(r);
|
|
1113
|
+
if (!c) return this._decodeFirstContact(i, o, s, r);
|
|
1114
|
+
let l = this._stringData(e);
|
|
1115
|
+
if (l.startsWith(c.accumulated)) {
|
|
1116
|
+
let e = l.slice(c.accumulated.length), t = [];
|
|
1117
|
+
return e.length > 0 && (c.accumulated = l, t.push(...this._hooks.buildDeltaEvents(c, e))), s === "finished" && !c.closed ? (c.closed = !0, t.push(...this._hooks.buildEndEvents(c, a))) : s === "aborted" && !c.closed && (c.closed = !0), t;
|
|
1118
|
+
}
|
|
1119
|
+
return c.accumulated = l, c.headers = { ...a }, this._invokeOnStreamUpdate(c), [];
|
|
1120
|
+
}
|
|
1121
|
+
_decodeFirstContact(e, t, n, r) {
|
|
1122
|
+
if (!t) return this._hooks.decodeDiscrete(e);
|
|
1123
|
+
let i = e.headers?.["x-ably-stream-id"] ?? "", a = e.headers ?? {}, o = typeof e.data == "string" ? e.data : "";
|
|
1124
|
+
this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
|
|
1125
|
+
name: e.name,
|
|
1126
|
+
streamId: i,
|
|
1127
|
+
serial: r
|
|
1128
|
+
});
|
|
1129
|
+
let s = {
|
|
1130
|
+
name: e.name,
|
|
1131
|
+
streamId: i,
|
|
1132
|
+
accumulated: o,
|
|
1133
|
+
headers: { ...a },
|
|
1134
|
+
closed: n === "finished" || n === "aborted"
|
|
1135
|
+
};
|
|
1136
|
+
this._serialState.set(r, s);
|
|
1137
|
+
let c = this._hooks.buildStartEvents(s);
|
|
1138
|
+
return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "finished" && c.push(...this._hooks.buildEndEvents(s, a)), c;
|
|
1139
|
+
}
|
|
1140
|
+
_decodeDelete(e) {
|
|
1141
|
+
let t = e.serial;
|
|
1142
|
+
if (!t) return [];
|
|
1143
|
+
let n = this._serialState.get(t);
|
|
1144
|
+
return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
|
|
1145
|
+
}
|
|
1146
|
+
}, oe = (e, t = {}) => new ae(e, t), $ = class {
|
|
1147
|
+
constructor(e, t = {}) {
|
|
1148
|
+
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" });
|
|
1149
|
+
}
|
|
1150
|
+
async publishDiscrete(e, t) {
|
|
1151
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscrete();", { name: e.name });
|
|
1152
|
+
let n = this._buildDiscreteMessage(e, t);
|
|
1153
|
+
return this._writer.publish(n);
|
|
1154
|
+
}
|
|
1155
|
+
async publishDiscreteBatch(e, t) {
|
|
1156
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
|
|
1157
|
+
let n = e.map((e) => this._buildDiscreteMessage(e, t));
|
|
1158
|
+
return this._writer.publish(n);
|
|
1159
|
+
}
|
|
1160
|
+
async startStream(i, a, o) {
|
|
1161
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.startStream();", {
|
|
1162
|
+
name: a.name,
|
|
1163
|
+
streamId: i
|
|
1164
|
+
});
|
|
1165
|
+
let s = this._buildHeaders(a.headers ?? {}, o);
|
|
1166
|
+
s[t] = "true", s[n] = "streaming", s[r] = i;
|
|
1167
|
+
let c = this._resolveClientId(o), l = {
|
|
1168
|
+
name: a.name,
|
|
1169
|
+
data: a.data,
|
|
1170
|
+
extras: { headers: s },
|
|
1171
|
+
...c ? { clientId: c } : {}
|
|
1172
|
+
};
|
|
1173
|
+
this._invokeOnMessage(l);
|
|
1174
|
+
let u = (await this._writer.publish(l)).serials[0];
|
|
1175
|
+
if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${i})`, x.BadRequest, 400);
|
|
1176
|
+
this._trackers.set(i, {
|
|
1177
|
+
serial: u,
|
|
1178
|
+
name: a.name,
|
|
1179
|
+
streamId: i,
|
|
1180
|
+
accumulated: a.data,
|
|
1181
|
+
persistentHeaders: s,
|
|
1182
|
+
aborted: !1
|
|
1183
|
+
}), this._logger?.debug("DefaultEncoderCore.startStream(); stream started", {
|
|
1184
|
+
name: a.name,
|
|
1185
|
+
streamId: i,
|
|
1186
|
+
serial: u
|
|
1187
|
+
});
|
|
1188
|
+
}
|
|
1189
|
+
appendStream(t, n) {
|
|
1190
|
+
this._assertNotClosed();
|
|
1191
|
+
let r = this._trackers.get(t);
|
|
1192
|
+
if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, x.InvalidArgument, 400);
|
|
1193
|
+
r.accumulated += n;
|
|
1194
|
+
let i = {
|
|
1195
|
+
serial: r.serial,
|
|
1196
|
+
data: n,
|
|
1197
|
+
extras: { headers: { ...r.persistentHeaders } }
|
|
1198
|
+
};
|
|
1199
|
+
this._invokeOnMessage(i);
|
|
1200
|
+
let a = this._writer.appendMessage(i);
|
|
1201
|
+
this._pending.push({
|
|
1202
|
+
promise: a,
|
|
1203
|
+
streamId: t
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
async closeStream(t, r) {
|
|
1207
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.closeStream();", { streamId: t });
|
|
1208
|
+
let i = this._trackers.get(t);
|
|
1209
|
+
if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, x.InvalidArgument, 400);
|
|
1210
|
+
i.accumulated += r.data;
|
|
1211
|
+
let a = this._buildClosingHeaders(i, r.headers ?? {});
|
|
1212
|
+
a[n] = "finished";
|
|
1213
|
+
let o = {
|
|
1214
|
+
serial: i.serial,
|
|
1215
|
+
data: r.data,
|
|
1216
|
+
extras: { headers: a }
|
|
1217
|
+
};
|
|
1218
|
+
this._invokeOnMessage(o);
|
|
1219
|
+
let s = this._writer.appendMessage(o);
|
|
1220
|
+
this._pending.push({
|
|
1221
|
+
promise: s,
|
|
1222
|
+
streamId: t
|
|
1223
|
+
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.closeStream(); stream closed", { streamId: t });
|
|
1224
|
+
}
|
|
1225
|
+
async abortStream(t, r) {
|
|
1226
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortStream();", { streamId: t });
|
|
1227
|
+
let i = this._trackers.get(t);
|
|
1228
|
+
if (!i) throw new e.ErrorInfo(`unable to abort stream; no active stream for streamId '${t}'`, x.InvalidArgument, 400);
|
|
1229
|
+
i.aborted = !0;
|
|
1230
|
+
let a = this._buildClosingHeaders(i, {}, r);
|
|
1231
|
+
a[n] = "aborted";
|
|
1232
|
+
let o = {
|
|
1233
|
+
serial: i.serial,
|
|
1234
|
+
data: "",
|
|
1235
|
+
extras: { headers: a }
|
|
1236
|
+
};
|
|
1237
|
+
this._invokeOnMessage(o);
|
|
1238
|
+
let s = this._writer.appendMessage(o);
|
|
1239
|
+
this._pending.push({
|
|
1240
|
+
promise: s,
|
|
1241
|
+
streamId: t
|
|
1242
|
+
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.abortStream(); stream aborted", { streamId: t });
|
|
1243
|
+
}
|
|
1244
|
+
async abortAllStreams(e) {
|
|
1245
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortAllStreams();", { streamCount: this._trackers.size });
|
|
1246
|
+
for (let t of this._trackers.values()) {
|
|
1247
|
+
t.aborted = !0;
|
|
1248
|
+
let r = this._buildClosingHeaders(t, {}, e);
|
|
1249
|
+
r[n] = "aborted";
|
|
1250
|
+
let i = {
|
|
1251
|
+
serial: t.serial,
|
|
1252
|
+
data: "",
|
|
1253
|
+
extras: { headers: r }
|
|
1254
|
+
};
|
|
1255
|
+
this._invokeOnMessage(i);
|
|
1256
|
+
let a = this._writer.appendMessage(i);
|
|
1257
|
+
this._pending.push({
|
|
1258
|
+
promise: a,
|
|
1259
|
+
streamId: t.streamId
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
await this._flushPending();
|
|
1263
|
+
}
|
|
1264
|
+
async _flushPending() {
|
|
1265
|
+
if (this._flushPromise) return this._flushPromise;
|
|
1266
|
+
let e = this._pending;
|
|
1267
|
+
if (this._pending = [], e.length !== 0) {
|
|
1268
|
+
this._logger?.trace("DefaultEncoderCore._flushPending();", { count: e.length }), this._flushPromise = this._doFlush(e);
|
|
1269
|
+
try {
|
|
1270
|
+
await this._flushPromise;
|
|
1271
|
+
} finally {
|
|
1272
|
+
this._flushPromise = void 0;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
async _doFlush(t) {
|
|
1277
|
+
let r = await Promise.allSettled(t.map(async (e) => e.promise)), i = /* @__PURE__ */ new Set();
|
|
1278
|
+
for (let [e, n] of r.entries()) {
|
|
1279
|
+
let r = t[e];
|
|
1280
|
+
r && n.status === "rejected" && i.add(r.streamId);
|
|
1281
|
+
}
|
|
1282
|
+
if (i.size === 0) {
|
|
1283
|
+
this._logger?.debug("DefaultEncoderCore._flushPending(); all appends succeeded");
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
this._logger?.warn("DefaultEncoderCore._flushPending(); recovering failed appends", { failedStreams: [...i] });
|
|
1287
|
+
let a = [];
|
|
1288
|
+
for (let e of i) {
|
|
1289
|
+
let t = this._trackers.get(e);
|
|
1290
|
+
if (!t) continue;
|
|
1291
|
+
let r = t.aborted ? "aborted" : "finished", i = {
|
|
1292
|
+
serial: t.serial,
|
|
1293
|
+
data: t.accumulated,
|
|
1294
|
+
extras: { headers: {
|
|
1295
|
+
...t.persistentHeaders,
|
|
1296
|
+
[n]: r
|
|
1297
|
+
} }
|
|
1298
|
+
};
|
|
1299
|
+
try {
|
|
1300
|
+
await this._writer.updateMessage(i);
|
|
1301
|
+
} catch (t) {
|
|
1302
|
+
a.push({
|
|
1303
|
+
streamId: e,
|
|
1304
|
+
error: t
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
if (a.length > 0) {
|
|
1309
|
+
let t = a.map((e) => e.streamId).join(", ");
|
|
1310
|
+
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, x.EncoderRecoveryFailed, 500);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
async close() {
|
|
1314
|
+
if (!this._closed) {
|
|
1315
|
+
this._logger?.trace("DefaultEncoderCore.close();"), this._closed = !0;
|
|
1316
|
+
try {
|
|
1317
|
+
await this._flushPending();
|
|
1318
|
+
} finally {
|
|
1319
|
+
this._trackers.clear();
|
|
1320
|
+
}
|
|
1321
|
+
this._logger?.debug("DefaultEncoderCore.close(); encoder closed");
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
_invokeOnMessage(e) {
|
|
1325
|
+
try {
|
|
1326
|
+
this._onMessageHook(e);
|
|
1327
|
+
} catch (e) {
|
|
1328
|
+
this._logger?.error("DefaultEncoderCore._invokeOnMessage(); hook threw", { error: e });
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
_assertNotClosed() {
|
|
1332
|
+
if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", x.InvalidArgument, 400);
|
|
1333
|
+
}
|
|
1334
|
+
_resolveClientId(e) {
|
|
1335
|
+
return e?.clientId ?? this._defaultClientId;
|
|
1336
|
+
}
|
|
1337
|
+
_buildHeaders(e, t) {
|
|
1338
|
+
let n = {
|
|
1339
|
+
...T(this._defaultExtras?.headers, t?.extras?.headers),
|
|
1340
|
+
...e
|
|
1341
|
+
};
|
|
1342
|
+
return t?.messageId !== void 0 && (n[a] = t.messageId), n;
|
|
1343
|
+
}
|
|
1344
|
+
_buildDiscreteMessage(e, n) {
|
|
1345
|
+
let r = this._buildHeaders(e.headers ?? {}, n);
|
|
1346
|
+
r[t] = "false";
|
|
1347
|
+
let i = this._resolveClientId(n), a = {
|
|
1348
|
+
name: e.name,
|
|
1349
|
+
data: e.data,
|
|
1350
|
+
extras: {
|
|
1351
|
+
headers: r,
|
|
1352
|
+
...e.ephemeral ? { ephemeral: !0 } : {}
|
|
1353
|
+
},
|
|
1354
|
+
...i ? { clientId: i } : {}
|
|
1355
|
+
};
|
|
1356
|
+
return this._invokeOnMessage(a), a;
|
|
1357
|
+
}
|
|
1358
|
+
_buildClosingHeaders(e, t, n) {
|
|
1359
|
+
let r = { ...e.persistentHeaders }, i = T(this._defaultExtras?.headers, n?.extras?.headers);
|
|
1360
|
+
return Object.assign(r, i), Object.assign(r, t), r;
|
|
1361
|
+
}
|
|
1362
|
+
}, se = (e, t = {}) => new $(e, t), ce = class {
|
|
1363
|
+
constructor(e) {
|
|
1364
|
+
this._emitted = /* @__PURE__ */ new Map(), this._phases = e;
|
|
1365
|
+
}
|
|
1366
|
+
ensurePhases(e, t) {
|
|
1367
|
+
let n = this._getOrCreate(e), r = [];
|
|
1368
|
+
for (let e of this._phases) n.has(e.key) || (n.add(e.key), r.push(...e.build(t)));
|
|
1369
|
+
return r;
|
|
1370
|
+
}
|
|
1371
|
+
markEmitted(e, t) {
|
|
1372
|
+
this._getOrCreate(e).add(t);
|
|
1373
|
+
}
|
|
1374
|
+
resetPhase(e, t) {
|
|
1375
|
+
this._emitted.get(e)?.delete(t);
|
|
1376
|
+
}
|
|
1377
|
+
clearScope(e) {
|
|
1378
|
+
this._emitted.delete(e);
|
|
1379
|
+
}
|
|
1380
|
+
_getOrCreate(e) {
|
|
1381
|
+
let t = this._emitted.get(e);
|
|
1382
|
+
return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
|
|
1383
|
+
}
|
|
1384
|
+
}, le = (e) => new ce(e);
|
|
1385
|
+
//#endregion
|
|
1386
|
+
export { b as DOMAIN_HEADER_PREFIX, v as EVENT_ABORT, h as EVENT_CANCEL, y as EVENT_ERROR, _ as EVENT_TURN_END, g as EVENT_TURN_START, x as ErrorCode, R as EventEmitter, u as HEADER_CANCEL_ALL, d as HEADER_CANCEL_CLIENT_ID, l as HEADER_CANCEL_OWN, c as HEADER_CANCEL_TURN_ID, p as HEADER_FORK_OF, a as HEADER_MSG_ID, f as HEADER_PARENT, s as HEADER_ROLE, n as HEADER_STATUS, t as HEADER_STREAM, r as HEADER_STREAM_ID, o as HEADER_TURN_CLIENT_ID, i as HEADER_TURN_ID, m as HEADER_TURN_REASON, z as LogLevel, j as buildTransportHeaders, B as consoleLogger, re as createClientTransport, oe as createDecoderCore, se as createEncoderCore, le as createLifecycleTracker, F as createServerTransport, S as errorInfoIs, ie as eventOutput, C as getHeaders, k as headerReader, A as headerWriter, V as makeLogger, T as mergeHeaders, O as stripUndefined };
|
|
1387
|
+
|
|
1388
|
+
//# sourceMappingURL=ably-ai-transport.js.map
|