@ably/ai-transport 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +91 -100
- package/dist/ably-ai-transport.js +1553 -1238
- 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 +116 -42
- package/dist/core/agent.d.ts +29 -0
- package/dist/core/codec/decoder.d.ts +20 -23
- package/dist/core/codec/encoder.d.ts +11 -8
- package/dist/core/codec/index.d.ts +1 -2
- package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
- package/dist/core/codec/types.d.ts +407 -115
- package/dist/core/transport/agent-session.d.ts +10 -0
- package/dist/core/transport/branch-chain.d.ts +43 -0
- package/dist/core/transport/client-session.d.ts +13 -0
- package/dist/core/transport/decode-fold.d.ts +47 -0
- package/dist/core/transport/headers.d.ts +96 -18
- package/dist/core/transport/index.d.ts +5 -6
- package/dist/core/transport/internal/bounded-map.d.ts +20 -0
- package/dist/core/transport/invocation.d.ts +74 -0
- package/dist/core/transport/load-conversation.d.ts +128 -0
- package/dist/core/transport/load-history.d.ts +39 -0
- package/dist/core/transport/pipe-stream.d.ts +9 -9
- package/dist/core/transport/run-manager.d.ts +78 -0
- package/dist/core/transport/tree.d.ts +373 -109
- package/dist/core/transport/types/agent.d.ts +353 -0
- package/dist/core/transport/types/client.d.ts +168 -0
- package/dist/core/transport/types/shared.d.ts +24 -0
- package/dist/core/transport/types/tree.d.ts +315 -0
- package/dist/core/transport/types/view.d.ts +222 -0
- package/dist/core/transport/types.d.ts +13 -553
- package/dist/core/transport/view.d.ts +272 -84
- package/dist/errors.d.ts +21 -10
- package/dist/index.d.ts +6 -8
- package/dist/logger.d.ts +12 -0
- package/dist/react/ably-ai-transport-react.js +976 -990
- 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/client-session-context.d.ts +36 -0
- package/dist/react/contexts/client-session-provider.d.ts +53 -0
- package/dist/react/create-session-hooks.d.ts +116 -0
- package/dist/react/index.d.ts +12 -12
- package/dist/react/internal/use-resolved-session.d.ts +36 -0
- package/dist/react/use-ably-messages.d.ts +17 -14
- package/dist/react/use-client-session.d.ts +81 -0
- package/dist/react/use-create-view.d.ts +14 -13
- package/dist/react/use-tree.d.ts +30 -15
- package/dist/react/use-view.d.ts +82 -51
- package/dist/utils.d.ts +32 -23
- package/dist/vercel/ably-ai-transport-vercel.js +2573 -2086
- 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/decoder.d.ts +5 -18
- package/dist/vercel/codec/encoder.d.ts +6 -36
- package/dist/vercel/codec/events.d.ts +51 -0
- package/dist/vercel/codec/index.d.ts +24 -12
- package/dist/vercel/codec/reducer.d.ts +144 -0
- package/dist/vercel/codec/tool-transitions.d.ts +2 -2
- package/dist/vercel/index.d.ts +4 -5
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +3907 -3266
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +33 -8
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
- package/dist/vercel/react/contexts/chat-transport-context.d.ts +7 -6
- package/dist/vercel/react/contexts/chat-transport-provider.d.ts +53 -41
- package/dist/vercel/react/index.d.ts +1 -2
- package/dist/vercel/react/use-chat-transport.d.ts +30 -26
- package/dist/vercel/react/use-message-sync.d.ts +17 -30
- package/dist/vercel/run-end-reason.d.ts +29 -0
- package/dist/vercel/transport/chat-transport.d.ts +43 -24
- package/dist/vercel/transport/index.d.ts +25 -21
- package/dist/vercel/transport/run-output-stream.d.ts +56 -0
- package/dist/version.d.ts +2 -0
- package/package.json +30 -23
- package/src/constants.ts +124 -51
- package/src/core/agent.ts +68 -0
- package/src/core/codec/decoder.ts +71 -98
- package/src/core/codec/encoder.ts +113 -65
- package/src/core/codec/index.ts +13 -6
- package/src/core/codec/lifecycle-tracker.ts +10 -9
- package/src/core/codec/types.ts +436 -120
- package/src/core/transport/agent-session.ts +1344 -0
- package/src/core/transport/branch-chain.ts +58 -0
- package/src/core/transport/client-session.ts +775 -0
- package/src/core/transport/decode-fold.ts +91 -0
- package/src/core/transport/headers.ts +181 -22
- package/src/core/transport/index.ts +25 -26
- package/src/core/transport/internal/bounded-map.ts +27 -0
- package/src/core/transport/invocation.ts +98 -0
- package/src/core/transport/load-conversation.ts +355 -0
- package/src/core/transport/load-history.ts +269 -0
- package/src/core/transport/pipe-stream.ts +54 -39
- package/src/core/transport/run-manager.ts +249 -0
- package/src/core/transport/tree.ts +926 -308
- package/src/core/transport/types/agent.ts +407 -0
- package/src/core/transport/types/client.ts +211 -0
- package/src/core/transport/types/shared.ts +27 -0
- package/src/core/transport/types/tree.ts +344 -0
- package/src/core/transport/types/view.ts +259 -0
- package/src/core/transport/types.ts +13 -706
- package/src/core/transport/view.ts +864 -433
- package/src/errors.ts +22 -9
- package/src/event-emitter.ts +3 -2
- package/src/index.ts +52 -41
- package/src/logger.ts +14 -1
- package/src/react/contexts/client-session-context.ts +41 -0
- package/src/react/contexts/client-session-provider.tsx +186 -0
- package/src/react/create-session-hooks.ts +141 -0
- package/src/react/index.ts +23 -13
- package/src/react/internal/use-resolved-session.ts +63 -0
- package/src/react/use-ably-messages.ts +32 -22
- package/src/react/use-client-session.ts +201 -0
- package/src/react/use-create-view.ts +33 -29
- package/src/react/use-tree.ts +61 -30
- package/src/react/use-view.ts +139 -97
- package/src/utils.ts +63 -45
- package/src/vercel/codec/decoder.ts +336 -258
- package/src/vercel/codec/encoder.ts +343 -205
- package/src/vercel/codec/events.ts +87 -0
- package/src/vercel/codec/index.ts +60 -13
- package/src/vercel/codec/reducer.ts +977 -0
- package/src/vercel/codec/tool-transitions.ts +2 -2
- package/src/vercel/index.ts +6 -19
- package/src/vercel/react/contexts/chat-transport-context.ts +7 -6
- package/src/vercel/react/contexts/chat-transport-provider.tsx +87 -59
- package/src/vercel/react/index.ts +3 -5
- package/src/vercel/react/use-chat-transport.ts +47 -49
- package/src/vercel/react/use-message-sync.ts +80 -39
- package/src/vercel/run-end-reason.ts +78 -0
- package/src/vercel/transport/chat-transport.ts +392 -98
- package/src/vercel/transport/index.ts +39 -38
- package/src/vercel/transport/run-output-stream.ts +170 -0
- package/src/version.ts +2 -0
- package/dist/core/transport/client-transport.d.ts +0 -10
- package/dist/core/transport/decode-history.d.ts +0 -43
- package/dist/core/transport/server-transport.d.ts +0 -7
- package/dist/core/transport/stream-router.d.ts +0 -29
- package/dist/core/transport/turn-manager.d.ts +0 -37
- package/dist/react/contexts/transport-context.d.ts +0 -31
- package/dist/react/contexts/transport-provider.d.ts +0 -49
- package/dist/react/create-transport-hooks.d.ts +0 -124
- package/dist/react/use-active-turns.d.ts +0 -12
- package/dist/react/use-client-transport.d.ts +0 -80
- package/dist/vercel/codec/accumulator.d.ts +0 -21
- package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +0 -30
- package/dist/vercel/tool-approvals.d.ts +0 -124
- package/dist/vercel/tool-events.d.ts +0 -26
- package/src/core/transport/client-transport.ts +0 -977
- package/src/core/transport/decode-history.ts +0 -485
- package/src/core/transport/server-transport.ts +0 -612
- package/src/core/transport/stream-router.ts +0 -136
- package/src/core/transport/turn-manager.ts +0 -165
- package/src/react/contexts/transport-context.ts +0 -37
- package/src/react/contexts/transport-provider.tsx +0 -164
- package/src/react/create-transport-hooks.ts +0 -144
- package/src/react/use-active-turns.ts +0 -72
- package/src/react/use-client-transport.ts +0 -197
- package/src/vercel/codec/accumulator.ts +0 -588
- package/src/vercel/react/use-staged-add-tool-approval-response.ts +0 -87
- package/src/vercel/tool-approvals.ts +0 -380
- package/src/vercel/tool-events.ts +0 -53
|
@@ -1,437 +1,822 @@
|
|
|
1
1
|
import * as e from "ably";
|
|
2
|
-
//#region src/
|
|
3
|
-
var t =
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
2
|
+
//#region src/core/transport/invocation.ts
|
|
3
|
+
var t = class e {
|
|
4
|
+
constructor(e) {
|
|
5
|
+
this.inputEventId = e.inputEventId, this.sessionName = e.sessionName;
|
|
6
|
+
}
|
|
7
|
+
static fromJSON(t) {
|
|
8
|
+
return new e(t);
|
|
9
|
+
}
|
|
10
|
+
toJSON() {
|
|
11
|
+
return {
|
|
12
|
+
inputEventId: this.inputEventId,
|
|
13
|
+
sessionName: this.sessionName
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
}, n = "stream", r = "status", i = "stream-id", a = "discrete", o = "run-id", s = "invocation-id", c = "event-id", l = "codec-message-id", u = "run-client-id", d = "input-client-id", f = "role", p = "parent", m = "fork-of", h = "msg-regenerate", g = "run-reason", _ = "input-codec-message-id", v = "error-code", y = "error-message", b = "ai-cancel", x = "ai-run-start", S = "ai-run-suspend", C = "ai-run-resume", w = "ai-run-end", T = /* @__PURE__ */ function(e) {
|
|
17
|
+
return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.InsufficientCapability = 40160] = "InsufficientCapability", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.SessionSubscriptionError = 104001] = "SessionSubscriptionError", e[e.CancelListenerError = 104002] = "CancelListenerError", e[e.RunLifecycleError = 104003] = "RunLifecycleError", e[e.SessionClosed = 104004] = "SessionClosed", e[e.SessionSendFailed = 104005] = "SessionSendFailed", e[e.ChannelContinuityLost = 104006] = "ChannelContinuityLost", e[e.ChannelNotReady = 104007] = "ChannelNotReady", e[e.StreamError = 104008] = "StreamError", e[e.InputEventNotFound = 104010] = "InputEventNotFound", e;
|
|
18
|
+
}({}), E = (e, t) => e.code === t, D = (e, t) => {
|
|
19
|
+
let n = e.extras;
|
|
20
|
+
if (!n || typeof n != "object") return {};
|
|
21
|
+
let r = n.ai;
|
|
22
|
+
if (!r || typeof r != "object") return {};
|
|
23
|
+
let i = r[t];
|
|
24
|
+
return !i || typeof i != "object" ? {} : i;
|
|
25
|
+
}, O = (e) => D(e, "transport"), k = (e) => D(e, "codec"), ee = (e) => {
|
|
11
26
|
if (e !== void 0) try {
|
|
12
27
|
return JSON.parse(e);
|
|
13
28
|
} catch {
|
|
14
29
|
return;
|
|
15
30
|
}
|
|
16
|
-
},
|
|
31
|
+
}, A = (e, t) => ({
|
|
17
32
|
...e,
|
|
18
33
|
...t
|
|
19
|
-
}),
|
|
34
|
+
}), j = (e) => {
|
|
20
35
|
if (e !== void 0) return e === "true";
|
|
21
|
-
},
|
|
36
|
+
}, M = (e, t) => e.serial === void 0 && t.serial === void 0 ? 0 : e.serial === void 0 ? 1 : t.serial === void 0 || e.serial < t.serial ? -1 : +(e.serial > t.serial), N = (e, t) => e[t], P = (e) => {
|
|
22
37
|
let t = {};
|
|
23
38
|
for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
|
|
24
39
|
return t;
|
|
25
|
-
},
|
|
26
|
-
str: (t) =>
|
|
27
|
-
strOr: (t, n) =>
|
|
28
|
-
bool: (t) =>
|
|
29
|
-
json: (t) =>
|
|
30
|
-
}),
|
|
40
|
+
}, F = (e) => ({
|
|
41
|
+
str: (t) => N(e, t),
|
|
42
|
+
strOr: (t, n) => N(e, t) ?? n,
|
|
43
|
+
bool: (t) => j(N(e, t)),
|
|
44
|
+
json: (t) => ee(N(e, t))
|
|
45
|
+
}), I = () => {
|
|
31
46
|
let e = {}, t = {
|
|
32
|
-
str: (n, r) => (r !== void 0 && (e[
|
|
33
|
-
bool: (n, r) => (r !== void 0 && (e[
|
|
34
|
-
json: (n, r) => (r != null && (e[
|
|
47
|
+
str: (n, r) => (r !== void 0 && (e[n] = r), t),
|
|
48
|
+
bool: (n, r) => (r !== void 0 && (e[n] = String(r)), t),
|
|
49
|
+
json: (n, r) => (r != null && (e[n] = JSON.stringify(r)), t),
|
|
35
50
|
build: () => e
|
|
36
51
|
};
|
|
37
52
|
return t;
|
|
38
|
-
},
|
|
53
|
+
}, L = "0.2.0", R = "ai-transport-js", z = (e, t) => {
|
|
54
|
+
let n = e;
|
|
55
|
+
return n.options.agents = {
|
|
56
|
+
...n.options.agents,
|
|
57
|
+
...t
|
|
58
|
+
}, { params: { agent: Object.entries(t).map(([e, t]) => `${e}/${t}`).join(" ") } };
|
|
59
|
+
}, B = (e, t) => {
|
|
60
|
+
let n = t?.adapterTag, r = { [R]: L };
|
|
61
|
+
return n && (r[n] = L), z(e, r);
|
|
62
|
+
}, V = (e) => {
|
|
39
63
|
let t = {
|
|
40
|
-
[
|
|
41
|
-
[
|
|
42
|
-
[o]: e.msgId
|
|
64
|
+
[f]: e.role,
|
|
65
|
+
[l]: e.codecMessageId
|
|
43
66
|
};
|
|
44
|
-
return e.
|
|
45
|
-
},
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
67
|
+
return e.runId !== void 0 && (t[o] = e.runId), e.runClientId !== void 0 && (t[u] = e.runClientId), e.parent && (t[p] = e.parent), e.forkOf && (t[m] = e.forkOf), e.regenerates && (t[h] = e.regenerates), e.invocationId && (t[s] = e.invocationId), e.inputClientId !== void 0 && (t[d] = e.inputClientId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), e.inputEventId && (t[c] = e.inputEventId), t;
|
|
68
|
+
}, H = (e) => {
|
|
69
|
+
let t = {
|
|
70
|
+
[o]: e.runId,
|
|
71
|
+
[u]: e.runClientId
|
|
72
|
+
};
|
|
73
|
+
return e.reason !== void 0 && (t[g] = e.reason), e.parent !== void 0 && (t[p] = e.parent), e.forkOf !== void 0 && (t[m] = e.forkOf), e.regenerates !== void 0 && (t[h] = e.regenerates), e.invocationId !== void 0 && (t[s] = e.invocationId), e.inputClientId !== void 0 && (t[d] = e.inputClientId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), t;
|
|
74
|
+
}, U = (e) => e === "ai-run-start" || e === "ai-run-suspend" || e === "ai-run-resume" || e === "ai-run-end", W = (e, t, n) => {
|
|
75
|
+
let r = t[o];
|
|
76
|
+
if (!r) return;
|
|
77
|
+
let i = t["run-client-id"] ?? "";
|
|
78
|
+
if (e === "ai-run-start") {
|
|
79
|
+
let e = t[p], a = t[m], o = t[h];
|
|
80
|
+
return {
|
|
81
|
+
type: "start",
|
|
82
|
+
runId: r,
|
|
83
|
+
clientId: i,
|
|
84
|
+
serial: n,
|
|
85
|
+
invocationId: t["invocation-id"] ?? "",
|
|
86
|
+
...e !== void 0 && { parent: e },
|
|
87
|
+
...a !== void 0 && { forkOf: a },
|
|
88
|
+
...o !== void 0 && { regenerates: o }
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (e === "ai-run-suspend") return {
|
|
92
|
+
type: "suspend",
|
|
93
|
+
runId: r,
|
|
94
|
+
clientId: i,
|
|
95
|
+
serial: n,
|
|
96
|
+
invocationId: t["invocation-id"] ?? ""
|
|
97
|
+
};
|
|
98
|
+
if (e === "ai-run-resume") return {
|
|
99
|
+
type: "resume",
|
|
100
|
+
runId: r,
|
|
101
|
+
clientId: i,
|
|
102
|
+
serial: n,
|
|
103
|
+
invocationId: t["invocation-id"] ?? ""
|
|
104
|
+
};
|
|
105
|
+
if (e === "ai-run-end") {
|
|
106
|
+
let e = t["run-reason"] ?? "complete";
|
|
107
|
+
return {
|
|
108
|
+
type: "end",
|
|
109
|
+
runId: r,
|
|
110
|
+
clientId: i,
|
|
111
|
+
serial: n,
|
|
112
|
+
invocationId: t["invocation-id"] ?? "",
|
|
113
|
+
reason: e
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}, G = (e, t, n) => {
|
|
117
|
+
if (e.has(t) || e.size < n) return;
|
|
118
|
+
let r = e.keys().next().value;
|
|
119
|
+
if (r !== void 0) return e.delete(r), r;
|
|
120
|
+
}, K = (e, t) => {
|
|
121
|
+
let n = [], r = /* @__PURE__ */ new Set(), i = t;
|
|
122
|
+
for (; i !== void 0 && !r.has(i);) r.add(i), n.push(i), i = e.get(i)?.parentCodecMessageId;
|
|
123
|
+
return n.toReversed();
|
|
124
|
+
}, q = (e, t, n) => {
|
|
125
|
+
let r = O(n), i = n.serial;
|
|
126
|
+
if (U(n.name)) {
|
|
127
|
+
let t = W(n.name, r, i);
|
|
128
|
+
return t && e.applyRunLifecycle(t), t;
|
|
129
|
+
}
|
|
130
|
+
let { inputs: a, outputs: o } = t.decode(n);
|
|
131
|
+
(a.length > 0 || o.length > 0 || r["run-id"]) && e.applyMessage({
|
|
132
|
+
inputs: a,
|
|
133
|
+
outputs: o
|
|
134
|
+
}, r, i);
|
|
135
|
+
}, te = (e, t, n, r, i) => {
|
|
136
|
+
let { inputs: a, outputs: o } = t.decode(r), s = n;
|
|
137
|
+
for (let t of [...a, ...o]) s = e.fold(s, t, {
|
|
138
|
+
serial: r.serial ?? "",
|
|
139
|
+
messageId: i
|
|
140
|
+
});
|
|
141
|
+
return s;
|
|
142
|
+
}, ne = (e, t) => {
|
|
143
|
+
let n = /* @__PURE__ */ new Set(), r = [];
|
|
144
|
+
for (let t of e) t.serial !== void 0 && !n.has(t.serial) && (n.add(t.serial), r.push(t));
|
|
145
|
+
if (t !== void 0) for (let e of t) e.serial !== void 0 && !n.has(e.serial) && (n.add(e.serial), r.push(e));
|
|
146
|
+
return r.toSorted(M);
|
|
147
|
+
}, re = async (e, t, n) => {
|
|
148
|
+
let r = [], i = await e.history({ limit: t });
|
|
149
|
+
for (r.push(...i.items); i.hasNext() && r.length < n;) {
|
|
150
|
+
let e = await i.next();
|
|
151
|
+
if (!e) break;
|
|
152
|
+
r.push(...e.items), i = e;
|
|
153
|
+
}
|
|
154
|
+
return r;
|
|
155
|
+
}, J = (e, t, n, r) => {
|
|
156
|
+
let i = e.createDecoder(), a = e.init(), o = 0;
|
|
157
|
+
for (let s of t) {
|
|
158
|
+
let t = O(s);
|
|
159
|
+
if (t["run-id"] !== n || U(s.name)) continue;
|
|
160
|
+
let c = t[l];
|
|
161
|
+
if (r !== void 0 && c === r) break;
|
|
162
|
+
a = te(e, i, a, s, c ?? ""), o++;
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
projection: a,
|
|
166
|
+
folded: o
|
|
167
|
+
};
|
|
168
|
+
}, ie = (e, t, n) => {
|
|
169
|
+
let r = e.createDecoder(), i = e.init();
|
|
170
|
+
for (let a of t) {
|
|
171
|
+
let t = O(a);
|
|
172
|
+
t["run-id"] === void 0 && t["codec-message-id"] === n && (i = te(e, r, i, a, n));
|
|
173
|
+
}
|
|
174
|
+
return i;
|
|
175
|
+
}, ae = async (t) => {
|
|
176
|
+
let { channel: n, codec: r, runId: i, signal: a, logger: o, liveMessages: s } = t;
|
|
177
|
+
if (a.aborted) throw new e.ErrorInfo(`unable to load run projection; run ${i} was cancelled`, T.InvalidArgument, 400);
|
|
178
|
+
await n.attach();
|
|
179
|
+
let { projection: c, folded: l } = J(r, ne(await re(n, 200, 2e3), s), i);
|
|
180
|
+
return o?.debug("loadRunProjection(); folded run events", {
|
|
181
|
+
runId: i,
|
|
182
|
+
folded: l
|
|
183
|
+
}), c;
|
|
184
|
+
}, oe = async (t) => {
|
|
185
|
+
let { channel: n, codec: r, runId: i, signal: a, logger: s, liveMessages: c, assistantParentFallback: u, pageLimit: d, maxMessages: f } = t;
|
|
186
|
+
if (a.aborted) throw new e.ErrorInfo(`unable to load conversation; run ${i} was cancelled`, T.InvalidArgument, 400);
|
|
187
|
+
let m = ne(await re(n, d, f), c), h = /* @__PURE__ */ new Map(), g = /* @__PURE__ */ new Map();
|
|
188
|
+
for (let e of m) {
|
|
189
|
+
if (U(e.name)) continue;
|
|
190
|
+
let t = O(e), n = t[l];
|
|
191
|
+
if (n === void 0) continue;
|
|
192
|
+
let r = t[o];
|
|
193
|
+
r !== void 0 && g.set(r, n), h.has(n) || h.set(n, {
|
|
194
|
+
runId: r,
|
|
195
|
+
parentCodecMessageId: t[p]
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
for (let e of m) {
|
|
199
|
+
if (e.name !== "ai-run-start") continue;
|
|
200
|
+
let t = O(e), n = t[o];
|
|
201
|
+
if (n === void 0) continue;
|
|
202
|
+
let r = g.get(n);
|
|
203
|
+
if (r === void 0) continue;
|
|
204
|
+
let i = h.get(r);
|
|
205
|
+
i && i.parentCodecMessageId === void 0 && (i.parentCodecMessageId = t[p]);
|
|
206
|
+
}
|
|
207
|
+
let _ = [], v = 0;
|
|
208
|
+
if (u !== void 0) {
|
|
209
|
+
let e = K(h, u);
|
|
210
|
+
v = e.length;
|
|
211
|
+
for (let t of e) {
|
|
212
|
+
let e = h.get(t);
|
|
213
|
+
if (e?.runId === i) continue;
|
|
214
|
+
let n = e?.runId === void 0 ? ie(r, m, t) : J(r, m, e.runId).projection;
|
|
215
|
+
_.push(...r.getMessages(n).map((e) => e.message));
|
|
51
216
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
217
|
+
}
|
|
218
|
+
let { projection: y, folded: b } = J(r, m, i);
|
|
219
|
+
return _.push(...r.getMessages(y).map((e) => e.message)), s?.debug("loadConversation(); built", {
|
|
220
|
+
runId: i,
|
|
221
|
+
chainLength: v,
|
|
222
|
+
totalMessages: _.length,
|
|
223
|
+
folded: b
|
|
224
|
+
}), {
|
|
225
|
+
messages: _,
|
|
226
|
+
projection: y
|
|
227
|
+
};
|
|
228
|
+
}, se = (e) => {
|
|
229
|
+
let t;
|
|
230
|
+
return {
|
|
231
|
+
promise: e === void 0 ? new Promise(() => {}) : e.aborted ? Promise.resolve() : new Promise((n) => {
|
|
232
|
+
t = () => {
|
|
233
|
+
n();
|
|
234
|
+
}, e.addEventListener("abort", t, { once: !0 });
|
|
235
|
+
}),
|
|
236
|
+
cleanup: () => {
|
|
237
|
+
t && e && e.removeEventListener("abort", t);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}, ce = async (e, t, n, r, i, a) => {
|
|
241
|
+
a?.trace("pipeStream();");
|
|
242
|
+
let o = e.getReader(), s = se(n), c = "complete", l;
|
|
56
243
|
try {
|
|
57
244
|
for (;;) {
|
|
58
|
-
let e = await Promise.race([o.read(),
|
|
59
|
-
if (e === "
|
|
60
|
-
|
|
245
|
+
let e = await Promise.race([o.read(), s.promise.then(() => "cancelled")]);
|
|
246
|
+
if (e === "cancelled") {
|
|
247
|
+
c = "cancelled", a?.debug("pipeStream(); stream cancelled by AbortSignal"), r && await r(async (e) => t.publishOutput(e)), await t.cancel("cancelled");
|
|
61
248
|
break;
|
|
62
249
|
}
|
|
63
|
-
let { done: n, value:
|
|
250
|
+
let { done: n, value: l } = e;
|
|
64
251
|
if (n) {
|
|
65
252
|
await t.close(), a?.debug("pipeStream(); stream completed");
|
|
66
253
|
break;
|
|
67
254
|
}
|
|
68
|
-
await t.
|
|
255
|
+
await t.publishOutput(l, i?.(l));
|
|
69
256
|
}
|
|
70
257
|
} catch (e) {
|
|
71
|
-
|
|
258
|
+
c = "error", l = e instanceof Error ? e : Error(String(e)), a?.error("pipeStream(); stream error", { error: l.message });
|
|
72
259
|
try {
|
|
73
260
|
await t.close();
|
|
74
261
|
} catch {}
|
|
75
262
|
} finally {
|
|
76
|
-
s
|
|
263
|
+
s.cleanup(), o.releaseLock();
|
|
77
264
|
}
|
|
78
265
|
return {
|
|
79
|
-
reason:
|
|
80
|
-
error:
|
|
266
|
+
reason: c,
|
|
267
|
+
error: l
|
|
81
268
|
};
|
|
82
|
-
},
|
|
269
|
+
}, le = class {
|
|
83
270
|
constructor(e, t) {
|
|
84
|
-
this.
|
|
271
|
+
this._activeRuns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "RunManager" });
|
|
85
272
|
}
|
|
86
|
-
async
|
|
87
|
-
this._logger?.trace("
|
|
88
|
-
|
|
273
|
+
async startRun(e, t, n, r) {
|
|
274
|
+
this._logger?.trace("DefaultRunManager.startRun();", {
|
|
275
|
+
runId: e,
|
|
89
276
|
clientId: t
|
|
90
277
|
});
|
|
91
|
-
let i = n ?? new AbortController(),
|
|
92
|
-
this.
|
|
278
|
+
let i = n ?? new AbortController(), a = t ?? "";
|
|
279
|
+
this._activeRuns.set(e, {
|
|
93
280
|
controller: i,
|
|
94
|
-
clientId:
|
|
281
|
+
clientId: a
|
|
95
282
|
});
|
|
96
|
-
let
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
async endTurn(e, t) {
|
|
106
|
-
this._logger?.trace("DefaultTurnManager.endTurn();", {
|
|
107
|
-
turnId: e,
|
|
108
|
-
reason: t
|
|
283
|
+
let o = r?.continuation === !0, s = H({
|
|
284
|
+
runId: e,
|
|
285
|
+
runClientId: a,
|
|
286
|
+
parent: o ? void 0 : r?.parent,
|
|
287
|
+
forkOf: o ? void 0 : r?.forkOf,
|
|
288
|
+
regenerates: o ? void 0 : r?.regenerates,
|
|
289
|
+
invocationId: r?.invocationId,
|
|
290
|
+
inputClientId: r?.inputClientId,
|
|
291
|
+
inputCodecMessageId: r?.inputCodecMessageId
|
|
109
292
|
});
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
293
|
+
return await this._channel.publish({
|
|
294
|
+
name: o ? C : x,
|
|
295
|
+
extras: { ai: { transport: s } }
|
|
296
|
+
}), this._logger?.debug("DefaultRunManager.startRun(); run started", { runId: e }), i.signal;
|
|
297
|
+
}
|
|
298
|
+
async suspendRun(e, t, n, r) {
|
|
299
|
+
this._logger?.trace("DefaultRunManager.suspendRun();", { runId: e }), await this._publishTerminal(S, e, {
|
|
300
|
+
invocationId: t,
|
|
301
|
+
inputClientId: n,
|
|
302
|
+
inputCodecMessageId: r
|
|
303
|
+
}), this._logger?.debug("DefaultRunManager.suspendRun(); run suspended", { runId: e });
|
|
304
|
+
}
|
|
305
|
+
async endRun(e, t, n, r, i) {
|
|
306
|
+
this._logger?.trace("DefaultRunManager.endRun();", {
|
|
307
|
+
runId: e,
|
|
120
308
|
reason: t
|
|
309
|
+
}), await this._publishTerminal(w, e, {
|
|
310
|
+
reason: t,
|
|
311
|
+
invocationId: n,
|
|
312
|
+
inputClientId: r,
|
|
313
|
+
inputCodecMessageId: i
|
|
314
|
+
}), this._logger?.debug("DefaultRunManager.endRun(); run ended", {
|
|
315
|
+
runId: e,
|
|
316
|
+
reason: t
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
async _publishTerminal(e, t, n) {
|
|
320
|
+
let r = H({
|
|
321
|
+
runId: t,
|
|
322
|
+
runClientId: this._activeRuns.get(t)?.clientId ?? "",
|
|
323
|
+
...n
|
|
121
324
|
});
|
|
325
|
+
await this._channel.publish({
|
|
326
|
+
name: e,
|
|
327
|
+
extras: { ai: { transport: r } }
|
|
328
|
+
}), this._activeRuns.delete(t);
|
|
122
329
|
}
|
|
123
330
|
getSignal(e) {
|
|
124
|
-
return this.
|
|
331
|
+
return this._activeRuns.get(e)?.controller.signal;
|
|
125
332
|
}
|
|
126
333
|
getClientId(e) {
|
|
127
|
-
return this.
|
|
334
|
+
return this._activeRuns.get(e)?.clientId;
|
|
128
335
|
}
|
|
129
|
-
|
|
130
|
-
this._logger?.debug("
|
|
336
|
+
cancel(e) {
|
|
337
|
+
this._logger?.debug("DefaultRunManager.cancel();", { runId: e }), this._activeRuns.get(e)?.controller.abort();
|
|
131
338
|
}
|
|
132
|
-
|
|
133
|
-
return [...this.
|
|
339
|
+
getActiveRunIds() {
|
|
340
|
+
return [...this._activeRuns.keys()];
|
|
134
341
|
}
|
|
135
342
|
close() {
|
|
136
|
-
this._logger?.trace("
|
|
137
|
-
for (let e of this.
|
|
138
|
-
this.
|
|
139
|
-
}
|
|
140
|
-
},
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
343
|
+
this._logger?.trace("DefaultRunManager.close();", { activeRuns: this._activeRuns.size });
|
|
344
|
+
for (let e of this._activeRuns.values()) e.controller.abort();
|
|
345
|
+
this._activeRuns.clear();
|
|
346
|
+
}
|
|
347
|
+
}, ue = (e, t) => new le(e, t), de = async (t) => {
|
|
348
|
+
let { register: n, codec: r, invocationId: i, runId: a, expectedInputEventIds: o, timeoutMs: s, signal: l, logger: u } = t, d = new Set(o), f = d.size, h = [], g = [], _ = /* @__PURE__ */ new Set(), v, y, b = (e) => {
|
|
349
|
+
let t = r.createDecoder(), n = O(e), i = n["codec-message-id"] ?? "", { inputs: a, outputs: o } = t.decode(e), s = [...a, ...o], c = r.init();
|
|
350
|
+
for (let t of s) c = r.fold(c, t, {
|
|
351
|
+
serial: e.serial ?? "",
|
|
352
|
+
messageId: i
|
|
353
|
+
});
|
|
354
|
+
return r.getMessages(c).map(({ message: t }) => ({
|
|
355
|
+
kind: "message",
|
|
356
|
+
message: t,
|
|
357
|
+
codecMessageId: i,
|
|
358
|
+
parentId: n[p],
|
|
359
|
+
forkOf: n[m],
|
|
360
|
+
headers: n,
|
|
361
|
+
serial: e.serial
|
|
362
|
+
}));
|
|
363
|
+
};
|
|
364
|
+
return new Promise((t, r) => {
|
|
365
|
+
let o = !1, p = /* @__PURE__ */ new Set(), m = () => {}, x, S = () => {
|
|
366
|
+
m(), x !== void 0 && clearTimeout(x), l.removeEventListener("abort", C);
|
|
367
|
+
}, C = () => {
|
|
368
|
+
o || (o = !0, S(), r(new e.ErrorInfo(`unable to look up input event; run ${a} was cancelled`, T.InvalidArgument, 400)));
|
|
369
|
+
};
|
|
370
|
+
if (l.addEventListener("abort", C, { once: !0 }), !o) {
|
|
371
|
+
if (m = n((n) => {
|
|
372
|
+
if (o || n.serial !== void 0 && p.has(n.serial)) return;
|
|
373
|
+
n.serial !== void 0 && p.add(n.serial);
|
|
374
|
+
let s = O(n), l = s[c];
|
|
375
|
+
if (!l || !d.has(l) || _.has(l)) return;
|
|
376
|
+
_.add(l), v === void 0 && (v = s, y = n.clientId);
|
|
377
|
+
let m;
|
|
378
|
+
try {
|
|
379
|
+
m = b(n);
|
|
380
|
+
} catch (t) {
|
|
381
|
+
o = !0, S();
|
|
382
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
383
|
+
r(new e.ErrorInfo(`unable to look up input event; decode failed for invocation ${i}: ${t instanceof Error ? t.message : String(t)}`, T.InputEventNotFound, 504, n));
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
for (let e of m) h.push(e);
|
|
387
|
+
g.push(n), !(_.size < f) && (o = !0, S(), h.sort(M), u?.debug("lookupInputEvents(); collected input events", {
|
|
388
|
+
runId: a,
|
|
389
|
+
invocationId: i,
|
|
390
|
+
count: h.length
|
|
391
|
+
}), t({
|
|
392
|
+
nodes: h,
|
|
393
|
+
firstHeaders: v,
|
|
394
|
+
firstClientId: y,
|
|
395
|
+
rawMessages: g
|
|
396
|
+
}));
|
|
397
|
+
}), o) {
|
|
398
|
+
m();
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
x = setTimeout(() => {
|
|
402
|
+
o || (o = !0, S(), r(new e.ErrorInfo(`unable to look up input event; received ${String(h.length)} of ${String(f)} input events for invocation ${i} within ${String(s)}ms`, T.InputEventNotFound, 504)));
|
|
403
|
+
}, s);
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
}, fe = class {
|
|
407
|
+
constructor(e) {
|
|
408
|
+
this._registeredRuns = /* @__PURE__ */ new Map(), this._runIdByInputCodecMessageId = /* @__PURE__ */ new Map(), this._deferredCancels = /* @__PURE__ */ new Map(), this._pendingInputEventLookups = /* @__PURE__ */ new Map(), this._inputEventBuffer = /* @__PURE__ */ new Map(), this._state = "ready", this._codec = e.codec;
|
|
409
|
+
let t = { params: {
|
|
410
|
+
...B(e.client, e.codec).params,
|
|
411
|
+
rewind: e.rewindWindow ?? "2m"
|
|
412
|
+
} };
|
|
413
|
+
this._channel = e.client.channels.get(e.channelName, t), this._logger = e.logger?.withContext({ component: "AgentSession" }), this._onError = e.onError, this._runManager = ue(this._channel, this._logger), this._inputEventLookupTimeoutMs = e.inputEventLookupTimeoutMs ?? 3e4, this._inputEventBufferLimit = e.inputEventBufferLimit ?? 200, this._channelListener = (e) => {
|
|
147
414
|
this._handleChannelMessage(e);
|
|
148
|
-
}, this.
|
|
149
|
-
let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`, C.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
150
|
-
this._logger?.error("DefaultServerTransport(); subscribe failed"), this._onError?.(n);
|
|
151
|
-
}), this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
|
|
415
|
+
}, this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
|
|
152
416
|
this._handleChannelStateChange(e);
|
|
153
|
-
}, this._channel.on(this._onChannelStateChange), this._logger?.debug("
|
|
417
|
+
}, this._channel.on(this._onChannelStateChange), this._logger?.debug("DefaultAgentSession(); session created");
|
|
418
|
+
}
|
|
419
|
+
connect() {
|
|
420
|
+
return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", T.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger?.trace("DefaultAgentSession.connect();"), this._connectPromise = this._channel.subscribe(this._channelListener).then(() => {
|
|
421
|
+
this._logger?.debug("DefaultAgentSession.connect(); subscribed and attached");
|
|
422
|
+
}, (t) => {
|
|
423
|
+
let n = new e.ErrorInfo(`unable to subscribe to channel; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
424
|
+
throw this._logger?.error("DefaultAgentSession.connect(); subscribe failed"), this._onError?.(n), n;
|
|
425
|
+
}), this._connectPromise);
|
|
426
|
+
}
|
|
427
|
+
_registerInputEventListener(e, t) {
|
|
428
|
+
for (let n of e) this._pendingInputEventLookups.set(n, t);
|
|
429
|
+
for (let n of e) {
|
|
430
|
+
let e = this._inputEventBuffer.get(n);
|
|
431
|
+
if (e) {
|
|
432
|
+
this._inputEventBuffer.delete(n);
|
|
433
|
+
for (let n of e) t(n);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return () => {
|
|
437
|
+
for (let n of e) this._pendingInputEventLookups.get(n) === t && this._pendingInputEventLookups.delete(n);
|
|
438
|
+
};
|
|
154
439
|
}
|
|
155
|
-
|
|
156
|
-
return this._logger?.trace("
|
|
440
|
+
createRun(e, t) {
|
|
441
|
+
return this._logger?.trace("DefaultAgentSession.createRun();", { inputEventId: e.inputEventId }), this._createRun(e, t ?? {});
|
|
157
442
|
}
|
|
158
|
-
close() {
|
|
159
|
-
if (this._state !==
|
|
160
|
-
this._state =
|
|
161
|
-
for (let e of this.
|
|
162
|
-
this.
|
|
443
|
+
async close() {
|
|
444
|
+
if (this._state !== "closed") {
|
|
445
|
+
this._state = "closed", this._logger?.trace("DefaultAgentSession.close();"), this._connectPromise && this._channel.unsubscribe(this._channelListener), this._channel.off(this._onChannelStateChange);
|
|
446
|
+
for (let e of this._registeredRuns.values()) e.controller.abort();
|
|
447
|
+
if (this._registeredRuns.clear(), this._runIdByInputCodecMessageId.clear(), this._deferredCancels.clear(), this._pendingInputEventLookups.clear(), this._inputEventBuffer.clear(), this._runManager.close(), this._connectPromise) try {
|
|
448
|
+
await this._channel.detach();
|
|
449
|
+
} catch (e) {
|
|
450
|
+
this._logger?.debug("DefaultAgentSession.close(); channel detach failed", { error: e });
|
|
451
|
+
}
|
|
452
|
+
this._logger?.debug("DefaultAgentSession.close(); session closed");
|
|
163
453
|
}
|
|
164
454
|
}
|
|
165
|
-
|
|
166
|
-
let n = [
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
let n = w(t), r = {};
|
|
171
|
-
n["x-ably-cancel-turn-id"] ? r.turnId = n[u] : n["x-ably-cancel-own"] === "true" ? r.own = !0 : n["x-ably-cancel-client-id"] ? r.clientId = n[p] : n["x-ably-cancel-all"] === "true" && (r.all = !0);
|
|
172
|
-
let i = this._resolveFilter(r, t.clientId);
|
|
173
|
-
if (i.length === 0) return;
|
|
174
|
-
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); matched turns", {
|
|
175
|
-
matchedTurnIds: i,
|
|
176
|
-
filter: r
|
|
177
|
-
});
|
|
178
|
-
let a = /* @__PURE__ */ new Map();
|
|
179
|
-
for (let e of i) {
|
|
180
|
-
let t = this._registeredTurns.get(e);
|
|
181
|
-
a.set(e, t?.clientId ?? "");
|
|
455
|
+
async _handleCancelMessage(e) {
|
|
456
|
+
let t = O(e), n = t[o], r = t[_];
|
|
457
|
+
if (!n && !r) {
|
|
458
|
+
this._logger?.warn("DefaultAgentSession._handleCancelMessage(); missing run-id and input-codec-message-id", { serial: e.serial });
|
|
459
|
+
return;
|
|
182
460
|
}
|
|
183
|
-
let
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
461
|
+
let i = n ?? (r ? this._runIdByInputCodecMessageId.get(r) : void 0), a = i ? this._registeredRuns.get(i) : void 0;
|
|
462
|
+
if (!a) {
|
|
463
|
+
r !== void 0 && this._bufferDeferredCancel(r, e);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
await this._cancelRegistration(a, e);
|
|
467
|
+
}
|
|
468
|
+
_bufferDeferredCancel(e, t) {
|
|
469
|
+
let n = G(this._deferredCancels, e, this._inputEventBufferLimit);
|
|
470
|
+
n !== void 0 && this._logger?.warn("DefaultAgentSession._bufferDeferredCancel(); deferred-cancel buffer full, dropping oldest", {
|
|
471
|
+
evictedInputCodecMessageId: n,
|
|
472
|
+
limit: this._inputEventBufferLimit
|
|
473
|
+
}), this._deferredCancels.set(e, t), this._logger?.debug("DefaultAgentSession._bufferDeferredCancel(); buffered early cancel", {
|
|
474
|
+
inputCodecMessageId: e,
|
|
475
|
+
serial: t.serial
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
async _pullDeferredCancel(e, t) {
|
|
479
|
+
let n = this._deferredCancels.get(t);
|
|
480
|
+
n !== void 0 && (this._deferredCancels.delete(t), this._logger?.debug("DefaultAgentSession._pullDeferredCancel(); honouring buffered cancel", {
|
|
481
|
+
runId: e.runId,
|
|
482
|
+
inputCodecMessageId: t
|
|
483
|
+
}), await this._cancelRegistration(e, n));
|
|
484
|
+
}
|
|
485
|
+
async _cancelRegistration(t, n) {
|
|
486
|
+
let { runId: r } = t;
|
|
487
|
+
this._logger?.debug("DefaultAgentSession._cancelRegistration(); matched run", { runId: r });
|
|
488
|
+
let i = {
|
|
489
|
+
message: n,
|
|
490
|
+
runId: r
|
|
188
491
|
};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); cancel rejected by onCancel", { turnId: t });
|
|
194
|
-
continue;
|
|
195
|
-
}
|
|
196
|
-
n.controller.abort(), this._logger?.debug("DefaultServerTransport._handleCancelMessage(); turn aborted", { turnId: t });
|
|
197
|
-
} catch (r) {
|
|
198
|
-
let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`, C.CancelListenerError, 500, r instanceof e.ErrorInfo ? r : void 0);
|
|
199
|
-
this._logger?.error("DefaultServerTransport._handleCancelMessage(); onCancel threw", { turnId: t }), (n.onError ?? this._onError)?.(i);
|
|
492
|
+
try {
|
|
493
|
+
if (t.onCancel && !await t.onCancel(i)) {
|
|
494
|
+
this._logger?.debug("DefaultAgentSession._cancelRegistration(); cancel rejected by onCancel", { runId: r });
|
|
495
|
+
return;
|
|
200
496
|
}
|
|
497
|
+
t.controller.abort(), this._logger?.debug("DefaultAgentSession._cancelRegistration(); run cancelled", { runId: r });
|
|
498
|
+
} catch (n) {
|
|
499
|
+
let i = new e.ErrorInfo(`unable to process cancel for run ${r}; onCancel handler threw: ${n instanceof Error ? n.message : String(n)}`, T.CancelListenerError, 500, n instanceof e.ErrorInfo ? n : void 0);
|
|
500
|
+
this._logger?.error("DefaultAgentSession._cancelRegistration(); onCancel threw", { runId: r }), (t.onError ?? this._onError)?.(i);
|
|
201
501
|
}
|
|
202
502
|
}
|
|
203
503
|
_handleChannelStateChange(t) {
|
|
204
|
-
if (this._state ===
|
|
504
|
+
if (this._state === "closed") return;
|
|
205
505
|
let { current: n, resumed: r } = t;
|
|
206
506
|
if (n === "attached" && !this._hasAttachedOnce) {
|
|
207
507
|
this._hasAttachedOnce = !0;
|
|
208
508
|
return;
|
|
209
509
|
}
|
|
210
510
|
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
211
|
-
this._logger?.error("
|
|
511
|
+
this._logger?.error("DefaultAgentSession._handleChannelStateChange(); channel continuity lost", {
|
|
212
512
|
current: n,
|
|
213
513
|
resumed: r,
|
|
214
514
|
previous: t.previous
|
|
215
515
|
});
|
|
216
|
-
let i = new e.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`,
|
|
516
|
+
let i = new e.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, T.ChannelContinuityLost, 500, t.reason);
|
|
217
517
|
this._onError?.(i);
|
|
218
518
|
}
|
|
219
519
|
_handleChannelMessage(t) {
|
|
220
520
|
try {
|
|
221
|
-
t.name === "
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
521
|
+
if (t.name === "ai-cancel") {
|
|
522
|
+
this._handleCancelMessage(t).catch((t) => {
|
|
523
|
+
let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, T.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
524
|
+
this._logger?.error("DefaultAgentSession._handleChannelMessage(); cancel routing error"), this._onError?.(n);
|
|
525
|
+
});
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
let n = O(t)[c];
|
|
529
|
+
if (n !== void 0) {
|
|
530
|
+
let e = this._pendingInputEventLookups.get(n);
|
|
531
|
+
if (e) e(t);
|
|
532
|
+
else {
|
|
533
|
+
let e = this._inputEventBuffer.get(n);
|
|
534
|
+
if (e) e.push(t);
|
|
535
|
+
else {
|
|
536
|
+
let e = G(this._inputEventBuffer, n, this._inputEventBufferLimit);
|
|
537
|
+
e !== void 0 && this._logger?.warn("DefaultAgentSession._handleChannelMessage(); input-event buffer full, dropping oldest entry", {
|
|
538
|
+
evictedEventId: e,
|
|
539
|
+
limit: this._inputEventBufferLimit
|
|
540
|
+
}), this._inputEventBuffer.set(n, [t]);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
225
544
|
} catch (t) {
|
|
226
|
-
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`,
|
|
227
|
-
this._logger?.error("
|
|
545
|
+
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
546
|
+
this._logger?.error("DefaultAgentSession._handleChannelMessage(); subscription error"), this._onError?.(n);
|
|
228
547
|
}
|
|
229
548
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
549
|
+
async _requireConnected(t) {
|
|
550
|
+
if (!this._connectPromise) throw new e.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`, T.InvalidArgument, 400);
|
|
551
|
+
return this._connectPromise;
|
|
552
|
+
}
|
|
553
|
+
_createRun(t, n) {
|
|
554
|
+
let r = n.runId ?? crypto.randomUUID(), i = n.invocationId ?? crypto.randomUUID(), a = this._inputEventLookupTimeoutMs, { onMessage: s, onCancelled: c, onCancel: d, onError: f, signal: g } = n, _ = new AbortController(), v = "initialized", y = g ? AbortSignal.any([_.signal, g]) : _.signal, b = {
|
|
555
|
+
runId: r,
|
|
556
|
+
invocationId: i,
|
|
557
|
+
controller: _,
|
|
558
|
+
signal: y,
|
|
559
|
+
onCancel: d,
|
|
560
|
+
onError: f
|
|
238
561
|
};
|
|
239
|
-
this.
|
|
240
|
-
let
|
|
562
|
+
this._registeredRuns.set(r, b);
|
|
563
|
+
let x = this._logger, S = this._runManager, C = this._codec, w = this._channel, E = this._registeredRuns, D = this._runIdByInputCodecMessageId, O = this._deferredCancels, k = this._requireConnected.bind(this), ee = this._registerInputEventListener.bind(this), A = this._pullDeferredCancel.bind(this), j = t.inputEventId, M = [], N = { get messages() {
|
|
564
|
+
return M;
|
|
565
|
+
} }, P, F, I, L, R, z, B = !1, H, U, W, G = () => {
|
|
566
|
+
E.delete(r), z !== void 0 && (D.delete(z), O.delete(z));
|
|
567
|
+
}, K, q;
|
|
241
568
|
return {
|
|
242
|
-
get
|
|
243
|
-
return
|
|
569
|
+
get runId() {
|
|
570
|
+
return r;
|
|
571
|
+
},
|
|
572
|
+
get invocationId() {
|
|
573
|
+
return i;
|
|
244
574
|
},
|
|
245
575
|
get abortSignal() {
|
|
246
|
-
return
|
|
576
|
+
return y;
|
|
577
|
+
},
|
|
578
|
+
get view() {
|
|
579
|
+
return N;
|
|
580
|
+
},
|
|
581
|
+
get messages() {
|
|
582
|
+
return q === void 0 ? K === void 0 ? M.map((e) => e.message) : C.getMessages(K).map((e) => e.message) : [...q];
|
|
247
583
|
},
|
|
248
584
|
start: async () => {
|
|
249
|
-
if (
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
585
|
+
if (x?.trace("Run.start();", {
|
|
586
|
+
runId: r,
|
|
587
|
+
inputEventId: j
|
|
588
|
+
}), await k("start"), y.aborted) throw new e.ErrorInfo(`unable to start run; run ${r} was cancelled before start()`, T.InvalidArgument, 400);
|
|
589
|
+
if (v !== "initialized") return;
|
|
590
|
+
if (v = "started", j && a > 0) try {
|
|
591
|
+
let e = await de({
|
|
592
|
+
register: (e) => ee([j], e),
|
|
593
|
+
codec: C,
|
|
594
|
+
invocationId: i,
|
|
595
|
+
runId: r,
|
|
596
|
+
expectedInputEventIds: [j],
|
|
597
|
+
timeoutMs: a,
|
|
598
|
+
signal: y,
|
|
599
|
+
logger: x
|
|
600
|
+
});
|
|
601
|
+
for (let t of e.nodes) M.push(t);
|
|
602
|
+
e.firstHeaders !== void 0 && (H = e.firstHeaders), e.firstClientId !== void 0 && (F = e.firstClientId), W = e.rawMessages;
|
|
603
|
+
} catch (t) {
|
|
604
|
+
let n = t instanceof e.ErrorInfo ? t : new e.ErrorInfo(`unable to look up input event; ${t instanceof Error ? t.message : String(t)}`, T.InputEventNotFound, 504);
|
|
605
|
+
throw G(), x?.error("Run.start(); input-event lookup failed", {
|
|
606
|
+
runId: r,
|
|
607
|
+
invocationId: i
|
|
608
|
+
}), n;
|
|
262
609
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
}
|
|
269
|
-
await
|
|
270
|
-
let a = [];
|
|
610
|
+
let t = H ?? M[0]?.headers;
|
|
611
|
+
if (t) {
|
|
612
|
+
P = t[u], I = t[p], L = t[m], R = t[h], z = t[l];
|
|
613
|
+
let e = t[o];
|
|
614
|
+
B = e !== void 0, e !== void 0 && e !== r && (E.delete(r), r = e, b.runId = r, E.set(r, b));
|
|
615
|
+
}
|
|
616
|
+
U = M.at(-1)?.codecMessageId ?? I, z !== void 0 && (D.set(z, r), await A(b, z));
|
|
271
617
|
try {
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
await v.createEncoder(y, {
|
|
282
|
-
extras: { headers: t },
|
|
283
|
-
onMessage: i
|
|
284
|
-
}).writeMessages([e.message], r?.clientId ? { clientId: r.clientId } : void 0), a.push(e.msgId);
|
|
285
|
-
}
|
|
618
|
+
await S.startRun(r, P, _, {
|
|
619
|
+
parent: U,
|
|
620
|
+
forkOf: L,
|
|
621
|
+
regenerates: R,
|
|
622
|
+
invocationId: i,
|
|
623
|
+
inputClientId: F,
|
|
624
|
+
inputCodecMessageId: z,
|
|
625
|
+
continuation: B
|
|
626
|
+
});
|
|
286
627
|
} catch (t) {
|
|
287
|
-
let
|
|
288
|
-
throw
|
|
628
|
+
let n = new e.ErrorInfo(`unable to publish run-start for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
629
|
+
throw x?.error("Run.start(); failed to publish run-start", { runId: r }), n;
|
|
289
630
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
})
|
|
631
|
+
x?.debug("Run.start(); run started", {
|
|
632
|
+
runId: r,
|
|
633
|
+
inputEventId: j
|
|
634
|
+
});
|
|
294
635
|
},
|
|
295
636
|
addEvents: async (t) => {
|
|
296
|
-
if (
|
|
297
|
-
|
|
637
|
+
if (x?.trace("Run.addEvents();", {
|
|
638
|
+
runId: r,
|
|
298
639
|
count: t.length
|
|
299
|
-
}),
|
|
300
|
-
|
|
301
|
-
let r = g.getClientId(n);
|
|
640
|
+
}), await k("addEvents"), v === "initialized") throw new e.ErrorInfo(`unable to add events; start() must be called before addEvents() (run ${r})`, T.InvalidArgument, 400);
|
|
641
|
+
let n = S.getClientId(r);
|
|
302
642
|
try {
|
|
303
643
|
for (let e of t) {
|
|
304
|
-
let t =
|
|
644
|
+
let t = V({
|
|
305
645
|
role: "assistant",
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
646
|
+
runId: r,
|
|
647
|
+
codecMessageId: e.codecMessageId,
|
|
648
|
+
runClientId: n,
|
|
649
|
+
invocationId: i,
|
|
650
|
+
inputClientId: F,
|
|
651
|
+
inputCodecMessageId: z
|
|
652
|
+
}), a = C.createEncoder(w, {
|
|
311
653
|
extras: { headers: t },
|
|
312
|
-
onMessage:
|
|
654
|
+
onMessage: s
|
|
313
655
|
});
|
|
314
|
-
for (let t of e.events) await a.
|
|
656
|
+
for (let t of e.events) await a.publishOutput(t);
|
|
315
657
|
await a.close();
|
|
316
658
|
}
|
|
317
659
|
} catch (t) {
|
|
318
|
-
let
|
|
319
|
-
throw
|
|
660
|
+
let n = new e.ErrorInfo(`unable to publish events for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
661
|
+
throw x?.error("Run.addEvents(); publish failed", { runId: r }), n;
|
|
320
662
|
}
|
|
321
|
-
|
|
322
|
-
|
|
663
|
+
x?.debug("Run.addEvents(); events published", {
|
|
664
|
+
runId: r,
|
|
323
665
|
count: t.length
|
|
324
666
|
});
|
|
325
667
|
},
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
await
|
|
329
|
-
|
|
668
|
+
loadProjection: async () => {
|
|
669
|
+
x?.trace("Run.loadProjection();", { runId: r }), await k("loadProjection");
|
|
670
|
+
let e = await ae({
|
|
671
|
+
channel: w,
|
|
672
|
+
codec: C,
|
|
673
|
+
runId: r,
|
|
674
|
+
signal: y,
|
|
675
|
+
logger: x,
|
|
676
|
+
liveMessages: W
|
|
677
|
+
});
|
|
678
|
+
return K = e, e;
|
|
679
|
+
},
|
|
680
|
+
loadConversation: async (e) => {
|
|
681
|
+
x?.trace("Run.loadConversation();", { runId: r }), await k("loadConversation");
|
|
682
|
+
let { messages: t, projection: n } = await oe({
|
|
683
|
+
channel: w,
|
|
684
|
+
codec: C,
|
|
685
|
+
runId: r,
|
|
686
|
+
signal: y,
|
|
687
|
+
logger: x,
|
|
688
|
+
liveMessages: W,
|
|
689
|
+
assistantParentFallback: U,
|
|
690
|
+
pageLimit: e?.pageLimit ?? 200,
|
|
691
|
+
maxMessages: e?.maxMessages ?? 2e3
|
|
692
|
+
});
|
|
693
|
+
return K = n, q = t, t;
|
|
694
|
+
},
|
|
695
|
+
pipe: async (t, n) => {
|
|
696
|
+
if (x?.trace("Run.pipe();", { runId: r }), await k("pipe"), v === "initialized") throw new e.ErrorInfo(`unable to pipe stream; start() must be called before pipe() (run ${r})`, T.InvalidArgument, 400);
|
|
697
|
+
let a = S.getClientId(r), o = n?.parent ?? U, l = n?.forkOf ?? L, u = R, d = crypto.randomUUID(), p = V({
|
|
330
698
|
role: "assistant",
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
parent:
|
|
335
|
-
forkOf:
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
699
|
+
runId: r,
|
|
700
|
+
codecMessageId: d,
|
|
701
|
+
runClientId: a,
|
|
702
|
+
parent: o,
|
|
703
|
+
forkOf: l,
|
|
704
|
+
invocationId: i,
|
|
705
|
+
inputClientId: F,
|
|
706
|
+
inputCodecMessageId: z,
|
|
707
|
+
regenerates: u
|
|
708
|
+
}), m = await ce(t, C.createEncoder(w, {
|
|
709
|
+
extras: { headers: p },
|
|
710
|
+
onMessage: s,
|
|
339
711
|
messageId: d
|
|
340
|
-
}),
|
|
341
|
-
if (
|
|
342
|
-
let t = new e.ErrorInfo(`unable to
|
|
343
|
-
|
|
712
|
+
}), y, c, n?.resolveWriteOptions, x);
|
|
713
|
+
if (m.error) {
|
|
714
|
+
let t = new e.ErrorInfo(`unable to pipe response for run ${r}; ${m.error.message}`, T.StreamError, 500, m.error instanceof e.ErrorInfo ? m.error : void 0);
|
|
715
|
+
x?.error("Run.pipe(); stream error", { runId: r }), f?.(t);
|
|
716
|
+
}
|
|
717
|
+
return x?.debug("Run.pipe(); stream finished", {
|
|
718
|
+
runId: r,
|
|
719
|
+
reason: m.reason
|
|
720
|
+
}), m;
|
|
721
|
+
},
|
|
722
|
+
suspend: async () => {
|
|
723
|
+
if (x?.trace("Run.suspend();", { runId: r }), await k("suspend"), v === "initialized") throw new e.ErrorInfo(`unable to suspend run; start() must be called before suspend() (run ${r})`, T.InvalidArgument, 400);
|
|
724
|
+
if (v !== "ended") {
|
|
725
|
+
v = "ended";
|
|
726
|
+
try {
|
|
727
|
+
await S.suspendRun(r, i, F, z);
|
|
728
|
+
} catch (t) {
|
|
729
|
+
let n = new e.ErrorInfo(`unable to publish run-suspend for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
730
|
+
throw x?.error("Run.suspend(); failed to publish run-suspend", { runId: r }), n;
|
|
731
|
+
} finally {
|
|
732
|
+
G();
|
|
733
|
+
}
|
|
734
|
+
x?.debug("Run.suspend(); run suspended", { runId: r });
|
|
344
735
|
}
|
|
345
|
-
return h?.debug("Turn.streamResponse(); stream finished", {
|
|
346
|
-
turnId: n,
|
|
347
|
-
reason: b.reason
|
|
348
|
-
}), b;
|
|
349
736
|
},
|
|
350
737
|
end: async (t) => {
|
|
351
|
-
if (
|
|
352
|
-
|
|
738
|
+
if (x?.trace("Run.end();", {
|
|
739
|
+
runId: r,
|
|
353
740
|
reason: t
|
|
354
|
-
}),
|
|
355
|
-
if (
|
|
356
|
-
|
|
741
|
+
}), await k("end"), v === "initialized") throw new e.ErrorInfo(`unable to end run; start() must be called before end() (run ${r})`, T.InvalidArgument, 400);
|
|
742
|
+
if (v !== "ended") {
|
|
743
|
+
v = "ended";
|
|
357
744
|
try {
|
|
358
|
-
await
|
|
745
|
+
await S.endRun(r, t, i, F, z);
|
|
359
746
|
} catch (t) {
|
|
360
|
-
let
|
|
361
|
-
throw
|
|
747
|
+
let n = new e.ErrorInfo(`unable to publish run-end for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
748
|
+
throw x?.error("Run.end(); failed to publish run-end", { runId: r }), n;
|
|
362
749
|
} finally {
|
|
363
|
-
|
|
750
|
+
G();
|
|
364
751
|
}
|
|
365
|
-
|
|
366
|
-
|
|
752
|
+
x?.debug("Run.end(); run ended", {
|
|
753
|
+
runId: r,
|
|
367
754
|
reason: t
|
|
368
755
|
});
|
|
369
756
|
}
|
|
370
757
|
}
|
|
371
758
|
};
|
|
372
759
|
}
|
|
373
|
-
},
|
|
760
|
+
}, pe = (e) => new fe(e), me = (e) => ({
|
|
374
761
|
logAction: (t, n, r) => {
|
|
375
762
|
e.error(n, { detail: r });
|
|
376
763
|
},
|
|
377
764
|
shouldLog: () => !0
|
|
378
|
-
}),
|
|
765
|
+
}), he = e.Realtime.EventEmitter, Y = class extends he {
|
|
379
766
|
constructor(e) {
|
|
380
|
-
super(
|
|
767
|
+
super(me(e));
|
|
381
768
|
}
|
|
382
|
-
},
|
|
769
|
+
}, ge = /* @__PURE__ */ function(e) {
|
|
383
770
|
return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
|
|
384
|
-
}({}),
|
|
771
|
+
}({}), _e = (e, t, n) => {
|
|
385
772
|
let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
|
|
386
773
|
switch (t) {
|
|
387
|
-
case
|
|
388
|
-
case
|
|
774
|
+
case "trace":
|
|
775
|
+
case "debug":
|
|
389
776
|
console.log(i);
|
|
390
777
|
break;
|
|
391
|
-
case
|
|
778
|
+
case "info":
|
|
392
779
|
console.info(i);
|
|
393
780
|
break;
|
|
394
|
-
case
|
|
781
|
+
case "warn":
|
|
395
782
|
console.warn(i);
|
|
396
783
|
break;
|
|
397
|
-
case
|
|
784
|
+
case "error":
|
|
398
785
|
console.error(i);
|
|
399
786
|
break;
|
|
400
|
-
case
|
|
401
|
-
}
|
|
402
|
-
},
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
[
|
|
406
|
-
[
|
|
407
|
-
[
|
|
408
|
-
[
|
|
409
|
-
|
|
410
|
-
[R.Silent, V.Silent]
|
|
411
|
-
]), U = class t {
|
|
787
|
+
case "silent": break;
|
|
788
|
+
}
|
|
789
|
+
}, ve = (e) => new be(e.logHandler ?? _e, e.logLevel), ye = new Map([
|
|
790
|
+
["trace", 0],
|
|
791
|
+
["debug", 1],
|
|
792
|
+
["info", 2],
|
|
793
|
+
["warn", 3],
|
|
794
|
+
["error", 4],
|
|
795
|
+
["silent", 5]
|
|
796
|
+
]), be = class t {
|
|
412
797
|
constructor(t, n, r) {
|
|
413
798
|
this._handler = t, this._context = r;
|
|
414
|
-
let i =
|
|
415
|
-
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`,
|
|
799
|
+
let i = ye.get(n);
|
|
800
|
+
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, T.InvalidArgument, 400);
|
|
416
801
|
this._levelNumber = i;
|
|
417
802
|
}
|
|
418
803
|
trace(e, t) {
|
|
419
|
-
this._write(e,
|
|
804
|
+
this._write(e, "trace", 0, t);
|
|
420
805
|
}
|
|
421
806
|
debug(e, t) {
|
|
422
|
-
this._write(e,
|
|
807
|
+
this._write(e, "debug", 1, t);
|
|
423
808
|
}
|
|
424
809
|
info(e, t) {
|
|
425
|
-
this._write(e,
|
|
810
|
+
this._write(e, "info", 2, t);
|
|
426
811
|
}
|
|
427
812
|
warn(e, t) {
|
|
428
|
-
this._write(e,
|
|
813
|
+
this._write(e, "warn", 3, t);
|
|
429
814
|
}
|
|
430
815
|
error(e, t) {
|
|
431
|
-
this._write(e,
|
|
816
|
+
this._write(e, "error", 4, t);
|
|
432
817
|
}
|
|
433
818
|
withContext(e) {
|
|
434
|
-
let n = [...
|
|
819
|
+
let n = [...ye.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? "error";
|
|
435
820
|
return new t(this._handler, n, this._mergeContext(e));
|
|
436
821
|
}
|
|
437
822
|
_write(e, t, n, r) {
|
|
@@ -443,143 +828,131 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
443
828
|
...e
|
|
444
829
|
} : this._context : e ?? void 0;
|
|
445
830
|
}
|
|
446
|
-
},
|
|
831
|
+
}, X = (e) => e.kind === "run" ? e.runId : e.codecMessageId, Z = (e) => e.kind === "run" ? e.startSerial : e.serial, xe = (e, t, n) => {
|
|
832
|
+
let r = e.get(t);
|
|
833
|
+
r || (r = /* @__PURE__ */ new Set(), e.set(t, r)), r.add(n);
|
|
834
|
+
}, Se = (e, t, n) => {
|
|
835
|
+
let r = e.get(t);
|
|
836
|
+
r && (r.delete(n), r.size === 0 && e.delete(t));
|
|
837
|
+
}, Ce = class {
|
|
447
838
|
constructor(e, t) {
|
|
448
|
-
this.
|
|
449
|
-
}
|
|
450
|
-
createStream(t) {
|
|
451
|
-
this._logger.trace("StreamRouter.createStream();", { turnId: t });
|
|
452
|
-
let n = {}, r = new ReadableStream({ start(e) {
|
|
453
|
-
n.controller = e;
|
|
454
|
-
} });
|
|
455
|
-
if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", C.TransportSubscriptionError, 500);
|
|
456
|
-
return this._turns.set(t, {
|
|
457
|
-
controller: n.controller,
|
|
458
|
-
turnId: t
|
|
459
|
-
}), r;
|
|
460
|
-
}
|
|
461
|
-
closeStream(e) {
|
|
462
|
-
let t = this._turns.get(e);
|
|
463
|
-
if (!t) return !1;
|
|
464
|
-
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
465
|
-
try {
|
|
466
|
-
t.controller.close();
|
|
467
|
-
} catch {}
|
|
468
|
-
return this._turns.delete(e), !0;
|
|
469
|
-
}
|
|
470
|
-
errorStream(e, t) {
|
|
471
|
-
let n = this._turns.get(e);
|
|
472
|
-
if (!n) return !1;
|
|
473
|
-
this._logger.debug("StreamRouter.errorStream(); erroring stream", { turnId: e });
|
|
474
|
-
try {
|
|
475
|
-
n.controller.error(t);
|
|
476
|
-
} catch {}
|
|
477
|
-
return this._turns.delete(e), !0;
|
|
478
|
-
}
|
|
479
|
-
route(e, t) {
|
|
480
|
-
let n = this._turns.get(e);
|
|
481
|
-
if (!n) return !1;
|
|
482
|
-
try {
|
|
483
|
-
n.controller.enqueue(t);
|
|
484
|
-
} catch {
|
|
485
|
-
return this._turns.delete(e), !1;
|
|
486
|
-
}
|
|
487
|
-
return this._isTerminal(t) && this.closeStream(e), !0;
|
|
488
|
-
}
|
|
489
|
-
has(e) {
|
|
490
|
-
return this._turns.has(e);
|
|
491
|
-
}
|
|
492
|
-
}, G = (e, t) => new W(e, t), K = class {
|
|
493
|
-
get structuralVersion() {
|
|
494
|
-
return this._structuralVersion;
|
|
495
|
-
}
|
|
496
|
-
constructor(e) {
|
|
497
|
-
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 L(e);
|
|
839
|
+
this._nodeIndex = /* @__PURE__ */ new Map(), this._codecMessageIdToNodeKey = /* @__PURE__ */ new Map(), this._sortedNodes = [], this._parentIndex = /* @__PURE__ */ new Map(), this._replyRunsByInput = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._structuralVersion = 0, this._siblingCache = /* @__PURE__ */ new Map(), this._siblingCacheVersion = -1, this._codec = e, this._logger = t, this._emitter = new Y(t);
|
|
498
840
|
}
|
|
499
841
|
_compareNodes(e, t) {
|
|
500
|
-
let n = e.node
|
|
842
|
+
let n = Z(e.node), r = Z(t.node);
|
|
501
843
|
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;
|
|
502
844
|
}
|
|
503
|
-
|
|
504
|
-
if (e.node
|
|
505
|
-
this.
|
|
845
|
+
_insertSortedNode(e) {
|
|
846
|
+
if (Z(e.node) === void 0) {
|
|
847
|
+
this._sortedNodes.push(e);
|
|
506
848
|
return;
|
|
507
849
|
}
|
|
508
|
-
let t = 0, n = this.
|
|
850
|
+
let t = 0, n = this._sortedNodes.length;
|
|
509
851
|
for (; t < n;) {
|
|
510
|
-
let r = t + n >>> 1, i = this.
|
|
852
|
+
let r = t + n >>> 1, i = this._sortedNodes[r];
|
|
511
853
|
if (!i) break;
|
|
512
854
|
this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
|
|
513
855
|
}
|
|
514
|
-
this.
|
|
856
|
+
this._sortedNodes.splice(t, 0, e);
|
|
857
|
+
}
|
|
858
|
+
_removeSortedNode(e) {
|
|
859
|
+
let t = this._sortedNodes.indexOf(e);
|
|
860
|
+
t !== -1 && this._sortedNodes.splice(t, 1);
|
|
515
861
|
}
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
862
|
+
_insertNode(e, t, n) {
|
|
863
|
+
this._nodeIndex.set(e, t), this._addToParentIndex(n, e), this._insertSortedNode(t), this._structuralVersion++;
|
|
864
|
+
}
|
|
865
|
+
_promoteSerial(e) {
|
|
866
|
+
this._removeSortedNode(e), this._insertSortedNode(e), this._structuralVersion++;
|
|
867
|
+
}
|
|
868
|
+
_foldInto(e, t, n, r) {
|
|
869
|
+
for (let i of t) try {
|
|
870
|
+
e.node.projection = this._codec.fold(e.node.projection, i, {
|
|
871
|
+
serial: n ?? "",
|
|
872
|
+
messageId: r
|
|
873
|
+
});
|
|
874
|
+
} catch (t) {
|
|
875
|
+
this._logger.error("Tree._foldInto(); fold threw", {
|
|
876
|
+
key: X(e.node),
|
|
877
|
+
messageId: r,
|
|
878
|
+
err: t
|
|
879
|
+
});
|
|
880
|
+
}
|
|
519
881
|
}
|
|
520
882
|
_addToParentIndex(e, t) {
|
|
521
|
-
|
|
522
|
-
n || (n = /* @__PURE__ */ new Set(), this._parentIndex.set(e, n)), n.add(t);
|
|
883
|
+
xe(this._parentIndex, e, t);
|
|
523
884
|
}
|
|
524
885
|
_removeFromParentIndex(e, t) {
|
|
525
|
-
|
|
526
|
-
|
|
886
|
+
Se(this._parentIndex, e, t);
|
|
887
|
+
}
|
|
888
|
+
_parentKeyOf(e) {
|
|
889
|
+
let t = e.parentCodecMessageId;
|
|
890
|
+
return t === void 0 ? void 0 : this._codecMessageIdToNodeKey.get(t);
|
|
891
|
+
}
|
|
892
|
+
_inputGroupRoot(e) {
|
|
893
|
+
let t = e, n = new Set([X(t)]);
|
|
894
|
+
for (; t.forkOf !== void 0 && !n.has(t.forkOf);) {
|
|
895
|
+
let e = this._nodeIndex.get(t.forkOf);
|
|
896
|
+
if (e?.node.kind !== "input" || e.node.parentCodecMessageId !== t.parentCodecMessageId) break;
|
|
897
|
+
t = e.node, n.add(X(t));
|
|
898
|
+
}
|
|
899
|
+
return t;
|
|
527
900
|
}
|
|
528
901
|
_getSiblingGroup(e) {
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
if (s) for (let e of s) {
|
|
902
|
+
this._siblingCacheVersion !== this._structuralVersion && (this._siblingCache.clear(), this._siblingCacheVersion = this._structuralVersion);
|
|
903
|
+
let t = this._siblingCache.get(e);
|
|
904
|
+
if (t) return t;
|
|
905
|
+
let n = this._nodeIndex.get(e);
|
|
906
|
+
if (!n) return [];
|
|
907
|
+
let r = n.node;
|
|
908
|
+
r.kind === "input" && (r = this._inputGroupRoot(r));
|
|
909
|
+
let i = r.parentCodecMessageId, a = [], o = this._parentIndex.get(i);
|
|
910
|
+
if (o) for (let e of o) {
|
|
539
911
|
let t = this._nodeIndex.get(e);
|
|
540
|
-
t && this._isSiblingOf(t.node,
|
|
912
|
+
t && this._isSiblingOf(t.node, r) && a.push(t);
|
|
541
913
|
}
|
|
542
|
-
|
|
914
|
+
a.sort((e, t) => this._compareNodes(e, t));
|
|
915
|
+
for (let e of a) this._siblingCache.set(X(e.node), a);
|
|
916
|
+
return this._siblingCache.set(e, a), a;
|
|
543
917
|
}
|
|
544
918
|
_isSiblingOf(e, t) {
|
|
545
|
-
if (e.
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
919
|
+
if (e.kind !== t.kind || e.parentCodecMessageId !== t.parentCodecMessageId) return !1;
|
|
920
|
+
if (e.kind === "run") return !0;
|
|
921
|
+
let n = X(t);
|
|
922
|
+
if (X(e) === n) return !0;
|
|
923
|
+
let r = e, i = new Set([X(r)]);
|
|
924
|
+
for (; r.kind === "input" && r.forkOf !== void 0;) {
|
|
925
|
+
if (r.forkOf === n) return !0;
|
|
926
|
+
if (i.has(r.forkOf)) break;
|
|
927
|
+
let e = this._nodeIndex.get(r.forkOf);
|
|
551
928
|
if (!e) break;
|
|
552
|
-
|
|
929
|
+
r = e.node, i.add(X(r));
|
|
553
930
|
}
|
|
554
931
|
return !1;
|
|
555
932
|
}
|
|
556
933
|
getGroupRoot(e) {
|
|
557
934
|
let t = this._nodeIndex.get(e);
|
|
558
935
|
if (!t) return e;
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
if (!e || e.node.parentId !== n.parentId) break;
|
|
563
|
-
n = e.node, r.add(n.msgId);
|
|
564
|
-
}
|
|
565
|
-
return n.msgId;
|
|
936
|
+
if (t.node.kind === "input") return X(this._inputGroupRoot(t.node));
|
|
937
|
+
let n = this._getSiblingGroup(e)[0]?.node;
|
|
938
|
+
return n ? X(n) : e;
|
|
566
939
|
}
|
|
567
|
-
|
|
568
|
-
this._logger.trace("DefaultTree.
|
|
940
|
+
visibleNodes(e = /* @__PURE__ */ new Map()) {
|
|
941
|
+
this._logger.trace("DefaultTree.visibleNodes();");
|
|
569
942
|
let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
|
|
570
|
-
for (let i of this.
|
|
571
|
-
let a = i.node,
|
|
943
|
+
for (let i of this._sortedNodes) {
|
|
944
|
+
let a = i.node, o = X(a), s = this._parentKeyOf(a);
|
|
572
945
|
if (s !== void 0 && !n.has(s)) continue;
|
|
573
946
|
let c = this._getSiblingGroup(o);
|
|
574
947
|
if (c.length > 1) {
|
|
575
948
|
let t = this.getGroupRoot(o), n = r.get(t);
|
|
576
949
|
if (n === void 0) {
|
|
577
950
|
let i = e.get(t);
|
|
578
|
-
if (i && c.some((e) => e.
|
|
951
|
+
if (i !== void 0 && c.some((e) => X(e.node) === i)) n = i;
|
|
579
952
|
else {
|
|
580
953
|
let e = c.at(-1);
|
|
581
954
|
if (!e) break;
|
|
582
|
-
n = e.
|
|
955
|
+
n = X(e.node);
|
|
583
956
|
}
|
|
584
957
|
r.set(t, n);
|
|
585
958
|
}
|
|
@@ -589,64 +962,185 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
589
962
|
}
|
|
590
963
|
return t;
|
|
591
964
|
}
|
|
592
|
-
|
|
593
|
-
|
|
965
|
+
getRunNode(e) {
|
|
966
|
+
this._logger.trace("DefaultTree.getRunNode();", { runId: e });
|
|
967
|
+
let t = this._nodeIndex.get(e)?.node;
|
|
968
|
+
return t?.kind === "run" ? t : void 0;
|
|
594
969
|
}
|
|
595
|
-
|
|
596
|
-
return this.
|
|
970
|
+
getNode(e) {
|
|
971
|
+
return this._logger.trace("DefaultTree.getNode();", { key: e }), this._nodeIndex.get(e)?.node;
|
|
597
972
|
}
|
|
598
|
-
|
|
599
|
-
|
|
973
|
+
getNodeByCodecMessageId(e) {
|
|
974
|
+
this._logger.trace("DefaultTree.getNodeByCodecMessageId();", { codecMessageId: e });
|
|
975
|
+
let t = this._codecMessageIdToNodeKey.get(e);
|
|
976
|
+
return t === void 0 ? void 0 : this._nodeIndex.get(t)?.node;
|
|
600
977
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
978
|
+
getReplyRuns(e) {
|
|
979
|
+
let t = this._replyRunsByInput.get(e);
|
|
980
|
+
if (!t) return [];
|
|
981
|
+
let n = [];
|
|
982
|
+
for (let e of t) {
|
|
983
|
+
let t = this._nodeIndex.get(e)?.node;
|
|
984
|
+
t?.kind === "run" && n.push(t);
|
|
985
|
+
}
|
|
986
|
+
return n;
|
|
987
|
+
}
|
|
988
|
+
getSiblingNodes(e) {
|
|
989
|
+
return this._logger.trace("DefaultTree.getSiblingNodes();", { key: e }), this._getSiblingGroup(e).map((e) => e.node);
|
|
990
|
+
}
|
|
991
|
+
applyMessage(e, t, n) {
|
|
992
|
+
let r = t[o], i = t[l], a = r === void 0 && i !== void 0 && t.role === "user" && e.inputs.length > 0 ? i : void 0;
|
|
993
|
+
if (r === void 0 && a === void 0) {
|
|
994
|
+
this._logger.warn("Tree.applyMessage(); message has no run-id and is not a user input; skipping");
|
|
614
995
|
return;
|
|
615
996
|
}
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
997
|
+
let s = [...e.inputs, ...e.outputs], c = a ?? r;
|
|
998
|
+
if (s.length === 0 && c !== void 0 && !this._nodeIndex.has(c)) return;
|
|
999
|
+
let u = this._structuralVersion;
|
|
1000
|
+
a === void 0 ? r !== void 0 && this._applyRunMessage(r, e, t, n) : this._applyInputMessage(a, t, n, s), this._structuralVersion !== u && this._emitter.emit("update");
|
|
1001
|
+
}
|
|
1002
|
+
_applyInputMessage(e, t, n, r) {
|
|
1003
|
+
let i = this._nodeIndex.get(e);
|
|
1004
|
+
i ? i.node.kind === "input" && n && !i.node.serial && (this._logger.debug("Tree.applyMessage(); promoting input serial", {
|
|
1005
|
+
codecMessageId: e,
|
|
1006
|
+
serial: n
|
|
1007
|
+
}), i.node.serial = n, this._promoteSerial(i)) : (i = this._createInputNodeFromHeaders(e, t, n), this._insertNode(e, i, i.node.parentCodecMessageId), this._codecMessageIdToNodeKey.set(e, e), this._logger.debug("Tree.applyMessage(); created input node", { codecMessageId: e })), this._foldInto(i, r, n, e), this._emitter.emit("output", {
|
|
1008
|
+
runId: void 0,
|
|
1009
|
+
inputCodecMessageId: e,
|
|
1010
|
+
codecMessageId: e,
|
|
1011
|
+
serial: n,
|
|
1012
|
+
events: []
|
|
620
1013
|
});
|
|
621
|
-
|
|
1014
|
+
}
|
|
1015
|
+
_applyRunMessage(e, t, n, r) {
|
|
1016
|
+
let i = n[l], a = n[_], o = [...t.inputs, ...t.outputs], s = t.outputs, c = this._nodeIndex.get(e);
|
|
1017
|
+
if (!c && i !== void 0) {
|
|
1018
|
+
let e = this._codecMessageIdToNodeKey.get(i), t = e === void 0 ? void 0 : this._nodeIndex.get(e);
|
|
1019
|
+
t?.node.kind === "run" && t.node.startSerial === void 0 && (c = t);
|
|
1020
|
+
}
|
|
1021
|
+
c ? r && c.node.kind === "run" && !c.node.startSerial && (this._logger.debug("Tree.applyMessage(); promoting startSerial", {
|
|
1022
|
+
runId: e,
|
|
1023
|
+
serial: r
|
|
1024
|
+
}), c.node.startSerial = r, this._promoteSerial(c)) : (c = this._createRunFromHeaders(e, n, r), this._insertNode(e, c, c.node.parentCodecMessageId), this._indexReplyRun(c.node, e), this._logger.debug("Tree.applyMessage(); created new Run", { runId: e }));
|
|
1025
|
+
let u = X(c.node);
|
|
1026
|
+
i && this._codecMessageIdToNodeKey.set(i, u), this._foldInto(c, o, r, i), this._emitter.emit("output", {
|
|
1027
|
+
runId: u,
|
|
1028
|
+
inputCodecMessageId: a,
|
|
1029
|
+
codecMessageId: i,
|
|
1030
|
+
serial: r,
|
|
1031
|
+
events: s
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
_indexReplyRun(e, t) {
|
|
1035
|
+
e.parentCodecMessageId !== void 0 && xe(this._replyRunsByInput, e.parentCodecMessageId, t);
|
|
1036
|
+
}
|
|
1037
|
+
applyRunLifecycle(e) {
|
|
1038
|
+
this._logger.trace("DefaultTree.applyRunLifecycle();", {
|
|
1039
|
+
type: e.type,
|
|
1040
|
+
runId: e.runId
|
|
1041
|
+
});
|
|
1042
|
+
let t = this._structuralVersion;
|
|
1043
|
+
switch (e.type) {
|
|
1044
|
+
case "start":
|
|
1045
|
+
this._applyRunStart(e);
|
|
1046
|
+
break;
|
|
1047
|
+
case "suspend":
|
|
1048
|
+
this._applyRunSuspend(e);
|
|
1049
|
+
break;
|
|
1050
|
+
case "resume":
|
|
1051
|
+
this._applyRunResume(e);
|
|
1052
|
+
break;
|
|
1053
|
+
case "end":
|
|
1054
|
+
this._applyRunEnd(e);
|
|
1055
|
+
break;
|
|
1056
|
+
}
|
|
1057
|
+
this._emitter.emit("run", e), this._structuralVersion !== t && this._emitter.emit("update");
|
|
1058
|
+
}
|
|
1059
|
+
_applyRunStart(e) {
|
|
1060
|
+
let t = this._nodeIndex.get(e.runId);
|
|
1061
|
+
if (t?.node.kind === "run") {
|
|
1062
|
+
let n = t.node;
|
|
1063
|
+
if (n.status !== "active" && (n.status = "active"), e.serial && !n.startSerial && (n.startSerial = e.serial, this._promoteSerial(t)), n.parentCodecMessageId === void 0 && e.parent !== void 0 && (n.parentCodecMessageId = e.parent, this._removeFromParentIndex(void 0, e.runId), this._addToParentIndex(n.parentCodecMessageId, e.runId), this._indexReplyRun(n, e.runId), this._structuralVersion++), n.forkOf === void 0 && e.forkOf !== void 0) {
|
|
1064
|
+
let t = this._codecMessageIdToNodeKey.get(e.forkOf);
|
|
1065
|
+
t !== void 0 && t !== e.runId && (n.forkOf = t, this._structuralVersion++);
|
|
1066
|
+
}
|
|
1067
|
+
n.regeneratesCodecMessageId === void 0 && e.regenerates !== void 0 && (n.regeneratesCodecMessageId = e.regenerates, this._structuralVersion++), n.invocationId === "" && e.invocationId !== "" && (n.invocationId = e.invocationId);
|
|
1068
|
+
} else if (!t) {
|
|
1069
|
+
let t = this._createRunFromLifecycle(e);
|
|
1070
|
+
this._insertNode(e.runId, t, t.node.parentCodecMessageId), this._indexReplyRun(t.node, e.runId);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
_applyRunSuspend(e) {
|
|
1074
|
+
let t = this._nodeIndex.get(e.runId);
|
|
1075
|
+
t?.node.kind === "run" && (t.node.status = "suspended", t.node.endSerial = e.serial);
|
|
1076
|
+
}
|
|
1077
|
+
_applyRunResume(e) {
|
|
1078
|
+
let t = this._nodeIndex.get(e.runId);
|
|
1079
|
+
t?.node.kind === "run" && t.node.status === "suspended" && (t.node.status = "active");
|
|
1080
|
+
}
|
|
1081
|
+
_applyRunEnd(e) {
|
|
1082
|
+
let t = this._nodeIndex.get(e.runId);
|
|
1083
|
+
t?.node.kind === "run" && (t.node.status = e.reason, t.node.endSerial = e.serial);
|
|
1084
|
+
}
|
|
1085
|
+
delete(e) {
|
|
1086
|
+
let t = this._nodeIndex.get(e);
|
|
1087
|
+
t && (this._logger.debug("Tree.delete();", { key: e }), this._removeFromParentIndex(t.node.parentCodecMessageId, e), this._removeSortedNode(t), this._nodeIndex.delete(e), t.node.kind === "run" && t.node.parentCodecMessageId !== void 0 && Se(this._replyRunsByInput, t.node.parentCodecMessageId, e), this._structuralVersion++, this._emitter.emit("update"));
|
|
1088
|
+
}
|
|
1089
|
+
_createRunFromHeaders(e, t, n) {
|
|
1090
|
+
let r = t[m];
|
|
1091
|
+
return this._buildRunNode({
|
|
1092
|
+
runId: e,
|
|
1093
|
+
parentCodecMessageId: t[p],
|
|
1094
|
+
forkOf: r ? this._codecMessageIdToNodeKey.get(r) : void 0,
|
|
1095
|
+
regeneratesCodecMessageId: t[h],
|
|
1096
|
+
clientId: t["run-client-id"] ?? "",
|
|
1097
|
+
invocationId: t["invocation-id"] ?? "",
|
|
1098
|
+
startSerial: n
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
_buildRunNode(e) {
|
|
1102
|
+
return {
|
|
622
1103
|
node: {
|
|
623
|
-
kind: "
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
1104
|
+
kind: "run",
|
|
1105
|
+
runId: e.runId,
|
|
1106
|
+
parentCodecMessageId: e.parentCodecMessageId,
|
|
1107
|
+
forkOf: e.forkOf,
|
|
1108
|
+
regeneratesCodecMessageId: e.regeneratesCodecMessageId,
|
|
1109
|
+
clientId: e.clientId,
|
|
1110
|
+
invocationId: e.invocationId,
|
|
1111
|
+
status: "active",
|
|
1112
|
+
projection: this._codec.init(),
|
|
1113
|
+
startSerial: e.startSerial,
|
|
1114
|
+
endSerial: void 0
|
|
630
1115
|
},
|
|
631
1116
|
insertSeq: this._seqCounter++
|
|
632
1117
|
};
|
|
633
|
-
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s), this._structuralVersion++, this._emitter.emit("update");
|
|
634
1118
|
}
|
|
635
|
-
|
|
636
|
-
let
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
1119
|
+
_createInputNodeFromHeaders(e, t, n) {
|
|
1120
|
+
let r = t[m];
|
|
1121
|
+
return {
|
|
1122
|
+
node: {
|
|
1123
|
+
kind: "input",
|
|
1124
|
+
codecMessageId: e,
|
|
1125
|
+
parentCodecMessageId: t[p],
|
|
1126
|
+
forkOf: r,
|
|
1127
|
+
projection: this._codec.init(),
|
|
1128
|
+
serial: n
|
|
1129
|
+
},
|
|
1130
|
+
insertSeq: this._seqCounter++
|
|
1131
|
+
};
|
|
641
1132
|
}
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
1133
|
+
_createRunFromLifecycle(e) {
|
|
1134
|
+
let t = e.forkOf;
|
|
1135
|
+
return this._buildRunNode({
|
|
1136
|
+
runId: e.runId,
|
|
1137
|
+
parentCodecMessageId: e.parent,
|
|
1138
|
+
forkOf: t ? this._codecMessageIdToNodeKey.get(t) : void 0,
|
|
1139
|
+
regeneratesCodecMessageId: e.regenerates,
|
|
1140
|
+
clientId: e.clientId,
|
|
1141
|
+
invocationId: e.invocationId,
|
|
1142
|
+
startSerial: e.serial
|
|
1143
|
+
});
|
|
650
1144
|
}
|
|
651
1145
|
on(e, t) {
|
|
652
1146
|
let n = t;
|
|
@@ -657,165 +1151,101 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
657
1151
|
emitAblyMessage(e) {
|
|
658
1152
|
this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
|
|
659
1153
|
}
|
|
660
|
-
|
|
661
|
-
|
|
1154
|
+
}, we = (e, t) => new Ce(e, t), Te = (e, t) => {
|
|
1155
|
+
for (let n of t) {
|
|
1156
|
+
let t = O(n), i = t[l];
|
|
1157
|
+
if (!i) continue;
|
|
1158
|
+
let a = n.action, o = a === "message.create" && "discrete" in t, s = t.stream === "true" && (a === "message.create" || a === "message.update" || a === "message.append"), c = t[r], u = c === "complete" || c === "cancelled";
|
|
1159
|
+
(o || s) && e.startedCodecMessageIds.add(i), (o || u) && e.terminatedCodecMessageIds.add(i), e.startedCodecMessageIds.has(i) && e.terminatedCodecMessageIds.has(i) && e.completedCodecMessageIds.add(i);
|
|
662
1160
|
}
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
turnId: e,
|
|
666
|
-
clientId: t
|
|
667
|
-
}), this._turnClientIds.set(e, t);
|
|
668
|
-
}
|
|
669
|
-
untrackTurn(e) {
|
|
670
|
-
this._logger.trace("DefaultTree.untrackTurn();", { turnId: e }), this._turnClientIds.delete(e);
|
|
671
|
-
}
|
|
672
|
-
}, q = (e) => new K(e), oe = (e) => {
|
|
673
|
-
let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), i = e.codec.createAccumulator(), s = 0, c = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = [], f = [];
|
|
674
|
-
for (let p of t) {
|
|
675
|
-
let t = n.decode(p), m = w(p), h = m[a], g = m[o], _ = p.serial, v = m[l];
|
|
676
|
-
if (v) {
|
|
677
|
-
for (let e of r.values()) if (e.msgHeaders.has(v)) {
|
|
678
|
-
let n = [...e.msgHeaders.keys()].indexOf(v), r = n === -1 ? void 0 : e.accumulator.messages[n];
|
|
679
|
-
r && e.accumulator.initMessage(v, r), e.accumulator.processOutputs(t), f.push({
|
|
680
|
-
accumulator: e.accumulator,
|
|
681
|
-
messageId: v
|
|
682
|
-
});
|
|
683
|
-
break;
|
|
684
|
-
}
|
|
685
|
-
continue;
|
|
686
|
-
}
|
|
687
|
-
if (h) {
|
|
688
|
-
let n = r.get(h);
|
|
689
|
-
if (n || (n = {
|
|
690
|
-
accumulator: e.codec.createAccumulator(),
|
|
691
|
-
firstSeen: s++,
|
|
692
|
-
msgHeaders: /* @__PURE__ */ new Map(),
|
|
693
|
-
msgSerials: /* @__PURE__ */ new Map()
|
|
694
|
-
}, r.set(h, n)), g) {
|
|
695
|
-
let e = n.msgHeaders.get(g);
|
|
696
|
-
e ? Object.keys(m).length > 0 && Object.assign(e, m) : (n.msgHeaders.set(g, { ...m }), _ && n.msgSerials.set(g, _));
|
|
697
|
-
}
|
|
698
|
-
n.accumulator.processOutputs(t);
|
|
699
|
-
} else {
|
|
700
|
-
i.processOutputs(t);
|
|
701
|
-
for (let e of t) if (e.kind === "message" && g) {
|
|
702
|
-
d.push(g);
|
|
703
|
-
let e = c.get(g);
|
|
704
|
-
e ? Object.keys(m).length > 0 && Object.assign(e, m) : (c.set(g, { ...m }), _ && u.set(g, _));
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
for (let { accumulator: e, messageId: t } of f) e.completeMessage(t);
|
|
709
|
-
let p = [];
|
|
710
|
-
for (let [e, t] of i.completedMessages.entries()) {
|
|
711
|
-
let n = d[e];
|
|
712
|
-
p.push({
|
|
713
|
-
message: t,
|
|
714
|
-
headers: n ? c.get(n) ?? {} : {},
|
|
715
|
-
serial: n ? u.get(n) ?? "" : ""
|
|
716
|
-
});
|
|
717
|
-
}
|
|
718
|
-
let m = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
|
|
719
|
-
for (let e of m) {
|
|
720
|
-
let t = [...e.msgHeaders.entries()], n = 0;
|
|
721
|
-
for (let r of e.accumulator.completedMessages) {
|
|
722
|
-
let i = t[n];
|
|
723
|
-
if (i) {
|
|
724
|
-
let [t, a] = i;
|
|
725
|
-
p.push({
|
|
726
|
-
message: r,
|
|
727
|
-
headers: a,
|
|
728
|
-
serial: e.msgSerials.get(t) ?? ""
|
|
729
|
-
}), n++;
|
|
730
|
-
} else p.push({
|
|
731
|
-
message: r,
|
|
732
|
-
headers: {},
|
|
733
|
-
serial: ""
|
|
734
|
-
});
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
return p.toReversed();
|
|
738
|
-
}, se = (e) => {
|
|
739
|
-
if (e.cachedDecode && e.cachedAtRawLength === e.rawMessages.length) return e.cachedDecode;
|
|
740
|
-
let t = oe(e);
|
|
741
|
-
return e.cachedDecode = t, e.cachedAtRawLength = e.rawMessages.length, t;
|
|
742
|
-
}, J = (e, t) => {
|
|
743
|
-
for (let r of t) {
|
|
744
|
-
let t = w(r), i = t[o];
|
|
745
|
-
if (!i || t["x-ably-amend"]) continue;
|
|
746
|
-
let a = r.action, s = a === "message.create" && "x-ably-discrete" in t, c = t["x-ably-stream"] === "true" && (a === "message.create" || a === "message.update" || a === "message.append"), l = t[n], u = l === "finished" || l === "aborted";
|
|
747
|
-
(s || c) && e.startedMsgIds.add(i), (s || u) && e.terminatedMsgIds.add(i), e.startedMsgIds.has(i) && e.terminatedMsgIds.has(i) && e.completedMsgIds.add(i);
|
|
748
|
-
}
|
|
749
|
-
}, Y = async (e, t, n) => {
|
|
750
|
-
e.rawMessages.push(...t.items), e.lastAblyPage = t, J(e, t.items);
|
|
1161
|
+
}, Ee = async (e, t, n) => {
|
|
1162
|
+
e.rawMessages.push(...t.items), e.lastAblyPage = t, Te(e, t.items);
|
|
751
1163
|
let r = e.returnedCount + n;
|
|
752
|
-
for (; e.
|
|
753
|
-
e.logger.debug("
|
|
1164
|
+
for (; e.completedCodecMessageIds.size < r && t.hasNext();) {
|
|
1165
|
+
e.logger.debug("loadHistory.fetchUntilLimit(); fetching next page", {
|
|
754
1166
|
collected: e.rawMessages.length,
|
|
755
|
-
completed: e.
|
|
1167
|
+
completed: e.completedCodecMessageIds.size
|
|
756
1168
|
});
|
|
757
1169
|
let n = await t.next();
|
|
758
1170
|
if (!n) break;
|
|
759
|
-
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n,
|
|
1171
|
+
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, Te(e, n.items);
|
|
760
1172
|
}
|
|
761
|
-
},
|
|
762
|
-
let n =
|
|
763
|
-
e.returnedCount += r
|
|
764
|
-
let
|
|
1173
|
+
}, Q = (e, t) => {
|
|
1174
|
+
let n = e.completedCodecMessageIds.size, r = Math.min(t, Math.max(0, n - e.returnedCount));
|
|
1175
|
+
e.returnedCount += r;
|
|
1176
|
+
let i = n > e.returnedCount, a = e.lastAblyPage?.hasNext() ?? !1, o = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
|
|
765
1177
|
return e.returnedRawCount = e.rawMessages.length, {
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
headers: e.headers,
|
|
769
|
-
serial: e.serial
|
|
770
|
-
})),
|
|
771
|
-
rawMessages: s,
|
|
772
|
-
hasNext: () => a || o,
|
|
1178
|
+
rawMessages: o,
|
|
1179
|
+
hasNext: () => i || a,
|
|
773
1180
|
next: async () => {
|
|
774
|
-
if (
|
|
775
|
-
if (!
|
|
1181
|
+
if (i) return Q(e, t);
|
|
1182
|
+
if (!a || !e.lastAblyPage) return;
|
|
776
1183
|
let n = await e.lastAblyPage.next();
|
|
777
|
-
if (n) return await
|
|
1184
|
+
if (n) return await Ee(e, n, t), Q(e, t);
|
|
778
1185
|
}
|
|
779
1186
|
};
|
|
780
|
-
},
|
|
781
|
-
let
|
|
782
|
-
codec: t,
|
|
1187
|
+
}, De = async (e, t, n) => {
|
|
1188
|
+
let r = t?.limit ?? 100, i = {
|
|
783
1189
|
rawMessages: [],
|
|
784
1190
|
returnedCount: 0,
|
|
785
1191
|
returnedRawCount: 0,
|
|
786
1192
|
lastAblyPage: void 0,
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
completedMsgIds: /* @__PURE__ */ new Set(),
|
|
792
|
-
logger: r
|
|
1193
|
+
startedCodecMessageIds: /* @__PURE__ */ new Set(),
|
|
1194
|
+
terminatedCodecMessageIds: /* @__PURE__ */ new Set(),
|
|
1195
|
+
completedCodecMessageIds: /* @__PURE__ */ new Set(),
|
|
1196
|
+
logger: n
|
|
793
1197
|
};
|
|
794
|
-
|
|
795
|
-
let
|
|
796
|
-
return await e.attach(), await
|
|
1198
|
+
n.trace("loadHistory();", { limit: r });
|
|
1199
|
+
let a = r * 10;
|
|
1200
|
+
return await e.attach(), await Ee(i, await e.history({
|
|
797
1201
|
untilAttach: !0,
|
|
798
|
-
limit:
|
|
799
|
-
}),
|
|
800
|
-
},
|
|
1202
|
+
limit: a
|
|
1203
|
+
}), r), Q(i, r);
|
|
1204
|
+
}, Oe = (e) => Array.isArray(e) ? e : [e], ke = 3, $ = (e) => ({
|
|
1205
|
+
runId: e.runId,
|
|
1206
|
+
clientId: e.clientId,
|
|
1207
|
+
status: e.status,
|
|
1208
|
+
invocationId: e.invocationId
|
|
1209
|
+
}), Ae = class {
|
|
801
1210
|
constructor(e) {
|
|
802
|
-
this._branchSelections = /* @__PURE__ */ new Map(), this.
|
|
1211
|
+
this._branchSelections = /* @__PURE__ */ new Map(), this._regenSelections = /* @__PURE__ */ new Map(), this._withheldRunIds = /* @__PURE__ */ new Set(), this._lastVisibleNodeKeys = [], this._lastVisibleProjections = [], this._lastVisibleMessagePairs = [], this._lastVisibleNodeKeySet = /* @__PURE__ */ new Set(), this._hasMoreHistory = !1, this._withheldBuffer = [], this._unsubs = [], this._cachedNodes = [], 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 Y(this._logger), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
|
|
803
1212
|
this._onTreeUpdate();
|
|
804
1213
|
}), this._tree.on("ably-message", (e) => {
|
|
805
1214
|
this._onTreeAblyMessage(e);
|
|
806
|
-
}), this._tree.on("
|
|
807
|
-
this.
|
|
1215
|
+
}), this._tree.on("run", (e) => {
|
|
1216
|
+
this._onTreeRun(e);
|
|
1217
|
+
}), this._tree.on("output", (e) => {
|
|
1218
|
+
this._onTreeOutput(e);
|
|
808
1219
|
}));
|
|
809
1220
|
}
|
|
1221
|
+
_onTreeOutput(e) {
|
|
1222
|
+
this._processingHistory || (e.runId !== void 0 && this._lastVisibleNodeKeySet.has(e.runId) || e.inputCodecMessageId !== void 0 && this._lastVisibleNodeKeySet.has(e.inputCodecMessageId)) && (this._lastVisibleProjections = this._cachedNodes.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(this._cachedNodes), this._emitter.emit("update"));
|
|
1223
|
+
}
|
|
810
1224
|
getMessages() {
|
|
811
|
-
return this.
|
|
1225
|
+
return this._lastVisibleMessagePairs;
|
|
812
1226
|
}
|
|
813
|
-
|
|
814
|
-
return this._cachedNodes;
|
|
1227
|
+
runs() {
|
|
1228
|
+
return this._cachedNodes.filter((e) => e.kind === "run").map((e) => $(e));
|
|
815
1229
|
}
|
|
816
1230
|
_computeFlatNodes() {
|
|
817
|
-
let e = this.
|
|
818
|
-
return this.
|
|
1231
|
+
let e = this._treeVisibleNodes();
|
|
1232
|
+
return this._withheldRunIds.size === 0 ? e : e.filter((e) => !this._withheldRunIds.has(X(e)));
|
|
1233
|
+
}
|
|
1234
|
+
_recomputeAndEmit() {
|
|
1235
|
+
this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update");
|
|
1236
|
+
}
|
|
1237
|
+
_recomputeAndEmitIfChanged() {
|
|
1238
|
+
let e = this._computeFlatNodes();
|
|
1239
|
+
this._visibleChanged(e) && (this._cachedNodes = e, this._updateVisibleSnapshot(e), this._emitter.emit("update"));
|
|
1240
|
+
}
|
|
1241
|
+
_runByCodecMessageId(e) {
|
|
1242
|
+
let t = this._tree.getNodeByCodecMessageId(e);
|
|
1243
|
+
return t?.kind === "run" ? t : void 0;
|
|
1244
|
+
}
|
|
1245
|
+
_extractMessages(e) {
|
|
1246
|
+
let t = [];
|
|
1247
|
+
for (let n of e) for (let e of this._codec.getMessages(n.projection)) t.push(e);
|
|
1248
|
+
return t;
|
|
819
1249
|
}
|
|
820
1250
|
hasOlder() {
|
|
821
1251
|
return this._withheldBuffer.length > 0 || this._hasMoreHistory;
|
|
@@ -843,7 +1273,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
843
1273
|
t || (this._hasMoreHistory = !1);
|
|
844
1274
|
return;
|
|
845
1275
|
}
|
|
846
|
-
await this.
|
|
1276
|
+
await this._revealFromPage(t, e);
|
|
847
1277
|
} catch (e) {
|
|
848
1278
|
throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
|
|
849
1279
|
} finally {
|
|
@@ -851,132 +1281,182 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
851
1281
|
}
|
|
852
1282
|
}
|
|
853
1283
|
}
|
|
854
|
-
|
|
855
|
-
this._logger.trace("DefaultView.
|
|
856
|
-
|
|
1284
|
+
runOf(e) {
|
|
1285
|
+
this._logger.trace("DefaultView.runOf();", { codecMessageId: e });
|
|
1286
|
+
let t = this._tree.getNodeByCodecMessageId(e);
|
|
1287
|
+
if (!t) return;
|
|
1288
|
+
if (t.kind === "run") return $(t);
|
|
1289
|
+
let n = this._selectedReplyRun(t.codecMessageId);
|
|
1290
|
+
return n ? $(n) : void 0;
|
|
1291
|
+
}
|
|
1292
|
+
_selectedReplyRun(e) {
|
|
1293
|
+
let t = this._tree.getReplyRuns(e);
|
|
1294
|
+
if (t.length === 0) return;
|
|
1295
|
+
if (t.length === 1) return t[0];
|
|
1296
|
+
let n = this._tree.getGroupRoot(t[0]?.runId ?? ""), r = this._regenSelections.get(n), i = r && r.kind !== "pending" ? r.selectedRunId : void 0;
|
|
1297
|
+
if (i !== void 0) {
|
|
1298
|
+
let e = t.find((e) => e.runId === i);
|
|
1299
|
+
if (e) return e;
|
|
1300
|
+
}
|
|
1301
|
+
return t.toSorted((e, t) => (e.startSerial ?? "").localeCompare(t.startSerial ?? "")).at(-1);
|
|
1302
|
+
}
|
|
1303
|
+
run(e) {
|
|
1304
|
+
this._logger.trace("DefaultView.run();", { runId: e });
|
|
1305
|
+
let t = this._tree.getRunNode(e);
|
|
1306
|
+
return t ? $(t) : void 0;
|
|
1307
|
+
}
|
|
1308
|
+
branchSelection(e) {
|
|
1309
|
+
let t = this._resolveMessageBranchPoint(e);
|
|
1310
|
+
if (t) {
|
|
1311
|
+
let e = t.siblings.flatMap((e) => {
|
|
1312
|
+
let t = this._codec.getMessages(e.projection).at(0);
|
|
1313
|
+
return t ? [t.message] : [];
|
|
1314
|
+
});
|
|
1315
|
+
if (e.length > 0) {
|
|
1316
|
+
let n = this._resolveSelectedIndex(t), r = Math.max(0, Math.min(n, e.length - 1)), i = e[r];
|
|
1317
|
+
return {
|
|
1318
|
+
hasSiblings: e.length > 1,
|
|
1319
|
+
siblings: e,
|
|
1320
|
+
index: r,
|
|
1321
|
+
selected: i
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
let n = this._tree.getNodeByCodecMessageId(e);
|
|
1326
|
+
if (n) {
|
|
1327
|
+
let t = this._codec.getMessages(n.projection).find((t) => t.codecMessageId === e);
|
|
1328
|
+
if (t !== void 0) return {
|
|
1329
|
+
hasSiblings: !1,
|
|
1330
|
+
siblings: [t.message],
|
|
1331
|
+
index: 0,
|
|
1332
|
+
selected: t.message
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
return {
|
|
1336
|
+
hasSiblings: !1,
|
|
1337
|
+
siblings: [],
|
|
1338
|
+
index: 0,
|
|
1339
|
+
selected: void 0
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
selectSibling(e, t) {
|
|
1343
|
+
this._logger.trace("DefaultView.selectSibling();", {
|
|
1344
|
+
codecMessageId: e,
|
|
857
1345
|
index: t
|
|
858
1346
|
});
|
|
859
|
-
let n = this.
|
|
860
|
-
if (n
|
|
861
|
-
let r =
|
|
862
|
-
|
|
1347
|
+
let n = this._resolveMessageBranchPoint(e);
|
|
1348
|
+
if (!n) return;
|
|
1349
|
+
let r = Math.max(0, Math.min(t, n.siblings.length - 1)), i = n.siblings[r];
|
|
1350
|
+
i && (n.kind === "fork-of" ? (this._branchSelections.set(n.groupRoot, {
|
|
1351
|
+
kind: "user",
|
|
1352
|
+
selectedKey: X(i)
|
|
1353
|
+
}), this._logger.debug("DefaultView.selectSibling(); fork-of", {
|
|
1354
|
+
codecMessageId: e,
|
|
1355
|
+
index: r,
|
|
1356
|
+
selectedKey: X(i)
|
|
1357
|
+
})) : (this._regenSelections.set(n.groupRoot, {
|
|
863
1358
|
kind: "user",
|
|
864
|
-
|
|
865
|
-
}), this._logger.debug("DefaultView.
|
|
866
|
-
|
|
867
|
-
index:
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
hasSiblings(e) {
|
|
884
|
-
return this._tree.hasSiblings(e);
|
|
1359
|
+
selectedRunId: X(i)
|
|
1360
|
+
}), this._logger.debug("DefaultView.selectSibling(); regenerate", {
|
|
1361
|
+
codecMessageId: e,
|
|
1362
|
+
index: r,
|
|
1363
|
+
selectedRunId: X(i),
|
|
1364
|
+
groupRoot: n.groupRoot
|
|
1365
|
+
})), this._recomputeAndEmit());
|
|
1366
|
+
}
|
|
1367
|
+
_resolveSelectedIndex(e) {
|
|
1368
|
+
if (e.kind === "fork-of") {
|
|
1369
|
+
let t = this._branchSelections.get(e.groupRoot);
|
|
1370
|
+
if (!t) return e.siblings.length - 1;
|
|
1371
|
+
let n = e.siblings.findIndex((e) => X(e) === t.selectedKey);
|
|
1372
|
+
return n === -1 ? e.siblings.length - 1 : n;
|
|
1373
|
+
}
|
|
1374
|
+
let t = this._regenSelections.get(e.groupRoot);
|
|
1375
|
+
if (!t || t.kind === "pending") return e.siblings.length - 1;
|
|
1376
|
+
let n = e.siblings.findIndex((e) => X(e) === t.selectedRunId);
|
|
1377
|
+
return n === -1 ? e.siblings.length - 1 : n;
|
|
885
1378
|
}
|
|
886
|
-
|
|
887
|
-
|
|
1379
|
+
_resolveMessageBranchPoint(e) {
|
|
1380
|
+
let t = this._tree.getNodeByCodecMessageId(e);
|
|
1381
|
+
if (!t) return;
|
|
1382
|
+
if (t.kind === "input") {
|
|
1383
|
+
let e = this._tree.getSiblingNodes(t.codecMessageId);
|
|
1384
|
+
return e.length > 1 ? {
|
|
1385
|
+
kind: "fork-of",
|
|
1386
|
+
groupRoot: this._tree.getGroupRoot(t.codecMessageId),
|
|
1387
|
+
siblings: e
|
|
1388
|
+
} : void 0;
|
|
1389
|
+
}
|
|
1390
|
+
let n = this._tree.getSiblingNodes(t.runId);
|
|
1391
|
+
if (n.length > 1 && this._codec.getMessages(t.projection).at(0)?.codecMessageId === e) return {
|
|
1392
|
+
kind: "regen",
|
|
1393
|
+
groupRoot: this._tree.getGroupRoot(t.runId),
|
|
1394
|
+
siblings: n
|
|
1395
|
+
};
|
|
888
1396
|
}
|
|
889
1397
|
async send(t, n) {
|
|
890
|
-
if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed",
|
|
891
|
-
let r = this.
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
this._unsubs.push(t);
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
return i;
|
|
1398
|
+
if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", T.InvalidArgument, 400);
|
|
1399
|
+
let r = Oe(t), i = this._lastVisibleMessagePairs.at(-1)?.codecMessageId, a = await this._sendDelegate(r, n, i);
|
|
1400
|
+
return this._applyForkAutoSelect(a, n), a;
|
|
1401
|
+
}
|
|
1402
|
+
_applyForkAutoSelect(e, t) {
|
|
1403
|
+
if (!t?.forkOf) return;
|
|
1404
|
+
let n = e.optimisticCodecMessageIds.at(0);
|
|
1405
|
+
if (n === void 0) return;
|
|
1406
|
+
let r = this._tree.getGroupRoot(n);
|
|
1407
|
+
this._branchSelections.set(r, {
|
|
1408
|
+
kind: "auto",
|
|
1409
|
+
selectedKey: n
|
|
1410
|
+
}), this._recomputeAndEmit();
|
|
1411
|
+
}
|
|
1412
|
+
_applyRegenerateAutoSelect(e, t) {
|
|
1413
|
+
let n = this._runByCodecMessageId(t);
|
|
1414
|
+
if (!n) return;
|
|
1415
|
+
let r = this._tree.getGroupRoot(n.runId);
|
|
1416
|
+
this._regenSelections.set(r, {
|
|
1417
|
+
kind: "pending",
|
|
1418
|
+
carrierCodecMessageId: e.inputCodecMessageId
|
|
1419
|
+
}), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection", {
|
|
1420
|
+
anchorCodecMessageId: t,
|
|
1421
|
+
groupRoot: r,
|
|
1422
|
+
carrier: e.inputCodecMessageId
|
|
1423
|
+
}), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged();
|
|
920
1424
|
}
|
|
921
1425
|
async regenerate(t, n) {
|
|
922
|
-
this._logger.trace("DefaultView.regenerate();", { messageId: t });
|
|
923
|
-
let r = this.
|
|
924
|
-
if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`,
|
|
925
|
-
let i = r
|
|
926
|
-
|
|
1426
|
+
if (this._logger.trace("DefaultView.regenerate();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to regenerate; view is closed", T.InvalidArgument, 400);
|
|
1427
|
+
let r = this._runByCodecMessageId(t);
|
|
1428
|
+
if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, T.InvalidArgument, 400);
|
|
1429
|
+
let i = this._findParentMsgId(r, t);
|
|
1430
|
+
if (!i) throw new e.ErrorInfo(`unable to regenerate; parent user message not found for ${t}`, T.InvalidArgument, 400);
|
|
1431
|
+
let a = t;
|
|
1432
|
+
r.regeneratesCodecMessageId !== void 0 && this._codec.getMessages(r.projection).at(0)?.codecMessageId === t && (a = r.regeneratesCodecMessageId);
|
|
1433
|
+
let o = {
|
|
927
1434
|
...n,
|
|
928
|
-
body: {
|
|
929
|
-
history: this._getHistoryBefore(t),
|
|
930
|
-
...n?.body
|
|
931
|
-
},
|
|
932
|
-
forkOf: t,
|
|
933
1435
|
parent: i
|
|
934
|
-
});
|
|
1436
|
+
}, s = this._codec.createRegenerate(a, i), c = await this._sendDelegate([s], o, i);
|
|
1437
|
+
return this._applyRegenerateAutoSelect(c, a), c;
|
|
935
1438
|
}
|
|
936
1439
|
async edit(t, n, r) {
|
|
937
|
-
this._logger.trace("DefaultView.edit();", { messageId: t });
|
|
938
|
-
let i = this._tree.
|
|
939
|
-
if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`,
|
|
940
|
-
let a = i
|
|
1440
|
+
if (this._logger.trace("DefaultView.edit();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to edit; view is closed", T.InvalidArgument, 400);
|
|
1441
|
+
let i = this._tree.getNodeByCodecMessageId(t);
|
|
1442
|
+
if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, T.InvalidArgument, 400);
|
|
1443
|
+
let a = this._findParentMsgId(i, t);
|
|
941
1444
|
return this.send(n, {
|
|
942
1445
|
...r,
|
|
943
|
-
body: {
|
|
944
|
-
history: this._getHistoryBefore(t),
|
|
945
|
-
...r?.body
|
|
946
|
-
},
|
|
947
1446
|
forkOf: t,
|
|
948
1447
|
parent: a
|
|
949
1448
|
});
|
|
950
1449
|
}
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
events: n
|
|
961
|
-
}];
|
|
962
|
-
return this._sendDelegate([], r, this.flattenNodes(), i);
|
|
963
|
-
}
|
|
964
|
-
_getHistoryBefore(e) {
|
|
965
|
-
this._logger.trace("DefaultView._getHistoryBefore();", { messageId: e });
|
|
966
|
-
let t = this.flattenNodes(), n = t.findIndex((t) => t.msgId === e);
|
|
967
|
-
return n === -1 ? (this._logger.warn("DefaultView._getHistoryBefore(); target not in visible nodes, returning full list", { messageId: e }), t) : t.slice(0, n);
|
|
968
|
-
}
|
|
969
|
-
getActiveTurnIds() {
|
|
970
|
-
this._logger.trace("DefaultView.getActiveTurnIds();");
|
|
971
|
-
let e = this._tree.getActiveTurnIds();
|
|
972
|
-
if (this._withheldMsgIds.size === 0) return e;
|
|
973
|
-
let t = /* @__PURE__ */ new Map();
|
|
974
|
-
for (let [n, r] of e) {
|
|
975
|
-
let e = /* @__PURE__ */ new Set();
|
|
976
|
-
for (let t of r) this._lastVisibleTurnIds.has(t) && e.add(t);
|
|
977
|
-
e.size > 0 && t.set(n, e);
|
|
1450
|
+
_findParentMsgId(e, t) {
|
|
1451
|
+
let n = this._lastVisibleMessagePairs, r = n.findIndex((e) => e.codecMessageId === t);
|
|
1452
|
+
if (r > 0) return n[r - 1]?.codecMessageId;
|
|
1453
|
+
if (r === 0) return;
|
|
1454
|
+
let i = this._codec.getMessages(e.projection), a = i.findIndex((e) => e.codecMessageId === t);
|
|
1455
|
+
if (a > 0) return i[a - 1]?.codecMessageId;
|
|
1456
|
+
if (a === 0 && e.parentCodecMessageId !== void 0) {
|
|
1457
|
+
let t = this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);
|
|
1458
|
+
if (t) return this._codec.getMessages(t.projection).at(-1)?.codecMessageId;
|
|
978
1459
|
}
|
|
979
|
-
return t;
|
|
980
1460
|
}
|
|
981
1461
|
on(e, t) {
|
|
982
1462
|
let n = t;
|
|
@@ -985,35 +1465,38 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
985
1465
|
};
|
|
986
1466
|
}
|
|
987
1467
|
close() {
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
1468
|
+
if (!this._closed) {
|
|
1469
|
+
this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
|
|
1470
|
+
for (let e of this._unsubs) e();
|
|
1471
|
+
this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._regenSelections.clear(), this._withheldRunIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
|
|
1472
|
+
}
|
|
991
1473
|
}
|
|
992
1474
|
async _loadFirstPage(e) {
|
|
993
|
-
let t =
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1475
|
+
let t = e * ke, n = await De(this._channel, { limit: t }, this._logger);
|
|
1476
|
+
this._closed || await this._revealFromPage(n, e);
|
|
1477
|
+
}
|
|
1478
|
+
async _revealFromPage(e, t) {
|
|
1479
|
+
let n = new Set(this._treeVisibleNodes().map((e) => X(e))), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
|
|
1480
|
+
this._closed || (this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext(), this._splitReveal(r, t));
|
|
1481
|
+
}
|
|
1482
|
+
_splitReveal(e, t) {
|
|
1483
|
+
let n = 0, r = e.length;
|
|
1484
|
+
for (let i = e.length - 1; i >= 0; i--) {
|
|
1485
|
+
if (e[i]?.kind === "run") {
|
|
1486
|
+
if (n === t) break;
|
|
1487
|
+
n++;
|
|
1488
|
+
}
|
|
1489
|
+
r = i;
|
|
1490
|
+
}
|
|
1491
|
+
let i = e.slice(r), a = e.slice(0, r);
|
|
1492
|
+
for (let e of a) this._withheldRunIds.add(X(e));
|
|
1493
|
+
this._withheldBuffer.push(...a), this._releaseWithheld(i);
|
|
1009
1494
|
}
|
|
1010
1495
|
_processHistoryPage(e) {
|
|
1011
1496
|
this._processingHistory = !0;
|
|
1012
1497
|
try {
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
e && this._tree.upsert(e, t.message, t.headers, t.serial);
|
|
1016
|
-
}
|
|
1498
|
+
let t = this._codec.createDecoder();
|
|
1499
|
+
for (let n of e.rawMessages) q(this._tree, t, n);
|
|
1017
1500
|
for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
|
|
1018
1501
|
} finally {
|
|
1019
1502
|
this._processingHistory = !1;
|
|
@@ -1023,7 +1506,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1023
1506
|
this._processHistoryPage(e);
|
|
1024
1507
|
let r = e, i = () => {
|
|
1025
1508
|
let e = 0;
|
|
1026
|
-
for (let t of this.
|
|
1509
|
+
for (let t of this._treeVisibleNodes()) t.kind === "run" && !n.has(X(t)) && e++;
|
|
1027
1510
|
return e;
|
|
1028
1511
|
};
|
|
1029
1512
|
for (; i() < t && r.hasNext();) {
|
|
@@ -1032,290 +1515,173 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1032
1515
|
this._processHistoryPage(e), r = e;
|
|
1033
1516
|
}
|
|
1034
1517
|
return {
|
|
1035
|
-
newVisible: this.
|
|
1518
|
+
newVisible: this._treeVisibleNodes().filter((e) => !n.has(X(e))),
|
|
1036
1519
|
lastPage: r
|
|
1037
1520
|
};
|
|
1038
1521
|
}
|
|
1039
1522
|
_releaseWithheld(e) {
|
|
1040
|
-
for (let t of e) this.
|
|
1041
|
-
e.length > 0 &&
|
|
1523
|
+
for (let t of e) this._withheldRunIds.delete(X(t));
|
|
1524
|
+
e.length > 0 && this._recomputeAndEmit();
|
|
1042
1525
|
}
|
|
1043
1526
|
_updateVisibleSnapshot(e) {
|
|
1044
|
-
let t = e ?? this.
|
|
1045
|
-
this.
|
|
1046
|
-
for (let e of t) {
|
|
1047
|
-
let t = e.headers[a];
|
|
1048
|
-
t && this._lastVisibleTurnIds.add(t);
|
|
1049
|
-
}
|
|
1527
|
+
let t = e ?? this._cachedNodes;
|
|
1528
|
+
this._lastVisibleNodeKeys = t.map((e) => X(e)), this._lastVisibleNodeKeySet = new Set(this._lastVisibleNodeKeys), this._lastVisibleProjections = t.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(t);
|
|
1050
1529
|
}
|
|
1051
1530
|
_onTreeUpdate() {
|
|
1052
|
-
|
|
1053
|
-
let e = this._tree.structuralVersion;
|
|
1054
|
-
if (e === this._lastStructuralVersion) {
|
|
1055
|
-
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"));
|
|
1056
|
-
return;
|
|
1057
|
-
}
|
|
1058
|
-
this._lastStructuralVersion = e, this._pinBranchSelections(), this._resolvePendingSelections();
|
|
1059
|
-
let t = this._computeFlatNodes(), n = t.map((e) => e.msgId), r = t.map((e) => e.message);
|
|
1060
|
-
this._visibleChanged(n, r) && (this._cachedNodes = t, this._updateVisibleSnapshot(t), this._emitter.emit("update"));
|
|
1531
|
+
this._processingHistory || (this._pinBranchSelections(), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged());
|
|
1061
1532
|
}
|
|
1062
1533
|
_resolveSelections() {
|
|
1063
1534
|
let e = /* @__PURE__ */ new Map();
|
|
1064
|
-
for (let [t, n] of this._branchSelections)
|
|
1535
|
+
for (let [t, n] of this._branchSelections) e.set(t, n.selectedKey);
|
|
1536
|
+
for (let [t, n] of this._regenSelections) n.kind !== "pending" && e.set(t, n.selectedRunId);
|
|
1065
1537
|
return e;
|
|
1066
1538
|
}
|
|
1539
|
+
_treeVisibleNodes() {
|
|
1540
|
+
return this._tree.visibleNodes(this._resolveSelections());
|
|
1541
|
+
}
|
|
1067
1542
|
_pinBranchSelections() {
|
|
1068
|
-
for (let e of this.
|
|
1069
|
-
if (
|
|
1070
|
-
let t = this._tree.getGroupRoot(e)
|
|
1071
|
-
|
|
1072
|
-
let r = this._tree.getSiblingNodes(e).at(-1);
|
|
1073
|
-
r && r.msgId !== e && r.headers["x-ably-turn-id"] === n.turnId && (this._logger.debug("DefaultView._pinBranchSelections(); auto-selecting pending fork", {
|
|
1074
|
-
msgId: e,
|
|
1075
|
-
newestId: r.msgId,
|
|
1076
|
-
turnId: n.turnId
|
|
1077
|
-
}), this._branchSelections.set(t, {
|
|
1078
|
-
kind: "auto",
|
|
1079
|
-
selectedId: r.msgId
|
|
1080
|
-
}));
|
|
1081
|
-
continue;
|
|
1082
|
-
}
|
|
1083
|
-
n || this._branchSelections.set(t, {
|
|
1543
|
+
for (let e of this._lastVisibleNodeKeys) {
|
|
1544
|
+
if (this._tree.getNode(e)?.kind !== "input" || this._tree.getSiblingNodes(e).length <= 1) continue;
|
|
1545
|
+
let t = this._tree.getGroupRoot(e);
|
|
1546
|
+
this._branchSelections.get(t) || this._branchSelections.set(t, {
|
|
1084
1547
|
kind: "pinned",
|
|
1085
|
-
|
|
1548
|
+
selectedKey: e
|
|
1086
1549
|
});
|
|
1087
1550
|
}
|
|
1088
1551
|
}
|
|
1089
|
-
|
|
1090
|
-
for (let [e, t] of this.
|
|
1091
|
-
if (t.kind
|
|
1092
|
-
let n = this._tree.getSiblingNodes(e);
|
|
1552
|
+
_resolvePendingRegenSelections() {
|
|
1553
|
+
for (let [e, t] of this._regenSelections) {
|
|
1554
|
+
if (t.kind === "user") continue;
|
|
1555
|
+
let n = this._tree.getSiblingNodes(e).filter((e) => e.kind === "run");
|
|
1093
1556
|
if (n.length <= 1) continue;
|
|
1094
1557
|
let r = n.at(-1);
|
|
1095
|
-
|
|
1096
|
-
groupRoot: e,
|
|
1097
|
-
newestId: r.msgId,
|
|
1098
|
-
turnId: t.turnId
|
|
1099
|
-
}), this._branchSelections.set(e, {
|
|
1558
|
+
r && this._regenSelections.set(e, {
|
|
1100
1559
|
kind: "auto",
|
|
1101
|
-
|
|
1102
|
-
})
|
|
1560
|
+
selectedRunId: r.runId
|
|
1561
|
+
});
|
|
1103
1562
|
}
|
|
1104
1563
|
}
|
|
1105
1564
|
_onTreeAblyMessage(e) {
|
|
1106
|
-
let t =
|
|
1107
|
-
if (!
|
|
1565
|
+
let t = O(e), n = t[l], r = t[o];
|
|
1566
|
+
if (!n && !r) {
|
|
1108
1567
|
this._emitter.emit("ably-message", e);
|
|
1109
1568
|
return;
|
|
1110
1569
|
}
|
|
1111
|
-
this.
|
|
1570
|
+
r && this._lastVisibleNodeKeySet.has(r) && this._emitter.emit("ably-message", e);
|
|
1112
1571
|
}
|
|
1113
|
-
|
|
1114
|
-
if (this.
|
|
1115
|
-
this._emitter.emit("
|
|
1572
|
+
_onTreeRun(e) {
|
|
1573
|
+
if (this._lastVisibleNodeKeySet.has(e.runId)) {
|
|
1574
|
+
this._emitter.emit("run", e);
|
|
1116
1575
|
return;
|
|
1117
1576
|
}
|
|
1118
|
-
e.type === "
|
|
1577
|
+
e.type === "start" && this._isRunStartVisible(e) && (this._lastVisibleNodeKeySet.add(e.runId), this._emitter.emit("run", e));
|
|
1119
1578
|
}
|
|
1120
|
-
|
|
1579
|
+
_isRunStartVisible(e) {
|
|
1121
1580
|
let { parent: t } = e;
|
|
1122
|
-
|
|
1581
|
+
if (t === void 0) return !0;
|
|
1582
|
+
let n = this._tree.getNodeByCodecMessageId(t);
|
|
1583
|
+
return n ? this._lastVisibleNodeKeySet.has(X(n)) : !0;
|
|
1123
1584
|
}
|
|
1124
|
-
_visibleChanged(e
|
|
1125
|
-
if (e.length !== this.
|
|
1126
|
-
for (let [t, n] of e.entries()) if (n !== this.
|
|
1127
|
-
for (let [e, n] of t.entries()) if (n !== this._lastVisibleMessages[e]) return !0;
|
|
1585
|
+
_visibleChanged(e) {
|
|
1586
|
+
if (e.length !== this._lastVisibleNodeKeys.length) return !0;
|
|
1587
|
+
for (let [t, n] of e.entries()) if (X(n) !== this._lastVisibleNodeKeys[t] || n.projection !== this._lastVisibleProjections[t]) return !0;
|
|
1128
1588
|
return !1;
|
|
1129
1589
|
}
|
|
1130
|
-
},
|
|
1131
|
-
return e.READY = "ready", e.CLOSED = "closed", e;
|
|
1132
|
-
}(Q || {}), de = class {
|
|
1590
|
+
}, je = (e) => new Ae(e), Me = () => {}, Ne = class {
|
|
1133
1591
|
constructor(e) {
|
|
1134
|
-
|
|
1592
|
+
this._views = /* @__PURE__ */ new Set(), this._state = "ready", this._pendingRunStarts = /* @__PURE__ */ new Map();
|
|
1593
|
+
let t = B(e.client, e.codec);
|
|
1594
|
+
if (this._channel = e.client.channels.get(e.channelName, t), this._codec = e.codec, this._clientId = e.clientId, this._logger = (e.logger ?? ve({ logLevel: ge.Silent })).withContext({ component: "ClientSession" }), this._emitter = new Y(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = we(this._codec, this._logger), this._view = je({
|
|
1135
1595
|
tree: this._tree,
|
|
1136
1596
|
channel: this._channel,
|
|
1137
1597
|
codec: this._codec,
|
|
1138
1598
|
sendDelegate: this._internalSend.bind(this),
|
|
1139
1599
|
logger: this._logger,
|
|
1140
1600
|
onClose: () => this._views.delete(this._view)
|
|
1141
|
-
}), this.
|
|
1601
|
+
}), this._decoder = this._codec.createDecoder(), this._encoder = this._codec.createEncoder(this._channel, this._clientId === void 0 ? void 0 : { clientId: this._clientId }), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
|
|
1142
1602
|
let t;
|
|
1143
1603
|
for (let n of e.messages) {
|
|
1144
|
-
let e = crypto.randomUUID(), r = {
|
|
1145
|
-
|
|
1604
|
+
let e = crypto.randomUUID(), r = {
|
|
1605
|
+
[l]: e,
|
|
1606
|
+
[f]: "user"
|
|
1607
|
+
};
|
|
1608
|
+
t && (r[p] = t), this._tree.applyMessage({
|
|
1609
|
+
inputs: [this._codec.createUserMessage(n)],
|
|
1610
|
+
outputs: []
|
|
1611
|
+
}, r), t = e;
|
|
1146
1612
|
}
|
|
1147
1613
|
}
|
|
1148
1614
|
this._onMessage = (e) => {
|
|
1149
1615
|
this._handleMessage(e);
|
|
1150
|
-
}, this.
|
|
1616
|
+
}, this._onChannelStateChange = (e) => {
|
|
1151
1617
|
this._handleChannelStateChange(e);
|
|
1152
1618
|
}, this._channel.on(this._onChannelStateChange);
|
|
1153
1619
|
}
|
|
1620
|
+
connect() {
|
|
1621
|
+
return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", T.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger.trace("DefaultClientSession.connect();"), this._connectPromise = this._channel.subscribe(this._onMessage).then(() => {
|
|
1622
|
+
this._logger.debug("DefaultClientSession.connect(); subscribed and attached");
|
|
1623
|
+
}, (t) => {
|
|
1624
|
+
let n = new e.ErrorInfo(`unable to subscribe to channel; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
1625
|
+
throw this._logger.error("DefaultClientSession.connect(); subscribe failed"), this._emitter.emit("error", n), n;
|
|
1626
|
+
}), this._connectPromise);
|
|
1627
|
+
}
|
|
1628
|
+
async _requireConnected(t) {
|
|
1629
|
+
if (!this._connectPromise) throw new e.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`, T.InvalidArgument, 400);
|
|
1630
|
+
return this._connectPromise;
|
|
1631
|
+
}
|
|
1154
1632
|
_handleMessage(t) {
|
|
1155
|
-
if (this._state !==
|
|
1156
|
-
if (t.name === "
|
|
1157
|
-
let
|
|
1158
|
-
if (n) {
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
...t !== void 0 && { parent: t },
|
|
1166
|
-
...i !== void 0 && { forkOf: i }
|
|
1167
|
-
});
|
|
1633
|
+
if (this._state !== "closed") try {
|
|
1634
|
+
if (t.name === "ai-run-end") {
|
|
1635
|
+
let n = O(t);
|
|
1636
|
+
if ((n["run-reason"] ?? "complete") === "error") {
|
|
1637
|
+
let t = n[v], r = t === void 0 ? NaN : Number(t), i = Number.isFinite(r) ? r : T.SessionSubscriptionError, a = n["error-message"] ?? "agent reported an error", c = i >= 1e4 && i < 6e4 ? Math.floor(i / 100) : 500, l = new e.ErrorInfo(a, i, c);
|
|
1638
|
+
this._logger.error("ClientSession._handleMessage(); agent error received", {
|
|
1639
|
+
runId: n[o],
|
|
1640
|
+
invocationId: n[s],
|
|
1641
|
+
code: i
|
|
1642
|
+
}), this._emitter.emit("error", l);
|
|
1168
1643
|
}
|
|
1169
|
-
this._tree.emitAblyMessage(t);
|
|
1170
|
-
return;
|
|
1171
1644
|
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
let
|
|
1177
|
-
|
|
1178
|
-
for (let t of e) this._ownMsgIds.delete(t);
|
|
1179
|
-
this._turnMsgIds.delete(n);
|
|
1180
|
-
}
|
|
1181
|
-
this._ownTurnIds.delete(n), this._tree.emitTurn({
|
|
1182
|
-
type: y,
|
|
1183
|
-
turnId: n,
|
|
1184
|
-
clientId: r,
|
|
1185
|
-
reason: i
|
|
1186
|
-
});
|
|
1645
|
+
let n = q(this._tree, this._decoder, t);
|
|
1646
|
+
if (n && (n.type === "start" || n.type === "resume")) {
|
|
1647
|
+
let e = O(t)[_];
|
|
1648
|
+
if (e !== void 0) {
|
|
1649
|
+
let t = this._pendingRunStarts.get(e);
|
|
1650
|
+
t && (this._pendingRunStarts.delete(e), t.resolve(n.runId));
|
|
1187
1651
|
}
|
|
1188
|
-
this._tree.emitAblyMessage(t);
|
|
1189
|
-
return;
|
|
1190
|
-
}
|
|
1191
|
-
let e = this._decoder.decode(t), n = w(t), r = t.serial, i = n[l];
|
|
1192
|
-
if (i) {
|
|
1193
|
-
for (let t of e) t.kind === "event" && this._handleAmendmentEvent(i, t);
|
|
1194
|
-
return;
|
|
1195
1652
|
}
|
|
1196
|
-
let o = n[a];
|
|
1197
|
-
o && this._updateTurnObserverHeaders(o, n, r);
|
|
1198
|
-
for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
|
|
1199
1653
|
this._tree.emitAblyMessage(t);
|
|
1200
1654
|
} catch (t) {
|
|
1201
1655
|
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
1202
|
-
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`,
|
|
1656
|
+
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, n));
|
|
1203
1657
|
}
|
|
1204
1658
|
}
|
|
1205
|
-
_handleMessageOutput(e, t, n, r) {
|
|
1206
|
-
let i = t[o];
|
|
1207
|
-
if (i && this._ownMsgIds.has(i)) {
|
|
1208
|
-
this._upsertAndNotify(e, t, n);
|
|
1209
|
-
return;
|
|
1210
|
-
}
|
|
1211
|
-
r === "message.create" && this._upsertAndNotify(e, t, n);
|
|
1212
|
-
}
|
|
1213
|
-
_handleEventOutput(e, t) {
|
|
1214
|
-
if (e.kind !== "event") return;
|
|
1215
|
-
let n = e.event, r = t[a];
|
|
1216
|
-
if (r) {
|
|
1217
|
-
if (this._router.route(r, n)) {
|
|
1218
|
-
this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
|
|
1219
|
-
return;
|
|
1220
|
-
}
|
|
1221
|
-
this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
_handleAmendmentEvent(e, t) {
|
|
1225
|
-
this._logger.trace("ClientTransport._handleAmendmentEvent();", { targetMsgId: e });
|
|
1226
|
-
let n = this._tree.getNode(e);
|
|
1227
|
-
if (!n) {
|
|
1228
|
-
this._logger.debug("ClientTransport._handleAmendmentEvent(); target not found, dropping", { targetMsgId: e });
|
|
1229
|
-
return;
|
|
1230
|
-
}
|
|
1231
|
-
let r = this._codec.createAccumulator();
|
|
1232
|
-
r.initMessage(e, n.message), r.processOutputs([t]);
|
|
1233
|
-
let i = r.messages.at(-1);
|
|
1234
|
-
i && this._tree.upsert(e, i, n.headers, n.serial);
|
|
1235
|
-
}
|
|
1236
1659
|
_handleChannelStateChange(t) {
|
|
1237
|
-
if (this._state ===
|
|
1660
|
+
if (this._state === "closed") return;
|
|
1238
1661
|
let { current: n, resumed: r } = t;
|
|
1239
1662
|
if (n === "attached" && !this._hasAttachedOnce) {
|
|
1240
1663
|
this._hasAttachedOnce = !0;
|
|
1241
1664
|
return;
|
|
1242
1665
|
}
|
|
1243
1666
|
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
1244
|
-
this._logger.error("
|
|
1667
|
+
this._logger.error("ClientSession._handleChannelStateChange(); channel continuity lost", {
|
|
1245
1668
|
current: n,
|
|
1246
1669
|
resumed: r,
|
|
1247
1670
|
previous: t.previous
|
|
1248
1671
|
});
|
|
1249
|
-
let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`,
|
|
1250
|
-
for (let e of this._ownTurnIds) this._router.errorStream(e, i);
|
|
1672
|
+
let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, T.ChannelContinuityLost, 500, t.reason);
|
|
1251
1673
|
this._emitter.emit("error", i);
|
|
1252
1674
|
}
|
|
1253
|
-
|
|
1254
|
-
let
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
_updateTurnObserverHeaders(e, t, n) {
|
|
1258
|
-
let r = this._turnObservers.get(e);
|
|
1259
|
-
r ? (Object.keys(t).length > 0 && Object.assign(r.headers, t), n !== void 0 && (r.serial = n)) : this._turnObservers.set(e, {
|
|
1260
|
-
headers: { ...t },
|
|
1261
|
-
serial: n,
|
|
1262
|
-
accumulator: this._codec.createAccumulator()
|
|
1263
|
-
});
|
|
1264
|
-
}
|
|
1265
|
-
_accumulateAndEmit(e, t) {
|
|
1266
|
-
let n = this._turnObservers.get(e);
|
|
1267
|
-
if (!n) return;
|
|
1268
|
-
let r = n.headers[o];
|
|
1269
|
-
if (r) {
|
|
1270
|
-
let e = this._tree.getNode(r);
|
|
1271
|
-
e && n.accumulator.initMessage(r, e.message);
|
|
1272
|
-
}
|
|
1273
|
-
n.accumulator.processOutputs([t]);
|
|
1274
|
-
let i = n.accumulator.messages;
|
|
1275
|
-
if (i.length === 0) return;
|
|
1276
|
-
let a;
|
|
1277
|
-
try {
|
|
1278
|
-
a = structuredClone(i.at(-1));
|
|
1279
|
-
} catch {
|
|
1280
|
-
a = i.at(-1);
|
|
1281
|
-
}
|
|
1282
|
-
if (a) {
|
|
1283
|
-
let e = n.headers[o];
|
|
1284
|
-
e && this._tree.upsert(e, a, { ...n.headers }, n.serial);
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
async _publishCancel(e) {
|
|
1288
|
-
this._logger.trace("ClientTransport._publishCancel();", { filter: e });
|
|
1289
|
-
let t = {};
|
|
1290
|
-
e.turnId ? t[u] = e.turnId : e.own ? t[d] = "true" : e.clientId ? t[p] = e.clientId : e.all && (t[f] = "true"), await this._channel.publish({
|
|
1291
|
-
name: _,
|
|
1292
|
-
extras: { headers: t }
|
|
1293
|
-
});
|
|
1294
|
-
}
|
|
1295
|
-
_closeMatchingTurnStreams(e) {
|
|
1296
|
-
for (let t of this._getMatchingTurnIds(e)) this._router.closeStream(t);
|
|
1297
|
-
}
|
|
1298
|
-
_getMatchingTurnIds(e) {
|
|
1299
|
-
let t = /* @__PURE__ */ new Set(), n = this._tree.getActiveTurnIds();
|
|
1300
|
-
if (e.all) for (let e of n.values()) for (let n of e) t.add(n);
|
|
1301
|
-
else if (e.own) {
|
|
1302
|
-
let e = n.get(this._clientId ?? "");
|
|
1303
|
-
if (e) for (let n of e) t.add(n);
|
|
1304
|
-
} else if (e.clientId) {
|
|
1305
|
-
let r = n.get(e.clientId);
|
|
1306
|
-
if (r) for (let e of r) t.add(e);
|
|
1307
|
-
} else if (e.turnId) {
|
|
1308
|
-
for (let r of n.values()) if (r.has(e.turnId)) {
|
|
1309
|
-
t.add(e.turnId);
|
|
1310
|
-
break;
|
|
1311
|
-
}
|
|
1675
|
+
_cleanupFailedSend(e) {
|
|
1676
|
+
for (let t of e) {
|
|
1677
|
+
let e = this._tree.getNodeByCodecMessageId(t);
|
|
1678
|
+
e?.kind === "input" && e.serial === void 0 && this._tree.delete(e.codecMessageId);
|
|
1312
1679
|
}
|
|
1313
|
-
return t;
|
|
1314
1680
|
}
|
|
1315
1681
|
createView() {
|
|
1316
|
-
if (this._state ===
|
|
1317
|
-
this._logger.trace("
|
|
1318
|
-
let t =
|
|
1682
|
+
if (this._state === "closed") throw new e.ErrorInfo("unable to create view; session is closed", T.SessionClosed, 400);
|
|
1683
|
+
this._logger.trace("DefaultClientSession.createView();");
|
|
1684
|
+
let t = je({
|
|
1319
1685
|
tree: this._tree,
|
|
1320
1686
|
channel: this._channel,
|
|
1321
1687
|
codec: this._codec,
|
|
@@ -1325,291 +1691,116 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1325
1691
|
});
|
|
1326
1692
|
return this._views.add(t), t;
|
|
1327
1693
|
}
|
|
1328
|
-
async _internalSend(
|
|
1329
|
-
if (this._state ===
|
|
1694
|
+
async _internalSend(n, r, i) {
|
|
1695
|
+
if (this._state === "closed" || (await this._requireConnected("send"), this._state === "closed")) throw new e.ErrorInfo("unable to send; session is closed", T.SessionClosed, 400);
|
|
1330
1696
|
let a = this._channel.state;
|
|
1331
|
-
if (a !== "attached" && a !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${a}`,
|
|
1332
|
-
this._logger.trace("
|
|
1333
|
-
let o =
|
|
1334
|
-
|
|
1335
|
-
let
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
let e =
|
|
1340
|
-
e && (p = e.msgId);
|
|
1341
|
-
}
|
|
1342
|
-
let m = n?.parent === void 0 ? p : n.parent;
|
|
1343
|
-
for (let e of o) {
|
|
1344
|
-
let t = crypto.randomUUID();
|
|
1345
|
-
this._ownMsgIds.add(t), u.add(t);
|
|
1346
|
-
let r = n?.parent === void 0 ? p : n.parent, i = j({
|
|
1697
|
+
if (a !== "attached" && a !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${a}`, T.ChannelNotReady, 400);
|
|
1698
|
+
this._logger.trace("ClientSession._internalSend();");
|
|
1699
|
+
let o = r?.runId !== void 0, s = r?.runId, c;
|
|
1700
|
+
r?.parent === void 0 && !r?.forkOf && (c = i);
|
|
1701
|
+
let l = /* @__PURE__ */ new Set(), u = [];
|
|
1702
|
+
for (let e of n) {
|
|
1703
|
+
let t = crypto.randomUUID(), n = e.codecMessageId ?? crypto.randomUUID();
|
|
1704
|
+
l.add(n);
|
|
1705
|
+
let i = e.kind !== "user-message" && (e.kind === "regenerate" || e.codecMessageId !== void 0), a = e.parent ?? (r?.parent === void 0 ? c : r.parent), o = r?.forkOf, d = e.kind === "regenerate" ? e.target : void 0, f = V({
|
|
1347
1706
|
role: "user",
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
parent:
|
|
1352
|
-
forkOf:
|
|
1707
|
+
runId: s,
|
|
1708
|
+
codecMessageId: n,
|
|
1709
|
+
runClientId: this._clientId,
|
|
1710
|
+
...a !== void 0 && { parent: a },
|
|
1711
|
+
...o !== void 0 && { forkOf: o },
|
|
1712
|
+
...d !== void 0 && { regenerates: d },
|
|
1713
|
+
inputEventId: t
|
|
1353
1714
|
});
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1715
|
+
i || this._tree.applyMessage({
|
|
1716
|
+
inputs: [e],
|
|
1717
|
+
outputs: []
|
|
1718
|
+
}, f), u.push({
|
|
1719
|
+
input: e,
|
|
1720
|
+
codecMessageId: n,
|
|
1721
|
+
inputEventId: t,
|
|
1722
|
+
headers: f,
|
|
1723
|
+
isWireOnly: i
|
|
1724
|
+
}), !i && r?.parent === void 0 && !r?.forkOf && e.parent === void 0 && (c = n);
|
|
1363
1725
|
}
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
"Content-Type": "application/json",
|
|
1383
|
-
...v
|
|
1384
|
-
},
|
|
1385
|
-
body: JSON.stringify(_),
|
|
1386
|
-
...this._credentials ? { credentials: this._credentials } : {}
|
|
1387
|
-
}).then((t) => {
|
|
1388
|
-
if (!t.ok) {
|
|
1389
|
-
let n = new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(t.status)} ${t.statusText}`, C.TransportSendFailed, t.status);
|
|
1390
|
-
this._emitter.emit("error", n), this._router.errorStream(s, n);
|
|
1726
|
+
let d = u.at(-1);
|
|
1727
|
+
if (d === void 0) throw new e.ErrorInfo("unable to send; inputs array is empty (include at least one input)", T.InvalidArgument, 400);
|
|
1728
|
+
let f = d.inputEventId, p = d.codecMessageId, m = new Promise((e, t) => {
|
|
1729
|
+
this._pendingRunStarts.set(p, {
|
|
1730
|
+
resolve: e,
|
|
1731
|
+
reject: t
|
|
1732
|
+
});
|
|
1733
|
+
});
|
|
1734
|
+
return m.catch(() => {}), await (async () => {
|
|
1735
|
+
try {
|
|
1736
|
+
for (let e of u) await this._encoder.publishInput(e.input, {
|
|
1737
|
+
extras: { headers: e.headers },
|
|
1738
|
+
messageId: e.codecMessageId,
|
|
1739
|
+
...this._clientId !== void 0 && { clientId: this._clientId }
|
|
1740
|
+
});
|
|
1741
|
+
} catch (t) {
|
|
1742
|
+
let n = t instanceof e.ErrorInfo ? t : void 0, r = n?.statusCode === 401 || n?.statusCode === 403, i = new e.ErrorInfo(r ? "unable to publish events; missing publish capability on the channel" : `unable to publish events; ${t instanceof Error ? t.message : String(t)}`, r ? T.InsufficientCapability : T.SessionSendFailed, r ? 401 : 500, n);
|
|
1743
|
+
throw this._emitter.emit("error", i), this._pendingRunStarts.delete(p), o || this._cleanupFailedSend([...l]), i;
|
|
1391
1744
|
}
|
|
1392
|
-
})
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1745
|
+
})(), {
|
|
1746
|
+
inputCodecMessageId: p,
|
|
1747
|
+
runId: m,
|
|
1748
|
+
inputEventId: f,
|
|
1749
|
+
cancel: async () => {
|
|
1750
|
+
await this._publishCancel({
|
|
1751
|
+
inputCodecMessageId: p,
|
|
1752
|
+
...s !== void 0 && { runId: s }
|
|
1753
|
+
});
|
|
1754
|
+
},
|
|
1755
|
+
optimisticCodecMessageIds: [...l],
|
|
1756
|
+
toInvocation: () => t.fromJSON({
|
|
1757
|
+
inputEventId: f,
|
|
1758
|
+
sessionName: this._channel.name
|
|
1759
|
+
})
|
|
1400
1760
|
};
|
|
1401
1761
|
}
|
|
1402
1762
|
async cancel(e) {
|
|
1403
|
-
|
|
1404
|
-
let t = e ?? { own: !0 };
|
|
1405
|
-
this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
|
|
1406
|
-
}
|
|
1407
|
-
stageEvents(e, t) {
|
|
1408
|
-
if (this._logger.trace("ClientTransport.stageEvents();", {
|
|
1409
|
-
msgId: e,
|
|
1410
|
-
eventCount: t.length
|
|
1411
|
-
}), this._state === Q.CLOSED) {
|
|
1412
|
-
this._logger.warn("ClientTransport.stageEvents(); transport is closed", { msgId: e });
|
|
1413
|
-
return;
|
|
1414
|
-
}
|
|
1415
|
-
if (!this._tree.getNode(e)) {
|
|
1416
|
-
this._logger.warn("ClientTransport.stageEvents(); msgId not found in tree", { msgId: e });
|
|
1417
|
-
return;
|
|
1418
|
-
}
|
|
1419
|
-
if (t.length === 0) return;
|
|
1420
|
-
let n = {
|
|
1421
|
-
kind: "event",
|
|
1422
|
-
msgId: e,
|
|
1423
|
-
events: t
|
|
1424
|
-
};
|
|
1425
|
-
this._applyEventsToTree([n]), this._pendingLocalEvents.push(n);
|
|
1763
|
+
return this._publishCancel({ runId: e });
|
|
1426
1764
|
}
|
|
1427
|
-
|
|
1428
|
-
if (this.
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
this._tree.upsert(e, t, n.headers, n.serial);
|
|
1438
|
-
}
|
|
1439
|
-
_applyEventsToTree(e) {
|
|
1440
|
-
for (let t of e) {
|
|
1441
|
-
let e = this._tree.getNode(t.msgId);
|
|
1442
|
-
if (!e) continue;
|
|
1443
|
-
let n = t.events.map((e) => ({
|
|
1444
|
-
kind: "event",
|
|
1445
|
-
event: e,
|
|
1446
|
-
messageId: t.msgId
|
|
1447
|
-
})), r = this._codec.createAccumulator();
|
|
1448
|
-
r.initMessage(t.msgId, e.message), r.processOutputs(n);
|
|
1449
|
-
let i = r.messages.at(-1);
|
|
1450
|
-
i && this._tree.upsert(t.msgId, i, e.headers, e.serial);
|
|
1451
|
-
}
|
|
1452
|
-
}
|
|
1453
|
-
async waitForTurn(e) {
|
|
1454
|
-
if (this._state === Q.CLOSED) return;
|
|
1455
|
-
let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
|
|
1456
|
-
if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
|
|
1457
|
-
let t = !1, r = () => {
|
|
1458
|
-
if (t) return;
|
|
1459
|
-
t = !0, i();
|
|
1460
|
-
let n = this._closeResolvers.indexOf(r);
|
|
1461
|
-
n !== -1 && this._closeResolvers.splice(n, 1), e();
|
|
1462
|
-
}, i = this._tree.on("turn", (e) => {
|
|
1463
|
-
e.type === "x-ably-turn-end" && (n.delete(e.turnId), n.size === 0 && r());
|
|
1464
|
-
});
|
|
1465
|
-
this._closeResolvers.push(r);
|
|
1765
|
+
async _publishCancel(e) {
|
|
1766
|
+
if (this._state === "closed" || (await this._requireConnected("cancel"), this._state === "closed")) return;
|
|
1767
|
+
this._logger.debug("ClientSession._publishCancel();", {
|
|
1768
|
+
runId: e.runId,
|
|
1769
|
+
inputCodecMessageId: e.inputCodecMessageId
|
|
1770
|
+
});
|
|
1771
|
+
let t = { [c]: crypto.randomUUID() };
|
|
1772
|
+
e.runId !== void 0 && (t[o] = e.runId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), await this._channel.publish({
|
|
1773
|
+
name: b,
|
|
1774
|
+
extras: { ai: { transport: t } }
|
|
1466
1775
|
});
|
|
1467
1776
|
}
|
|
1468
1777
|
on(e, t) {
|
|
1469
|
-
if (this._state ===
|
|
1778
|
+
if (this._state === "closed") return Me;
|
|
1470
1779
|
let n = t;
|
|
1471
1780
|
return this._emitter.on(e, n), () => {
|
|
1472
1781
|
this._emitter.off(e, n);
|
|
1473
1782
|
};
|
|
1474
1783
|
}
|
|
1475
|
-
async close(
|
|
1476
|
-
if (this._state !==
|
|
1477
|
-
|
|
1478
|
-
try {
|
|
1479
|
-
await this._publishCancel(e.cancel);
|
|
1480
|
-
} catch {}
|
|
1481
|
-
this._closeMatchingTurnStreams(e.cancel);
|
|
1482
|
-
}
|
|
1483
|
-
this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange);
|
|
1484
|
-
for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
1485
|
-
this._turnObservers.clear(), this._emitter.off();
|
|
1784
|
+
async close() {
|
|
1785
|
+
if (this._state !== "closed") {
|
|
1786
|
+
this._state = "closed", this._logger.info("ClientSession.close();"), this._connectPromise && this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange), this._emitter.off();
|
|
1486
1787
|
for (let e of this._views) e.close();
|
|
1487
|
-
this._views.clear()
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
decode(e) {
|
|
1500
|
-
let t = e.action;
|
|
1501
|
-
this._logger?.trace("DefaultDecoderCore.decode();", {
|
|
1502
|
-
action: t,
|
|
1503
|
-
serial: e.serial,
|
|
1504
|
-
name: e.name
|
|
1505
|
-
});
|
|
1506
|
-
let n;
|
|
1507
|
-
switch (t) {
|
|
1508
|
-
case "message.create": {
|
|
1509
|
-
let t = this._toPayload(e);
|
|
1510
|
-
n = t.headers?.["x-ably-stream"] === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
|
|
1511
|
-
break;
|
|
1788
|
+
if (this._views.clear(), this._pendingRunStarts.size > 0) {
|
|
1789
|
+
let t = new e.ErrorInfo("unable to await run-start; session closed", T.SessionClosed, 400);
|
|
1790
|
+
for (let e of this._pendingRunStarts.values()) e.reject(t);
|
|
1791
|
+
this._pendingRunStarts.clear();
|
|
1792
|
+
}
|
|
1793
|
+
try {
|
|
1794
|
+
await this._encoder.close();
|
|
1795
|
+
} catch {}
|
|
1796
|
+
if (this._connectPromise) try {
|
|
1797
|
+
await this._channel.detach();
|
|
1798
|
+
} catch (e) {
|
|
1799
|
+
this._logger.debug("ClientSession.close(); channel detach failed", { error: e });
|
|
1512
1800
|
}
|
|
1513
|
-
case "message.append":
|
|
1514
|
-
n = this._decodeAppend(e);
|
|
1515
|
-
break;
|
|
1516
|
-
case "message.update":
|
|
1517
|
-
n = this._decodeUpdate(e);
|
|
1518
|
-
break;
|
|
1519
|
-
case "message.delete":
|
|
1520
|
-
n = this._decodeDelete(e);
|
|
1521
|
-
break;
|
|
1522
|
-
default: return [];
|
|
1523
|
-
}
|
|
1524
|
-
let r = w(e)[o];
|
|
1525
|
-
if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
|
|
1526
|
-
return n;
|
|
1527
|
-
}
|
|
1528
|
-
_toPayload(e) {
|
|
1529
|
-
return {
|
|
1530
|
-
name: e.name ?? "",
|
|
1531
|
-
data: e.data,
|
|
1532
|
-
headers: w(e)
|
|
1533
|
-
};
|
|
1534
|
-
}
|
|
1535
|
-
_stringData(e) {
|
|
1536
|
-
return typeof e.data == "string" ? e.data : "";
|
|
1537
|
-
}
|
|
1538
|
-
_invokeOnStreamUpdate(e) {
|
|
1539
|
-
if (this._onStreamUpdate) try {
|
|
1540
|
-
this._onStreamUpdate(e);
|
|
1541
|
-
} catch (e) {
|
|
1542
|
-
this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
|
|
1543
|
-
}
|
|
1544
|
-
}
|
|
1545
|
-
_invokeOnStreamDelete(e, t) {
|
|
1546
|
-
if (this._onStreamDelete) try {
|
|
1547
|
-
this._onStreamDelete(e, t);
|
|
1548
|
-
} catch (e) {
|
|
1549
|
-
this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
|
|
1550
|
-
}
|
|
1551
|
-
}
|
|
1552
|
-
_decodeStreamedCreate(e, t) {
|
|
1553
|
-
if (!t) return [];
|
|
1554
|
-
let n = e.headers?.["x-ably-stream-id"] ?? "", r = e.headers ?? {}, i = {
|
|
1555
|
-
name: e.name,
|
|
1556
|
-
streamId: n,
|
|
1557
|
-
accumulated: "",
|
|
1558
|
-
headers: { ...r },
|
|
1559
|
-
closed: !1
|
|
1560
|
-
};
|
|
1561
|
-
return this._serialState.set(t, i), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
|
|
1562
|
-
name: e.name,
|
|
1563
|
-
streamId: n,
|
|
1564
|
-
serial: t
|
|
1565
|
-
}), this._hooks.buildStartEvents(i);
|
|
1566
|
-
}
|
|
1567
|
-
_decodeAppend(e) {
|
|
1568
|
-
let t = e.serial;
|
|
1569
|
-
if (!t) return [];
|
|
1570
|
-
let r = this._serialState.get(t);
|
|
1571
|
-
if (!r) return this._decodeUpdate(e);
|
|
1572
|
-
let i = w(e), a = typeof e.data == "string" ? e.data : "", o = i[n], s = [];
|
|
1573
|
-
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;
|
|
1574
|
-
}
|
|
1575
|
-
_decodeUpdate(e) {
|
|
1576
|
-
let r = e.serial;
|
|
1577
|
-
if (!r) return [];
|
|
1578
|
-
let i = this._toPayload(e), a = i.headers ?? {}, o = a[t] === "true", s = a[n], c = this._serialState.get(r);
|
|
1579
|
-
if (!c) return this._decodeFirstContact(i, o, s, r);
|
|
1580
|
-
let l = this._stringData(e);
|
|
1581
|
-
if (l.startsWith(c.accumulated)) {
|
|
1582
|
-
let e = l.slice(c.accumulated.length), t = [];
|
|
1583
|
-
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;
|
|
1584
1801
|
}
|
|
1585
|
-
return c.accumulated = l, c.headers = { ...a }, this._invokeOnStreamUpdate(c), [];
|
|
1586
|
-
}
|
|
1587
|
-
_decodeFirstContact(e, t, n, r) {
|
|
1588
|
-
if (!t) return this._hooks.decodeDiscrete(e);
|
|
1589
|
-
let i = e.headers?.["x-ably-stream-id"] ?? "", a = e.headers ?? {}, o = typeof e.data == "string" ? e.data : "";
|
|
1590
|
-
this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
|
|
1591
|
-
name: e.name,
|
|
1592
|
-
streamId: i,
|
|
1593
|
-
serial: r
|
|
1594
|
-
});
|
|
1595
|
-
let s = {
|
|
1596
|
-
name: e.name,
|
|
1597
|
-
streamId: i,
|
|
1598
|
-
accumulated: o,
|
|
1599
|
-
headers: { ...a },
|
|
1600
|
-
closed: n === "finished" || n === "aborted"
|
|
1601
|
-
};
|
|
1602
|
-
this._serialState.set(r, s);
|
|
1603
|
-
let c = this._hooks.buildStartEvents(s);
|
|
1604
|
-
return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "finished" && c.push(...this._hooks.buildEndEvents(s, a)), c;
|
|
1605
|
-
}
|
|
1606
|
-
_decodeDelete(e) {
|
|
1607
|
-
let t = e.serial;
|
|
1608
|
-
if (!t) return [];
|
|
1609
|
-
let n = this._serialState.get(t);
|
|
1610
|
-
return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
|
|
1611
1802
|
}
|
|
1612
|
-
},
|
|
1803
|
+
}, Pe = (e) => new Ne(e), Fe = class {
|
|
1613
1804
|
constructor(e, t = {}) {
|
|
1614
1805
|
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" });
|
|
1615
1806
|
}
|
|
@@ -1620,48 +1811,48 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1620
1811
|
}
|
|
1621
1812
|
async publishDiscreteBatch(e, t) {
|
|
1622
1813
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
|
|
1623
|
-
let n = e.map((e) => this._buildDiscreteMessage(e, t));
|
|
1624
|
-
for (let e of n) e.extras.headers[i] = "true";
|
|
1814
|
+
let n = e.map((e) => this._buildDiscreteMessage(e, t, !0));
|
|
1625
1815
|
return this._writer.publish(n);
|
|
1626
1816
|
}
|
|
1627
|
-
async startStream(
|
|
1817
|
+
async startStream(t, a, o) {
|
|
1628
1818
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.startStream();", {
|
|
1629
1819
|
name: a.name,
|
|
1630
|
-
streamId:
|
|
1820
|
+
streamId: t
|
|
1631
1821
|
});
|
|
1632
|
-
let s = this.
|
|
1633
|
-
s[
|
|
1634
|
-
let c = this._resolveClientId(o),
|
|
1822
|
+
let s = this._buildTransport(a.transportHeaders, o);
|
|
1823
|
+
s[n] = "true", s[r] = "streaming", s[i] = t;
|
|
1824
|
+
let c = a.codecHeaders ?? {}, l = this._resolveClientId(o), u = {
|
|
1635
1825
|
name: a.name,
|
|
1636
1826
|
data: a.data,
|
|
1637
|
-
extras: {
|
|
1638
|
-
...
|
|
1827
|
+
extras: { ai: this._aiExtras(s, c) },
|
|
1828
|
+
...l ? { clientId: l } : {}
|
|
1639
1829
|
};
|
|
1640
|
-
this._invokeOnMessage(
|
|
1641
|
-
let
|
|
1642
|
-
if (!
|
|
1643
|
-
this._trackers.set(
|
|
1644
|
-
serial:
|
|
1830
|
+
this._invokeOnMessage(u);
|
|
1831
|
+
let d = (await this._writer.publish(u)).serials[0];
|
|
1832
|
+
if (!d) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${t})`, T.BadRequest, 400);
|
|
1833
|
+
this._trackers.set(t, {
|
|
1834
|
+
serial: d,
|
|
1645
1835
|
name: a.name,
|
|
1646
|
-
streamId:
|
|
1836
|
+
streamId: t,
|
|
1647
1837
|
accumulated: a.data,
|
|
1648
|
-
|
|
1649
|
-
|
|
1838
|
+
persistentTransport: s,
|
|
1839
|
+
persistentCodec: c,
|
|
1840
|
+
cancelled: !1
|
|
1650
1841
|
}), this._logger?.debug("DefaultEncoderCore.startStream(); stream started", {
|
|
1651
1842
|
name: a.name,
|
|
1652
|
-
streamId:
|
|
1653
|
-
serial:
|
|
1843
|
+
streamId: t,
|
|
1844
|
+
serial: d
|
|
1654
1845
|
});
|
|
1655
1846
|
}
|
|
1656
1847
|
appendStream(t, n) {
|
|
1657
1848
|
this._assertNotClosed();
|
|
1658
1849
|
let r = this._trackers.get(t);
|
|
1659
|
-
if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`,
|
|
1850
|
+
if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, T.InvalidArgument, 400);
|
|
1660
1851
|
r.accumulated += n;
|
|
1661
1852
|
let i = {
|
|
1662
1853
|
serial: r.serial,
|
|
1663
1854
|
data: n,
|
|
1664
|
-
extras: {
|
|
1855
|
+
extras: { ai: this._aiExtras({ ...r.persistentTransport }, { ...r.persistentCodec }) }
|
|
1665
1856
|
};
|
|
1666
1857
|
this._invokeOnMessage(i);
|
|
1667
1858
|
let a = this._writer.appendMessage(i);
|
|
@@ -1670,59 +1861,59 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1670
1861
|
streamId: t
|
|
1671
1862
|
});
|
|
1672
1863
|
}
|
|
1673
|
-
async closeStream(t,
|
|
1864
|
+
async closeStream(t, n) {
|
|
1674
1865
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.closeStream();", { streamId: t });
|
|
1675
1866
|
let i = this._trackers.get(t);
|
|
1676
|
-
if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`,
|
|
1677
|
-
i.accumulated +=
|
|
1678
|
-
let a = this.
|
|
1679
|
-
a[
|
|
1680
|
-
let
|
|
1867
|
+
if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, T.InvalidArgument, 400);
|
|
1868
|
+
i.accumulated += n.data;
|
|
1869
|
+
let { transport: a, codec: o } = this._buildClosing(i, n);
|
|
1870
|
+
a[r] = "complete";
|
|
1871
|
+
let s = {
|
|
1681
1872
|
serial: i.serial,
|
|
1682
|
-
data:
|
|
1683
|
-
extras: {
|
|
1873
|
+
data: n.data,
|
|
1874
|
+
extras: { ai: this._aiExtras(a, o) }
|
|
1684
1875
|
};
|
|
1685
|
-
this._invokeOnMessage(
|
|
1686
|
-
let
|
|
1876
|
+
this._invokeOnMessage(s);
|
|
1877
|
+
let c = this._writer.appendMessage(s);
|
|
1687
1878
|
this._pending.push({
|
|
1688
|
-
promise:
|
|
1879
|
+
promise: c,
|
|
1689
1880
|
streamId: t
|
|
1690
1881
|
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.closeStream(); stream closed", { streamId: t });
|
|
1691
1882
|
}
|
|
1692
|
-
async
|
|
1693
|
-
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.
|
|
1883
|
+
async cancelStream(t, n) {
|
|
1884
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.cancelStream();", { streamId: t });
|
|
1694
1885
|
let i = this._trackers.get(t);
|
|
1695
|
-
if (!i) throw new e.ErrorInfo(`unable to
|
|
1696
|
-
i.
|
|
1697
|
-
let a = this.
|
|
1698
|
-
a[
|
|
1699
|
-
let
|
|
1886
|
+
if (!i) throw new e.ErrorInfo(`unable to cancel stream; no active stream for streamId '${t}'`, T.InvalidArgument, 400);
|
|
1887
|
+
i.cancelled = !0;
|
|
1888
|
+
let { transport: a, codec: o } = this._buildClosing(i, void 0, n);
|
|
1889
|
+
a[r] = "cancelled";
|
|
1890
|
+
let s = {
|
|
1700
1891
|
serial: i.serial,
|
|
1701
1892
|
data: "",
|
|
1702
|
-
extras: {
|
|
1893
|
+
extras: { ai: this._aiExtras(a, o) }
|
|
1703
1894
|
};
|
|
1704
|
-
this._invokeOnMessage(
|
|
1705
|
-
let
|
|
1895
|
+
this._invokeOnMessage(s);
|
|
1896
|
+
let c = this._writer.appendMessage(s);
|
|
1706
1897
|
this._pending.push({
|
|
1707
|
-
promise:
|
|
1898
|
+
promise: c,
|
|
1708
1899
|
streamId: t
|
|
1709
|
-
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.
|
|
1900
|
+
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.cancelStream(); stream cancelled", { streamId: t });
|
|
1710
1901
|
}
|
|
1711
|
-
async
|
|
1712
|
-
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.
|
|
1902
|
+
async cancelAllStreams(e) {
|
|
1903
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.cancelAllStreams();", { streamCount: this._trackers.size });
|
|
1713
1904
|
for (let t of this._trackers.values()) {
|
|
1714
|
-
t.
|
|
1715
|
-
let
|
|
1716
|
-
r
|
|
1717
|
-
let
|
|
1905
|
+
t.cancelled = !0;
|
|
1906
|
+
let { transport: n, codec: i } = this._buildClosing(t, void 0, e);
|
|
1907
|
+
n[r] = "cancelled";
|
|
1908
|
+
let a = {
|
|
1718
1909
|
serial: t.serial,
|
|
1719
1910
|
data: "",
|
|
1720
|
-
extras: {
|
|
1911
|
+
extras: { ai: this._aiExtras(n, i) }
|
|
1721
1912
|
};
|
|
1722
|
-
this._invokeOnMessage(
|
|
1723
|
-
let
|
|
1913
|
+
this._invokeOnMessage(a);
|
|
1914
|
+
let o = this._writer.appendMessage(a);
|
|
1724
1915
|
this._pending.push({
|
|
1725
|
-
promise:
|
|
1916
|
+
promise: o,
|
|
1726
1917
|
streamId: t.streamId
|
|
1727
1918
|
});
|
|
1728
1919
|
}
|
|
@@ -1741,10 +1932,10 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1741
1932
|
}
|
|
1742
1933
|
}
|
|
1743
1934
|
async _doFlush(t) {
|
|
1744
|
-
let
|
|
1745
|
-
for (let [e,
|
|
1746
|
-
let
|
|
1747
|
-
|
|
1935
|
+
let n = await Promise.allSettled(t.map(async (e) => e.promise)), i = /* @__PURE__ */ new Set();
|
|
1936
|
+
for (let [e, r] of n.entries()) {
|
|
1937
|
+
let n = t[e];
|
|
1938
|
+
n && r.status === "rejected" && i.add(n.streamId);
|
|
1748
1939
|
}
|
|
1749
1940
|
if (i.size === 0) {
|
|
1750
1941
|
this._logger?.debug("DefaultEncoderCore._flushPending(); all appends succeeded");
|
|
@@ -1755,13 +1946,13 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1755
1946
|
for (let e of i) {
|
|
1756
1947
|
let t = this._trackers.get(e);
|
|
1757
1948
|
if (!t) continue;
|
|
1758
|
-
let
|
|
1949
|
+
let n = t.cancelled ? "cancelled" : "complete", i = {
|
|
1759
1950
|
serial: t.serial,
|
|
1760
1951
|
data: t.accumulated,
|
|
1761
|
-
extras: {
|
|
1762
|
-
...t.
|
|
1763
|
-
[
|
|
1764
|
-
} }
|
|
1952
|
+
extras: { ai: this._aiExtras({
|
|
1953
|
+
...t.persistentTransport,
|
|
1954
|
+
[r]: n
|
|
1955
|
+
}, { ...t.persistentCodec }) }
|
|
1765
1956
|
};
|
|
1766
1957
|
try {
|
|
1767
1958
|
await this._writer.updateMessage(i);
|
|
@@ -1774,7 +1965,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1774
1965
|
}
|
|
1775
1966
|
if (a.length > 0) {
|
|
1776
1967
|
let t = a.map((e) => e.streamId).join(", ");
|
|
1777
|
-
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`,
|
|
1968
|
+
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, T.EncoderRecoveryFailed, 500);
|
|
1778
1969
|
}
|
|
1779
1970
|
}
|
|
1780
1971
|
async close() {
|
|
@@ -1796,37 +1987,161 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1796
1987
|
}
|
|
1797
1988
|
}
|
|
1798
1989
|
_assertNotClosed() {
|
|
1799
|
-
if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed",
|
|
1990
|
+
if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", T.InvalidArgument, 400);
|
|
1800
1991
|
}
|
|
1801
1992
|
_resolveClientId(e) {
|
|
1802
1993
|
return e?.clientId ?? this._defaultClientId;
|
|
1803
1994
|
}
|
|
1804
|
-
|
|
1995
|
+
_buildTransport(e, t) {
|
|
1805
1996
|
let n = {
|
|
1806
|
-
...
|
|
1997
|
+
...A(this._defaultExtras?.headers, t?.extras?.headers),
|
|
1807
1998
|
...e
|
|
1808
1999
|
};
|
|
1809
|
-
return t?.messageId !== void 0 && (n[
|
|
1810
|
-
}
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
2000
|
+
return t?.messageId !== void 0 && (n[l] = t.messageId), n;
|
|
2001
|
+
}
|
|
2002
|
+
_aiExtras(e, t) {
|
|
2003
|
+
return Object.keys(t).length > 0 ? {
|
|
2004
|
+
transport: e,
|
|
2005
|
+
codec: t
|
|
2006
|
+
} : { transport: e };
|
|
2007
|
+
}
|
|
2008
|
+
_buildDiscreteMessage(e, t, r = !1) {
|
|
2009
|
+
let i = this._buildTransport(e.transportHeaders, t);
|
|
2010
|
+
i[n] = "false", r && (i[a] = "true");
|
|
2011
|
+
let o = this._resolveClientId(t), s = {
|
|
1815
2012
|
name: e.name,
|
|
1816
2013
|
data: e.data,
|
|
1817
2014
|
extras: {
|
|
1818
|
-
|
|
2015
|
+
ai: this._aiExtras(i, e.codecHeaders ?? {}),
|
|
1819
2016
|
...e.ephemeral ? { ephemeral: !0 } : {}
|
|
1820
2017
|
},
|
|
1821
|
-
...
|
|
2018
|
+
...o ? { clientId: o } : {}
|
|
2019
|
+
};
|
|
2020
|
+
return this._invokeOnMessage(s), s;
|
|
2021
|
+
}
|
|
2022
|
+
_buildClosing(e, t, n) {
|
|
2023
|
+
let r = A(this._defaultExtras?.headers, n?.extras?.headers);
|
|
2024
|
+
return {
|
|
2025
|
+
transport: {
|
|
2026
|
+
...e.persistentTransport,
|
|
2027
|
+
...r,
|
|
2028
|
+
...t?.transportHeaders
|
|
2029
|
+
},
|
|
2030
|
+
codec: {
|
|
2031
|
+
...e.persistentCodec,
|
|
2032
|
+
...t?.codecHeaders
|
|
2033
|
+
}
|
|
2034
|
+
};
|
|
2035
|
+
}
|
|
2036
|
+
}, Ie = (e, t = {}) => new Fe(e, t), Le = class {
|
|
2037
|
+
constructor(e, t = {}) {
|
|
2038
|
+
this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
|
|
2039
|
+
}
|
|
2040
|
+
decode(e) {
|
|
2041
|
+
let t = e.action;
|
|
2042
|
+
switch (this._logger?.trace("DefaultDecoderCore.decode();", {
|
|
2043
|
+
action: t,
|
|
2044
|
+
serial: e.serial,
|
|
2045
|
+
name: e.name
|
|
2046
|
+
}), t) {
|
|
2047
|
+
case "message.create": {
|
|
2048
|
+
let t = this._toPayload(e);
|
|
2049
|
+
return t.transportHeaders?.stream === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
|
|
2050
|
+
}
|
|
2051
|
+
case "message.append": return this._decodeAppend(e);
|
|
2052
|
+
case "message.update": return this._decodeUpdate(e);
|
|
2053
|
+
case "message.delete": return this._decodeDelete(e);
|
|
2054
|
+
default: return [];
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
_toPayload(e) {
|
|
2058
|
+
return {
|
|
2059
|
+
name: e.name ?? "",
|
|
2060
|
+
data: e.data,
|
|
2061
|
+
transportHeaders: O(e),
|
|
2062
|
+
codecHeaders: k(e)
|
|
2063
|
+
};
|
|
2064
|
+
}
|
|
2065
|
+
_stringData(e) {
|
|
2066
|
+
return typeof e.data == "string" ? e.data : "";
|
|
2067
|
+
}
|
|
2068
|
+
_invokeOnStreamUpdate(e) {
|
|
2069
|
+
if (this._onStreamUpdate) try {
|
|
2070
|
+
this._onStreamUpdate(e);
|
|
2071
|
+
} catch (e) {
|
|
2072
|
+
this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
_invokeOnStreamDelete(e, t) {
|
|
2076
|
+
if (this._onStreamDelete) try {
|
|
2077
|
+
this._onStreamDelete(e, t);
|
|
2078
|
+
} catch (e) {
|
|
2079
|
+
this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
_decodeStreamedCreate(e, t) {
|
|
2083
|
+
if (!t) return [];
|
|
2084
|
+
let n = e.transportHeaders?.["stream-id"] ?? "", r = {
|
|
2085
|
+
name: e.name,
|
|
2086
|
+
streamId: n,
|
|
2087
|
+
accumulated: "",
|
|
2088
|
+
codecHeaders: { ...e.codecHeaders },
|
|
2089
|
+
transportHeaders: { ...e.transportHeaders },
|
|
2090
|
+
closed: !1
|
|
2091
|
+
};
|
|
2092
|
+
return this._serialState.set(t, r), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
|
|
2093
|
+
name: e.name,
|
|
2094
|
+
streamId: n,
|
|
2095
|
+
serial: t
|
|
2096
|
+
}), this._hooks.buildStartEvents(r);
|
|
2097
|
+
}
|
|
2098
|
+
_decodeAppend(e) {
|
|
2099
|
+
let t = e.serial;
|
|
2100
|
+
if (!t) return [];
|
|
2101
|
+
let n = this._serialState.get(t);
|
|
2102
|
+
if (!n) return this._decodeUpdate(e);
|
|
2103
|
+
let i = O(e), a = k(e), o = typeof e.data == "string" ? e.data : "", s = i[r], c = [];
|
|
2104
|
+
return o.length > 0 && (n.accumulated += o, c.push(...this._hooks.buildDeltaEvents(n, o))), s === "complete" && !n.closed ? (n.closed = !0, c.push(...this._hooks.buildEndEvents(n, a)), this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream complete", { streamId: n.streamId })) : s === "cancelled" && !n.closed && (n.closed = !0, this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream cancelled", { streamId: n.streamId })), c;
|
|
2105
|
+
}
|
|
2106
|
+
_decodeUpdate(e) {
|
|
2107
|
+
let t = e.serial;
|
|
2108
|
+
if (!t) return [];
|
|
2109
|
+
let i = this._toPayload(e), a = i.transportHeaders ?? {}, o = i.codecHeaders ?? {}, s = a[n] === "true", c = a[r], l = this._serialState.get(t);
|
|
2110
|
+
if (!l) return this._decodeFirstContact(i, s, c, t);
|
|
2111
|
+
let u = this._stringData(e);
|
|
2112
|
+
if (u.startsWith(l.accumulated)) {
|
|
2113
|
+
let e = u.slice(l.accumulated.length), t = [];
|
|
2114
|
+
return e.length > 0 && (l.accumulated = u, t.push(...this._hooks.buildDeltaEvents(l, e))), c === "complete" && !l.closed ? (l.closed = !0, t.push(...this._hooks.buildEndEvents(l, o))) : c === "cancelled" && !l.closed && (l.closed = !0), t;
|
|
2115
|
+
}
|
|
2116
|
+
return l.accumulated = u, l.codecHeaders = { ...o }, l.transportHeaders = { ...a }, this._invokeOnStreamUpdate(l), [];
|
|
2117
|
+
}
|
|
2118
|
+
_decodeFirstContact(e, t, n, r) {
|
|
2119
|
+
if (!t) return this._hooks.decodeDiscrete(e);
|
|
2120
|
+
let i = e.transportHeaders?.["stream-id"] ?? "", a = e.codecHeaders ?? {}, o = typeof e.data == "string" ? e.data : "";
|
|
2121
|
+
this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
|
|
2122
|
+
name: e.name,
|
|
2123
|
+
streamId: i,
|
|
2124
|
+
serial: r
|
|
2125
|
+
});
|
|
2126
|
+
let s = {
|
|
2127
|
+
name: e.name,
|
|
2128
|
+
streamId: i,
|
|
2129
|
+
accumulated: o,
|
|
2130
|
+
codecHeaders: { ...a },
|
|
2131
|
+
transportHeaders: { ...e.transportHeaders },
|
|
2132
|
+
closed: n === "complete" || n === "cancelled"
|
|
1822
2133
|
};
|
|
1823
|
-
|
|
2134
|
+
this._serialState.set(r, s);
|
|
2135
|
+
let c = this._hooks.buildStartEvents(s);
|
|
2136
|
+
return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "complete" && c.push(...this._hooks.buildEndEvents(s, a)), c;
|
|
1824
2137
|
}
|
|
1825
|
-
|
|
1826
|
-
let
|
|
1827
|
-
|
|
2138
|
+
_decodeDelete(e) {
|
|
2139
|
+
let t = e.serial;
|
|
2140
|
+
if (!t) return [];
|
|
2141
|
+
let n = this._serialState.get(t);
|
|
2142
|
+
return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
|
|
1828
2143
|
}
|
|
1829
|
-
},
|
|
2144
|
+
}, Re = (e, t = {}) => new Le(e, t), ze = class {
|
|
1830
2145
|
constructor(e) {
|
|
1831
2146
|
this._emitted = /* @__PURE__ */ new Map(), this._phases = e;
|
|
1832
2147
|
}
|
|
@@ -1848,8 +2163,8 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1848
2163
|
let t = this._emitted.get(e);
|
|
1849
2164
|
return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
|
|
1850
2165
|
}
|
|
1851
|
-
},
|
|
2166
|
+
}, Be = (e) => new ze(e);
|
|
1852
2167
|
//#endregion
|
|
1853
|
-
export {
|
|
2168
|
+
export { b as EVENT_CANCEL, w as EVENT_RUN_END, x as EVENT_RUN_START, T as ErrorCode, Y as EventEmitter, l as HEADER_CODEC_MESSAGE_ID, v as HEADER_ERROR_CODE, y as HEADER_ERROR_MESSAGE, m as HEADER_FORK_OF, d as HEADER_INPUT_CLIENT_ID, h as HEADER_MSG_REGENERATE, p as HEADER_PARENT, f as HEADER_ROLE, u as HEADER_RUN_CLIENT_ID, o as HEADER_RUN_ID, g as HEADER_RUN_REASON, r as HEADER_STATUS, n as HEADER_STREAM, i as HEADER_STREAM_ID, t as Invocation, ge as LogLevel, V as buildTransportHeaders, _e as consoleLogger, pe as createAgentSession, Pe as createClientSession, Re as createDecoderCore, Ie as createEncoderCore, Be as createLifecycleTracker, E as errorInfoIs, k as getCodecHeaders, O as getTransportHeaders, F as headerReader, I as headerWriter, ve as makeLogger, A as mergeHeaders, P as stripUndefined };
|
|
1854
2169
|
|
|
1855
2170
|
//# sourceMappingURL=ably-ai-transport.js.map
|