@ably/ai-transport 0.0.1 → 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 +114 -116
- package/dist/ably-ai-transport.js +1743 -961
- 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 +117 -39
- 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 +410 -101
- 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 +97 -17
- package/dist/core/transport/index.d.ts +5 -3
- 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 -8
- package/dist/core/transport/run-manager.d.ts +78 -0
- package/dist/core/transport/tree.d.ts +435 -0
- 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 -402
- package/dist/core/transport/view.d.ts +354 -0
- package/dist/errors.d.ts +37 -9
- package/dist/index.d.ts +6 -6
- package/dist/logger.d.ts +12 -0
- package/dist/react/ably-ai-transport-react.js +1164 -645
- 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 +16 -10
- package/dist/react/internal/use-resolved-session.d.ts +36 -0
- package/dist/react/use-ably-messages.d.ts +20 -11
- package/dist/react/use-client-session.d.ts +81 -0
- package/dist/react/use-create-view.d.ts +23 -0
- package/dist/react/use-tree.d.ts +35 -0
- package/dist/react/use-view.d.ts +110 -0
- package/dist/utils.d.ts +32 -23
- package/dist/vercel/ably-ai-transport-vercel.js +2748 -1625
- 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 +50 -0
- package/dist/vercel/index.d.ts +4 -2
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +10298 -1410
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +70 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
- package/dist/vercel/react/contexts/chat-transport-context.d.ts +33 -0
- package/dist/vercel/react/contexts/chat-transport-provider.d.ts +96 -0
- package/dist/vercel/react/index.d.ts +4 -0
- package/dist/vercel/react/use-chat-transport.d.ts +66 -21
- package/dist/vercel/react/use-message-sync.d.ts +31 -12
- package/dist/vercel/run-end-reason.d.ts +29 -0
- package/dist/vercel/transport/chat-transport.d.ts +71 -30
- package/dist/vercel/transport/index.d.ts +25 -18
- package/dist/vercel/transport/run-output-stream.d.ts +56 -0
- package/dist/version.d.ts +2 -0
- package/package.json +47 -34
- package/src/constants.ts +126 -47
- package/src/core/agent.ts +68 -0
- package/src/core/codec/decoder.ts +71 -98
- package/src/core/codec/encoder.ts +115 -58
- package/src/core/codec/index.ts +13 -6
- package/src/core/codec/lifecycle-tracker.ts +10 -9
- package/src/core/codec/types.ts +438 -106
- 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 +182 -19
- package/src/core/transport/index.ts +29 -22
- 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 +58 -40
- package/src/core/transport/run-manager.ts +249 -0
- package/src/core/transport/tree.ts +1167 -0
- 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 -527
- package/src/core/transport/view.ts +1271 -0
- package/src/errors.ts +42 -9
- package/src/event-emitter.ts +3 -2
- package/src/index.ts +55 -39
- 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 +27 -10
- package/src/react/internal/use-resolved-session.ts +63 -0
- package/src/react/use-ably-messages.ts +47 -19
- package/src/react/use-client-session.ts +201 -0
- package/src/react/use-create-view.ts +72 -0
- package/src/react/use-tree.ts +84 -0
- package/src/react/use-view.ts +275 -0
- package/src/react/vite.config.ts +4 -1
- package/src/utils.ts +63 -45
- package/src/vercel/codec/decoder.ts +336 -255
- package/src/vercel/codec/encoder.ts +348 -196
- package/src/vercel/codec/events.ts +87 -0
- package/src/vercel/codec/index.ts +59 -14
- package/src/vercel/codec/reducer.ts +977 -0
- package/src/vercel/codec/tool-transitions.ts +122 -0
- package/src/vercel/index.ts +7 -3
- package/src/vercel/react/contexts/chat-transport-context.ts +41 -0
- package/src/vercel/react/contexts/chat-transport-provider.tsx +150 -0
- package/src/vercel/react/index.ts +13 -1
- package/src/vercel/react/use-chat-transport.ts +162 -42
- package/src/vercel/react/use-message-sync.ts +121 -22
- package/src/vercel/react/vite.config.ts +4 -2
- package/src/vercel/run-end-reason.ts +78 -0
- package/src/vercel/transport/chat-transport.ts +553 -113
- package/src/vercel/transport/index.ts +40 -28
- 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/conversation-tree.d.ts +0 -9
- package/dist/core/transport/decode-history.d.ts +0 -41
- package/dist/core/transport/server-transport.d.ts +0 -7
- package/dist/core/transport/stream-router.d.ts +0 -19
- package/dist/core/transport/turn-manager.d.ts +0 -34
- package/dist/react/use-active-turns.d.ts +0 -8
- package/dist/react/use-client-transport.d.ts +0 -7
- package/dist/react/use-conversation-tree.d.ts +0 -20
- package/dist/react/use-edit.d.ts +0 -7
- package/dist/react/use-history.d.ts +0 -19
- package/dist/react/use-messages.d.ts +0 -7
- package/dist/react/use-regenerate.d.ts +0 -7
- package/dist/react/use-send.d.ts +0 -7
- package/dist/vercel/codec/accumulator.d.ts +0 -21
- package/src/core/transport/client-transport.ts +0 -959
- package/src/core/transport/conversation-tree.ts +0 -434
- package/src/core/transport/decode-history.ts +0 -337
- package/src/core/transport/server-transport.ts +0 -458
- package/src/core/transport/stream-router.ts +0 -118
- package/src/core/transport/turn-manager.ts +0 -147
- package/src/react/use-active-turns.ts +0 -61
- package/src/react/use-client-transport.ts +0 -37
- package/src/react/use-conversation-tree.ts +0 -71
- package/src/react/use-edit.ts +0 -24
- package/src/react/use-history.ts +0 -111
- package/src/react/use-messages.ts +0 -32
- package/src/react/use-regenerate.ts +0 -24
- package/src/react/use-send.ts +0 -25
- package/src/vercel/codec/accumulator.ts +0 -603
|
@@ -1,407 +1,68 @@
|
|
|
1
1
|
import * as e from "ably";
|
|
2
2
|
import { isDataUIPart as t } from "ai";
|
|
3
3
|
//#region src/constants.ts
|
|
4
|
-
var n = "
|
|
5
|
-
let
|
|
6
|
-
if (!
|
|
7
|
-
let
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
var 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 = "ai-cancel", b = "ai-run-start", x = "ai-run-suspend", S = "ai-run-resume", C = "ai-run-end", w = "ai-output", T = "ai-input", E = (e, t) => {
|
|
5
|
+
let n = e.extras;
|
|
6
|
+
if (!n || typeof n != "object") return {};
|
|
7
|
+
let r = n.ai;
|
|
8
|
+
if (!r || typeof r != "object") return {};
|
|
9
|
+
let i = r[t];
|
|
10
|
+
return !i || typeof i != "object" ? {} : i;
|
|
11
|
+
}, D = (e) => E(e, "transport"), O = (e) => E(e, "codec"), ee = (e) => {
|
|
10
12
|
if (e !== void 0) try {
|
|
11
13
|
return JSON.parse(e);
|
|
12
14
|
} catch {
|
|
13
15
|
return;
|
|
14
16
|
}
|
|
15
|
-
},
|
|
17
|
+
}, te = (e, t) => ({
|
|
16
18
|
...e,
|
|
17
19
|
...t
|
|
18
|
-
}),
|
|
20
|
+
}), k = (e) => {
|
|
19
21
|
if (e !== void 0) return e === "true";
|
|
20
|
-
},
|
|
22
|
+
}, A = (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), j = (e, t) => e[t], M = (e) => {
|
|
21
23
|
let t = {};
|
|
22
24
|
for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
|
|
23
25
|
return t;
|
|
24
|
-
},
|
|
25
|
-
str: (t) =>
|
|
26
|
-
strOr: (t, n) =>
|
|
27
|
-
bool: (t) =>
|
|
28
|
-
json: (t) => ee(
|
|
29
|
-
}),
|
|
26
|
+
}, N = (e) => ({
|
|
27
|
+
str: (t) => j(e, t),
|
|
28
|
+
strOr: (t, n) => j(e, t) ?? n,
|
|
29
|
+
bool: (t) => k(j(e, t)),
|
|
30
|
+
json: (t) => ee(j(e, t))
|
|
31
|
+
}), P = () => {
|
|
30
32
|
let e = {}, t = {
|
|
31
|
-
str: (n, r) => (r !== void 0 && (e[
|
|
32
|
-
bool: (n, r) => (r !== void 0 && (e[
|
|
33
|
-
json: (n, r) => (r != null && (e[
|
|
33
|
+
str: (n, r) => (r !== void 0 && (e[n] = r), t),
|
|
34
|
+
bool: (n, r) => (r !== void 0 && (e[n] = String(r)), t),
|
|
35
|
+
json: (n, r) => (r != null && (e[n] = JSON.stringify(r)), t),
|
|
34
36
|
build: () => e
|
|
35
37
|
};
|
|
36
38
|
return t;
|
|
37
|
-
},
|
|
38
|
-
type: "dynamic-tool",
|
|
39
|
-
toolCallId: e.toolCallId,
|
|
40
|
-
toolName: e.toolName,
|
|
41
|
-
title: e.title,
|
|
42
|
-
providerExecuted: e.providerExecuted
|
|
43
|
-
}), E = class {
|
|
44
|
-
constructor(e) {
|
|
45
|
-
this._activeIndex = /* @__PURE__ */ new Map(), this._partType = e;
|
|
46
|
-
}
|
|
47
|
-
start(e, t, n) {
|
|
48
|
-
this._activeIndex.set(e, t.parts.length), t.parts.push({
|
|
49
|
-
type: this._partType,
|
|
50
|
-
text: ""
|
|
51
|
-
}), n.set(e, "streaming");
|
|
52
|
-
}
|
|
53
|
-
delta(e, t, n) {
|
|
54
|
-
let r = this._activeIndex.get(e);
|
|
55
|
-
if (r === void 0) return;
|
|
56
|
-
let i = t.parts[r];
|
|
57
|
-
i?.type === this._partType && (i.text += n);
|
|
58
|
-
}
|
|
59
|
-
end(e, t) {
|
|
60
|
-
t.set(e, "finished"), this._activeIndex.delete(e);
|
|
61
|
-
}
|
|
62
|
-
reset() {
|
|
63
|
-
this._activeIndex = /* @__PURE__ */ new Map();
|
|
64
|
-
}
|
|
65
|
-
}, D = class {
|
|
66
|
-
constructor() {
|
|
67
|
-
this._messageList = [], this._activeMessages = /* @__PURE__ */ new Map();
|
|
68
|
-
}
|
|
69
|
-
get messages() {
|
|
70
|
-
return this._messageList;
|
|
71
|
-
}
|
|
72
|
-
get completedMessages() {
|
|
73
|
-
let e = /* @__PURE__ */ new Set();
|
|
74
|
-
for (let t of this._activeMessages.values()) e.add(t.message);
|
|
75
|
-
return this._messageList.filter((t) => !e.has(t));
|
|
76
|
-
}
|
|
77
|
-
get hasActiveStream() {
|
|
78
|
-
for (let e of this._activeMessages.values()) for (let t of e.streamStatus.values()) if (t === "streaming") return !0;
|
|
79
|
-
return !1;
|
|
80
|
-
}
|
|
81
|
-
processOutputs(e) {
|
|
82
|
-
for (let t of e) t.kind === "message" ? this._messageList.push(t.message) : t.messageId !== void 0 && this._processEvent(t.event, t.messageId);
|
|
83
|
-
}
|
|
84
|
-
updateMessage(e) {
|
|
85
|
-
let t = this._messageList.findIndex((t) => t.id === e.id);
|
|
86
|
-
t !== -1 && (this._messageList[t] = e);
|
|
87
|
-
}
|
|
88
|
-
_ensureActiveMessage(e) {
|
|
89
|
-
let t = this._activeMessages.get(e);
|
|
90
|
-
if (t) return t;
|
|
91
|
-
let n = {
|
|
92
|
-
message: {
|
|
93
|
-
id: e,
|
|
94
|
-
role: "assistant",
|
|
95
|
-
parts: []
|
|
96
|
-
},
|
|
97
|
-
textStreams: new E("text"),
|
|
98
|
-
reasoningStreams: new E("reasoning"),
|
|
99
|
-
toolTrackers: {},
|
|
100
|
-
streamStatus: /* @__PURE__ */ new Map()
|
|
101
|
-
};
|
|
102
|
-
return this._activeMessages.set(e, n), this._messageList.push(n.message), n;
|
|
103
|
-
}
|
|
104
|
-
_getToolPart(e, t) {
|
|
105
|
-
let n = t.toolTrackers[e];
|
|
106
|
-
if (!n) return;
|
|
107
|
-
let r = t.message.parts[n.partIndex];
|
|
108
|
-
if (r?.type === "dynamic-tool") return {
|
|
109
|
-
tracker: n,
|
|
110
|
-
part: r
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
_processEvent(e, t) {
|
|
114
|
-
switch (e.type) {
|
|
115
|
-
case "start":
|
|
116
|
-
case "start-step":
|
|
117
|
-
case "finish-step":
|
|
118
|
-
case "finish":
|
|
119
|
-
case "abort":
|
|
120
|
-
case "error":
|
|
121
|
-
case "message-metadata":
|
|
122
|
-
this._processLifecycle(e, t);
|
|
123
|
-
break;
|
|
124
|
-
case "text-start":
|
|
125
|
-
case "text-delta":
|
|
126
|
-
case "text-end":
|
|
127
|
-
case "reasoning-start":
|
|
128
|
-
case "reasoning-delta":
|
|
129
|
-
case "reasoning-end":
|
|
130
|
-
this._processTextOrReasoning(e, t);
|
|
131
|
-
break;
|
|
132
|
-
case "tool-input-start":
|
|
133
|
-
case "tool-input-delta":
|
|
134
|
-
case "tool-input-available":
|
|
135
|
-
case "tool-input-error":
|
|
136
|
-
this._processToolInput(e, t);
|
|
137
|
-
break;
|
|
138
|
-
case "tool-output-available":
|
|
139
|
-
case "tool-output-error":
|
|
140
|
-
case "tool-output-denied":
|
|
141
|
-
case "tool-approval-request":
|
|
142
|
-
this._processToolOutput(e, t);
|
|
143
|
-
break;
|
|
144
|
-
case "file":
|
|
145
|
-
case "source-url":
|
|
146
|
-
case "source-document":
|
|
147
|
-
this._processContentPart(e, t);
|
|
148
|
-
break;
|
|
149
|
-
default:
|
|
150
|
-
if (e.type.startsWith("data-")) {
|
|
151
|
-
if (e.transient) break;
|
|
152
|
-
let n = this._ensureActiveMessage(t), r = C({
|
|
153
|
-
type: e.type,
|
|
154
|
-
id: e.id,
|
|
155
|
-
data: e.data
|
|
156
|
-
});
|
|
157
|
-
if (e.id !== void 0) {
|
|
158
|
-
let t = n.message.parts.findIndex((t) => t.type === e.type && "id" in t && t.id === e.id);
|
|
159
|
-
if (t !== -1) {
|
|
160
|
-
n.message.parts[t] = r;
|
|
161
|
-
break;
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
n.message.parts.push(r);
|
|
165
|
-
}
|
|
166
|
-
break;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
_processLifecycle(e, t) {
|
|
170
|
-
switch (e.type) {
|
|
171
|
-
case "start": {
|
|
172
|
-
let n = this._ensureActiveMessage(t);
|
|
173
|
-
e.messageId && (n.message.id = e.messageId), e.messageMetadata !== void 0 && (n.message.metadata = e.messageMetadata);
|
|
174
|
-
break;
|
|
175
|
-
}
|
|
176
|
-
case "start-step":
|
|
177
|
-
this._ensureActiveMessage(t).message.parts.push({ type: "step-start" });
|
|
178
|
-
break;
|
|
179
|
-
case "finish-step": {
|
|
180
|
-
let e = this._activeMessages.get(t);
|
|
181
|
-
e && (e.textStreams.reset(), e.reasoningStreams.reset());
|
|
182
|
-
break;
|
|
183
|
-
}
|
|
184
|
-
case "finish": {
|
|
185
|
-
let n = this._activeMessages.get(t);
|
|
186
|
-
n && e.messageMetadata !== void 0 && (n.message.metadata = e.messageMetadata), this._activeMessages.delete(t);
|
|
187
|
-
break;
|
|
188
|
-
}
|
|
189
|
-
case "abort": {
|
|
190
|
-
let e = this._activeMessages.get(t);
|
|
191
|
-
if (e) for (let [t, n] of e.streamStatus) n === "streaming" && e.streamStatus.set(t, "aborted");
|
|
192
|
-
this._activeMessages.delete(t);
|
|
193
|
-
break;
|
|
194
|
-
}
|
|
195
|
-
case "error": break;
|
|
196
|
-
case "message-metadata": {
|
|
197
|
-
let n = this._activeMessages.get(t);
|
|
198
|
-
n && e.messageMetadata !== void 0 && (n.message.metadata = e.messageMetadata);
|
|
199
|
-
break;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
_processTextOrReasoning(e, t) {
|
|
204
|
-
let n = this._ensureActiveMessage(t);
|
|
205
|
-
switch (e.type) {
|
|
206
|
-
case "text-start":
|
|
207
|
-
n.textStreams.start(e.id, n.message, n.streamStatus);
|
|
208
|
-
break;
|
|
209
|
-
case "text-delta":
|
|
210
|
-
n.textStreams.delta(e.id, n.message, e.delta);
|
|
211
|
-
break;
|
|
212
|
-
case "text-end":
|
|
213
|
-
n.textStreams.end(e.id, n.streamStatus);
|
|
214
|
-
break;
|
|
215
|
-
case "reasoning-start":
|
|
216
|
-
n.reasoningStreams.start(e.id, n.message, n.streamStatus);
|
|
217
|
-
break;
|
|
218
|
-
case "reasoning-delta":
|
|
219
|
-
n.reasoningStreams.delta(e.id, n.message, e.delta);
|
|
220
|
-
break;
|
|
221
|
-
case "reasoning-end":
|
|
222
|
-
n.reasoningStreams.end(e.id, n.streamStatus);
|
|
223
|
-
break;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
_processToolInput(e, t) {
|
|
227
|
-
switch (e.type) {
|
|
228
|
-
case "tool-input-start": {
|
|
229
|
-
let n = this._ensureActiveMessage(t), r = n.message.parts.length;
|
|
230
|
-
n.message.parts.push({
|
|
231
|
-
...T(e),
|
|
232
|
-
state: "input-streaming",
|
|
233
|
-
input: void 0
|
|
234
|
-
}), n.toolTrackers[e.toolCallId] = {
|
|
235
|
-
partIndex: r,
|
|
236
|
-
inputText: ""
|
|
237
|
-
}, n.streamStatus.set(e.toolCallId, "streaming");
|
|
238
|
-
break;
|
|
239
|
-
}
|
|
240
|
-
case "tool-input-delta": {
|
|
241
|
-
let n = this._ensureActiveMessage(t), r = n.toolTrackers[e.toolCallId];
|
|
242
|
-
if (!r) break;
|
|
243
|
-
r.inputText += e.inputTextDelta;
|
|
244
|
-
let i;
|
|
245
|
-
try {
|
|
246
|
-
i = JSON.parse(r.inputText);
|
|
247
|
-
} catch {
|
|
248
|
-
i = void 0;
|
|
249
|
-
}
|
|
250
|
-
let a = this._getToolPart(e.toolCallId, n);
|
|
251
|
-
if (!a) break;
|
|
252
|
-
n.message.parts[a.tracker.partIndex] = {
|
|
253
|
-
...T(a.part),
|
|
254
|
-
state: "input-streaming",
|
|
255
|
-
input: i
|
|
256
|
-
};
|
|
257
|
-
break;
|
|
258
|
-
}
|
|
259
|
-
case "tool-input-available": {
|
|
260
|
-
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
261
|
-
if (!r) break;
|
|
262
|
-
n.message.parts[r.tracker.partIndex] = {
|
|
263
|
-
...T(r.part),
|
|
264
|
-
state: "input-available",
|
|
265
|
-
input: e.input
|
|
266
|
-
}, n.streamStatus.set(e.toolCallId, "finished");
|
|
267
|
-
break;
|
|
268
|
-
}
|
|
269
|
-
case "tool-input-error": {
|
|
270
|
-
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
271
|
-
if (r) n.message.parts[r.tracker.partIndex] = {
|
|
272
|
-
...T(r.part),
|
|
273
|
-
state: "output-error",
|
|
274
|
-
input: e.input,
|
|
275
|
-
errorText: e.errorText
|
|
276
|
-
};
|
|
277
|
-
else {
|
|
278
|
-
let t = n.message.parts.length;
|
|
279
|
-
n.message.parts.push({
|
|
280
|
-
...T(e),
|
|
281
|
-
state: "output-error",
|
|
282
|
-
input: e.input,
|
|
283
|
-
errorText: e.errorText
|
|
284
|
-
}), n.toolTrackers[e.toolCallId] = {
|
|
285
|
-
partIndex: t,
|
|
286
|
-
inputText: ""
|
|
287
|
-
};
|
|
288
|
-
}
|
|
289
|
-
n.streamStatus.set(e.toolCallId, "finished");
|
|
290
|
-
break;
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
_processToolOutput(e, t) {
|
|
295
|
-
let n = this._ensureActiveMessage(t), r = this._getToolPart(e.toolCallId, n);
|
|
296
|
-
if (r) switch (e.type) {
|
|
297
|
-
case "tool-output-available":
|
|
298
|
-
n.message.parts[r.tracker.partIndex] = C({
|
|
299
|
-
...T(r.part),
|
|
300
|
-
state: "output-available",
|
|
301
|
-
input: r.part.input,
|
|
302
|
-
output: e.output,
|
|
303
|
-
preliminary: e.preliminary
|
|
304
|
-
});
|
|
305
|
-
break;
|
|
306
|
-
case "tool-output-error":
|
|
307
|
-
n.message.parts[r.tracker.partIndex] = {
|
|
308
|
-
...T(r.part),
|
|
309
|
-
state: "output-error",
|
|
310
|
-
input: r.part.input,
|
|
311
|
-
errorText: e.errorText
|
|
312
|
-
};
|
|
313
|
-
break;
|
|
314
|
-
case "tool-output-denied":
|
|
315
|
-
n.message.parts[r.tracker.partIndex] = {
|
|
316
|
-
...T(r.part),
|
|
317
|
-
state: "output-denied",
|
|
318
|
-
input: r.part.input,
|
|
319
|
-
approval: {
|
|
320
|
-
id: "",
|
|
321
|
-
approved: !1
|
|
322
|
-
}
|
|
323
|
-
};
|
|
324
|
-
break;
|
|
325
|
-
case "tool-approval-request":
|
|
326
|
-
n.message.parts[r.tracker.partIndex] = {
|
|
327
|
-
...T(r.part),
|
|
328
|
-
state: "approval-requested",
|
|
329
|
-
input: r.part.input,
|
|
330
|
-
approval: { id: e.approvalId }
|
|
331
|
-
};
|
|
332
|
-
break;
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
_processContentPart(e, t) {
|
|
336
|
-
let n = this._ensureActiveMessage(t);
|
|
337
|
-
switch (e.type) {
|
|
338
|
-
case "file":
|
|
339
|
-
n.message.parts.push({
|
|
340
|
-
type: "file",
|
|
341
|
-
mediaType: e.mediaType,
|
|
342
|
-
url: e.url
|
|
343
|
-
});
|
|
344
|
-
break;
|
|
345
|
-
case "source-url":
|
|
346
|
-
n.message.parts.push(C({
|
|
347
|
-
type: "source-url",
|
|
348
|
-
sourceId: e.sourceId,
|
|
349
|
-
url: e.url,
|
|
350
|
-
title: e.title
|
|
351
|
-
}));
|
|
352
|
-
break;
|
|
353
|
-
case "source-document":
|
|
354
|
-
n.message.parts.push(C({
|
|
355
|
-
type: "source-document",
|
|
356
|
-
sourceId: e.sourceId,
|
|
357
|
-
mediaType: e.mediaType,
|
|
358
|
-
title: e.title,
|
|
359
|
-
filename: e.filename
|
|
360
|
-
}));
|
|
361
|
-
break;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
}, re = () => new D(), ie = (e) => [{
|
|
365
|
-
kind: "event",
|
|
366
|
-
event: e
|
|
367
|
-
}], ae = class {
|
|
39
|
+
}, F = class {
|
|
368
40
|
constructor(e, t = {}) {
|
|
369
41
|
this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
|
|
370
42
|
}
|
|
371
43
|
decode(e) {
|
|
372
44
|
let t = e.action;
|
|
373
|
-
this._logger?.trace("DefaultDecoderCore.decode();", {
|
|
45
|
+
switch (this._logger?.trace("DefaultDecoderCore.decode();", {
|
|
374
46
|
action: t,
|
|
375
47
|
serial: e.serial,
|
|
376
48
|
name: e.name
|
|
377
|
-
})
|
|
378
|
-
let n;
|
|
379
|
-
switch (t) {
|
|
49
|
+
}), t) {
|
|
380
50
|
case "message.create": {
|
|
381
51
|
let t = this._toPayload(e);
|
|
382
|
-
|
|
383
|
-
break;
|
|
52
|
+
return t.transportHeaders?.stream === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
|
|
384
53
|
}
|
|
385
|
-
case "message.append":
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
case "message.update":
|
|
389
|
-
n = this._decodeUpdate(e);
|
|
390
|
-
break;
|
|
391
|
-
case "message.delete":
|
|
392
|
-
n = this._decodeDelete(e);
|
|
393
|
-
break;
|
|
54
|
+
case "message.append": return this._decodeAppend(e);
|
|
55
|
+
case "message.update": return this._decodeUpdate(e);
|
|
56
|
+
case "message.delete": return this._decodeDelete(e);
|
|
394
57
|
default: return [];
|
|
395
58
|
}
|
|
396
|
-
let r = b(e)[o];
|
|
397
|
-
if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
|
|
398
|
-
return n;
|
|
399
59
|
}
|
|
400
60
|
_toPayload(e) {
|
|
401
61
|
return {
|
|
402
62
|
name: e.name ?? "",
|
|
403
63
|
data: e.data,
|
|
404
|
-
|
|
64
|
+
transportHeaders: D(e),
|
|
65
|
+
codecHeaders: O(e)
|
|
405
66
|
};
|
|
406
67
|
}
|
|
407
68
|
_stringData(e) {
|
|
@@ -423,42 +84,43 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
423
84
|
}
|
|
424
85
|
_decodeStreamedCreate(e, t) {
|
|
425
86
|
if (!t) return [];
|
|
426
|
-
let n = e.
|
|
87
|
+
let n = e.transportHeaders?.["stream-id"] ?? "", r = {
|
|
427
88
|
name: e.name,
|
|
428
89
|
streamId: n,
|
|
429
90
|
accumulated: "",
|
|
430
|
-
|
|
91
|
+
codecHeaders: { ...e.codecHeaders },
|
|
92
|
+
transportHeaders: { ...e.transportHeaders },
|
|
431
93
|
closed: !1
|
|
432
94
|
};
|
|
433
|
-
return this._serialState.set(t,
|
|
95
|
+
return this._serialState.set(t, r), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
|
|
434
96
|
name: e.name,
|
|
435
97
|
streamId: n,
|
|
436
98
|
serial: t
|
|
437
|
-
}), this._hooks.buildStartEvents(
|
|
99
|
+
}), this._hooks.buildStartEvents(r);
|
|
438
100
|
}
|
|
439
101
|
_decodeAppend(e) {
|
|
440
102
|
let t = e.serial;
|
|
441
103
|
if (!t) return [];
|
|
442
104
|
let n = this._serialState.get(t);
|
|
443
105
|
if (!n) return this._decodeUpdate(e);
|
|
444
|
-
let i =
|
|
445
|
-
return
|
|
106
|
+
let i = D(e), a = O(e), o = typeof e.data == "string" ? e.data : "", s = i[r], c = [];
|
|
107
|
+
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;
|
|
446
108
|
}
|
|
447
109
|
_decodeUpdate(e) {
|
|
448
110
|
let t = e.serial;
|
|
449
111
|
if (!t) return [];
|
|
450
|
-
let i = this._toPayload(e), a = i.
|
|
451
|
-
if (!
|
|
452
|
-
let
|
|
453
|
-
if (
|
|
454
|
-
let e =
|
|
455
|
-
return e.length > 0 && (
|
|
112
|
+
let i = this._toPayload(e), a = i.transportHeaders ?? {}, o = i.codecHeaders ?? {}, s = a[n] === "true", c = a[r], l = this._serialState.get(t);
|
|
113
|
+
if (!l) return this._decodeFirstContact(i, s, c, t);
|
|
114
|
+
let u = this._stringData(e);
|
|
115
|
+
if (u.startsWith(l.accumulated)) {
|
|
116
|
+
let e = u.slice(l.accumulated.length), t = [];
|
|
117
|
+
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;
|
|
456
118
|
}
|
|
457
|
-
return
|
|
119
|
+
return l.accumulated = u, l.codecHeaders = { ...o }, l.transportHeaders = { ...a }, this._invokeOnStreamUpdate(l), [];
|
|
458
120
|
}
|
|
459
121
|
_decodeFirstContact(e, t, n, r) {
|
|
460
122
|
if (!t) return this._hooks.decodeDiscrete(e);
|
|
461
|
-
let i = e.
|
|
123
|
+
let i = e.transportHeaders?.["stream-id"] ?? "", a = e.codecHeaders ?? {}, o = typeof e.data == "string" ? e.data : "";
|
|
462
124
|
this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
|
|
463
125
|
name: e.name,
|
|
464
126
|
streamId: i,
|
|
@@ -468,12 +130,13 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
468
130
|
name: e.name,
|
|
469
131
|
streamId: i,
|
|
470
132
|
accumulated: o,
|
|
471
|
-
|
|
472
|
-
|
|
133
|
+
codecHeaders: { ...a },
|
|
134
|
+
transportHeaders: { ...e.transportHeaders },
|
|
135
|
+
closed: n === "complete" || n === "cancelled"
|
|
473
136
|
};
|
|
474
137
|
this._serialState.set(r, s);
|
|
475
138
|
let c = this._hooks.buildStartEvents(s);
|
|
476
|
-
return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "
|
|
139
|
+
return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "complete" && c.push(...this._hooks.buildEndEvents(s, a)), c;
|
|
477
140
|
}
|
|
478
141
|
_decodeDelete(e) {
|
|
479
142
|
let t = e.serial;
|
|
@@ -481,7 +144,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
481
144
|
let n = this._serialState.get(t);
|
|
482
145
|
return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
|
|
483
146
|
}
|
|
484
|
-
},
|
|
147
|
+
}, I = (e, t = {}) => new F(e, t), L = class {
|
|
485
148
|
constructor(e) {
|
|
486
149
|
this._emitted = /* @__PURE__ */ new Map(), this._phases = e;
|
|
487
150
|
}
|
|
@@ -503,32 +166,32 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
503
166
|
let t = this._emitted.get(e);
|
|
504
167
|
return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
|
|
505
168
|
}
|
|
506
|
-
},
|
|
507
|
-
let t =
|
|
169
|
+
}, ne = (e) => new L(e), R = (e) => {
|
|
170
|
+
let t = N(e);
|
|
508
171
|
return {
|
|
509
172
|
...t,
|
|
510
173
|
providerMetadata: () => t.json("providerMetadata")
|
|
511
174
|
};
|
|
512
|
-
},
|
|
175
|
+
}, z = (e, t) => e === "stop" || e === "length" || e === "content-filter" || e === "tool-calls" || e === "error" || e === "other" ? e : t, B = (e) => e.startsWith("data-"), V = (e) => {
|
|
513
176
|
if (e) try {
|
|
514
177
|
return JSON.parse(e);
|
|
515
178
|
} catch {
|
|
516
179
|
return e;
|
|
517
180
|
}
|
|
518
|
-
},
|
|
519
|
-
let t =
|
|
520
|
-
switch (e
|
|
521
|
-
case "text": return
|
|
181
|
+
}, H = (e) => R(e.codecHeaders).strOr("type", ""), U = (e) => {
|
|
182
|
+
let t = R(e.codecHeaders);
|
|
183
|
+
switch (H(e)) {
|
|
184
|
+
case "text": return M({
|
|
522
185
|
type: "text-start",
|
|
523
186
|
id: e.streamId,
|
|
524
187
|
providerMetadata: t.providerMetadata()
|
|
525
188
|
});
|
|
526
|
-
case "reasoning": return
|
|
189
|
+
case "reasoning": return M({
|
|
527
190
|
type: "reasoning-start",
|
|
528
191
|
id: e.streamId,
|
|
529
192
|
providerMetadata: t.providerMetadata()
|
|
530
193
|
});
|
|
531
|
-
case "tool-input": return
|
|
194
|
+
case "tool-input": return M({
|
|
532
195
|
type: "tool-input-start",
|
|
533
196
|
toolCallId: e.streamId,
|
|
534
197
|
toolName: t.strOr("toolName", ""),
|
|
@@ -542,8 +205,8 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
542
205
|
id: e.streamId
|
|
543
206
|
};
|
|
544
207
|
}
|
|
545
|
-
},
|
|
546
|
-
switch (e
|
|
208
|
+
}, re = (e, t) => {
|
|
209
|
+
switch (H(e)) {
|
|
547
210
|
case "text": return {
|
|
548
211
|
type: "text-delta",
|
|
549
212
|
id: e.streamId,
|
|
@@ -565,24 +228,24 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
565
228
|
delta: t
|
|
566
229
|
};
|
|
567
230
|
}
|
|
568
|
-
},
|
|
569
|
-
let n =
|
|
570
|
-
switch (e
|
|
571
|
-
case "text": return
|
|
231
|
+
}, ie = (e, t) => {
|
|
232
|
+
let n = R(t);
|
|
233
|
+
switch (H(e)) {
|
|
234
|
+
case "text": return M({
|
|
572
235
|
type: "text-end",
|
|
573
236
|
id: e.streamId,
|
|
574
237
|
providerMetadata: n.providerMetadata()
|
|
575
238
|
});
|
|
576
|
-
case "reasoning": return
|
|
239
|
+
case "reasoning": return M({
|
|
577
240
|
type: "reasoning-end",
|
|
578
241
|
id: e.streamId,
|
|
579
242
|
providerMetadata: n.providerMetadata()
|
|
580
243
|
});
|
|
581
|
-
case "tool-input": return
|
|
244
|
+
case "tool-input": return M({
|
|
582
245
|
type: "tool-input-available",
|
|
583
246
|
toolCallId: e.streamId,
|
|
584
|
-
toolName: n.strOr("toolName",
|
|
585
|
-
input:
|
|
247
|
+
toolName: n.strOr("toolName", R(e.codecHeaders).strOr("toolName", "")),
|
|
248
|
+
input: V(e.accumulated),
|
|
586
249
|
providerMetadata: n.providerMetadata()
|
|
587
250
|
});
|
|
588
251
|
default: return {
|
|
@@ -590,56 +253,53 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
590
253
|
id: e.streamId
|
|
591
254
|
};
|
|
592
255
|
}
|
|
593
|
-
},
|
|
256
|
+
}, ae = () => ne([{
|
|
594
257
|
key: "start",
|
|
595
|
-
build: (e) => [
|
|
258
|
+
build: (e) => [M({
|
|
596
259
|
type: "start",
|
|
597
260
|
messageId: e.messageId
|
|
598
261
|
})]
|
|
599
262
|
}, {
|
|
600
263
|
key: "start-step",
|
|
601
264
|
build: () => [{ type: "start-step" }]
|
|
602
|
-
}]),
|
|
603
|
-
kind: "event",
|
|
604
|
-
event: e
|
|
605
|
-
})), I = (e, t, n) => (n.markEmitted(t, "start"), k(C({
|
|
265
|
+
}]), oe = (e, t, n) => (n.markEmitted(t, "start"), [M({
|
|
606
266
|
type: "start",
|
|
607
267
|
messageId: e.str("messageId"),
|
|
608
268
|
messageMetadata: e.json("messageMetadata")
|
|
609
|
-
}))
|
|
269
|
+
})]), se = (e, t) => (t.markEmitted(e, "start-step"), [{ type: "start-step" }]), ce = (e, t) => (t.resetPhase(e, "start-step"), [{ type: "finish-step" }]), le = (e, t, n) => (n.clearScope(t), [M({
|
|
610
270
|
type: "finish",
|
|
611
|
-
finishReason:
|
|
271
|
+
finishReason: z(e.str("finishReason"), "stop"),
|
|
612
272
|
messageMetadata: e.json("messageMetadata")
|
|
613
|
-
}))
|
|
273
|
+
})]), ue = (e, t, n) => (n.clearScope(t), [{
|
|
614
274
|
type: "error",
|
|
615
275
|
errorText: typeof e == "string" ? e : ""
|
|
616
|
-
}),
|
|
276
|
+
}]), de = (e, t, n) => (n.clearScope(t), [M({
|
|
617
277
|
type: "abort",
|
|
618
278
|
reason: typeof e == "string" && e ? e : void 0
|
|
619
|
-
}))
|
|
279
|
+
})]), fe = (e) => [{
|
|
620
280
|
type: "message-metadata",
|
|
621
281
|
messageMetadata: e.json("messageMetadata")
|
|
622
|
-
}
|
|
282
|
+
}], pe = (e, t) => [M({
|
|
623
283
|
type: "file",
|
|
624
284
|
url: typeof t == "string" ? t : "",
|
|
625
285
|
mediaType: e.strOr("mediaType", ""),
|
|
626
286
|
providerMetadata: e.providerMetadata()
|
|
627
|
-
})
|
|
287
|
+
})], me = (e, t) => [M({
|
|
628
288
|
type: "source-url",
|
|
629
289
|
sourceId: e.strOr("sourceId", ""),
|
|
630
290
|
url: typeof t == "string" ? t : "",
|
|
631
291
|
title: e.str("title"),
|
|
632
292
|
providerMetadata: e.providerMetadata()
|
|
633
|
-
})
|
|
293
|
+
})], he = (e) => [M({
|
|
634
294
|
type: "source-document",
|
|
635
295
|
sourceId: e.strOr("sourceId", ""),
|
|
636
296
|
mediaType: e.strOr("mediaType", ""),
|
|
637
297
|
title: e.strOr("title", ""),
|
|
638
298
|
filename: e.str("filename"),
|
|
639
299
|
providerMetadata: e.providerMetadata()
|
|
640
|
-
})
|
|
300
|
+
})], ge = (e, t) => {
|
|
641
301
|
let n = t;
|
|
642
|
-
return
|
|
302
|
+
return [M({
|
|
643
303
|
type: "tool-input-error",
|
|
644
304
|
toolCallId: e.strOr("toolCallId", ""),
|
|
645
305
|
toolName: e.strOr("toolName", ""),
|
|
@@ -649,64 +309,59 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
649
309
|
title: e.str("title"),
|
|
650
310
|
providerExecuted: e.bool("providerExecuted"),
|
|
651
311
|
providerMetadata: e.providerMetadata()
|
|
652
|
-
})
|
|
653
|
-
},
|
|
312
|
+
})];
|
|
313
|
+
}, _e = (e, t) => {
|
|
654
314
|
let n = t;
|
|
655
|
-
return
|
|
315
|
+
return [M({
|
|
656
316
|
type: "tool-output-available",
|
|
657
317
|
toolCallId: e.strOr("toolCallId", ""),
|
|
658
318
|
output: n?.output,
|
|
659
319
|
dynamic: e.bool("dynamic"),
|
|
660
320
|
providerExecuted: e.bool("providerExecuted"),
|
|
661
321
|
preliminary: e.bool("preliminary")
|
|
662
|
-
})
|
|
663
|
-
},
|
|
322
|
+
})];
|
|
323
|
+
}, ve = (e, t) => {
|
|
664
324
|
let n = t;
|
|
665
|
-
return
|
|
325
|
+
return [M({
|
|
666
326
|
type: "tool-output-error",
|
|
667
327
|
toolCallId: e.strOr("toolCallId", ""),
|
|
668
328
|
errorText: n?.errorText ?? "",
|
|
669
329
|
dynamic: e.bool("dynamic"),
|
|
670
330
|
providerExecuted: e.bool("providerExecuted")
|
|
671
|
-
})
|
|
672
|
-
},
|
|
331
|
+
})];
|
|
332
|
+
}, ye = (e) => [{
|
|
673
333
|
type: "tool-approval-request",
|
|
674
334
|
toolCallId: e.strOr("toolCallId", ""),
|
|
675
335
|
approvalId: e.strOr("approvalId", "")
|
|
676
|
-
}
|
|
336
|
+
}], be = (e) => [{
|
|
677
337
|
type: "tool-output-denied",
|
|
678
338
|
toolCallId: e.strOr("toolCallId", "")
|
|
679
|
-
}
|
|
339
|
+
}], xe = (e, t, n) => [M({
|
|
680
340
|
type: e,
|
|
681
341
|
data: n,
|
|
682
342
|
id: t.str("id"),
|
|
683
343
|
transient: t.bool("transient")
|
|
684
|
-
})
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
})
|
|
706
|
-
}), i;
|
|
707
|
-
}, be = (e) => {
|
|
708
|
-
let t = e.headers ?? {}, n = O(t), r = t["x-ably-role"] ?? "user", i = n.str("messageId") ?? "", a;
|
|
709
|
-
switch (e.name) {
|
|
344
|
+
})], Se = (e, t, n, r) => [
|
|
345
|
+
...r.ensurePhases(n, { messageId: e.str("messageId") }),
|
|
346
|
+
M({
|
|
347
|
+
type: "tool-input-start",
|
|
348
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
349
|
+
toolName: e.strOr("toolName", ""),
|
|
350
|
+
dynamic: e.bool("dynamic"),
|
|
351
|
+
title: e.str("title"),
|
|
352
|
+
providerExecuted: e.bool("providerExecuted"),
|
|
353
|
+
providerMetadata: e.providerMetadata()
|
|
354
|
+
}),
|
|
355
|
+
M({
|
|
356
|
+
type: "tool-input-available",
|
|
357
|
+
toolCallId: e.strOr("toolCallId", ""),
|
|
358
|
+
toolName: e.strOr("toolName", ""),
|
|
359
|
+
input: t,
|
|
360
|
+
providerMetadata: e.providerMetadata()
|
|
361
|
+
})
|
|
362
|
+
], Ce = (e) => {
|
|
363
|
+
let t = R(e.codecHeaders ?? {}), n = e.transportHeaders?.role ?? "user", r = t.str("messageId") ?? "", i = t.strOr("type", ""), a;
|
|
364
|
+
switch (i) {
|
|
710
365
|
case "text":
|
|
711
366
|
a = {
|
|
712
367
|
type: "text",
|
|
@@ -716,69 +371,110 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
716
371
|
case "file":
|
|
717
372
|
a = {
|
|
718
373
|
type: "file",
|
|
719
|
-
mediaType:
|
|
374
|
+
mediaType: t.strOr("mediaType", ""),
|
|
720
375
|
url: typeof e.data == "string" ? e.data : ""
|
|
721
376
|
};
|
|
722
377
|
break;
|
|
723
378
|
default:
|
|
724
|
-
|
|
725
|
-
type:
|
|
726
|
-
id:
|
|
379
|
+
B(i) && (a = M({
|
|
380
|
+
type: i,
|
|
381
|
+
id: t.str("id"),
|
|
727
382
|
data: e.data
|
|
728
383
|
}));
|
|
729
384
|
break;
|
|
730
385
|
}
|
|
731
386
|
return a ? [{
|
|
732
|
-
kind: "message",
|
|
387
|
+
kind: "user-message",
|
|
733
388
|
message: {
|
|
734
|
-
id:
|
|
735
|
-
role:
|
|
389
|
+
id: r,
|
|
390
|
+
role: n,
|
|
736
391
|
parts: [a]
|
|
737
392
|
}
|
|
738
393
|
}] : [];
|
|
739
|
-
},
|
|
740
|
-
let
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
394
|
+
}, we = (e, t) => (e === "text" || e === "file" || B(e)) && "discrete" in t, Te = (e, t, n) => {
|
|
395
|
+
let r = n;
|
|
396
|
+
return [{
|
|
397
|
+
kind: "tool-result",
|
|
398
|
+
codecMessageId: e,
|
|
399
|
+
payload: {
|
|
400
|
+
toolCallId: t.strOr("toolCallId", ""),
|
|
401
|
+
output: r?.output
|
|
402
|
+
}
|
|
403
|
+
}];
|
|
404
|
+
}, Ee = (e, t, n) => {
|
|
405
|
+
let r = n;
|
|
406
|
+
return [{
|
|
407
|
+
kind: "tool-result-error",
|
|
408
|
+
codecMessageId: e,
|
|
409
|
+
payload: {
|
|
410
|
+
toolCallId: t.strOr("toolCallId", ""),
|
|
411
|
+
message: r?.message ?? ""
|
|
412
|
+
}
|
|
413
|
+
}];
|
|
414
|
+
}, De = (e, t) => [{
|
|
415
|
+
kind: "tool-approval-response",
|
|
416
|
+
codecMessageId: e,
|
|
417
|
+
payload: M({
|
|
418
|
+
toolCallId: t.strOr("toolCallId", ""),
|
|
419
|
+
approved: t.bool("approved") ?? !1,
|
|
420
|
+
reason: t.str("reason")
|
|
421
|
+
})
|
|
422
|
+
}], Oe = (e, t, n, r, i) => {
|
|
423
|
+
switch (e) {
|
|
424
|
+
case "start": return oe(t, r, i);
|
|
425
|
+
case "start-step": return se(r, i);
|
|
426
|
+
case "finish-step": return ce(r, i);
|
|
427
|
+
case "finish": return le(t, r, i);
|
|
428
|
+
case "error": return ue(n, r, i);
|
|
429
|
+
case "abort": return de(n, r, i);
|
|
430
|
+
case "message-metadata": return fe(t);
|
|
431
|
+
case "file": return pe(t, n);
|
|
432
|
+
case "source-url": return me(t, n);
|
|
433
|
+
case "source-document": return he(t);
|
|
434
|
+
case "tool-input": return Se(t, n, r, i);
|
|
435
|
+
case "tool-input-error": return ge(t, n);
|
|
436
|
+
case "tool-output-available": return _e(t, n);
|
|
437
|
+
case "tool-output-error": return ve(t, n);
|
|
438
|
+
case "tool-approval-request": return ye(t);
|
|
439
|
+
case "tool-output-denied": return be(t);
|
|
440
|
+
default: return B(e) ? xe(e, t, n) : [];
|
|
441
|
+
}
|
|
442
|
+
}, ke = (e, t, n) => {
|
|
443
|
+
if (we(e, t.transportHeaders ?? {})) return Ce(t);
|
|
444
|
+
let r = t.transportHeaders?.["codec-message-id"] ?? "";
|
|
445
|
+
switch (e) {
|
|
446
|
+
case "tool-result": return Te(r, n, t.data);
|
|
447
|
+
case "tool-result-error": return Ee(r, n, t.data);
|
|
448
|
+
case "tool-approval-response": return De(r, n);
|
|
449
|
+
case "regenerate": return [];
|
|
450
|
+
default: return [];
|
|
451
|
+
}
|
|
452
|
+
}, Ae = (e, t) => {
|
|
453
|
+
let n = R(e.codecHeaders ?? {}), r = e.transportHeaders?.["run-id"] ?? "", i = n.strOr("type", "");
|
|
454
|
+
return e.name === "ai-input" ? ke(i, e, n) : e.name === "ai-output" ? Oe(i, n, e.data, r, t) : [];
|
|
455
|
+
}, je = (e) => ({
|
|
762
456
|
buildStartEvents: (t) => {
|
|
763
|
-
let n =
|
|
764
|
-
return
|
|
765
|
-
kind: "event",
|
|
766
|
-
event: j(t)
|
|
767
|
-
}), n;
|
|
457
|
+
let n = t.transportHeaders["run-id"] ?? "", r = R(t.codecHeaders).str("messageId");
|
|
458
|
+
return [...e.ensurePhases(n, { messageId: r }), U(t)];
|
|
768
459
|
},
|
|
769
|
-
buildDeltaEvents: (e, t) =>
|
|
770
|
-
buildEndEvents: (e, t) =>
|
|
771
|
-
decodeDiscrete: (t) =>
|
|
772
|
-
}),
|
|
460
|
+
buildDeltaEvents: (e, t) => [re(e, t)],
|
|
461
|
+
buildEndEvents: (e, t) => [ie(e, t)],
|
|
462
|
+
decodeDiscrete: (t) => Ae(t, e)
|
|
463
|
+
}), Me = (e) => "kind" in e, Ne = class {
|
|
773
464
|
constructor(e = {}) {
|
|
774
|
-
this._core =
|
|
465
|
+
this._core = I(je(ae()), e);
|
|
775
466
|
}
|
|
776
467
|
decode(e) {
|
|
777
|
-
|
|
468
|
+
let t = this._core.decode(e), n = [], r = [];
|
|
469
|
+
for (let e of t) Me(e) ? n.push(e) : r.push(e);
|
|
470
|
+
return {
|
|
471
|
+
inputs: n,
|
|
472
|
+
outputs: r
|
|
473
|
+
};
|
|
778
474
|
}
|
|
779
|
-
},
|
|
780
|
-
return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.
|
|
781
|
-
}({}),
|
|
475
|
+
}, Pe = (e = {}) => new Ne(e), W = /* @__PURE__ */ function(e) {
|
|
476
|
+
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;
|
|
477
|
+
}({}), Fe = (e, t) => e.code === t, Ie = class {
|
|
782
478
|
constructor(e, t = {}) {
|
|
783
479
|
this._trackers = /* @__PURE__ */ new Map(), this._pending = [], this._closed = !1, this._writer = e, this._defaultClientId = t.clientId, this._defaultExtras = t.extras, this._onMessageHook = t.onMessage ?? (() => {}), this._logger = t.logger?.withContext({ component: "EncoderCore" });
|
|
784
480
|
}
|
|
@@ -789,7 +485,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
789
485
|
}
|
|
790
486
|
async publishDiscreteBatch(e, t) {
|
|
791
487
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
|
|
792
|
-
let n = e.map((e) => this._buildDiscreteMessage(e, t));
|
|
488
|
+
let n = e.map((e) => this._buildDiscreteMessage(e, t, !0));
|
|
793
489
|
return this._writer.publish(n);
|
|
794
490
|
}
|
|
795
491
|
async startStream(t, a, o) {
|
|
@@ -797,28 +493,29 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
797
493
|
name: a.name,
|
|
798
494
|
streamId: t
|
|
799
495
|
});
|
|
800
|
-
let s = this.
|
|
496
|
+
let s = this._buildTransport(a.transportHeaders, o);
|
|
801
497
|
s[n] = "true", s[r] = "streaming", s[i] = t;
|
|
802
|
-
let c = this._resolveClientId(o),
|
|
498
|
+
let c = a.codecHeaders ?? {}, l = this._resolveClientId(o), u = {
|
|
803
499
|
name: a.name,
|
|
804
500
|
data: a.data,
|
|
805
|
-
extras: {
|
|
806
|
-
...
|
|
501
|
+
extras: { ai: this._aiExtras(s, c) },
|
|
502
|
+
...l ? { clientId: l } : {}
|
|
807
503
|
};
|
|
808
|
-
this._invokeOnMessage(
|
|
809
|
-
let
|
|
810
|
-
if (!
|
|
504
|
+
this._invokeOnMessage(u);
|
|
505
|
+
let d = (await this._writer.publish(u)).serials[0];
|
|
506
|
+
if (!d) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${t})`, W.BadRequest, 400);
|
|
811
507
|
this._trackers.set(t, {
|
|
812
|
-
serial:
|
|
508
|
+
serial: d,
|
|
813
509
|
name: a.name,
|
|
814
510
|
streamId: t,
|
|
815
511
|
accumulated: a.data,
|
|
816
|
-
|
|
817
|
-
|
|
512
|
+
persistentTransport: s,
|
|
513
|
+
persistentCodec: c,
|
|
514
|
+
cancelled: !1
|
|
818
515
|
}), this._logger?.debug("DefaultEncoderCore.startStream(); stream started", {
|
|
819
516
|
name: a.name,
|
|
820
517
|
streamId: t,
|
|
821
|
-
serial:
|
|
518
|
+
serial: d
|
|
822
519
|
});
|
|
823
520
|
}
|
|
824
521
|
appendStream(t, n) {
|
|
@@ -829,7 +526,7 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
829
526
|
let i = {
|
|
830
527
|
serial: r.serial,
|
|
831
528
|
data: n,
|
|
832
|
-
extras: {
|
|
529
|
+
extras: { ai: this._aiExtras({ ...r.persistentTransport }, { ...r.persistentCodec }) }
|
|
833
530
|
};
|
|
834
531
|
this._invokeOnMessage(i);
|
|
835
532
|
let a = this._writer.appendMessage(i);
|
|
@@ -843,54 +540,54 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
843
540
|
let i = this._trackers.get(t);
|
|
844
541
|
if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, W.InvalidArgument, 400);
|
|
845
542
|
i.accumulated += n.data;
|
|
846
|
-
let a = this.
|
|
847
|
-
a[r] = "
|
|
848
|
-
let
|
|
543
|
+
let { transport: a, codec: o } = this._buildClosing(i, n);
|
|
544
|
+
a[r] = "complete";
|
|
545
|
+
let s = {
|
|
849
546
|
serial: i.serial,
|
|
850
547
|
data: n.data,
|
|
851
|
-
extras: {
|
|
548
|
+
extras: { ai: this._aiExtras(a, o) }
|
|
852
549
|
};
|
|
853
|
-
this._invokeOnMessage(
|
|
854
|
-
let
|
|
550
|
+
this._invokeOnMessage(s);
|
|
551
|
+
let c = this._writer.appendMessage(s);
|
|
855
552
|
this._pending.push({
|
|
856
|
-
promise:
|
|
553
|
+
promise: c,
|
|
857
554
|
streamId: t
|
|
858
555
|
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.closeStream(); stream closed", { streamId: t });
|
|
859
556
|
}
|
|
860
|
-
async
|
|
861
|
-
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.
|
|
557
|
+
async cancelStream(t, n) {
|
|
558
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.cancelStream();", { streamId: t });
|
|
862
559
|
let i = this._trackers.get(t);
|
|
863
|
-
if (!i) throw new e.ErrorInfo(`unable to
|
|
864
|
-
i.
|
|
865
|
-
let a = this.
|
|
866
|
-
a[r] = "
|
|
867
|
-
let
|
|
560
|
+
if (!i) throw new e.ErrorInfo(`unable to cancel stream; no active stream for streamId '${t}'`, W.InvalidArgument, 400);
|
|
561
|
+
i.cancelled = !0;
|
|
562
|
+
let { transport: a, codec: o } = this._buildClosing(i, void 0, n);
|
|
563
|
+
a[r] = "cancelled";
|
|
564
|
+
let s = {
|
|
868
565
|
serial: i.serial,
|
|
869
566
|
data: "",
|
|
870
|
-
extras: {
|
|
567
|
+
extras: { ai: this._aiExtras(a, o) }
|
|
871
568
|
};
|
|
872
|
-
this._invokeOnMessage(
|
|
873
|
-
let
|
|
569
|
+
this._invokeOnMessage(s);
|
|
570
|
+
let c = this._writer.appendMessage(s);
|
|
874
571
|
this._pending.push({
|
|
875
|
-
promise:
|
|
572
|
+
promise: c,
|
|
876
573
|
streamId: t
|
|
877
|
-
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.
|
|
574
|
+
}), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.cancelStream(); stream cancelled", { streamId: t });
|
|
878
575
|
}
|
|
879
|
-
async
|
|
880
|
-
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.
|
|
576
|
+
async cancelAllStreams(e) {
|
|
577
|
+
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.cancelAllStreams();", { streamCount: this._trackers.size });
|
|
881
578
|
for (let t of this._trackers.values()) {
|
|
882
|
-
t.
|
|
883
|
-
let n = this.
|
|
884
|
-
n[r] = "
|
|
885
|
-
let
|
|
579
|
+
t.cancelled = !0;
|
|
580
|
+
let { transport: n, codec: i } = this._buildClosing(t, void 0, e);
|
|
581
|
+
n[r] = "cancelled";
|
|
582
|
+
let a = {
|
|
886
583
|
serial: t.serial,
|
|
887
584
|
data: "",
|
|
888
|
-
extras: {
|
|
585
|
+
extras: { ai: this._aiExtras(n, i) }
|
|
889
586
|
};
|
|
890
|
-
this._invokeOnMessage(
|
|
891
|
-
let
|
|
587
|
+
this._invokeOnMessage(a);
|
|
588
|
+
let o = this._writer.appendMessage(a);
|
|
892
589
|
this._pending.push({
|
|
893
|
-
promise:
|
|
590
|
+
promise: o,
|
|
894
591
|
streamId: t.streamId
|
|
895
592
|
});
|
|
896
593
|
}
|
|
@@ -923,13 +620,13 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
923
620
|
for (let e of i) {
|
|
924
621
|
let t = this._trackers.get(e);
|
|
925
622
|
if (!t) continue;
|
|
926
|
-
let n = t.
|
|
623
|
+
let n = t.cancelled ? "cancelled" : "complete", i = {
|
|
927
624
|
serial: t.serial,
|
|
928
625
|
data: t.accumulated,
|
|
929
|
-
extras: {
|
|
930
|
-
...t.
|
|
626
|
+
extras: { ai: this._aiExtras({
|
|
627
|
+
...t.persistentTransport,
|
|
931
628
|
[r]: n
|
|
932
|
-
} }
|
|
629
|
+
}, { ...t.persistentCodec }) }
|
|
933
630
|
};
|
|
934
631
|
try {
|
|
935
632
|
await this._writer.updateMessage(i);
|
|
@@ -969,429 +666,878 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
969
666
|
_resolveClientId(e) {
|
|
970
667
|
return e?.clientId ?? this._defaultClientId;
|
|
971
668
|
}
|
|
972
|
-
|
|
669
|
+
_buildTransport(e, t) {
|
|
973
670
|
let n = {
|
|
974
|
-
...
|
|
671
|
+
...te(this._defaultExtras?.headers, t?.extras?.headers),
|
|
975
672
|
...e
|
|
976
673
|
};
|
|
977
|
-
return t?.messageId !== void 0 && (n[
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
674
|
+
return t?.messageId !== void 0 && (n[l] = t.messageId), n;
|
|
675
|
+
}
|
|
676
|
+
_aiExtras(e, t) {
|
|
677
|
+
return Object.keys(t).length > 0 ? {
|
|
678
|
+
transport: e,
|
|
679
|
+
codec: t
|
|
680
|
+
} : { transport: e };
|
|
681
|
+
}
|
|
682
|
+
_buildDiscreteMessage(e, t, r = !1) {
|
|
683
|
+
let i = this._buildTransport(e.transportHeaders, t);
|
|
684
|
+
i[n] = "false", r && (i[a] = "true");
|
|
685
|
+
let o = this._resolveClientId(t), s = {
|
|
983
686
|
name: e.name,
|
|
984
687
|
data: e.data,
|
|
985
688
|
extras: {
|
|
986
|
-
|
|
689
|
+
ai: this._aiExtras(i, e.codecHeaders ?? {}),
|
|
987
690
|
...e.ephemeral ? { ephemeral: !0 } : {}
|
|
988
691
|
},
|
|
989
|
-
...
|
|
692
|
+
...o ? { clientId: o } : {}
|
|
990
693
|
};
|
|
991
|
-
return this._invokeOnMessage(
|
|
694
|
+
return this._invokeOnMessage(s), s;
|
|
992
695
|
}
|
|
993
|
-
|
|
994
|
-
let r =
|
|
995
|
-
return
|
|
696
|
+
_buildClosing(e, t, n) {
|
|
697
|
+
let r = te(this._defaultExtras?.headers, n?.extras?.headers);
|
|
698
|
+
return {
|
|
699
|
+
transport: {
|
|
700
|
+
...e.persistentTransport,
|
|
701
|
+
...r,
|
|
702
|
+
...t?.transportHeaders
|
|
703
|
+
},
|
|
704
|
+
codec: {
|
|
705
|
+
...e.persistentCodec,
|
|
706
|
+
...t?.codecHeaders
|
|
707
|
+
}
|
|
708
|
+
};
|
|
996
709
|
}
|
|
997
|
-
},
|
|
710
|
+
}, Le = (e, t = {}) => new Ie(e, t), Re = class {
|
|
998
711
|
constructor(e, t = {}) {
|
|
999
|
-
this.
|
|
712
|
+
this._cancelled = !1, this._core = Le(e, t), this._messageId = t.messageId;
|
|
713
|
+
}
|
|
714
|
+
async publishInput(e, t) {
|
|
715
|
+
switch (e.kind) {
|
|
716
|
+
case "user-message":
|
|
717
|
+
await this._publishUserMessage(e, t);
|
|
718
|
+
return;
|
|
719
|
+
case "regenerate":
|
|
720
|
+
await this._publishRegenerate(t);
|
|
721
|
+
return;
|
|
722
|
+
case "tool-result":
|
|
723
|
+
await this._publishToolResult(e, t);
|
|
724
|
+
return;
|
|
725
|
+
case "tool-result-error":
|
|
726
|
+
await this._publishToolResultError(e, t);
|
|
727
|
+
return;
|
|
728
|
+
case "tool-approval-response":
|
|
729
|
+
await this._publishToolApprovalResponse(e, t);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
async publishOutput(e, t) {
|
|
734
|
+
await this._publishChunk(e, t);
|
|
735
|
+
}
|
|
736
|
+
async cancel(e) {
|
|
737
|
+
this._cancelled || (this._cancelled = !0, await this._core.cancelAllStreams(), await this._core.publishDiscrete({
|
|
738
|
+
name: w,
|
|
739
|
+
data: e ?? "",
|
|
740
|
+
codecHeaders: P().str("type", "abort").build(),
|
|
741
|
+
transportHeaders: { [r]: "cancelled" }
|
|
742
|
+
}));
|
|
743
|
+
}
|
|
744
|
+
async close() {
|
|
745
|
+
await this._core.close();
|
|
1000
746
|
}
|
|
1001
|
-
async
|
|
747
|
+
async _publishChunk(t, n) {
|
|
1002
748
|
switch (t.type) {
|
|
1003
749
|
case "text-start": {
|
|
1004
|
-
let e =
|
|
750
|
+
let e = P().str("type", "text").str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1005
751
|
await this._core.startStream(t.id, {
|
|
1006
|
-
name:
|
|
752
|
+
name: w,
|
|
1007
753
|
data: "",
|
|
1008
|
-
|
|
754
|
+
codecHeaders: e
|
|
1009
755
|
}, n);
|
|
1010
|
-
|
|
756
|
+
return;
|
|
1011
757
|
}
|
|
1012
758
|
case "reasoning-start": {
|
|
1013
|
-
let e =
|
|
759
|
+
let e = P().str("type", "reasoning").str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1014
760
|
await this._core.startStream(t.id, {
|
|
1015
|
-
name:
|
|
761
|
+
name: w,
|
|
1016
762
|
data: "",
|
|
1017
|
-
|
|
763
|
+
codecHeaders: e
|
|
1018
764
|
}, n);
|
|
1019
|
-
|
|
765
|
+
return;
|
|
1020
766
|
}
|
|
1021
767
|
case "tool-input-start": {
|
|
1022
|
-
let e =
|
|
768
|
+
let e = P().str("type", "tool-input").str("toolCallId", t.toolCallId).str("toolName", t.toolName).bool("dynamic", t.dynamic).str("title", t.title).bool("providerExecuted", t.providerExecuted).json("providerMetadata", t.providerMetadata).build();
|
|
1023
769
|
await this._core.startStream(t.toolCallId, {
|
|
1024
|
-
name:
|
|
770
|
+
name: w,
|
|
1025
771
|
data: "",
|
|
1026
|
-
|
|
772
|
+
codecHeaders: e
|
|
1027
773
|
}, n);
|
|
1028
|
-
|
|
774
|
+
return;
|
|
1029
775
|
}
|
|
1030
776
|
case "text-delta":
|
|
1031
777
|
this._core.appendStream(t.id, t.delta);
|
|
1032
|
-
|
|
778
|
+
return;
|
|
1033
779
|
case "reasoning-delta":
|
|
1034
780
|
this._core.appendStream(t.id, t.delta);
|
|
1035
|
-
|
|
781
|
+
return;
|
|
1036
782
|
case "tool-input-delta":
|
|
1037
783
|
this._core.appendStream(t.toolCallId, t.inputTextDelta);
|
|
1038
|
-
|
|
784
|
+
return;
|
|
1039
785
|
case "text-end": {
|
|
1040
|
-
let e =
|
|
786
|
+
let e = P().str("type", "text").str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1041
787
|
await this._core.closeStream(t.id, {
|
|
1042
|
-
name:
|
|
788
|
+
name: w,
|
|
1043
789
|
data: "",
|
|
1044
|
-
|
|
790
|
+
codecHeaders: e
|
|
1045
791
|
});
|
|
1046
|
-
|
|
792
|
+
return;
|
|
1047
793
|
}
|
|
1048
794
|
case "reasoning-end": {
|
|
1049
|
-
let e =
|
|
795
|
+
let e = P().str("type", "reasoning").str("id", t.id).json("providerMetadata", t.providerMetadata).build();
|
|
1050
796
|
await this._core.closeStream(t.id, {
|
|
1051
|
-
name:
|
|
797
|
+
name: w,
|
|
1052
798
|
data: "",
|
|
1053
|
-
|
|
799
|
+
codecHeaders: e
|
|
1054
800
|
});
|
|
1055
|
-
|
|
801
|
+
return;
|
|
1056
802
|
}
|
|
1057
803
|
case "tool-input-available":
|
|
1058
804
|
try {
|
|
1059
|
-
let e =
|
|
805
|
+
let e = P().str("type", "tool-input").str("toolCallId", t.toolCallId).str("toolName", t.toolName).json("providerMetadata", t.providerMetadata).build();
|
|
1060
806
|
await this._core.closeStream(t.toolCallId, {
|
|
1061
|
-
name:
|
|
807
|
+
name: w,
|
|
1062
808
|
data: "",
|
|
1063
|
-
|
|
809
|
+
codecHeaders: e
|
|
1064
810
|
});
|
|
1065
811
|
} catch (n) {
|
|
1066
|
-
if (!(n instanceof e.ErrorInfo &&
|
|
1067
|
-
let r =
|
|
812
|
+
if (!(n instanceof e.ErrorInfo && Fe(n, W.InvalidArgument))) throw n;
|
|
813
|
+
let r = P().str("type", "tool-input").str("toolCallId", t.toolCallId).str("toolName", t.toolName).bool("dynamic", t.dynamic).str("title", t.title).bool("providerExecuted", t.providerExecuted).json("providerMetadata", t.providerMetadata).build();
|
|
1068
814
|
await this._core.publishDiscrete({
|
|
1069
|
-
name:
|
|
815
|
+
name: w,
|
|
1070
816
|
data: t.input,
|
|
1071
|
-
|
|
817
|
+
codecHeaders: r
|
|
1072
818
|
});
|
|
1073
819
|
}
|
|
1074
|
-
|
|
820
|
+
return;
|
|
1075
821
|
case "start": {
|
|
1076
|
-
let e =
|
|
822
|
+
let e = P().str("type", "start").str("messageId", t.messageId ?? this._messageId).json("messageMetadata", t.messageMetadata).build();
|
|
1077
823
|
await this._core.publishDiscrete({
|
|
1078
|
-
name:
|
|
824
|
+
name: w,
|
|
1079
825
|
data: "",
|
|
1080
|
-
|
|
826
|
+
codecHeaders: e
|
|
1081
827
|
}, n);
|
|
1082
|
-
|
|
828
|
+
return;
|
|
1083
829
|
}
|
|
1084
|
-
case "start-step":
|
|
830
|
+
case "start-step": {
|
|
831
|
+
let e = P().str("type", "start-step").build();
|
|
1085
832
|
await this._core.publishDiscrete({
|
|
1086
|
-
name:
|
|
1087
|
-
data: ""
|
|
833
|
+
name: w,
|
|
834
|
+
data: "",
|
|
835
|
+
codecHeaders: e
|
|
1088
836
|
}, n);
|
|
1089
|
-
|
|
1090
|
-
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
case "finish-step": {
|
|
840
|
+
let e = P().str("type", "finish-step").build();
|
|
1091
841
|
await this._core.publishDiscrete({
|
|
1092
|
-
name:
|
|
1093
|
-
data: ""
|
|
842
|
+
name: w,
|
|
843
|
+
data: "",
|
|
844
|
+
codecHeaders: e
|
|
1094
845
|
}, n);
|
|
1095
|
-
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
1096
848
|
case "finish": {
|
|
1097
|
-
let e =
|
|
849
|
+
let e = P().str("type", "finish").str("finishReason", t.finishReason).json("messageMetadata", t.messageMetadata).build();
|
|
1098
850
|
await this._core.publishDiscrete({
|
|
1099
|
-
name:
|
|
851
|
+
name: w,
|
|
1100
852
|
data: "",
|
|
1101
|
-
|
|
853
|
+
codecHeaders: e
|
|
1102
854
|
}, n);
|
|
1103
|
-
|
|
855
|
+
return;
|
|
1104
856
|
}
|
|
1105
|
-
case "error":
|
|
857
|
+
case "error": {
|
|
858
|
+
let e = P().str("type", "error").build();
|
|
1106
859
|
await this._core.publishDiscrete({
|
|
1107
|
-
name:
|
|
1108
|
-
data: t.errorText
|
|
860
|
+
name: w,
|
|
861
|
+
data: t.errorText,
|
|
862
|
+
codecHeaders: e
|
|
1109
863
|
}, n);
|
|
1110
|
-
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
1111
866
|
case "abort":
|
|
1112
|
-
this.
|
|
1113
|
-
name:
|
|
867
|
+
this._cancelled = !0, await this._core.cancelAllStreams(n), await this._core.publishDiscrete({
|
|
868
|
+
name: w,
|
|
1114
869
|
data: t.reason ?? "",
|
|
1115
|
-
|
|
870
|
+
codecHeaders: P().str("type", "abort").build(),
|
|
871
|
+
transportHeaders: { [r]: "cancelled" }
|
|
1116
872
|
}, n);
|
|
1117
|
-
|
|
873
|
+
return;
|
|
874
|
+
case "message-metadata": {
|
|
875
|
+
let e = P().str("type", "message-metadata").json("messageMetadata", t.messageMetadata).build();
|
|
876
|
+
await this._core.publishDiscrete({
|
|
877
|
+
name: w,
|
|
878
|
+
data: "",
|
|
879
|
+
codecHeaders: e
|
|
880
|
+
}, n);
|
|
881
|
+
return;
|
|
882
|
+
}
|
|
1118
883
|
case "tool-input-error": {
|
|
1119
|
-
let e =
|
|
884
|
+
let e = P().str("type", "tool-input-error").str("toolCallId", t.toolCallId).str("toolName", t.toolName).bool("dynamic", t.dynamic).str("title", t.title).bool("providerExecuted", t.providerExecuted).json("providerMetadata", t.providerMetadata).build();
|
|
1120
885
|
await this._core.publishDiscrete({
|
|
1121
|
-
name:
|
|
886
|
+
name: w,
|
|
1122
887
|
data: {
|
|
1123
888
|
errorText: t.errorText,
|
|
1124
889
|
input: t.input
|
|
1125
890
|
},
|
|
1126
|
-
|
|
1127
|
-
});
|
|
1128
|
-
break;
|
|
1129
|
-
}
|
|
1130
|
-
case "tool-output-available": {
|
|
1131
|
-
let e = w().str("toolCallId", t.toolCallId).bool("dynamic", t.dynamic).bool("providerExecuted", t.providerExecuted).bool("preliminary", t.preliminary).build();
|
|
1132
|
-
await this._core.publishDiscrete({
|
|
1133
|
-
name: "tool-output-available",
|
|
1134
|
-
data: { output: t.output },
|
|
1135
|
-
headers: e
|
|
1136
|
-
});
|
|
1137
|
-
break;
|
|
1138
|
-
}
|
|
1139
|
-
case "tool-output-error": {
|
|
1140
|
-
let e = w().str("toolCallId", t.toolCallId).bool("dynamic", t.dynamic).bool("providerExecuted", t.providerExecuted).build();
|
|
1141
|
-
await this._core.publishDiscrete({
|
|
1142
|
-
name: "tool-output-error",
|
|
1143
|
-
data: { errorText: t.errorText },
|
|
1144
|
-
headers: e
|
|
1145
|
-
});
|
|
1146
|
-
break;
|
|
1147
|
-
}
|
|
1148
|
-
case "tool-approval-request": {
|
|
1149
|
-
let e = w().str("toolCallId", t.toolCallId).str("approvalId", t.approvalId).build();
|
|
1150
|
-
await this._core.publishDiscrete({
|
|
1151
|
-
name: "tool-approval-request",
|
|
1152
|
-
data: "",
|
|
1153
|
-
headers: e
|
|
1154
|
-
}, n);
|
|
1155
|
-
break;
|
|
1156
|
-
}
|
|
1157
|
-
case "tool-output-denied": {
|
|
1158
|
-
let e = w().str("toolCallId", t.toolCallId).build();
|
|
1159
|
-
await this._core.publishDiscrete({
|
|
1160
|
-
name: "tool-output-denied",
|
|
1161
|
-
data: "",
|
|
1162
|
-
headers: e
|
|
891
|
+
codecHeaders: e
|
|
1163
892
|
}, n);
|
|
1164
|
-
|
|
893
|
+
return;
|
|
1165
894
|
}
|
|
895
|
+
case "tool-output-available":
|
|
896
|
+
case "tool-output-error":
|
|
897
|
+
case "tool-approval-request":
|
|
898
|
+
case "tool-output-denied":
|
|
899
|
+
await this._core.publishDiscrete(ze(t), n);
|
|
900
|
+
return;
|
|
1166
901
|
case "file": {
|
|
1167
|
-
let e =
|
|
902
|
+
let e = P().str("type", "file").str("mediaType", t.mediaType).json("providerMetadata", t.providerMetadata).build();
|
|
1168
903
|
await this._core.publishDiscrete({
|
|
1169
|
-
name:
|
|
904
|
+
name: w,
|
|
1170
905
|
data: t.url,
|
|
1171
|
-
|
|
906
|
+
codecHeaders: e
|
|
1172
907
|
}, n);
|
|
1173
|
-
|
|
908
|
+
return;
|
|
1174
909
|
}
|
|
1175
910
|
case "source-url": {
|
|
1176
|
-
let e =
|
|
911
|
+
let e = P().str("type", "source-url").str("sourceId", t.sourceId).str("title", t.title).json("providerMetadata", t.providerMetadata).build();
|
|
1177
912
|
await this._core.publishDiscrete({
|
|
1178
|
-
name:
|
|
913
|
+
name: w,
|
|
1179
914
|
data: t.url,
|
|
1180
|
-
|
|
915
|
+
codecHeaders: e
|
|
1181
916
|
}, n);
|
|
1182
|
-
|
|
917
|
+
return;
|
|
1183
918
|
}
|
|
1184
919
|
case "source-document": {
|
|
1185
|
-
let e =
|
|
1186
|
-
await this._core.publishDiscrete({
|
|
1187
|
-
name: "source-document",
|
|
1188
|
-
data: "",
|
|
1189
|
-
headers: e
|
|
1190
|
-
}, n);
|
|
1191
|
-
break;
|
|
1192
|
-
}
|
|
1193
|
-
case "message-metadata": {
|
|
1194
|
-
let e = w().json("messageMetadata", t.messageMetadata).build();
|
|
920
|
+
let e = P().str("type", "source-document").str("sourceId", t.sourceId).str("mediaType", t.mediaType).str("title", t.title).str("filename", t.filename).json("providerMetadata", t.providerMetadata).build();
|
|
1195
921
|
await this._core.publishDiscrete({
|
|
1196
|
-
name:
|
|
922
|
+
name: w,
|
|
1197
923
|
data: "",
|
|
1198
|
-
|
|
924
|
+
codecHeaders: e
|
|
1199
925
|
}, n);
|
|
1200
|
-
|
|
926
|
+
return;
|
|
1201
927
|
}
|
|
1202
928
|
default:
|
|
1203
929
|
if (t.type.startsWith("data-")) {
|
|
1204
|
-
let e =
|
|
930
|
+
let e = t, r = P().str("type", e.type).str("id", e.id).bool("transient", e.transient).build(), i = e.transient === !0;
|
|
1205
931
|
await this._core.publishDiscrete({
|
|
1206
|
-
name:
|
|
1207
|
-
data:
|
|
1208
|
-
|
|
1209
|
-
ephemeral:
|
|
932
|
+
name: w,
|
|
933
|
+
data: e.data,
|
|
934
|
+
codecHeaders: r,
|
|
935
|
+
ephemeral: i
|
|
1210
936
|
}, n);
|
|
937
|
+
return;
|
|
1211
938
|
}
|
|
1212
|
-
|
|
939
|
+
throw new e.ErrorInfo(`unable to publish output; unsupported chunk type '${t.type}'`, W.InvalidArgument, 400);
|
|
1213
940
|
}
|
|
1214
941
|
}
|
|
1215
|
-
async
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
ephemeral: i
|
|
1223
|
-
}, n);
|
|
1224
|
-
}
|
|
1225
|
-
async writeMessages(e, t) {
|
|
1226
|
-
let n = e.flatMap((e) => Ae(e));
|
|
1227
|
-
return this._core.publishDiscreteBatch(n, t);
|
|
942
|
+
async _publishUserMessage(e, t) {
|
|
943
|
+
let n = Be(e.message);
|
|
944
|
+
for (let e of n) e.transportHeaders = {
|
|
945
|
+
...e.transportHeaders,
|
|
946
|
+
[f]: "user"
|
|
947
|
+
};
|
|
948
|
+
await this._core.publishDiscreteBatch(n, t);
|
|
1228
949
|
}
|
|
1229
|
-
async
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
950
|
+
async _publishRegenerate(e) {
|
|
951
|
+
let t = P().str("type", "regenerate").build();
|
|
952
|
+
await this._core.publishDiscrete({
|
|
953
|
+
name: T,
|
|
954
|
+
data: "",
|
|
955
|
+
codecHeaders: t
|
|
956
|
+
}, e);
|
|
957
|
+
}
|
|
958
|
+
async _publishToolResult(e, t) {
|
|
959
|
+
let n = P().str("type", "tool-result").str("toolCallId", e.payload.toolCallId).build();
|
|
960
|
+
await this._core.publishDiscrete({
|
|
961
|
+
name: T,
|
|
962
|
+
data: { output: e.payload.output },
|
|
963
|
+
codecHeaders: n
|
|
964
|
+
}, t);
|
|
965
|
+
}
|
|
966
|
+
async _publishToolResultError(e, t) {
|
|
967
|
+
let n = P().str("type", "tool-result-error").str("toolCallId", e.payload.toolCallId).build();
|
|
968
|
+
await this._core.publishDiscrete({
|
|
969
|
+
name: T,
|
|
970
|
+
data: { message: e.payload.message },
|
|
971
|
+
codecHeaders: n
|
|
972
|
+
}, t);
|
|
973
|
+
}
|
|
974
|
+
async _publishToolApprovalResponse(e, t) {
|
|
975
|
+
let n = P().str("type", "tool-approval-response").str("toolCallId", e.payload.toolCallId).bool("approved", e.payload.approved).str("reason", e.payload.reason).build();
|
|
976
|
+
await this._core.publishDiscrete({
|
|
977
|
+
name: T,
|
|
978
|
+
data: "",
|
|
979
|
+
codecHeaders: n
|
|
980
|
+
}, t);
|
|
981
|
+
}
|
|
982
|
+
}, ze = (e) => {
|
|
983
|
+
switch (e.type) {
|
|
984
|
+
case "tool-output-available": {
|
|
985
|
+
let t = P().str("type", "tool-output-available").str("toolCallId", e.toolCallId).bool("dynamic", e.dynamic).bool("providerExecuted", e.providerExecuted).bool("preliminary", e.preliminary).build();
|
|
986
|
+
return {
|
|
987
|
+
name: w,
|
|
988
|
+
data: { output: e.output },
|
|
989
|
+
codecHeaders: t
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
case "tool-output-error": {
|
|
993
|
+
let t = P().str("type", "tool-output-error").str("toolCallId", e.toolCallId).bool("dynamic", e.dynamic).bool("providerExecuted", e.providerExecuted).build();
|
|
994
|
+
return {
|
|
995
|
+
name: w,
|
|
996
|
+
data: { errorText: e.errorText },
|
|
997
|
+
codecHeaders: t
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
case "tool-approval-request": return {
|
|
1001
|
+
name: w,
|
|
1002
|
+
data: "",
|
|
1003
|
+
codecHeaders: P().str("type", "tool-approval-request").str("toolCallId", e.toolCallId).str("approvalId", e.approvalId).build()
|
|
1004
|
+
};
|
|
1005
|
+
case "tool-output-denied": return {
|
|
1006
|
+
name: w,
|
|
1007
|
+
data: "",
|
|
1008
|
+
codecHeaders: P().str("type", "tool-output-denied").str("toolCallId", e.toolCallId).build()
|
|
1009
|
+
};
|
|
1238
1010
|
}
|
|
1239
|
-
},
|
|
1011
|
+
}, Be = (e) => {
|
|
1240
1012
|
let n = e.id, r = [];
|
|
1241
1013
|
for (let i of e.parts) switch (i.type) {
|
|
1242
1014
|
case "text":
|
|
1243
1015
|
r.push({
|
|
1244
|
-
name:
|
|
1016
|
+
name: T,
|
|
1245
1017
|
data: i.text,
|
|
1246
|
-
|
|
1018
|
+
codecHeaders: P().str("type", "text").str("messageId", n).build()
|
|
1247
1019
|
});
|
|
1248
1020
|
break;
|
|
1249
1021
|
case "file":
|
|
1250
1022
|
r.push({
|
|
1251
|
-
name:
|
|
1023
|
+
name: T,
|
|
1252
1024
|
data: i.url,
|
|
1253
|
-
|
|
1025
|
+
codecHeaders: P().str("type", "file").str("messageId", n).str("mediaType", i.mediaType).build()
|
|
1254
1026
|
});
|
|
1255
1027
|
break;
|
|
1256
1028
|
default:
|
|
1257
1029
|
t(i) && r.push({
|
|
1258
|
-
name:
|
|
1030
|
+
name: T,
|
|
1259
1031
|
data: i.data,
|
|
1260
|
-
|
|
1032
|
+
codecHeaders: P().str("type", i.type).str("messageId", n).str("id", i.id).build()
|
|
1261
1033
|
});
|
|
1262
1034
|
break;
|
|
1263
1035
|
}
|
|
1264
1036
|
return r.length === 0 && r.push({
|
|
1265
|
-
name:
|
|
1037
|
+
name: T,
|
|
1266
1038
|
data: "",
|
|
1267
|
-
|
|
1039
|
+
codecHeaders: P().str("type", "text").str("messageId", n).build()
|
|
1268
1040
|
}), r;
|
|
1269
|
-
}, G = {
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
},
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
if (n?.prepareSendMessagesRequest) {
|
|
1291
|
-
let e = n.prepareSendMessagesRequest({
|
|
1292
|
-
id: r.chatId,
|
|
1293
|
-
trigger: o,
|
|
1294
|
-
messageId: s,
|
|
1295
|
-
history: l,
|
|
1296
|
-
messages: c,
|
|
1297
|
-
forkOf: u,
|
|
1298
|
-
parent: d
|
|
1299
|
-
});
|
|
1300
|
-
f = e.body ?? {}, p = e.headers;
|
|
1301
|
-
} else f = {
|
|
1302
|
-
history: l.map((e) => ({
|
|
1303
|
-
message: e,
|
|
1304
|
-
headers: t.getMessageHeaders(e)
|
|
1305
|
-
})),
|
|
1306
|
-
id: r.chatId,
|
|
1307
|
-
trigger: o,
|
|
1308
|
-
...s !== void 0 && { messageId: s },
|
|
1309
|
-
...u !== void 0 && { forkOf: u },
|
|
1310
|
-
...d !== void 0 && { parent: d }
|
|
1311
|
-
}, p = void 0;
|
|
1312
|
-
let m = {
|
|
1313
|
-
body: f,
|
|
1314
|
-
headers: p
|
|
1041
|
+
}, Ve = (e, t = {}) => new Re(e, t), G = (e) => M({
|
|
1042
|
+
type: "dynamic-tool",
|
|
1043
|
+
toolCallId: e.toolCallId,
|
|
1044
|
+
toolName: e.toolName,
|
|
1045
|
+
title: e.title,
|
|
1046
|
+
providerExecuted: e.providerExecuted
|
|
1047
|
+
}), K = (e, t) => {
|
|
1048
|
+
let n = G(e);
|
|
1049
|
+
switch (t.type) {
|
|
1050
|
+
case "tool-output-available": return M({
|
|
1051
|
+
...n,
|
|
1052
|
+
state: "output-available",
|
|
1053
|
+
input: e.input,
|
|
1054
|
+
output: t.output,
|
|
1055
|
+
preliminary: t.preliminary
|
|
1056
|
+
});
|
|
1057
|
+
case "tool-output-error": return {
|
|
1058
|
+
...n,
|
|
1059
|
+
state: "output-error",
|
|
1060
|
+
input: e.input,
|
|
1061
|
+
errorText: t.errorText
|
|
1315
1062
|
};
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
},
|
|
1324
|
-
abort: () => {
|
|
1325
|
-
v.close().catch(() => {});
|
|
1063
|
+
case "tool-output-denied": return {
|
|
1064
|
+
...n,
|
|
1065
|
+
state: "output-denied",
|
|
1066
|
+
input: e.input,
|
|
1067
|
+
approval: {
|
|
1068
|
+
id: "",
|
|
1069
|
+
approved: !1
|
|
1326
1070
|
}
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
}
|
|
1071
|
+
};
|
|
1072
|
+
case "tool-approval-request": return {
|
|
1073
|
+
...n,
|
|
1074
|
+
state: "approval-requested",
|
|
1075
|
+
input: e.input,
|
|
1076
|
+
approval: { id: t.approvalId }
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
}, He = () => ({
|
|
1080
|
+
messages: [],
|
|
1081
|
+
conflictSerials: /* @__PURE__ */ new Map(),
|
|
1082
|
+
trackers: /* @__PURE__ */ new Map(),
|
|
1083
|
+
pendingToolResolutions: []
|
|
1084
|
+
}), Ue = (e, t, n) => {
|
|
1085
|
+
if (n.serial) {
|
|
1086
|
+
let r = Ge(t, n);
|
|
1087
|
+
if (r !== void 0) {
|
|
1088
|
+
let t = e.conflictSerials.get(r);
|
|
1089
|
+
if (t !== void 0 && n.serial <= t) return e;
|
|
1090
|
+
e.conflictSerials.set(r, n.serial);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
if (We(t)) switch (t.kind) {
|
|
1094
|
+
case "user-message":
|
|
1095
|
+
Ke(e, t.message, n);
|
|
1096
|
+
break;
|
|
1097
|
+
case "regenerate": break;
|
|
1098
|
+
case "tool-result":
|
|
1099
|
+
qe(e, t, n);
|
|
1100
|
+
break;
|
|
1101
|
+
case "tool-result-error":
|
|
1102
|
+
Je(e, t, n);
|
|
1103
|
+
break;
|
|
1104
|
+
case "tool-approval-response":
|
|
1105
|
+
Ye(e, t, n);
|
|
1106
|
+
break;
|
|
1107
|
+
}
|
|
1108
|
+
else $e(e, t, n);
|
|
1109
|
+
return e.pendingToolResolutions.length > 0 && Qe(e), e;
|
|
1110
|
+
}, We = (e) => "kind" in e, Ge = (e, t) => {
|
|
1111
|
+
if (We(e)) switch (e.kind) {
|
|
1112
|
+
case "user-message": return t.messageId === void 0 ? void 0 : `user-msg:${t.messageId}`;
|
|
1113
|
+
case "tool-approval-response": return `tool-approval:${e.payload.toolCallId}`;
|
|
1114
|
+
case "tool-result":
|
|
1115
|
+
case "tool-result-error": return `tool-output:${e.payload.toolCallId}`;
|
|
1116
|
+
case "regenerate": return;
|
|
1117
|
+
}
|
|
1118
|
+
switch (e.type) {
|
|
1119
|
+
case "tool-input-start":
|
|
1120
|
+
case "tool-input-available":
|
|
1121
|
+
case "tool-input-error": return `${e.type}:${e.toolCallId}`;
|
|
1122
|
+
case "tool-output-available":
|
|
1123
|
+
case "tool-output-error":
|
|
1124
|
+
case "tool-output-denied":
|
|
1125
|
+
case "tool-approval-request": return `tool-output:${e.toolCallId}`;
|
|
1126
|
+
case "text-start":
|
|
1127
|
+
case "text-end":
|
|
1128
|
+
case "reasoning-start":
|
|
1129
|
+
case "reasoning-end": return `${e.type}:${t.messageId ?? ""}:${e.id}`;
|
|
1130
|
+
case "finish":
|
|
1131
|
+
case "message-metadata": return `${e.type}:${t.messageId ?? ""}`;
|
|
1132
|
+
default: return;
|
|
1133
|
+
}
|
|
1134
|
+
}, Ke = (e, t, n) => {
|
|
1135
|
+
let r = n.messageId;
|
|
1136
|
+
if (r === void 0) return e.messages.push({
|
|
1137
|
+
codecMessageId: t.id,
|
|
1138
|
+
message: t
|
|
1139
|
+
}), e;
|
|
1140
|
+
let i = e.messages.findIndex((e) => e.codecMessageId === r);
|
|
1141
|
+
return i === -1 ? e.messages.push({
|
|
1142
|
+
codecMessageId: r,
|
|
1143
|
+
message: t
|
|
1144
|
+
}) : e.messages[i] = {
|
|
1145
|
+
codecMessageId: r,
|
|
1146
|
+
message: t
|
|
1147
|
+
}, e;
|
|
1148
|
+
}, qe = (e, t, n) => {
|
|
1149
|
+
let { toolCallId: r, output: i } = t.payload, a = q(e, t.codecMessageId, r);
|
|
1150
|
+
return a ? (a.message.parts[a.tracker.partIndex] = K(a.part, {
|
|
1151
|
+
type: "tool-output-available",
|
|
1152
|
+
toolCallId: r,
|
|
1153
|
+
output: i
|
|
1154
|
+
}), e) : (e.pendingToolResolutions.push({
|
|
1155
|
+
targetCodecMessageId: t.codecMessageId,
|
|
1156
|
+
toolCallId: r,
|
|
1157
|
+
serial: n.serial,
|
|
1158
|
+
resolution: {
|
|
1159
|
+
kind: "tool-result",
|
|
1160
|
+
output: i
|
|
1161
|
+
}
|
|
1162
|
+
}), e);
|
|
1163
|
+
}, Je = (e, t, n) => {
|
|
1164
|
+
let { toolCallId: r, message: i } = t.payload, a = q(e, t.codecMessageId, r);
|
|
1165
|
+
return a ? (a.message.parts[a.tracker.partIndex] = K(a.part, {
|
|
1166
|
+
type: "tool-output-error",
|
|
1167
|
+
toolCallId: r,
|
|
1168
|
+
errorText: i
|
|
1169
|
+
}), e) : (e.pendingToolResolutions.push({
|
|
1170
|
+
targetCodecMessageId: t.codecMessageId,
|
|
1171
|
+
toolCallId: r,
|
|
1172
|
+
serial: n.serial,
|
|
1173
|
+
resolution: {
|
|
1174
|
+
kind: "tool-result-error",
|
|
1175
|
+
message: i
|
|
1176
|
+
}
|
|
1177
|
+
}), e);
|
|
1178
|
+
}, Ye = (e, t, n) => {
|
|
1179
|
+
let { toolCallId: r, approved: i, reason: a } = t.payload, o = q(e, t.codecMessageId, r);
|
|
1180
|
+
return o ? (o.message.parts[o.tracker.partIndex] = Ze(o.part, i, a), e) : (e.pendingToolResolutions.push({
|
|
1181
|
+
targetCodecMessageId: t.codecMessageId,
|
|
1182
|
+
toolCallId: r,
|
|
1183
|
+
serial: n.serial,
|
|
1184
|
+
resolution: {
|
|
1185
|
+
kind: "tool-approval-response",
|
|
1186
|
+
approved: i,
|
|
1187
|
+
...a === void 0 ? {} : { reason: a }
|
|
1188
|
+
}
|
|
1189
|
+
}), e);
|
|
1190
|
+
}, q = (e, t, n) => {
|
|
1191
|
+
let r = e.messages.find((e) => e.codecMessageId === t);
|
|
1192
|
+
if (!r) return;
|
|
1193
|
+
let i = Y(e, t), a = X(r.message, i, n);
|
|
1194
|
+
if (a) return {
|
|
1195
|
+
message: r.message,
|
|
1196
|
+
tracker: a.tracker,
|
|
1197
|
+
part: a.part
|
|
1198
|
+
};
|
|
1199
|
+
}, Xe = (e, t) => {
|
|
1200
|
+
for (let n of e.messages) {
|
|
1201
|
+
let r = e.trackers.get(n.codecMessageId);
|
|
1202
|
+
if (!r) continue;
|
|
1203
|
+
let i = X(n.message, r, t);
|
|
1204
|
+
if (i) return {
|
|
1205
|
+
message: n.message,
|
|
1206
|
+
tracker: i.tracker,
|
|
1207
|
+
part: i.part
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
}, Ze = (e, t, n) => t ? {
|
|
1211
|
+
...G(e),
|
|
1212
|
+
state: "approval-responded",
|
|
1213
|
+
input: "input" in e ? e.input : void 0,
|
|
1214
|
+
approval: {
|
|
1215
|
+
id: "approval" in e && e.approval ? e.approval.id : "",
|
|
1216
|
+
approved: !0,
|
|
1217
|
+
...n === void 0 ? {} : { reason: n }
|
|
1218
|
+
}
|
|
1219
|
+
} : K(e, {
|
|
1220
|
+
type: "tool-output-denied",
|
|
1221
|
+
toolCallId: e.toolCallId,
|
|
1222
|
+
...n === void 0 ? {} : { reason: n }
|
|
1223
|
+
}), Qe = (e) => {
|
|
1224
|
+
let t = [];
|
|
1225
|
+
for (let n of e.pendingToolResolutions) {
|
|
1226
|
+
let r = q(e, n.targetCodecMessageId, n.toolCallId);
|
|
1227
|
+
if (!r) {
|
|
1228
|
+
t.push(n);
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
switch (n.resolution.kind) {
|
|
1232
|
+
case "tool-result":
|
|
1233
|
+
r.message.parts[r.tracker.partIndex] = K(r.part, {
|
|
1234
|
+
type: "tool-output-available",
|
|
1235
|
+
toolCallId: n.toolCallId,
|
|
1236
|
+
output: n.resolution.output
|
|
1237
|
+
});
|
|
1238
|
+
break;
|
|
1239
|
+
case "tool-result-error":
|
|
1240
|
+
r.message.parts[r.tracker.partIndex] = K(r.part, {
|
|
1241
|
+
type: "tool-output-error",
|
|
1242
|
+
toolCallId: n.toolCallId,
|
|
1243
|
+
errorText: n.resolution.message
|
|
1244
|
+
});
|
|
1245
|
+
break;
|
|
1246
|
+
case "tool-approval-response":
|
|
1247
|
+
r.message.parts[r.tracker.partIndex] = Ze(r.part, n.resolution.approved, n.resolution.reason);
|
|
1248
|
+
break;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
e.pendingToolResolutions = t;
|
|
1252
|
+
}, $e = (e, t, n) => {
|
|
1253
|
+
let r = n.messageId;
|
|
1254
|
+
if (r === void 0) return e;
|
|
1255
|
+
switch (t.type) {
|
|
1256
|
+
case "start":
|
|
1257
|
+
case "start-step":
|
|
1258
|
+
case "finish-step":
|
|
1259
|
+
case "finish":
|
|
1260
|
+
case "abort":
|
|
1261
|
+
case "error":
|
|
1262
|
+
case "message-metadata": return et(e, t, r);
|
|
1263
|
+
case "text-start":
|
|
1264
|
+
case "text-delta":
|
|
1265
|
+
case "text-end":
|
|
1266
|
+
case "reasoning-start":
|
|
1267
|
+
case "reasoning-delta":
|
|
1268
|
+
case "reasoning-end": return tt(e, t, r);
|
|
1269
|
+
case "tool-input-start":
|
|
1270
|
+
case "tool-input-delta":
|
|
1271
|
+
case "tool-input-available":
|
|
1272
|
+
case "tool-input-error": return nt(e, t, r);
|
|
1273
|
+
case "tool-output-available":
|
|
1274
|
+
case "tool-output-error":
|
|
1275
|
+
case "tool-output-denied":
|
|
1276
|
+
case "tool-approval-request": return rt(e, t, r);
|
|
1277
|
+
case "file":
|
|
1278
|
+
case "source-url":
|
|
1279
|
+
case "source-document": return it(e, t, r);
|
|
1280
|
+
default: return t.type.startsWith("data-") ? at(e, t, r) : e;
|
|
1281
|
+
}
|
|
1282
|
+
}, J = (e, t) => {
|
|
1283
|
+
let n = e.messages.find((e) => e.codecMessageId === t);
|
|
1284
|
+
return n || (n = {
|
|
1285
|
+
codecMessageId: t,
|
|
1286
|
+
message: {
|
|
1287
|
+
id: t,
|
|
1288
|
+
role: "assistant",
|
|
1289
|
+
parts: []
|
|
1290
|
+
}
|
|
1291
|
+
}, e.messages.push(n)), n.message;
|
|
1292
|
+
}, Y = (e, t) => {
|
|
1293
|
+
let n = e.trackers.get(t);
|
|
1294
|
+
return n || (n = {
|
|
1295
|
+
text: /* @__PURE__ */ new Map(),
|
|
1296
|
+
reasoning: /* @__PURE__ */ new Map(),
|
|
1297
|
+
tools: /* @__PURE__ */ new Map()
|
|
1298
|
+
}, e.trackers.set(t, n)), n;
|
|
1299
|
+
}, X = (e, t, n) => {
|
|
1300
|
+
let r = t.tools.get(n);
|
|
1301
|
+
if (!r) return;
|
|
1302
|
+
let i = e.parts[r.partIndex];
|
|
1303
|
+
if (i?.type === "dynamic-tool") return {
|
|
1304
|
+
tracker: r,
|
|
1305
|
+
part: i
|
|
1306
|
+
};
|
|
1307
|
+
}, et = (e, t, n) => {
|
|
1308
|
+
switch (t.type) {
|
|
1309
|
+
case "start": {
|
|
1310
|
+
let r = J(e, n);
|
|
1311
|
+
return t.messageId !== void 0 && (r.id = t.messageId), t.messageMetadata !== void 0 && (r.metadata = t.messageMetadata), e;
|
|
1312
|
+
}
|
|
1313
|
+
case "start-step": return J(e, n).parts.push({ type: "step-start" }), e;
|
|
1314
|
+
case "finish-step": {
|
|
1315
|
+
let t = e.trackers.get(n);
|
|
1316
|
+
return t && (t.text.clear(), t.reasoning.clear()), e;
|
|
1317
|
+
}
|
|
1318
|
+
case "finish": {
|
|
1319
|
+
let r = e.messages.find((e) => e.codecMessageId === n)?.message;
|
|
1320
|
+
return r && t.messageMetadata !== void 0 && (r.metadata = t.messageMetadata), e;
|
|
1321
|
+
}
|
|
1322
|
+
case "abort":
|
|
1323
|
+
case "error": return e;
|
|
1324
|
+
case "message-metadata": {
|
|
1325
|
+
let r = e.messages.find((e) => e.codecMessageId === n)?.message;
|
|
1326
|
+
return r && t.messageMetadata !== void 0 && (r.metadata = t.messageMetadata), e;
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
}, tt = (e, t, n) => {
|
|
1330
|
+
let r = J(e, n), i = Y(e, n), a = t.type.startsWith("text-"), o = a ? "text" : "reasoning", s = a ? i.text : i.reasoning;
|
|
1331
|
+
switch (t.type) {
|
|
1332
|
+
case "text-start":
|
|
1333
|
+
case "reasoning-start": return s.set(t.id, r.parts.length), r.parts.push({
|
|
1334
|
+
type: o,
|
|
1335
|
+
text: ""
|
|
1336
|
+
}), e;
|
|
1337
|
+
case "text-delta":
|
|
1338
|
+
case "reasoning-delta": {
|
|
1339
|
+
let n = s.get(t.id);
|
|
1340
|
+
if (n === void 0) return e;
|
|
1341
|
+
let i = r.parts[n];
|
|
1342
|
+
return i?.type === o && (i.text += t.delta), e;
|
|
1343
|
+
}
|
|
1344
|
+
case "text-end":
|
|
1345
|
+
case "reasoning-end": return s.delete(t.id), e;
|
|
1346
|
+
}
|
|
1347
|
+
}, nt = (e, t, n) => {
|
|
1348
|
+
let r = J(e, n), i = Y(e, n);
|
|
1349
|
+
switch (t.type) {
|
|
1350
|
+
case "tool-input-start": {
|
|
1351
|
+
let n = r.parts.length;
|
|
1352
|
+
return r.parts.push({
|
|
1353
|
+
...G(t),
|
|
1354
|
+
state: "input-streaming",
|
|
1355
|
+
input: void 0
|
|
1356
|
+
}), i.tools.set(t.toolCallId, {
|
|
1357
|
+
partIndex: n,
|
|
1358
|
+
inputText: ""
|
|
1359
|
+
}), e;
|
|
1360
|
+
}
|
|
1361
|
+
case "tool-input-delta": {
|
|
1362
|
+
let n = i.tools.get(t.toolCallId);
|
|
1363
|
+
if (!n) return e;
|
|
1364
|
+
n.inputText += t.inputTextDelta;
|
|
1365
|
+
let a;
|
|
1366
|
+
try {
|
|
1367
|
+
a = JSON.parse(n.inputText);
|
|
1368
|
+
} catch {
|
|
1369
|
+
a = void 0;
|
|
1370
|
+
}
|
|
1371
|
+
let o = X(r, i, t.toolCallId);
|
|
1372
|
+
return o && (r.parts[o.tracker.partIndex] = {
|
|
1373
|
+
...G(o.part),
|
|
1374
|
+
state: "input-streaming",
|
|
1375
|
+
input: a
|
|
1376
|
+
}), e;
|
|
1377
|
+
}
|
|
1378
|
+
case "tool-input-available": {
|
|
1379
|
+
let n = X(r, i, t.toolCallId);
|
|
1380
|
+
return n && (r.parts[n.tracker.partIndex] = {
|
|
1381
|
+
...G(n.part),
|
|
1382
|
+
state: "input-available",
|
|
1383
|
+
input: t.input
|
|
1384
|
+
}), e;
|
|
1385
|
+
}
|
|
1386
|
+
case "tool-input-error": {
|
|
1387
|
+
let n = X(r, i, t.toolCallId);
|
|
1388
|
+
if (n) r.parts[n.tracker.partIndex] = {
|
|
1389
|
+
...G(n.part),
|
|
1390
|
+
state: "output-error",
|
|
1391
|
+
input: t.input,
|
|
1392
|
+
errorText: t.errorText
|
|
1393
|
+
};
|
|
1394
|
+
else {
|
|
1395
|
+
let e = r.parts.length;
|
|
1396
|
+
r.parts.push({
|
|
1397
|
+
...G(t),
|
|
1398
|
+
state: "output-error",
|
|
1399
|
+
input: t.input,
|
|
1400
|
+
errorText: t.errorText
|
|
1401
|
+
}), i.tools.set(t.toolCallId, {
|
|
1402
|
+
partIndex: e,
|
|
1403
|
+
inputText: ""
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
return e;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
}, rt = (e, t, n) => {
|
|
1410
|
+
if (t.type === "tool-output-available" || t.type === "tool-output-error") {
|
|
1411
|
+
let n = Xe(e, t.toolCallId);
|
|
1412
|
+
return n && (n.message.parts[n.tracker.partIndex] = K(n.part, t)), e;
|
|
1413
|
+
}
|
|
1414
|
+
let r = J(e, n), i = X(r, Y(e, n), t.toolCallId);
|
|
1415
|
+
return i && (r.parts[i.tracker.partIndex] = K(i.part, t)), e;
|
|
1416
|
+
}, it = (e, t, n) => {
|
|
1417
|
+
let r = J(e, n);
|
|
1418
|
+
switch (t.type) {
|
|
1419
|
+
case "file": return r.parts.push({
|
|
1420
|
+
type: "file",
|
|
1421
|
+
mediaType: t.mediaType,
|
|
1422
|
+
url: t.url
|
|
1423
|
+
}), e;
|
|
1424
|
+
case "source-url": return r.parts.push(M({
|
|
1425
|
+
type: "source-url",
|
|
1426
|
+
sourceId: t.sourceId,
|
|
1427
|
+
url: t.url,
|
|
1428
|
+
title: t.title
|
|
1429
|
+
})), e;
|
|
1430
|
+
case "source-document": return r.parts.push(M({
|
|
1431
|
+
type: "source-document",
|
|
1432
|
+
sourceId: t.sourceId,
|
|
1433
|
+
mediaType: t.mediaType,
|
|
1434
|
+
title: t.title,
|
|
1435
|
+
filename: t.filename
|
|
1436
|
+
})), e;
|
|
1437
|
+
}
|
|
1438
|
+
}, at = (e, t, n) => {
|
|
1439
|
+
if (t.transient) return e;
|
|
1440
|
+
let r = J(e, n), i = M({
|
|
1441
|
+
type: t.type,
|
|
1442
|
+
id: t.id,
|
|
1443
|
+
data: t.data
|
|
1444
|
+
});
|
|
1445
|
+
if (t.id !== void 0) {
|
|
1446
|
+
let n = r.parts.findIndex((e) => e.type === t.type && "id" in e && e.id === t.id);
|
|
1447
|
+
if (n !== -1) return r.parts[n] = i, e;
|
|
1448
|
+
}
|
|
1449
|
+
return r.parts.push(i), e;
|
|
1450
|
+
}, Z = {
|
|
1451
|
+
adapterTag: "vercel-ai-sdk-ui-message",
|
|
1452
|
+
init: He,
|
|
1453
|
+
fold: Ue,
|
|
1454
|
+
createEncoder: Ve,
|
|
1455
|
+
createDecoder: Pe,
|
|
1456
|
+
getMessages: (e) => e.messages,
|
|
1457
|
+
createUserMessage: (e) => ({
|
|
1458
|
+
kind: "user-message",
|
|
1459
|
+
message: e
|
|
1460
|
+
}),
|
|
1461
|
+
createRegenerate: (e, t) => ({
|
|
1462
|
+
kind: "regenerate",
|
|
1463
|
+
target: e,
|
|
1464
|
+
parent: t
|
|
1465
|
+
}),
|
|
1466
|
+
createToolResult: (e, t) => ({
|
|
1467
|
+
kind: "tool-result",
|
|
1468
|
+
codecMessageId: e,
|
|
1469
|
+
payload: t
|
|
1470
|
+
}),
|
|
1471
|
+
createToolResultError: (e, t) => ({
|
|
1472
|
+
kind: "tool-result-error",
|
|
1473
|
+
codecMessageId: e,
|
|
1474
|
+
payload: t
|
|
1475
|
+
}),
|
|
1476
|
+
createToolApprovalResponse: (e, t) => ({
|
|
1477
|
+
kind: "tool-approval-response",
|
|
1478
|
+
codecMessageId: e,
|
|
1479
|
+
payload: t
|
|
1480
|
+
})
|
|
1481
|
+
}, ot = (e) => ({
|
|
1334
1482
|
logAction: (t, n, r) => {
|
|
1335
1483
|
e.error(n, { detail: r });
|
|
1336
1484
|
},
|
|
1337
1485
|
shouldLog: () => !0
|
|
1338
|
-
}),
|
|
1486
|
+
}), st = e.Realtime.EventEmitter, Q = class extends st {
|
|
1339
1487
|
constructor(e) {
|
|
1340
|
-
super(
|
|
1488
|
+
super(ot(e));
|
|
1341
1489
|
}
|
|
1342
|
-
},
|
|
1490
|
+
}, ct = /* @__PURE__ */ function(e) {
|
|
1343
1491
|
return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
|
|
1344
|
-
}({}),
|
|
1492
|
+
}({}), lt = (e, t, n) => {
|
|
1345
1493
|
let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
|
|
1346
1494
|
switch (t) {
|
|
1347
|
-
case
|
|
1348
|
-
case
|
|
1495
|
+
case "trace":
|
|
1496
|
+
case "debug":
|
|
1349
1497
|
console.log(i);
|
|
1350
1498
|
break;
|
|
1351
|
-
case
|
|
1499
|
+
case "info":
|
|
1352
1500
|
console.info(i);
|
|
1353
1501
|
break;
|
|
1354
|
-
case
|
|
1502
|
+
case "warn":
|
|
1355
1503
|
console.warn(i);
|
|
1356
1504
|
break;
|
|
1357
|
-
case
|
|
1505
|
+
case "error":
|
|
1358
1506
|
console.error(i);
|
|
1359
1507
|
break;
|
|
1360
|
-
case
|
|
1361
|
-
}
|
|
1362
|
-
},
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
[
|
|
1366
|
-
[
|
|
1367
|
-
[
|
|
1368
|
-
[
|
|
1369
|
-
|
|
1370
|
-
[K.Silent, q.Silent]
|
|
1371
|
-
]), Le = class t {
|
|
1508
|
+
case "silent": break;
|
|
1509
|
+
}
|
|
1510
|
+
}, ut = (e) => new ft(e.logHandler ?? lt, e.logLevel), dt = new Map([
|
|
1511
|
+
["trace", 0],
|
|
1512
|
+
["debug", 1],
|
|
1513
|
+
["info", 2],
|
|
1514
|
+
["warn", 3],
|
|
1515
|
+
["error", 4],
|
|
1516
|
+
["silent", 5]
|
|
1517
|
+
]), ft = class t {
|
|
1372
1518
|
constructor(t, n, r) {
|
|
1373
1519
|
this._handler = t, this._context = r;
|
|
1374
|
-
let i =
|
|
1520
|
+
let i = dt.get(n);
|
|
1375
1521
|
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, W.InvalidArgument, 400);
|
|
1376
1522
|
this._levelNumber = i;
|
|
1377
1523
|
}
|
|
1378
1524
|
trace(e, t) {
|
|
1379
|
-
this._write(e,
|
|
1525
|
+
this._write(e, "trace", 0, t);
|
|
1380
1526
|
}
|
|
1381
1527
|
debug(e, t) {
|
|
1382
|
-
this._write(e,
|
|
1528
|
+
this._write(e, "debug", 1, t);
|
|
1383
1529
|
}
|
|
1384
1530
|
info(e, t) {
|
|
1385
|
-
this._write(e,
|
|
1531
|
+
this._write(e, "info", 2, t);
|
|
1386
1532
|
}
|
|
1387
1533
|
warn(e, t) {
|
|
1388
|
-
this._write(e,
|
|
1534
|
+
this._write(e, "warn", 3, t);
|
|
1389
1535
|
}
|
|
1390
1536
|
error(e, t) {
|
|
1391
|
-
this._write(e,
|
|
1537
|
+
this._write(e, "error", 4, t);
|
|
1392
1538
|
}
|
|
1393
1539
|
withContext(e) {
|
|
1394
|
-
let n = [...
|
|
1540
|
+
let n = [...dt.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? "error";
|
|
1395
1541
|
return new t(this._handler, n, this._mergeContext(e));
|
|
1396
1542
|
}
|
|
1397
1543
|
_write(e, t, n, r) {
|
|
@@ -1403,929 +1549,1906 @@ var n = "x-ably-stream", r = "x-ably-status", i = "x-ably-stream-id", a = "x-abl
|
|
|
1403
1549
|
...e
|
|
1404
1550
|
} : this._context : e ?? void 0;
|
|
1405
1551
|
}
|
|
1406
|
-
},
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
}
|
|
1414
|
-
_insertSorted(e) {
|
|
1415
|
-
if (e.node.serial === void 0) {
|
|
1416
|
-
this._sortedList.push(e);
|
|
1417
|
-
return;
|
|
1552
|
+
}, pt = (e) => e.type === "finish" || e.type === "error" || e.type === "abort", mt = (t, n, r) => {
|
|
1553
|
+
let i = {}, a = [], o = new ReadableStream({
|
|
1554
|
+
start: (e) => {
|
|
1555
|
+
i.controller = e;
|
|
1556
|
+
},
|
|
1557
|
+
cancel: () => {
|
|
1558
|
+
u();
|
|
1418
1559
|
}
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1560
|
+
}), { controller: s } = i;
|
|
1561
|
+
if (!s) throw new e.ErrorInfo("unable to create run stream; ReadableStream start() was not called synchronously", W.SessionSubscriptionError, 500);
|
|
1562
|
+
let c;
|
|
1563
|
+
n.then((e) => {
|
|
1564
|
+
c = e;
|
|
1565
|
+
}, () => {});
|
|
1566
|
+
let l = !1, u = () => {
|
|
1567
|
+
for (let e of a) e();
|
|
1568
|
+
a.length = 0;
|
|
1569
|
+
}, d = (e) => {
|
|
1570
|
+
if (!l) {
|
|
1571
|
+
l = !0;
|
|
1572
|
+
try {
|
|
1573
|
+
e();
|
|
1574
|
+
} catch {}
|
|
1575
|
+
u();
|
|
1424
1576
|
}
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
n = e.node, r.add(n.msgId);
|
|
1447
|
-
}
|
|
1448
|
-
let i = n.parentId, a = n.msgId, o = [], s = this._parentIndex.get(i);
|
|
1449
|
-
if (s) for (let e of s) {
|
|
1450
|
-
let t = this._nodeIndex.get(e);
|
|
1451
|
-
t && this._isSiblingOf(t.node, a) && o.push(t);
|
|
1577
|
+
}, f = () => {
|
|
1578
|
+
d(() => {
|
|
1579
|
+
s.close();
|
|
1580
|
+
});
|
|
1581
|
+
}, p = (e) => {
|
|
1582
|
+
d(() => {
|
|
1583
|
+
s.error(e);
|
|
1584
|
+
});
|
|
1585
|
+
};
|
|
1586
|
+
return a.push(t.tree.on("output", (e) => {
|
|
1587
|
+
if (e.inputCodecMessageId === r) for (let t of e.events) {
|
|
1588
|
+
try {
|
|
1589
|
+
s.enqueue(t);
|
|
1590
|
+
} catch {
|
|
1591
|
+
f();
|
|
1592
|
+
return;
|
|
1593
|
+
}
|
|
1594
|
+
if (pt(t)) {
|
|
1595
|
+
f();
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1452
1598
|
}
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1599
|
+
}), t.tree.on("run", (e) => {
|
|
1600
|
+
e.type === "end" && c !== void 0 && e.runId === c && f();
|
|
1601
|
+
}), t.on("error", (e) => {
|
|
1602
|
+
p(e);
|
|
1603
|
+
})), {
|
|
1604
|
+
stream: o,
|
|
1605
|
+
close: f,
|
|
1606
|
+
error: p
|
|
1607
|
+
};
|
|
1608
|
+
}, ht = (e) => {
|
|
1609
|
+
let t, n = new Promise((e) => {
|
|
1610
|
+
t = e;
|
|
1611
|
+
}), r = new TransformStream({ flush: () => {
|
|
1612
|
+
t();
|
|
1613
|
+
} }), i = new AbortController();
|
|
1614
|
+
return e.pipeTo(r.writable, {
|
|
1615
|
+
signal: i.signal,
|
|
1616
|
+
preventCancel: !0
|
|
1617
|
+
}).catch(() => {
|
|
1618
|
+
t();
|
|
1619
|
+
}), {
|
|
1620
|
+
stream: r.readable,
|
|
1621
|
+
done: n,
|
|
1622
|
+
fail: (e) => {
|
|
1623
|
+
i.abort(e);
|
|
1464
1624
|
}
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
let r = this._selections.get(e) ?? s.length - 1, i = s[Math.max(0, Math.min(r, s.length - 1))];
|
|
1488
|
-
if (!i) break;
|
|
1489
|
-
t = i.msgId, n.set(e, t);
|
|
1490
|
-
}
|
|
1491
|
-
if (a !== t) continue;
|
|
1625
|
+
};
|
|
1626
|
+
}, gt = (e) => (e.type === "dynamic-tool" || e.type.startsWith("tool-")) && "toolCallId" in e && "state" in e, _t = (e) => e.role === "assistant" && e.parts.some((e) => gt(e) && (e.state === "input-streaming" || e.state === "input-available" || e.state === "approval-requested")), vt = new Set([
|
|
1627
|
+
"input-streaming",
|
|
1628
|
+
"input-available",
|
|
1629
|
+
"approval-requested"
|
|
1630
|
+
]), yt = (e, t) => {
|
|
1631
|
+
let n = [];
|
|
1632
|
+
for (let r of t) {
|
|
1633
|
+
if (r.role !== "assistant") continue;
|
|
1634
|
+
let t = e.find((e) => e.message.id === r.id);
|
|
1635
|
+
if (!t) continue;
|
|
1636
|
+
let { codecMessageId: i, message: a } = t;
|
|
1637
|
+
for (let e of r.parts) {
|
|
1638
|
+
if (!gt(e)) continue;
|
|
1639
|
+
let t = a.parts.find((t) => gt(t) && t.toolCallId === e.toolCallId);
|
|
1640
|
+
if (e.state === "approval-responded" && (!t || t.state === "approval-requested")) {
|
|
1641
|
+
n.push(Z.createToolApprovalResponse(i, {
|
|
1642
|
+
toolCallId: e.toolCallId,
|
|
1643
|
+
approved: e.approval.approved,
|
|
1644
|
+
...e.approval.reason === void 0 ? {} : { reason: e.approval.reason }
|
|
1645
|
+
}));
|
|
1646
|
+
continue;
|
|
1492
1647
|
}
|
|
1493
|
-
t.
|
|
1648
|
+
e.state !== "output-available" && e.state !== "output-error" || t && !vt.has(t.state) || (e.state === "output-available" ? n.push(Z.createToolResult(i, {
|
|
1649
|
+
toolCallId: e.toolCallId,
|
|
1650
|
+
output: e.output
|
|
1651
|
+
})) : n.push(Z.createToolResultError(i, {
|
|
1652
|
+
toolCallId: e.toolCallId,
|
|
1653
|
+
message: e.errorText
|
|
1654
|
+
})));
|
|
1494
1655
|
}
|
|
1495
|
-
return e;
|
|
1496
1656
|
}
|
|
1497
|
-
|
|
1498
|
-
|
|
1657
|
+
return n;
|
|
1658
|
+
}, bt = (e, t) => {
|
|
1659
|
+
let n = e.findIndex((e) => e.message.id === t);
|
|
1660
|
+
if (!(n <= 0)) return e[n - 1]?.codecMessageId;
|
|
1661
|
+
}, xt = (t, n) => {
|
|
1662
|
+
let r = n?.api ?? "/api/chat", i = n?.fetch ?? globalThis.fetch.bind(globalThis), a = n?.credentials, o = !1, s = new Q(ut({ logLevel: ct.Silent })), c = (e) => {
|
|
1663
|
+
o = e, s.emit("streaming", e);
|
|
1664
|
+
};
|
|
1665
|
+
return {
|
|
1666
|
+
sendMessages: async (o) => {
|
|
1667
|
+
let { messages: s, abortSignal: l, trigger: u, messageId: d } = o, f = t.view.getMessages(), p = new Map(f.map((e) => [e.message.id, e.codecMessageId])), m = (e) => p.get(e), h = s.at(-1), g = !!h && p.has(h.id), _ = u === "submit-message" && h?.role === "assistant" && g, v = u === "submit-message" && !d && h?.role === "user" ? s.at(-2) : void 0, y = v && _t(v) && p.has(v.id) ? v.id : void 0, b, x;
|
|
1668
|
+
if (u === "regenerate-message" || _) b = [], x = s;
|
|
1669
|
+
else {
|
|
1670
|
+
if (s.length === 0) throw new e.ErrorInfo("unable to send messages; messages array is empty for submit-message trigger", W.InvalidArgument, 400);
|
|
1671
|
+
b = [s.at(-1)], x = y ? s.slice(0, -2) : s.slice(0, -1);
|
|
1672
|
+
}
|
|
1673
|
+
let S, C;
|
|
1674
|
+
u === "submit-message" && d && !_ ? (S = m(d), C = bt(f, d)) : y && (S = m(y), C = bt(f, y));
|
|
1675
|
+
let w, T;
|
|
1676
|
+
if (n?.prepareSendMessagesRequest) {
|
|
1677
|
+
let e = n.prepareSendMessagesRequest({
|
|
1678
|
+
chatId: o.chatId,
|
|
1679
|
+
trigger: u,
|
|
1680
|
+
messageId: d,
|
|
1681
|
+
history: x,
|
|
1682
|
+
messages: b,
|
|
1683
|
+
forkOf: S,
|
|
1684
|
+
parent: C
|
|
1685
|
+
});
|
|
1686
|
+
w = e.body ?? {}, T = e.headers;
|
|
1687
|
+
} else w = {}, T = void 0;
|
|
1688
|
+
let E = {};
|
|
1689
|
+
if (S !== void 0 && (E.forkOf = S), C !== void 0 && (E.parent = C), _) {
|
|
1690
|
+
let e = m(h.id), n = e === void 0 ? void 0 : t.view.runOf(e);
|
|
1691
|
+
n && (E.runId = n.runId);
|
|
1692
|
+
}
|
|
1693
|
+
let D;
|
|
1694
|
+
if (_) {
|
|
1695
|
+
let e = yt(f, s);
|
|
1696
|
+
D = await t.view.send(e, E);
|
|
1697
|
+
} else if (u === "regenerate-message") {
|
|
1698
|
+
if (d === void 0) throw new e.ErrorInfo("unable to regenerate; regenerate-message trigger fired without messageId", W.InvalidArgument, 400);
|
|
1699
|
+
let n = m(d);
|
|
1700
|
+
if (n === void 0) throw new e.ErrorInfo(`unable to regenerate; message not visible: ${d}`, W.InvalidArgument, 400);
|
|
1701
|
+
D = await t.view.regenerate(n, E);
|
|
1702
|
+
} else {
|
|
1703
|
+
let e = b.map((e) => Z.createUserMessage(e));
|
|
1704
|
+
D = await t.view.send(e, E);
|
|
1705
|
+
}
|
|
1706
|
+
let O = mt(t, D.runId, D.inputCodecMessageId);
|
|
1707
|
+
if (l) {
|
|
1708
|
+
let e = () => {
|
|
1709
|
+
D.cancel(), O.close();
|
|
1710
|
+
};
|
|
1711
|
+
l.aborted ? e() : l.addEventListener("abort", e, { once: !0 });
|
|
1712
|
+
}
|
|
1713
|
+
let { stream: ee, done: te, fail: k } = ht(O.stream);
|
|
1714
|
+
c(!0), te.then(() => {
|
|
1715
|
+
c(!1);
|
|
1716
|
+
});
|
|
1717
|
+
let A = {
|
|
1718
|
+
...w,
|
|
1719
|
+
...D.toInvocation().toJSON()
|
|
1720
|
+
};
|
|
1721
|
+
return i(r, {
|
|
1722
|
+
method: "POST",
|
|
1723
|
+
headers: {
|
|
1724
|
+
"Content-Type": "application/json",
|
|
1725
|
+
...T
|
|
1726
|
+
},
|
|
1727
|
+
body: JSON.stringify(A),
|
|
1728
|
+
...a ? { credentials: a } : {}
|
|
1729
|
+
}).then((t) => {
|
|
1730
|
+
t.ok || k(new e.ErrorInfo(`unable to send; HTTP POST to ${r} returned ${String(t.status)} ${t.statusText}`, W.SessionSendFailed, t.status));
|
|
1731
|
+
}).catch((t) => {
|
|
1732
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
1733
|
+
k(new e.ErrorInfo(`unable to send; HTTP POST to ${r} failed: ${t instanceof Error ? t.message : String(t)}`, W.SessionSendFailed, 500, n));
|
|
1734
|
+
}), ee;
|
|
1735
|
+
},
|
|
1736
|
+
reconnectToStream: () => Promise.resolve(null),
|
|
1737
|
+
close: async () => t.close(),
|
|
1738
|
+
get streaming() {
|
|
1739
|
+
return o;
|
|
1740
|
+
},
|
|
1741
|
+
onStreamingChange: (e) => (s.on("streaming", e), () => {
|
|
1742
|
+
s.off("streaming", e);
|
|
1743
|
+
})
|
|
1744
|
+
};
|
|
1745
|
+
}, St = "0.2.0", Ct = "ai-transport-js", wt = (e, t) => {
|
|
1746
|
+
let n = e;
|
|
1747
|
+
return n.options.agents = {
|
|
1748
|
+
...n.options.agents,
|
|
1749
|
+
...t
|
|
1750
|
+
}, { params: { agent: Object.entries(t).map(([e, t]) => `${e}/${t}`).join(" ") } };
|
|
1751
|
+
}, Tt = (e, t) => {
|
|
1752
|
+
let n = t?.adapterTag, r = { [Ct]: St };
|
|
1753
|
+
return n && (r[n] = St), wt(e, r);
|
|
1754
|
+
}, Et = (e) => {
|
|
1755
|
+
let t = {
|
|
1756
|
+
[f]: e.role,
|
|
1757
|
+
[l]: e.codecMessageId
|
|
1758
|
+
};
|
|
1759
|
+
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;
|
|
1760
|
+
}, Dt = (e) => {
|
|
1761
|
+
let t = {
|
|
1762
|
+
[o]: e.runId,
|
|
1763
|
+
[u]: e.runClientId
|
|
1764
|
+
};
|
|
1765
|
+
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;
|
|
1766
|
+
}, Ot = (e) => e === "ai-run-start" || e === "ai-run-suspend" || e === "ai-run-resume" || e === "ai-run-end", kt = (e, t, n) => {
|
|
1767
|
+
let r = t[o];
|
|
1768
|
+
if (!r) return;
|
|
1769
|
+
let i = t["run-client-id"] ?? "";
|
|
1770
|
+
if (e === "ai-run-start") {
|
|
1771
|
+
let e = t[p], a = t[m], o = t[h];
|
|
1772
|
+
return {
|
|
1773
|
+
type: "start",
|
|
1774
|
+
runId: r,
|
|
1775
|
+
clientId: i,
|
|
1776
|
+
serial: n,
|
|
1777
|
+
invocationId: t["invocation-id"] ?? "",
|
|
1778
|
+
...e !== void 0 && { parent: e },
|
|
1779
|
+
...a !== void 0 && { forkOf: a },
|
|
1780
|
+
...o !== void 0 && { regenerates: o }
|
|
1781
|
+
};
|
|
1499
1782
|
}
|
|
1500
|
-
|
|
1501
|
-
|
|
1783
|
+
if (e === "ai-run-suspend") return {
|
|
1784
|
+
type: "suspend",
|
|
1785
|
+
runId: r,
|
|
1786
|
+
clientId: i,
|
|
1787
|
+
serial: n,
|
|
1788
|
+
invocationId: t["invocation-id"] ?? ""
|
|
1789
|
+
};
|
|
1790
|
+
if (e === "ai-run-resume") return {
|
|
1791
|
+
type: "resume",
|
|
1792
|
+
runId: r,
|
|
1793
|
+
clientId: i,
|
|
1794
|
+
serial: n,
|
|
1795
|
+
invocationId: t["invocation-id"] ?? ""
|
|
1796
|
+
};
|
|
1797
|
+
if (e === "ai-run-end") {
|
|
1798
|
+
let e = t["run-reason"] ?? "complete";
|
|
1799
|
+
return {
|
|
1800
|
+
type: "end",
|
|
1801
|
+
runId: r,
|
|
1802
|
+
clientId: i,
|
|
1803
|
+
serial: n,
|
|
1804
|
+
invocationId: t["invocation-id"] ?? "",
|
|
1805
|
+
reason: e
|
|
1806
|
+
};
|
|
1502
1807
|
}
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1808
|
+
}, At = (e, t, n) => {
|
|
1809
|
+
if (e.has(t) || e.size < n) return;
|
|
1810
|
+
let r = e.keys().next().value;
|
|
1811
|
+
if (r !== void 0) return e.delete(r), r;
|
|
1812
|
+
}, jt = (e, t) => {
|
|
1813
|
+
let n = [], r = /* @__PURE__ */ new Set(), i = t;
|
|
1814
|
+
for (; i !== void 0 && !r.has(i);) r.add(i), n.push(i), i = e.get(i)?.parentCodecMessageId;
|
|
1815
|
+
return n.toReversed();
|
|
1816
|
+
}, Mt = (e, t, n) => {
|
|
1817
|
+
let r = D(n), i = n.serial;
|
|
1818
|
+
if (Ot(n.name)) {
|
|
1819
|
+
let t = kt(n.name, r, i);
|
|
1820
|
+
return t && e.applyRunLifecycle(t), t;
|
|
1821
|
+
}
|
|
1822
|
+
let { inputs: a, outputs: o } = t.decode(n);
|
|
1823
|
+
(a.length > 0 || o.length > 0 || r["run-id"]) && e.applyMessage({
|
|
1824
|
+
inputs: a,
|
|
1825
|
+
outputs: o
|
|
1826
|
+
}, r, i);
|
|
1827
|
+
}, Nt = (e, t, n, r, i) => {
|
|
1828
|
+
let { inputs: a, outputs: o } = t.decode(r), s = n;
|
|
1829
|
+
for (let t of [...a, ...o]) s = e.fold(s, t, {
|
|
1830
|
+
serial: r.serial ?? "",
|
|
1831
|
+
messageId: i
|
|
1832
|
+
});
|
|
1833
|
+
return s;
|
|
1834
|
+
}, Pt = (e, t) => {
|
|
1835
|
+
let n = /* @__PURE__ */ new Set(), r = [];
|
|
1836
|
+
for (let t of e) t.serial !== void 0 && !n.has(t.serial) && (n.add(t.serial), r.push(t));
|
|
1837
|
+
if (t !== void 0) for (let e of t) e.serial !== void 0 && !n.has(e.serial) && (n.add(e.serial), r.push(e));
|
|
1838
|
+
return r.toSorted(A);
|
|
1839
|
+
}, Ft = async (e, t, n) => {
|
|
1840
|
+
let r = [], i = await e.history({ limit: t });
|
|
1841
|
+
for (r.push(...i.items); i.hasNext() && r.length < n;) {
|
|
1842
|
+
let e = await i.next();
|
|
1843
|
+
if (!e) break;
|
|
1844
|
+
r.push(...e.items), i = e;
|
|
1845
|
+
}
|
|
1846
|
+
return r;
|
|
1847
|
+
}, It = (e, t, n, r) => {
|
|
1848
|
+
let i = e.createDecoder(), a = e.init(), o = 0;
|
|
1849
|
+
for (let s of t) {
|
|
1850
|
+
let t = D(s);
|
|
1851
|
+
if (t["run-id"] !== n || Ot(s.name)) continue;
|
|
1852
|
+
let c = t[l];
|
|
1853
|
+
if (r !== void 0 && c === r) break;
|
|
1854
|
+
a = Nt(e, i, a, s, c ?? ""), o++;
|
|
1508
1855
|
}
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1856
|
+
return {
|
|
1857
|
+
projection: a,
|
|
1858
|
+
folded: o
|
|
1859
|
+
};
|
|
1860
|
+
}, Lt = (e, t, n) => {
|
|
1861
|
+
let r = e.createDecoder(), i = e.init();
|
|
1862
|
+
for (let a of t) {
|
|
1863
|
+
let t = D(a);
|
|
1864
|
+
t["run-id"] === void 0 && t["codec-message-id"] === n && (i = Nt(e, r, i, a, n));
|
|
1865
|
+
}
|
|
1866
|
+
return i;
|
|
1867
|
+
}, Rt = async (t) => {
|
|
1868
|
+
let { channel: n, codec: r, runId: i, signal: a, logger: o, liveMessages: s } = t;
|
|
1869
|
+
if (a.aborted) throw new e.ErrorInfo(`unable to load run projection; run ${i} was cancelled`, W.InvalidArgument, 400);
|
|
1870
|
+
await n.attach();
|
|
1871
|
+
let { projection: c, folded: l } = It(r, Pt(await Ft(n, 200, 2e3), s), i);
|
|
1872
|
+
return o?.debug("loadRunProjection(); folded run events", {
|
|
1873
|
+
runId: i,
|
|
1874
|
+
folded: l
|
|
1875
|
+
}), c;
|
|
1876
|
+
}, zt = async (t) => {
|
|
1877
|
+
let { channel: n, codec: r, runId: i, signal: a, logger: s, liveMessages: c, assistantParentFallback: u, pageLimit: d, maxMessages: f } = t;
|
|
1878
|
+
if (a.aborted) throw new e.ErrorInfo(`unable to load conversation; run ${i} was cancelled`, W.InvalidArgument, 400);
|
|
1879
|
+
let m = Pt(await Ft(n, d, f), c), h = /* @__PURE__ */ new Map(), g = /* @__PURE__ */ new Map();
|
|
1880
|
+
for (let e of m) {
|
|
1881
|
+
if (Ot(e.name)) continue;
|
|
1882
|
+
let t = D(e), n = t[l];
|
|
1883
|
+
if (n === void 0) continue;
|
|
1884
|
+
let r = t[o];
|
|
1885
|
+
r !== void 0 && g.set(r, n), h.has(n) || h.set(n, {
|
|
1886
|
+
runId: r,
|
|
1887
|
+
parentCodecMessageId: t[p]
|
|
1513
1888
|
});
|
|
1514
|
-
let n = this._getSiblingGroup(e);
|
|
1515
|
-
if (n.length <= 1) return;
|
|
1516
|
-
let r = this._getGroupRoot(e);
|
|
1517
|
-
this._selections.set(r, Math.max(0, Math.min(t, n.length - 1)));
|
|
1518
1889
|
}
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
let
|
|
1524
|
-
if (
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
let
|
|
1531
|
-
|
|
1532
|
-
let
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
}), o.node.serial = r, this._removeSorted(o), this._insertSorted(o));
|
|
1538
|
-
return;
|
|
1890
|
+
for (let e of m) {
|
|
1891
|
+
if (e.name !== "ai-run-start") continue;
|
|
1892
|
+
let t = D(e), n = t[o];
|
|
1893
|
+
if (n === void 0) continue;
|
|
1894
|
+
let r = g.get(n);
|
|
1895
|
+
if (r === void 0) continue;
|
|
1896
|
+
let i = h.get(r);
|
|
1897
|
+
i && i.parentCodecMessageId === void 0 && (i.parentCodecMessageId = t[p]);
|
|
1898
|
+
}
|
|
1899
|
+
let _ = [], v = 0;
|
|
1900
|
+
if (u !== void 0) {
|
|
1901
|
+
let e = jt(h, u);
|
|
1902
|
+
v = e.length;
|
|
1903
|
+
for (let t of e) {
|
|
1904
|
+
let e = h.get(t);
|
|
1905
|
+
if (e?.runId === i) continue;
|
|
1906
|
+
let n = e?.runId === void 0 ? Lt(r, m, t) : It(r, m, e.runId).projection;
|
|
1907
|
+
_.push(...r.getMessages(n).map((e) => e.message));
|
|
1539
1908
|
}
|
|
1540
|
-
this._logger.trace("ConversationTree.upsert(); inserting new node", {
|
|
1541
|
-
msgId: e,
|
|
1542
|
-
parentId: i,
|
|
1543
|
-
forkOf: a
|
|
1544
|
-
});
|
|
1545
|
-
let s = {
|
|
1546
|
-
node: {
|
|
1547
|
-
message: t,
|
|
1548
|
-
msgId: e,
|
|
1549
|
-
parentId: i,
|
|
1550
|
-
forkOf: a,
|
|
1551
|
-
headers: { ...n },
|
|
1552
|
-
serial: r
|
|
1553
|
-
},
|
|
1554
|
-
insertSeq: this._seqCounter++
|
|
1555
|
-
};
|
|
1556
|
-
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s);
|
|
1557
1909
|
}
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
}
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
e ? Object.keys(d).length > 0 && Object.assign(e, d) : (n.msgHeaders.set(p, { ...d }), m && n.msgSerials.set(p, m));
|
|
1579
|
-
}
|
|
1580
|
-
n.accumulator.processOutputs(t);
|
|
1581
|
-
} else i.processOutputs(t);
|
|
1582
|
-
for (let n of t) if (n.kind === "message") {
|
|
1583
|
-
let t = e.getMessageKey(n.message), r = c.get(t);
|
|
1584
|
-
r ? Object.keys(d).length > 0 && Object.assign(r, d) : (c.set(t, { ...d }), m && l.set(t, m));
|
|
1910
|
+
let { projection: y, folded: b } = It(r, m, i);
|
|
1911
|
+
return _.push(...r.getMessages(y).map((e) => e.message)), s?.debug("loadConversation(); built", {
|
|
1912
|
+
runId: i,
|
|
1913
|
+
chainLength: v,
|
|
1914
|
+
totalMessages: _.length,
|
|
1915
|
+
folded: b
|
|
1916
|
+
}), {
|
|
1917
|
+
messages: _,
|
|
1918
|
+
projection: y
|
|
1919
|
+
};
|
|
1920
|
+
}, Bt = (e) => {
|
|
1921
|
+
let t;
|
|
1922
|
+
return {
|
|
1923
|
+
promise: e === void 0 ? new Promise(() => {}) : e.aborted ? Promise.resolve() : new Promise((n) => {
|
|
1924
|
+
t = () => {
|
|
1925
|
+
n();
|
|
1926
|
+
}, e.addEventListener("abort", t, { once: !0 });
|
|
1927
|
+
}),
|
|
1928
|
+
cleanup: () => {
|
|
1929
|
+
t && e && e.removeEventListener("abort", t);
|
|
1585
1930
|
}
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
let d = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
|
|
1597
|
-
for (let t of d) {
|
|
1598
|
-
let n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map();
|
|
1599
|
-
for (let a of t.accumulator.completedMessages) {
|
|
1600
|
-
let t = e.getMessageKey(a), s = c.get(t);
|
|
1601
|
-
if (s) {
|
|
1602
|
-
r.set(t, s);
|
|
1603
|
-
let e = l.get(t);
|
|
1604
|
-
e && i.set(t, e);
|
|
1605
|
-
let a = s[o];
|
|
1606
|
-
a && n.add(a);
|
|
1931
|
+
};
|
|
1932
|
+
}, Vt = async (e, t, n, r, i, a) => {
|
|
1933
|
+
a?.trace("pipeStream();");
|
|
1934
|
+
let o = e.getReader(), s = Bt(n), c = "complete", l;
|
|
1935
|
+
try {
|
|
1936
|
+
for (;;) {
|
|
1937
|
+
let e = await Promise.race([o.read(), s.promise.then(() => "cancelled")]);
|
|
1938
|
+
if (e === "cancelled") {
|
|
1939
|
+
c = "cancelled", a?.debug("pipeStream(); stream cancelled by AbortSignal"), r && await r(async (e) => t.publishOutput(e)), await t.cancel("cancelled");
|
|
1940
|
+
break;
|
|
1607
1941
|
}
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
if (!r.has(o) && c) {
|
|
1613
|
-
let [e, n] = c;
|
|
1614
|
-
r.set(o, n);
|
|
1615
|
-
let a = t.msgSerials.get(e);
|
|
1616
|
-
a && i.set(o, a), s++;
|
|
1942
|
+
let { done: n, value: l } = e;
|
|
1943
|
+
if (n) {
|
|
1944
|
+
await t.close(), a?.debug("pipeStream(); stream completed");
|
|
1945
|
+
break;
|
|
1617
1946
|
}
|
|
1947
|
+
await t.publishOutput(l, i?.(l));
|
|
1618
1948
|
}
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
}
|
|
1627
|
-
}
|
|
1628
|
-
return u.toReversed();
|
|
1629
|
-
}, X = async (e, t, n) => {
|
|
1630
|
-
e.rawMessages.push(...t.items), e.lastAblyPage = t;
|
|
1631
|
-
let r = Y(e).length;
|
|
1632
|
-
for (; r < e.returnedCount + n && t.hasNext();) {
|
|
1633
|
-
e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
|
|
1634
|
-
collected: e.rawMessages.length,
|
|
1635
|
-
decoded: r
|
|
1636
|
-
});
|
|
1637
|
-
let n = await t.next();
|
|
1638
|
-
if (!n) break;
|
|
1639
|
-
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, r = Y(e).length;
|
|
1949
|
+
} catch (e) {
|
|
1950
|
+
c = "error", l = e instanceof Error ? e : Error(String(e)), a?.error("pipeStream(); stream error", { error: l.message });
|
|
1951
|
+
try {
|
|
1952
|
+
await t.close();
|
|
1953
|
+
} catch {}
|
|
1954
|
+
} finally {
|
|
1955
|
+
s.cleanup(), o.releaseLock();
|
|
1640
1956
|
}
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
|
|
1645
|
-
return e.returnedRawCount = e.rawMessages.length, {
|
|
1646
|
-
items: i.map((e) => e.message),
|
|
1647
|
-
itemHeaders: i.map((e) => e.headers),
|
|
1648
|
-
itemSerials: i.map((e) => e.serial),
|
|
1649
|
-
rawMessages: s,
|
|
1650
|
-
hasNext: () => a || o,
|
|
1651
|
-
next: async () => {
|
|
1652
|
-
if (a) return Z(e, t);
|
|
1653
|
-
if (!o || !e.lastAblyPage) return;
|
|
1654
|
-
let n = await e.lastAblyPage.next();
|
|
1655
|
-
if (n) return await X(e, n, t), Z(e, t);
|
|
1656
|
-
}
|
|
1657
|
-
};
|
|
1658
|
-
}, Be = async (e, t, n, r) => {
|
|
1659
|
-
let i = n?.limit ?? 100, a = {
|
|
1660
|
-
codec: t,
|
|
1661
|
-
rawMessages: [],
|
|
1662
|
-
returnedCount: 0,
|
|
1663
|
-
returnedRawCount: 0,
|
|
1664
|
-
lastAblyPage: void 0,
|
|
1665
|
-
getMessageKey: t.getMessageKey.bind(t),
|
|
1666
|
-
logger: r
|
|
1667
|
-
};
|
|
1668
|
-
r.trace("decodeHistory();", { limit: i });
|
|
1669
|
-
let o = i * 10;
|
|
1670
|
-
return await e.attach(), await X(a, await e.history({
|
|
1671
|
-
untilAttach: !0,
|
|
1672
|
-
limit: o
|
|
1673
|
-
}), i), Z(a, i);
|
|
1674
|
-
}, Q = (e) => {
|
|
1675
|
-
let t = {
|
|
1676
|
-
[c]: e.role,
|
|
1677
|
-
[a]: e.turnId,
|
|
1678
|
-
[o]: e.msgId
|
|
1957
|
+
return {
|
|
1958
|
+
reason: c,
|
|
1959
|
+
error: l
|
|
1679
1960
|
};
|
|
1680
|
-
|
|
1681
|
-
}, Ve = class {
|
|
1961
|
+
}, Ht = class {
|
|
1682
1962
|
constructor(e, t) {
|
|
1683
|
-
this.
|
|
1684
|
-
}
|
|
1685
|
-
createStream(t) {
|
|
1686
|
-
this._logger.trace("StreamRouter.createStream();", { turnId: t });
|
|
1687
|
-
let n = {}, r = new ReadableStream({ start(e) {
|
|
1688
|
-
n.controller = e;
|
|
1689
|
-
} });
|
|
1690
|
-
if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", W.TransportSubscriptionError, 500);
|
|
1691
|
-
return this._turns.set(t, {
|
|
1692
|
-
controller: n.controller,
|
|
1693
|
-
turnId: t
|
|
1694
|
-
}), r;
|
|
1695
|
-
}
|
|
1696
|
-
closeStream(e) {
|
|
1697
|
-
let t = this._turns.get(e);
|
|
1698
|
-
if (!t) return !1;
|
|
1699
|
-
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
1700
|
-
try {
|
|
1701
|
-
t.controller.close();
|
|
1702
|
-
} catch {}
|
|
1703
|
-
return this._turns.delete(e), !0;
|
|
1963
|
+
this._activeRuns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "RunManager" });
|
|
1704
1964
|
}
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1965
|
+
async startRun(e, t, n, r) {
|
|
1966
|
+
this._logger?.trace("DefaultRunManager.startRun();", {
|
|
1967
|
+
runId: e,
|
|
1968
|
+
clientId: t
|
|
1969
|
+
});
|
|
1970
|
+
let i = n ?? new AbortController(), a = t ?? "";
|
|
1971
|
+
this._activeRuns.set(e, {
|
|
1972
|
+
controller: i,
|
|
1973
|
+
clientId: a
|
|
1974
|
+
});
|
|
1975
|
+
let o = r?.continuation === !0, s = Dt({
|
|
1976
|
+
runId: e,
|
|
1977
|
+
runClientId: a,
|
|
1978
|
+
parent: o ? void 0 : r?.parent,
|
|
1979
|
+
forkOf: o ? void 0 : r?.forkOf,
|
|
1980
|
+
regenerates: o ? void 0 : r?.regenerates,
|
|
1981
|
+
invocationId: r?.invocationId,
|
|
1982
|
+
inputClientId: r?.inputClientId,
|
|
1983
|
+
inputCodecMessageId: r?.inputCodecMessageId
|
|
1984
|
+
});
|
|
1985
|
+
return await this._channel.publish({
|
|
1986
|
+
name: o ? S : b,
|
|
1987
|
+
extras: { ai: { transport: s } }
|
|
1988
|
+
}), this._logger?.debug("DefaultRunManager.startRun(); run started", { runId: e }), i.signal;
|
|
1989
|
+
}
|
|
1990
|
+
async suspendRun(e, t, n, r) {
|
|
1991
|
+
this._logger?.trace("DefaultRunManager.suspendRun();", { runId: e }), await this._publishTerminal(x, e, {
|
|
1992
|
+
invocationId: t,
|
|
1993
|
+
inputClientId: n,
|
|
1994
|
+
inputCodecMessageId: r
|
|
1995
|
+
}), this._logger?.debug("DefaultRunManager.suspendRun(); run suspended", { runId: e });
|
|
1996
|
+
}
|
|
1997
|
+
async endRun(e, t, n, r, i) {
|
|
1998
|
+
this._logger?.trace("DefaultRunManager.endRun();", {
|
|
1999
|
+
runId: e,
|
|
2000
|
+
reason: t
|
|
2001
|
+
}), await this._publishTerminal(C, e, {
|
|
2002
|
+
reason: t,
|
|
2003
|
+
invocationId: n,
|
|
2004
|
+
inputClientId: r,
|
|
2005
|
+
inputCodecMessageId: i
|
|
2006
|
+
}), this._logger?.debug("DefaultRunManager.endRun(); run ended", {
|
|
2007
|
+
runId: e,
|
|
2008
|
+
reason: t
|
|
2009
|
+
});
|
|
2010
|
+
}
|
|
2011
|
+
async _publishTerminal(e, t, n) {
|
|
2012
|
+
let r = Dt({
|
|
2013
|
+
runId: t,
|
|
2014
|
+
runClientId: this._activeRuns.get(t)?.clientId ?? "",
|
|
2015
|
+
...n
|
|
2016
|
+
});
|
|
2017
|
+
await this._channel.publish({
|
|
2018
|
+
name: e,
|
|
2019
|
+
extras: { ai: { transport: r } }
|
|
2020
|
+
}), this._activeRuns.delete(t);
|
|
2021
|
+
}
|
|
2022
|
+
getSignal(e) {
|
|
2023
|
+
return this._activeRuns.get(e)?.controller.signal;
|
|
2024
|
+
}
|
|
2025
|
+
getClientId(e) {
|
|
2026
|
+
return this._activeRuns.get(e)?.clientId;
|
|
1714
2027
|
}
|
|
1715
|
-
|
|
1716
|
-
|
|
2028
|
+
cancel(e) {
|
|
2029
|
+
this._logger?.debug("DefaultRunManager.cancel();", { runId: e }), this._activeRuns.get(e)?.controller.abort();
|
|
1717
2030
|
}
|
|
1718
|
-
|
|
2031
|
+
getActiveRunIds() {
|
|
2032
|
+
return [...this._activeRuns.keys()];
|
|
2033
|
+
}
|
|
2034
|
+
close() {
|
|
2035
|
+
this._logger?.trace("DefaultRunManager.close();", { activeRuns: this._activeRuns.size });
|
|
2036
|
+
for (let e of this._activeRuns.values()) e.controller.abort();
|
|
2037
|
+
this._activeRuns.clear();
|
|
2038
|
+
}
|
|
2039
|
+
}, Ut = (e, t) => new Ht(e, t), Wt = async (t) => {
|
|
2040
|
+
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) => {
|
|
2041
|
+
let t = r.createDecoder(), n = D(e), i = n["codec-message-id"] ?? "", { inputs: a, outputs: o } = t.decode(e), s = [...a, ...o], c = r.init();
|
|
2042
|
+
for (let t of s) c = r.fold(c, t, {
|
|
2043
|
+
serial: e.serial ?? "",
|
|
2044
|
+
messageId: i
|
|
2045
|
+
});
|
|
2046
|
+
return r.getMessages(c).map(({ message: t }) => ({
|
|
2047
|
+
kind: "message",
|
|
2048
|
+
message: t,
|
|
2049
|
+
codecMessageId: i,
|
|
2050
|
+
parentId: n[p],
|
|
2051
|
+
forkOf: n[m],
|
|
2052
|
+
headers: n,
|
|
2053
|
+
serial: e.serial
|
|
2054
|
+
}));
|
|
2055
|
+
};
|
|
2056
|
+
return new Promise((t, r) => {
|
|
2057
|
+
let o = !1, p = /* @__PURE__ */ new Set(), m = () => {}, x, S = () => {
|
|
2058
|
+
m(), x !== void 0 && clearTimeout(x), l.removeEventListener("abort", C);
|
|
2059
|
+
}, C = () => {
|
|
2060
|
+
o || (o = !0, S(), r(new e.ErrorInfo(`unable to look up input event; run ${a} was cancelled`, W.InvalidArgument, 400)));
|
|
2061
|
+
};
|
|
2062
|
+
if (l.addEventListener("abort", C, { once: !0 }), !o) {
|
|
2063
|
+
if (m = n((n) => {
|
|
2064
|
+
if (o || n.serial !== void 0 && p.has(n.serial)) return;
|
|
2065
|
+
n.serial !== void 0 && p.add(n.serial);
|
|
2066
|
+
let s = D(n), l = s[c];
|
|
2067
|
+
if (!l || !d.has(l) || _.has(l)) return;
|
|
2068
|
+
_.add(l), v === void 0 && (v = s, y = n.clientId);
|
|
2069
|
+
let m;
|
|
2070
|
+
try {
|
|
2071
|
+
m = b(n);
|
|
2072
|
+
} catch (t) {
|
|
2073
|
+
o = !0, S();
|
|
2074
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
2075
|
+
r(new e.ErrorInfo(`unable to look up input event; decode failed for invocation ${i}: ${t instanceof Error ? t.message : String(t)}`, W.InputEventNotFound, 504, n));
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
for (let e of m) h.push(e);
|
|
2079
|
+
g.push(n), !(_.size < f) && (o = !0, S(), h.sort(A), u?.debug("lookupInputEvents(); collected input events", {
|
|
2080
|
+
runId: a,
|
|
2081
|
+
invocationId: i,
|
|
2082
|
+
count: h.length
|
|
2083
|
+
}), t({
|
|
2084
|
+
nodes: h,
|
|
2085
|
+
firstHeaders: v,
|
|
2086
|
+
firstClientId: y,
|
|
2087
|
+
rawMessages: g
|
|
2088
|
+
}));
|
|
2089
|
+
}), o) {
|
|
2090
|
+
m();
|
|
2091
|
+
return;
|
|
2092
|
+
}
|
|
2093
|
+
x = setTimeout(() => {
|
|
2094
|
+
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`, W.InputEventNotFound, 504)));
|
|
2095
|
+
}, s);
|
|
2096
|
+
}
|
|
2097
|
+
});
|
|
2098
|
+
}, Gt = class {
|
|
1719
2099
|
constructor(e) {
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
2100
|
+
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;
|
|
2101
|
+
let t = { params: {
|
|
2102
|
+
...Tt(e.client, e.codec).params,
|
|
2103
|
+
rewind: e.rewindWindow ?? "2m"
|
|
2104
|
+
} };
|
|
2105
|
+
this._channel = e.client.channels.get(e.channelName, t), this._logger = e.logger?.withContext({ component: "AgentSession" }), this._onError = e.onError, this._runManager = Ut(this._channel, this._logger), this._inputEventLookupTimeoutMs = e.inputEventLookupTimeoutMs ?? 3e4, this._inputEventBufferLimit = e.inputEventBufferLimit ?? 200, this._channelListener = (e) => {
|
|
2106
|
+
this._handleChannelMessage(e);
|
|
2107
|
+
}, this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
|
|
2108
|
+
this._handleChannelStateChange(e);
|
|
2109
|
+
}, this._channel.on(this._onChannelStateChange), this._logger?.debug("DefaultAgentSession(); session created");
|
|
2110
|
+
}
|
|
2111
|
+
connect() {
|
|
2112
|
+
return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", W.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger?.trace("DefaultAgentSession.connect();"), this._connectPromise = this._channel.subscribe(this._channelListener).then(() => {
|
|
2113
|
+
this._logger?.debug("DefaultAgentSession.connect(); subscribed and attached");
|
|
2114
|
+
}, (t) => {
|
|
2115
|
+
let n = new e.ErrorInfo(`unable to subscribe to channel; ${t instanceof Error ? t.message : String(t)}`, W.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2116
|
+
throw this._logger?.error("DefaultAgentSession.connect(); subscribe failed"), this._onError?.(n), n;
|
|
2117
|
+
}), this._connectPromise);
|
|
2118
|
+
}
|
|
2119
|
+
_registerInputEventListener(e, t) {
|
|
2120
|
+
for (let n of e) this._pendingInputEventLookups.set(n, t);
|
|
2121
|
+
for (let n of e) {
|
|
2122
|
+
let e = this._inputEventBuffer.get(n);
|
|
2123
|
+
if (e) {
|
|
2124
|
+
this._inputEventBuffer.delete(n);
|
|
2125
|
+
for (let n of e) t(n);
|
|
1725
2126
|
}
|
|
1726
|
-
this._emitter.emit("message");
|
|
1727
2127
|
}
|
|
1728
|
-
|
|
1729
|
-
this.
|
|
1730
|
-
}
|
|
2128
|
+
return () => {
|
|
2129
|
+
for (let n of e) this._pendingInputEventLookups.get(n) === t && this._pendingInputEventLookups.delete(n);
|
|
2130
|
+
};
|
|
1731
2131
|
}
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
return;
|
|
1744
|
-
}
|
|
1745
|
-
if (t.name === "x-ably-turn-end") {
|
|
1746
|
-
let e = b(t), n = e[a], r = e["x-ably-turn-client-id"] ?? "", i = e["x-ably-turn-reason"] ?? "complete";
|
|
1747
|
-
if (n) {
|
|
1748
|
-
this._router.closeStream(n), this._turnObservers.delete(n), this._turnClientIds.delete(n);
|
|
1749
|
-
let e = this._turnMsgIds.get(n);
|
|
1750
|
-
if (e) {
|
|
1751
|
-
for (let t of e) this._ownMsgIds.delete(t);
|
|
1752
|
-
this._turnMsgIds.delete(n);
|
|
1753
|
-
}
|
|
1754
|
-
this._ownTurnIds.delete(n), this._emitter.emit("turn", {
|
|
1755
|
-
type: v,
|
|
1756
|
-
turnId: n,
|
|
1757
|
-
clientId: r,
|
|
1758
|
-
reason: i
|
|
1759
|
-
});
|
|
1760
|
-
}
|
|
1761
|
-
return;
|
|
1762
|
-
}
|
|
1763
|
-
let e = this._decoder.decode(t), n = b(t), r = t.serial, i = n[a];
|
|
1764
|
-
i && this._updateTurnObserverHeaders(i, n, r);
|
|
1765
|
-
for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
|
|
1766
|
-
} catch (t) {
|
|
1767
|
-
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
1768
|
-
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, W.TransportSubscriptionError, 500, n));
|
|
2132
|
+
createRun(e, t) {
|
|
2133
|
+
return this._logger?.trace("DefaultAgentSession.createRun();", { inputEventId: e.inputEventId }), this._createRun(e, t ?? {});
|
|
2134
|
+
}
|
|
2135
|
+
async close() {
|
|
2136
|
+
if (this._state !== "closed") {
|
|
2137
|
+
this._state = "closed", this._logger?.trace("DefaultAgentSession.close();"), this._connectPromise && this._channel.unsubscribe(this._channelListener), this._channel.off(this._onChannelStateChange);
|
|
2138
|
+
for (let e of this._registeredRuns.values()) e.controller.abort();
|
|
2139
|
+
if (this._registeredRuns.clear(), this._runIdByInputCodecMessageId.clear(), this._deferredCancels.clear(), this._pendingInputEventLookups.clear(), this._inputEventBuffer.clear(), this._runManager.close(), this._connectPromise) try {
|
|
2140
|
+
await this._channel.detach();
|
|
2141
|
+
} catch (e) {
|
|
2142
|
+
this._logger?.debug("DefaultAgentSession.close(); channel detach failed", { error: e });
|
|
1769
2143
|
}
|
|
2144
|
+
this._logger?.debug("DefaultAgentSession.close(); session closed");
|
|
1770
2145
|
}
|
|
1771
2146
|
}
|
|
1772
|
-
|
|
1773
|
-
let
|
|
1774
|
-
if (
|
|
1775
|
-
this.
|
|
2147
|
+
async _handleCancelMessage(e) {
|
|
2148
|
+
let t = D(e), n = t[o], r = t[_];
|
|
2149
|
+
if (!n && !r) {
|
|
2150
|
+
this._logger?.warn("DefaultAgentSession._handleCancelMessage(); missing run-id and input-codec-message-id", { serial: e.serial });
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
let i = n ?? (r ? this._runIdByInputCodecMessageId.get(r) : void 0), a = i ? this._registeredRuns.get(i) : void 0;
|
|
2154
|
+
if (!a) {
|
|
2155
|
+
r !== void 0 && this._bufferDeferredCancel(r, e);
|
|
1776
2156
|
return;
|
|
1777
2157
|
}
|
|
1778
|
-
|
|
2158
|
+
await this._cancelRegistration(a, e);
|
|
2159
|
+
}
|
|
2160
|
+
_bufferDeferredCancel(e, t) {
|
|
2161
|
+
let n = At(this._deferredCancels, e, this._inputEventBufferLimit);
|
|
2162
|
+
n !== void 0 && this._logger?.warn("DefaultAgentSession._bufferDeferredCancel(); deferred-cancel buffer full, dropping oldest", {
|
|
2163
|
+
evictedInputCodecMessageId: n,
|
|
2164
|
+
limit: this._inputEventBufferLimit
|
|
2165
|
+
}), this._deferredCancels.set(e, t), this._logger?.debug("DefaultAgentSession._bufferDeferredCancel(); buffered early cancel", {
|
|
2166
|
+
inputCodecMessageId: e,
|
|
2167
|
+
serial: t.serial
|
|
2168
|
+
});
|
|
1779
2169
|
}
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
2170
|
+
async _pullDeferredCancel(e, t) {
|
|
2171
|
+
let n = this._deferredCancels.get(t);
|
|
2172
|
+
n !== void 0 && (this._deferredCancels.delete(t), this._logger?.debug("DefaultAgentSession._pullDeferredCancel(); honouring buffered cancel", {
|
|
2173
|
+
runId: e.runId,
|
|
2174
|
+
inputCodecMessageId: t
|
|
2175
|
+
}), await this._cancelRegistration(e, n));
|
|
2176
|
+
}
|
|
2177
|
+
async _cancelRegistration(t, n) {
|
|
2178
|
+
let { runId: r } = t;
|
|
2179
|
+
this._logger?.debug("DefaultAgentSession._cancelRegistration(); matched run", { runId: r });
|
|
2180
|
+
let i = {
|
|
2181
|
+
message: n,
|
|
2182
|
+
runId: r
|
|
2183
|
+
};
|
|
2184
|
+
try {
|
|
2185
|
+
if (t.onCancel && !await t.onCancel(i)) {
|
|
2186
|
+
this._logger?.debug("DefaultAgentSession._cancelRegistration(); cancel rejected by onCancel", { runId: r });
|
|
1786
2187
|
return;
|
|
1787
2188
|
}
|
|
1788
|
-
|
|
2189
|
+
t.controller.abort(), this._logger?.debug("DefaultAgentSession._cancelRegistration(); run cancelled", { runId: r });
|
|
2190
|
+
} catch (n) {
|
|
2191
|
+
let i = new e.ErrorInfo(`unable to process cancel for run ${r}; onCancel handler threw: ${n instanceof Error ? n.message : String(n)}`, W.CancelListenerError, 500, n instanceof e.ErrorInfo ? n : void 0);
|
|
2192
|
+
this._logger?.error("DefaultAgentSession._cancelRegistration(); onCancel threw", { runId: r }), (t.onError ?? this._onError)?.(i);
|
|
1789
2193
|
}
|
|
1790
2194
|
}
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
2195
|
+
_handleChannelStateChange(t) {
|
|
2196
|
+
if (this._state === "closed") return;
|
|
2197
|
+
let { current: n, resumed: r } = t;
|
|
2198
|
+
if (n === "attached" && !this._hasAttachedOnce) {
|
|
2199
|
+
this._hasAttachedOnce = !0;
|
|
2200
|
+
return;
|
|
2201
|
+
}
|
|
2202
|
+
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
2203
|
+
this._logger?.error("DefaultAgentSession._handleChannelStateChange(); channel continuity lost", {
|
|
2204
|
+
current: n,
|
|
2205
|
+
resumed: r,
|
|
2206
|
+
previous: t.previous
|
|
1801
2207
|
});
|
|
2208
|
+
let i = new e.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, W.ChannelContinuityLost, 500, t.reason);
|
|
2209
|
+
this._onError?.(i);
|
|
1802
2210
|
}
|
|
1803
|
-
|
|
1804
|
-
let n = this._turnObservers.get(e);
|
|
1805
|
-
if (!n) return;
|
|
1806
|
-
n.accumulator.processOutputs([t]);
|
|
1807
|
-
let r = n.accumulator.messages;
|
|
1808
|
-
if (r.length === 0) return;
|
|
1809
|
-
let i;
|
|
2211
|
+
_handleChannelMessage(t) {
|
|
1810
2212
|
try {
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
2213
|
+
if (t.name === "ai-cancel") {
|
|
2214
|
+
this._handleCancelMessage(t).catch((t) => {
|
|
2215
|
+
let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, W.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2216
|
+
this._logger?.error("DefaultAgentSession._handleChannelMessage(); cancel routing error"), this._onError?.(n);
|
|
2217
|
+
});
|
|
2218
|
+
return;
|
|
2219
|
+
}
|
|
2220
|
+
let n = D(t)[c];
|
|
2221
|
+
if (n !== void 0) {
|
|
2222
|
+
let e = this._pendingInputEventLookups.get(n);
|
|
2223
|
+
if (e) e(t);
|
|
2224
|
+
else {
|
|
2225
|
+
let e = this._inputEventBuffer.get(n);
|
|
2226
|
+
if (e) e.push(t);
|
|
2227
|
+
else {
|
|
2228
|
+
let e = At(this._inputEventBuffer, n, this._inputEventBufferLimit);
|
|
2229
|
+
e !== void 0 && this._logger?.warn("DefaultAgentSession._handleChannelMessage(); input-event buffer full, dropping oldest entry", {
|
|
2230
|
+
evictedEventId: e,
|
|
2231
|
+
limit: this._inputEventBufferLimit
|
|
2232
|
+
}), this._inputEventBuffer.set(n, [t]);
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
} catch (t) {
|
|
2237
|
+
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, W.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2238
|
+
this._logger?.error("DefaultAgentSession._handleChannelMessage(); subscription error"), this._onError?.(n);
|
|
1814
2239
|
}
|
|
1815
|
-
i && (this._tree.upsert(n.headers["x-ably-msg-id"] ?? this._codec.getMessageKey(i), i, { ...n.headers }, n.serial), this._emitter.emit("message"));
|
|
1816
2240
|
}
|
|
1817
|
-
async
|
|
1818
|
-
this.
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
2241
|
+
async _requireConnected(t) {
|
|
2242
|
+
if (!this._connectPromise) throw new e.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`, W.InvalidArgument, 400);
|
|
2243
|
+
return this._connectPromise;
|
|
2244
|
+
}
|
|
2245
|
+
_createRun(t, n) {
|
|
2246
|
+
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 = {
|
|
2247
|
+
runId: r,
|
|
2248
|
+
invocationId: i,
|
|
2249
|
+
controller: _,
|
|
2250
|
+
signal: y,
|
|
2251
|
+
onCancel: d,
|
|
2252
|
+
onError: f
|
|
2253
|
+
};
|
|
2254
|
+
this._registeredRuns.set(r, b);
|
|
2255
|
+
let x = this._logger, S = this._runManager, C = this._codec, w = this._channel, T = this._registeredRuns, E = this._runIdByInputCodecMessageId, D = this._deferredCancels, O = this._requireConnected.bind(this), ee = this._registerInputEventListener.bind(this), te = this._pullDeferredCancel.bind(this), k = t.inputEventId, A = [], j = { get messages() {
|
|
2256
|
+
return A;
|
|
2257
|
+
} }, M, N, P, F, I, L, ne = !1, R, z, B, V = () => {
|
|
2258
|
+
T.delete(r), L !== void 0 && (E.delete(L), D.delete(L));
|
|
2259
|
+
}, H, U;
|
|
2260
|
+
return {
|
|
2261
|
+
get runId() {
|
|
2262
|
+
return r;
|
|
2263
|
+
},
|
|
2264
|
+
get invocationId() {
|
|
2265
|
+
return i;
|
|
2266
|
+
},
|
|
2267
|
+
get abortSignal() {
|
|
2268
|
+
return y;
|
|
2269
|
+
},
|
|
2270
|
+
get view() {
|
|
2271
|
+
return j;
|
|
2272
|
+
},
|
|
2273
|
+
get messages() {
|
|
2274
|
+
return U === void 0 ? H === void 0 ? A.map((e) => e.message) : C.getMessages(H).map((e) => e.message) : [...U];
|
|
2275
|
+
},
|
|
2276
|
+
start: async () => {
|
|
2277
|
+
if (x?.trace("Run.start();", {
|
|
2278
|
+
runId: r,
|
|
2279
|
+
inputEventId: k
|
|
2280
|
+
}), await O("start"), y.aborted) throw new e.ErrorInfo(`unable to start run; run ${r} was cancelled before start()`, W.InvalidArgument, 400);
|
|
2281
|
+
if (v !== "initialized") return;
|
|
2282
|
+
if (v = "started", k && a > 0) try {
|
|
2283
|
+
let e = await Wt({
|
|
2284
|
+
register: (e) => ee([k], e),
|
|
2285
|
+
codec: C,
|
|
2286
|
+
invocationId: i,
|
|
2287
|
+
runId: r,
|
|
2288
|
+
expectedInputEventIds: [k],
|
|
2289
|
+
timeoutMs: a,
|
|
2290
|
+
signal: y,
|
|
2291
|
+
logger: x
|
|
2292
|
+
});
|
|
2293
|
+
for (let t of e.nodes) A.push(t);
|
|
2294
|
+
e.firstHeaders !== void 0 && (R = e.firstHeaders), e.firstClientId !== void 0 && (N = e.firstClientId), B = e.rawMessages;
|
|
2295
|
+
} catch (t) {
|
|
2296
|
+
let n = t instanceof e.ErrorInfo ? t : new e.ErrorInfo(`unable to look up input event; ${t instanceof Error ? t.message : String(t)}`, W.InputEventNotFound, 504);
|
|
2297
|
+
throw V(), x?.error("Run.start(); input-event lookup failed", {
|
|
2298
|
+
runId: r,
|
|
2299
|
+
invocationId: i
|
|
2300
|
+
}), n;
|
|
2301
|
+
}
|
|
2302
|
+
let t = R ?? A[0]?.headers;
|
|
2303
|
+
if (t) {
|
|
2304
|
+
M = t[u], P = t[p], F = t[m], I = t[h], L = t[l];
|
|
2305
|
+
let e = t[o];
|
|
2306
|
+
ne = e !== void 0, e !== void 0 && e !== r && (T.delete(r), r = e, b.runId = r, T.set(r, b));
|
|
2307
|
+
}
|
|
2308
|
+
z = A.at(-1)?.codecMessageId ?? P, L !== void 0 && (E.set(L, r), await te(b, L));
|
|
2309
|
+
try {
|
|
2310
|
+
await S.startRun(r, M, _, {
|
|
2311
|
+
parent: z,
|
|
2312
|
+
forkOf: F,
|
|
2313
|
+
regenerates: I,
|
|
2314
|
+
invocationId: i,
|
|
2315
|
+
inputClientId: N,
|
|
2316
|
+
inputCodecMessageId: L,
|
|
2317
|
+
continuation: ne
|
|
2318
|
+
});
|
|
2319
|
+
} catch (t) {
|
|
2320
|
+
let n = new e.ErrorInfo(`unable to publish run-start for run ${r}; ${t instanceof Error ? t.message : String(t)}`, W.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2321
|
+
throw x?.error("Run.start(); failed to publish run-start", { runId: r }), n;
|
|
2322
|
+
}
|
|
2323
|
+
x?.debug("Run.start(); run started", {
|
|
2324
|
+
runId: r,
|
|
2325
|
+
inputEventId: k
|
|
2326
|
+
});
|
|
2327
|
+
},
|
|
2328
|
+
addEvents: async (t) => {
|
|
2329
|
+
if (x?.trace("Run.addEvents();", {
|
|
2330
|
+
runId: r,
|
|
2331
|
+
count: t.length
|
|
2332
|
+
}), await O("addEvents"), v === "initialized") throw new e.ErrorInfo(`unable to add events; start() must be called before addEvents() (run ${r})`, W.InvalidArgument, 400);
|
|
2333
|
+
let n = S.getClientId(r);
|
|
2334
|
+
try {
|
|
2335
|
+
for (let e of t) {
|
|
2336
|
+
let t = Et({
|
|
2337
|
+
role: "assistant",
|
|
2338
|
+
runId: r,
|
|
2339
|
+
codecMessageId: e.codecMessageId,
|
|
2340
|
+
runClientId: n,
|
|
2341
|
+
invocationId: i,
|
|
2342
|
+
inputClientId: N,
|
|
2343
|
+
inputCodecMessageId: L
|
|
2344
|
+
}), a = C.createEncoder(w, {
|
|
2345
|
+
extras: { headers: t },
|
|
2346
|
+
onMessage: s
|
|
2347
|
+
});
|
|
2348
|
+
for (let t of e.events) await a.publishOutput(t);
|
|
2349
|
+
await a.close();
|
|
2350
|
+
}
|
|
2351
|
+
} catch (t) {
|
|
2352
|
+
let n = new e.ErrorInfo(`unable to publish events for run ${r}; ${t instanceof Error ? t.message : String(t)}`, W.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2353
|
+
throw x?.error("Run.addEvents(); publish failed", { runId: r }), n;
|
|
2354
|
+
}
|
|
2355
|
+
x?.debug("Run.addEvents(); events published", {
|
|
2356
|
+
runId: r,
|
|
2357
|
+
count: t.length
|
|
2358
|
+
});
|
|
2359
|
+
},
|
|
2360
|
+
loadProjection: async () => {
|
|
2361
|
+
x?.trace("Run.loadProjection();", { runId: r }), await O("loadProjection");
|
|
2362
|
+
let e = await Rt({
|
|
2363
|
+
channel: w,
|
|
2364
|
+
codec: C,
|
|
2365
|
+
runId: r,
|
|
2366
|
+
signal: y,
|
|
2367
|
+
logger: x,
|
|
2368
|
+
liveMessages: B
|
|
2369
|
+
});
|
|
2370
|
+
return H = e, e;
|
|
2371
|
+
},
|
|
2372
|
+
loadConversation: async (e) => {
|
|
2373
|
+
x?.trace("Run.loadConversation();", { runId: r }), await O("loadConversation");
|
|
2374
|
+
let { messages: t, projection: n } = await zt({
|
|
2375
|
+
channel: w,
|
|
2376
|
+
codec: C,
|
|
2377
|
+
runId: r,
|
|
2378
|
+
signal: y,
|
|
2379
|
+
logger: x,
|
|
2380
|
+
liveMessages: B,
|
|
2381
|
+
assistantParentFallback: z,
|
|
2382
|
+
pageLimit: e?.pageLimit ?? 200,
|
|
2383
|
+
maxMessages: e?.maxMessages ?? 2e3
|
|
2384
|
+
});
|
|
2385
|
+
return H = n, U = t, t;
|
|
2386
|
+
},
|
|
2387
|
+
pipe: async (t, n) => {
|
|
2388
|
+
if (x?.trace("Run.pipe();", { runId: r }), await O("pipe"), v === "initialized") throw new e.ErrorInfo(`unable to pipe stream; start() must be called before pipe() (run ${r})`, W.InvalidArgument, 400);
|
|
2389
|
+
let a = S.getClientId(r), o = n?.parent ?? z, l = n?.forkOf ?? F, u = I, d = crypto.randomUUID(), p = Et({
|
|
2390
|
+
role: "assistant",
|
|
2391
|
+
runId: r,
|
|
2392
|
+
codecMessageId: d,
|
|
2393
|
+
runClientId: a,
|
|
2394
|
+
parent: o,
|
|
2395
|
+
forkOf: l,
|
|
2396
|
+
invocationId: i,
|
|
2397
|
+
inputClientId: N,
|
|
2398
|
+
inputCodecMessageId: L,
|
|
2399
|
+
regenerates: u
|
|
2400
|
+
}), m = await Vt(t, C.createEncoder(w, {
|
|
2401
|
+
extras: { headers: p },
|
|
2402
|
+
onMessage: s,
|
|
2403
|
+
messageId: d
|
|
2404
|
+
}), y, c, n?.resolveWriteOptions, x);
|
|
2405
|
+
if (m.error) {
|
|
2406
|
+
let t = new e.ErrorInfo(`unable to pipe response for run ${r}; ${m.error.message}`, W.StreamError, 500, m.error instanceof e.ErrorInfo ? m.error : void 0);
|
|
2407
|
+
x?.error("Run.pipe(); stream error", { runId: r }), f?.(t);
|
|
2408
|
+
}
|
|
2409
|
+
return x?.debug("Run.pipe(); stream finished", {
|
|
2410
|
+
runId: r,
|
|
2411
|
+
reason: m.reason
|
|
2412
|
+
}), m;
|
|
2413
|
+
},
|
|
2414
|
+
suspend: async () => {
|
|
2415
|
+
if (x?.trace("Run.suspend();", { runId: r }), await O("suspend"), v === "initialized") throw new e.ErrorInfo(`unable to suspend run; start() must be called before suspend() (run ${r})`, W.InvalidArgument, 400);
|
|
2416
|
+
if (v !== "ended") {
|
|
2417
|
+
v = "ended";
|
|
2418
|
+
try {
|
|
2419
|
+
await S.suspendRun(r, i, N, L);
|
|
2420
|
+
} catch (t) {
|
|
2421
|
+
let n = new e.ErrorInfo(`unable to publish run-suspend for run ${r}; ${t instanceof Error ? t.message : String(t)}`, W.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2422
|
+
throw x?.error("Run.suspend(); failed to publish run-suspend", { runId: r }), n;
|
|
2423
|
+
} finally {
|
|
2424
|
+
V();
|
|
2425
|
+
}
|
|
2426
|
+
x?.debug("Run.suspend(); run suspended", { runId: r });
|
|
2427
|
+
}
|
|
2428
|
+
},
|
|
2429
|
+
end: async (t) => {
|
|
2430
|
+
if (x?.trace("Run.end();", {
|
|
2431
|
+
runId: r,
|
|
2432
|
+
reason: t
|
|
2433
|
+
}), await O("end"), v === "initialized") throw new e.ErrorInfo(`unable to end run; start() must be called before end() (run ${r})`, W.InvalidArgument, 400);
|
|
2434
|
+
if (v !== "ended") {
|
|
2435
|
+
v = "ended";
|
|
2436
|
+
try {
|
|
2437
|
+
await S.endRun(r, t, i, N, L);
|
|
2438
|
+
} catch (t) {
|
|
2439
|
+
let n = new e.ErrorInfo(`unable to publish run-end for run ${r}; ${t instanceof Error ? t.message : String(t)}`, W.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2440
|
+
throw x?.error("Run.end(); failed to publish run-end", { runId: r }), n;
|
|
2441
|
+
} finally {
|
|
2442
|
+
V();
|
|
2443
|
+
}
|
|
2444
|
+
x?.debug("Run.end(); run ended", {
|
|
2445
|
+
runId: r,
|
|
2446
|
+
reason: t
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
};
|
|
1824
2451
|
}
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
else if (e.clientId) for (let [t, n] of this._turnClientIds) n === e.clientId && this._router.closeStream(t);
|
|
1829
|
-
else e.turnId && this._router.closeStream(e.turnId);
|
|
1830
|
-
}
|
|
1831
|
-
_getMatchingTurnIds(e) {
|
|
1832
|
-
let t = /* @__PURE__ */ new Set();
|
|
1833
|
-
if (e.all) for (let e of this._turnClientIds.keys()) t.add(e);
|
|
1834
|
-
else if (e.own) for (let [e, n] of this._turnClientIds) n === this._clientId && t.add(e);
|
|
1835
|
-
else if (e.clientId) for (let [n, r] of this._turnClientIds) r === e.clientId && t.add(n);
|
|
1836
|
-
else e.turnId && this._turnClientIds.has(e.turnId) && t.add(e.turnId);
|
|
1837
|
-
return t;
|
|
2452
|
+
}, Kt = (e) => new Gt(e), qt = class e {
|
|
2453
|
+
constructor(e) {
|
|
2454
|
+
this.inputEventId = e.inputEventId, this.sessionName = e.sessionName;
|
|
1838
2455
|
}
|
|
1839
|
-
|
|
1840
|
-
return
|
|
1841
|
-
message: e,
|
|
1842
|
-
headers: this.getMessageHeaders(e)
|
|
1843
|
-
}));
|
|
2456
|
+
static fromJSON(t) {
|
|
2457
|
+
return new e(t);
|
|
1844
2458
|
}
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
2459
|
+
toJSON() {
|
|
2460
|
+
return {
|
|
2461
|
+
inputEventId: this.inputEventId,
|
|
2462
|
+
sessionName: this.sessionName
|
|
2463
|
+
};
|
|
1848
2464
|
}
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
2465
|
+
}, $ = (e) => e.kind === "run" ? e.runId : e.codecMessageId, Jt = (e) => e.kind === "run" ? e.startSerial : e.serial, Yt = (e, t, n) => {
|
|
2466
|
+
let r = e.get(t);
|
|
2467
|
+
r || (r = /* @__PURE__ */ new Set(), e.set(t, r)), r.add(n);
|
|
2468
|
+
}, Xt = (e, t, n) => {
|
|
2469
|
+
let r = e.get(t);
|
|
2470
|
+
r && (r.delete(n), r.size === 0 && e.delete(t));
|
|
2471
|
+
}, Zt = class {
|
|
2472
|
+
constructor(e, t) {
|
|
2473
|
+
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 Q(t);
|
|
2474
|
+
}
|
|
2475
|
+
_compareNodes(e, t) {
|
|
2476
|
+
let n = Jt(e.node), r = Jt(t.node);
|
|
2477
|
+
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;
|
|
2478
|
+
}
|
|
2479
|
+
_insertSortedNode(e) {
|
|
2480
|
+
if (Jt(e.node) === void 0) {
|
|
2481
|
+
this._sortedNodes.push(e);
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
let t = 0, n = this._sortedNodes.length;
|
|
2485
|
+
for (; t < n;) {
|
|
2486
|
+
let r = t + n >>> 1, i = this._sortedNodes[r];
|
|
2487
|
+
if (!i) break;
|
|
2488
|
+
this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
|
|
1853
2489
|
}
|
|
1854
|
-
this.
|
|
2490
|
+
this._sortedNodes.splice(t, 0, e);
|
|
1855
2491
|
}
|
|
1856
|
-
|
|
1857
|
-
this.
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
2492
|
+
_removeSortedNode(e) {
|
|
2493
|
+
let t = this._sortedNodes.indexOf(e);
|
|
2494
|
+
t !== -1 && this._sortedNodes.splice(t, 1);
|
|
2495
|
+
}
|
|
2496
|
+
_insertNode(e, t, n) {
|
|
2497
|
+
this._nodeIndex.set(e, t), this._addToParentIndex(n, e), this._insertSortedNode(t), this._structuralVersion++;
|
|
2498
|
+
}
|
|
2499
|
+
_promoteSerial(e) {
|
|
2500
|
+
this._removeSortedNode(e), this._insertSortedNode(e), this._structuralVersion++;
|
|
2501
|
+
}
|
|
2502
|
+
_foldInto(e, t, n, r) {
|
|
2503
|
+
for (let i of t) try {
|
|
2504
|
+
e.node.projection = this._codec.fold(e.node.projection, i, {
|
|
2505
|
+
serial: n ?? "",
|
|
2506
|
+
messageId: r
|
|
2507
|
+
});
|
|
2508
|
+
} catch (t) {
|
|
2509
|
+
this._logger.error("Tree._foldInto(); fold threw", {
|
|
2510
|
+
key: $(e.node),
|
|
2511
|
+
messageId: r,
|
|
2512
|
+
err: t
|
|
2513
|
+
});
|
|
1867
2514
|
}
|
|
1868
|
-
return {
|
|
1869
|
-
newVisible: this._tree.flatten().filter((e) => !n.has(this._codec.getMessageKey(e))),
|
|
1870
|
-
lastPage: r
|
|
1871
|
-
};
|
|
1872
2515
|
}
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
e.length > 0 && this._emitter.emit("message");
|
|
2516
|
+
_addToParentIndex(e, t) {
|
|
2517
|
+
Yt(this._parentIndex, e, t);
|
|
1876
2518
|
}
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
2519
|
+
_removeFromParentIndex(e, t) {
|
|
2520
|
+
Xt(this._parentIndex, e, t);
|
|
2521
|
+
}
|
|
2522
|
+
_parentKeyOf(e) {
|
|
2523
|
+
let t = e.parentCodecMessageId;
|
|
2524
|
+
return t === void 0 ? void 0 : this._codecMessageIdToNodeKey.get(t);
|
|
2525
|
+
}
|
|
2526
|
+
_inputGroupRoot(e) {
|
|
2527
|
+
let t = e, n = new Set([$(t)]);
|
|
2528
|
+
for (; t.forkOf !== void 0 && !n.has(t.forkOf);) {
|
|
2529
|
+
let e = this._nodeIndex.get(t.forkOf);
|
|
2530
|
+
if (e?.node.kind !== "input" || e.node.parentCodecMessageId !== t.parentCodecMessageId) break;
|
|
2531
|
+
t = e.node, n.add($(t));
|
|
2532
|
+
}
|
|
2533
|
+
return t;
|
|
2534
|
+
}
|
|
2535
|
+
_getSiblingGroup(e) {
|
|
2536
|
+
this._siblingCacheVersion !== this._structuralVersion && (this._siblingCache.clear(), this._siblingCacheVersion = this._structuralVersion);
|
|
2537
|
+
let t = this._siblingCache.get(e);
|
|
2538
|
+
if (t) return t;
|
|
2539
|
+
let n = this._nodeIndex.get(e);
|
|
2540
|
+
if (!n) return [];
|
|
2541
|
+
let r = n.node;
|
|
2542
|
+
r.kind === "input" && (r = this._inputGroupRoot(r));
|
|
2543
|
+
let i = r.parentCodecMessageId, a = [], o = this._parentIndex.get(i);
|
|
2544
|
+
if (o) for (let e of o) {
|
|
2545
|
+
let t = this._nodeIndex.get(e);
|
|
2546
|
+
t && this._isSiblingOf(t.node, r) && a.push(t);
|
|
2547
|
+
}
|
|
2548
|
+
a.sort((e, t) => this._compareNodes(e, t));
|
|
2549
|
+
for (let e of a) this._siblingCache.set($(e.node), a);
|
|
2550
|
+
return this._siblingCache.set(e, a), a;
|
|
2551
|
+
}
|
|
2552
|
+
_isSiblingOf(e, t) {
|
|
2553
|
+
if (e.kind !== t.kind || e.parentCodecMessageId !== t.parentCodecMessageId) return !1;
|
|
2554
|
+
if (e.kind === "run") return !0;
|
|
2555
|
+
let n = $(t);
|
|
2556
|
+
if ($(e) === n) return !0;
|
|
2557
|
+
let r = e, i = new Set([$(r)]);
|
|
2558
|
+
for (; r.kind === "input" && r.forkOf !== void 0;) {
|
|
2559
|
+
if (r.forkOf === n) return !0;
|
|
2560
|
+
if (i.has(r.forkOf)) break;
|
|
2561
|
+
let e = this._nodeIndex.get(r.forkOf);
|
|
2562
|
+
if (!e) break;
|
|
2563
|
+
r = e.node, i.add($(r));
|
|
2564
|
+
}
|
|
2565
|
+
return !1;
|
|
2566
|
+
}
|
|
2567
|
+
getGroupRoot(e) {
|
|
2568
|
+
let t = this._nodeIndex.get(e);
|
|
2569
|
+
if (!t) return e;
|
|
2570
|
+
if (t.node.kind === "input") return $(this._inputGroupRoot(t.node));
|
|
2571
|
+
let n = this._getSiblingGroup(e)[0]?.node;
|
|
2572
|
+
return n ? $(n) : e;
|
|
2573
|
+
}
|
|
2574
|
+
visibleNodes(e = /* @__PURE__ */ new Map()) {
|
|
2575
|
+
this._logger.trace("DefaultTree.visibleNodes();");
|
|
2576
|
+
let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
|
|
2577
|
+
for (let i of this._sortedNodes) {
|
|
2578
|
+
let a = i.node, o = $(a), s = this._parentKeyOf(a);
|
|
2579
|
+
if (s !== void 0 && !n.has(s)) continue;
|
|
2580
|
+
let c = this._getSiblingGroup(o);
|
|
2581
|
+
if (c.length > 1) {
|
|
2582
|
+
let t = this.getGroupRoot(o), n = r.get(t);
|
|
2583
|
+
if (n === void 0) {
|
|
2584
|
+
let i = e.get(t);
|
|
2585
|
+
if (i !== void 0 && c.some((e) => $(e.node) === i)) n = i;
|
|
2586
|
+
else {
|
|
2587
|
+
let e = c.at(-1);
|
|
2588
|
+
if (!e) break;
|
|
2589
|
+
n = $(e.node);
|
|
2590
|
+
}
|
|
2591
|
+
r.set(t, n);
|
|
1890
2592
|
}
|
|
2593
|
+
if (o !== n) continue;
|
|
1891
2594
|
}
|
|
2595
|
+
n.add(o), t.push(a);
|
|
1892
2596
|
}
|
|
1893
|
-
|
|
1894
|
-
for (let e of r) {
|
|
1895
|
-
let t = crypto.randomUUID();
|
|
1896
|
-
this._ownMsgIds.add(t), a.add(t);
|
|
1897
|
-
let r = n?.parent === void 0 ? u : n.parent ?? void 0, l = Q({
|
|
1898
|
-
role: "user",
|
|
1899
|
-
turnId: i,
|
|
1900
|
-
msgId: t,
|
|
1901
|
-
turnClientId: this._clientId,
|
|
1902
|
-
parent: r,
|
|
1903
|
-
forkOf: n?.forkOf
|
|
1904
|
-
});
|
|
1905
|
-
this._upsertAndNotify(e, l);
|
|
1906
|
-
let d = {
|
|
1907
|
-
[o]: t,
|
|
1908
|
-
[c]: "user"
|
|
1909
|
-
};
|
|
1910
|
-
r && (d[p] = r), s.push({
|
|
1911
|
-
message: e,
|
|
1912
|
-
headers: d
|
|
1913
|
-
}), n?.parent === void 0 && !n?.forkOf && (u = t);
|
|
1914
|
-
}
|
|
1915
|
-
this._turnMsgIds.set(i, a);
|
|
1916
|
-
let f = this._router.createStream(i), m = this._headersFn?.() ?? {}, h = {
|
|
1917
|
-
...this._bodyFn?.() ?? {},
|
|
1918
|
-
history: l,
|
|
1919
|
-
...n?.body,
|
|
1920
|
-
turnId: i,
|
|
1921
|
-
clientId: this._clientId,
|
|
1922
|
-
messages: s,
|
|
1923
|
-
...n?.forkOf !== void 0 && { forkOf: n.forkOf },
|
|
1924
|
-
...d !== void 0 && { parent: d }
|
|
1925
|
-
}, g = {
|
|
1926
|
-
...m,
|
|
1927
|
-
...n?.headers
|
|
1928
|
-
};
|
|
1929
|
-
return this._fetchFn(this._api, {
|
|
1930
|
-
method: "POST",
|
|
1931
|
-
headers: {
|
|
1932
|
-
"Content-Type": "application/json",
|
|
1933
|
-
...g
|
|
1934
|
-
},
|
|
1935
|
-
body: JSON.stringify(h),
|
|
1936
|
-
...this._credentials ? { credentials: this._credentials } : {}
|
|
1937
|
-
}).then((t) => {
|
|
1938
|
-
t.ok || (this._emitter.emit("error", new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(t.status)} ${t.statusText}`, W.TransportSendFailed, t.status)), this._router.closeStream(i));
|
|
1939
|
-
}).catch((t) => {
|
|
1940
|
-
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
1941
|
-
this._emitter.emit("error", new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${t instanceof Error ? t.message : String(t)}`, W.TransportSendFailed, 500, n)), this._router.closeStream(i);
|
|
1942
|
-
}), {
|
|
1943
|
-
stream: f,
|
|
1944
|
-
turnId: i,
|
|
1945
|
-
cancel: async () => this.cancel({ turnId: i })
|
|
1946
|
-
};
|
|
2597
|
+
return t;
|
|
1947
2598
|
}
|
|
1948
|
-
|
|
1949
|
-
this._logger.trace("
|
|
1950
|
-
let
|
|
1951
|
-
return
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
2599
|
+
getRunNode(e) {
|
|
2600
|
+
this._logger.trace("DefaultTree.getRunNode();", { runId: e });
|
|
2601
|
+
let t = this._nodeIndex.get(e)?.node;
|
|
2602
|
+
return t?.kind === "run" ? t : void 0;
|
|
2603
|
+
}
|
|
2604
|
+
getNode(e) {
|
|
2605
|
+
return this._logger.trace("DefaultTree.getNode();", { key: e }), this._nodeIndex.get(e)?.node;
|
|
2606
|
+
}
|
|
2607
|
+
getNodeByCodecMessageId(e) {
|
|
2608
|
+
this._logger.trace("DefaultTree.getNodeByCodecMessageId();", { codecMessageId: e });
|
|
2609
|
+
let t = this._codecMessageIdToNodeKey.get(e);
|
|
2610
|
+
return t === void 0 ? void 0 : this._nodeIndex.get(t)?.node;
|
|
2611
|
+
}
|
|
2612
|
+
getReplyRuns(e) {
|
|
2613
|
+
let t = this._replyRunsByInput.get(e);
|
|
2614
|
+
if (!t) return [];
|
|
2615
|
+
let n = [];
|
|
2616
|
+
for (let e of t) {
|
|
2617
|
+
let t = this._nodeIndex.get(e)?.node;
|
|
2618
|
+
t?.kind === "run" && n.push(t);
|
|
2619
|
+
}
|
|
2620
|
+
return n;
|
|
2621
|
+
}
|
|
2622
|
+
getSiblingNodes(e) {
|
|
2623
|
+
return this._logger.trace("DefaultTree.getSiblingNodes();", { key: e }), this._getSiblingGroup(e).map((e) => e.node);
|
|
2624
|
+
}
|
|
2625
|
+
applyMessage(e, t, n) {
|
|
2626
|
+
let r = t[o], i = t[l], a = r === void 0 && i !== void 0 && t.role === "user" && e.inputs.length > 0 ? i : void 0;
|
|
2627
|
+
if (r === void 0 && a === void 0) {
|
|
2628
|
+
this._logger.warn("Tree.applyMessage(); message has no run-id and is not a user input; skipping");
|
|
2629
|
+
return;
|
|
2630
|
+
}
|
|
2631
|
+
let s = [...e.inputs, ...e.outputs], c = a ?? r;
|
|
2632
|
+
if (s.length === 0 && c !== void 0 && !this._nodeIndex.has(c)) return;
|
|
2633
|
+
let u = this._structuralVersion;
|
|
2634
|
+
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");
|
|
2635
|
+
}
|
|
2636
|
+
_applyInputMessage(e, t, n, r) {
|
|
2637
|
+
let i = this._nodeIndex.get(e);
|
|
2638
|
+
i ? i.node.kind === "input" && n && !i.node.serial && (this._logger.debug("Tree.applyMessage(); promoting input serial", {
|
|
2639
|
+
codecMessageId: e,
|
|
2640
|
+
serial: n
|
|
2641
|
+
}), 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", {
|
|
2642
|
+
runId: void 0,
|
|
2643
|
+
inputCodecMessageId: e,
|
|
2644
|
+
codecMessageId: e,
|
|
2645
|
+
serial: n,
|
|
2646
|
+
events: []
|
|
1959
2647
|
});
|
|
1960
2648
|
}
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
2649
|
+
_applyRunMessage(e, t, n, r) {
|
|
2650
|
+
let i = n[l], a = n[_], o = [...t.inputs, ...t.outputs], s = t.outputs, c = this._nodeIndex.get(e);
|
|
2651
|
+
if (!c && i !== void 0) {
|
|
2652
|
+
let e = this._codecMessageIdToNodeKey.get(i), t = e === void 0 ? void 0 : this._nodeIndex.get(e);
|
|
2653
|
+
t?.node.kind === "run" && t.node.startSerial === void 0 && (c = t);
|
|
2654
|
+
}
|
|
2655
|
+
c ? r && c.node.kind === "run" && !c.node.startSerial && (this._logger.debug("Tree.applyMessage(); promoting startSerial", {
|
|
2656
|
+
runId: e,
|
|
2657
|
+
serial: r
|
|
2658
|
+
}), 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 }));
|
|
2659
|
+
let u = $(c.node);
|
|
2660
|
+
i && this._codecMessageIdToNodeKey.set(i, u), this._foldInto(c, o, r, i), this._emitter.emit("output", {
|
|
2661
|
+
runId: u,
|
|
2662
|
+
inputCodecMessageId: a,
|
|
2663
|
+
codecMessageId: i,
|
|
2664
|
+
serial: r,
|
|
2665
|
+
events: s
|
|
1972
2666
|
});
|
|
1973
2667
|
}
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
2668
|
+
_indexReplyRun(e, t) {
|
|
2669
|
+
e.parentCodecMessageId !== void 0 && Yt(this._replyRunsByInput, e.parentCodecMessageId, t);
|
|
2670
|
+
}
|
|
2671
|
+
applyRunLifecycle(e) {
|
|
2672
|
+
this._logger.trace("DefaultTree.applyRunLifecycle();", {
|
|
2673
|
+
type: e.type,
|
|
2674
|
+
runId: e.runId
|
|
2675
|
+
});
|
|
2676
|
+
let t = this._structuralVersion;
|
|
2677
|
+
switch (e.type) {
|
|
2678
|
+
case "start":
|
|
2679
|
+
this._applyRunStart(e);
|
|
2680
|
+
break;
|
|
2681
|
+
case "suspend":
|
|
2682
|
+
this._applyRunSuspend(e);
|
|
2683
|
+
break;
|
|
2684
|
+
case "resume":
|
|
2685
|
+
this._applyRunResume(e);
|
|
2686
|
+
break;
|
|
2687
|
+
case "end":
|
|
2688
|
+
this._applyRunEnd(e);
|
|
2689
|
+
break;
|
|
2690
|
+
}
|
|
2691
|
+
this._emitter.emit("run", e), this._structuralVersion !== t && this._emitter.emit("update");
|
|
2692
|
+
}
|
|
2693
|
+
_applyRunStart(e) {
|
|
2694
|
+
let t = this._nodeIndex.get(e.runId);
|
|
2695
|
+
if (t?.node.kind === "run") {
|
|
2696
|
+
let n = t.node;
|
|
2697
|
+
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) {
|
|
2698
|
+
let t = this._codecMessageIdToNodeKey.get(e.forkOf);
|
|
2699
|
+
t !== void 0 && t !== e.runId && (n.forkOf = t, this._structuralVersion++);
|
|
2700
|
+
}
|
|
2701
|
+
n.regeneratesCodecMessageId === void 0 && e.regenerates !== void 0 && (n.regeneratesCodecMessageId = e.regenerates, this._structuralVersion++), n.invocationId === "" && e.invocationId !== "" && (n.invocationId = e.invocationId);
|
|
2702
|
+
} else if (!t) {
|
|
2703
|
+
let t = this._createRunFromLifecycle(e);
|
|
2704
|
+
this._insertNode(e.runId, t, t.node.parentCodecMessageId), this._indexReplyRun(t.node, e.runId);
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
_applyRunSuspend(e) {
|
|
2708
|
+
let t = this._nodeIndex.get(e.runId);
|
|
2709
|
+
t?.node.kind === "run" && (t.node.status = "suspended", t.node.endSerial = e.serial);
|
|
2710
|
+
}
|
|
2711
|
+
_applyRunResume(e) {
|
|
2712
|
+
let t = this._nodeIndex.get(e.runId);
|
|
2713
|
+
t?.node.kind === "run" && t.node.status === "suspended" && (t.node.status = "active");
|
|
2714
|
+
}
|
|
2715
|
+
_applyRunEnd(e) {
|
|
2716
|
+
let t = this._nodeIndex.get(e.runId);
|
|
2717
|
+
t?.node.kind === "run" && (t.node.status = e.reason, t.node.endSerial = e.serial);
|
|
2718
|
+
}
|
|
2719
|
+
delete(e) {
|
|
2720
|
+
let t = this._nodeIndex.get(e);
|
|
2721
|
+
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 && Xt(this._replyRunsByInput, t.node.parentCodecMessageId, e), this._structuralVersion++, this._emitter.emit("update"));
|
|
2722
|
+
}
|
|
2723
|
+
_createRunFromHeaders(e, t, n) {
|
|
2724
|
+
let r = t[m];
|
|
2725
|
+
return this._buildRunNode({
|
|
2726
|
+
runId: e,
|
|
2727
|
+
parentCodecMessageId: t[p],
|
|
2728
|
+
forkOf: r ? this._codecMessageIdToNodeKey.get(r) : void 0,
|
|
2729
|
+
regeneratesCodecMessageId: t[h],
|
|
2730
|
+
clientId: t["run-client-id"] ?? "",
|
|
2731
|
+
invocationId: t["invocation-id"] ?? "",
|
|
2732
|
+
startSerial: n
|
|
2733
|
+
});
|
|
2734
|
+
}
|
|
2735
|
+
_buildRunNode(e) {
|
|
2736
|
+
return {
|
|
2737
|
+
node: {
|
|
2738
|
+
kind: "run",
|
|
2739
|
+
runId: e.runId,
|
|
2740
|
+
parentCodecMessageId: e.parentCodecMessageId,
|
|
2741
|
+
forkOf: e.forkOf,
|
|
2742
|
+
regeneratesCodecMessageId: e.regeneratesCodecMessageId,
|
|
2743
|
+
clientId: e.clientId,
|
|
2744
|
+
invocationId: e.invocationId,
|
|
2745
|
+
status: "active",
|
|
2746
|
+
projection: this._codec.init(),
|
|
2747
|
+
startSerial: e.startSerial,
|
|
2748
|
+
endSerial: void 0
|
|
2749
|
+
},
|
|
2750
|
+
insertSeq: this._seqCounter++
|
|
2751
|
+
};
|
|
2752
|
+
}
|
|
2753
|
+
_createInputNodeFromHeaders(e, t, n) {
|
|
2754
|
+
let r = t[m];
|
|
2755
|
+
return {
|
|
2756
|
+
node: {
|
|
2757
|
+
kind: "input",
|
|
2758
|
+
codecMessageId: e,
|
|
2759
|
+
parentCodecMessageId: t[p],
|
|
2760
|
+
forkOf: r,
|
|
2761
|
+
projection: this._codec.init(),
|
|
2762
|
+
serial: n
|
|
2763
|
+
},
|
|
2764
|
+
insertSeq: this._seqCounter++
|
|
2765
|
+
};
|
|
2766
|
+
}
|
|
2767
|
+
_createRunFromLifecycle(e) {
|
|
2768
|
+
let t = e.forkOf;
|
|
2769
|
+
return this._buildRunNode({
|
|
2770
|
+
runId: e.runId,
|
|
2771
|
+
parentCodecMessageId: e.parent,
|
|
2772
|
+
forkOf: t ? this._codecMessageIdToNodeKey.get(t) : void 0,
|
|
2773
|
+
regeneratesCodecMessageId: e.regenerates,
|
|
2774
|
+
clientId: e.clientId,
|
|
2775
|
+
invocationId: e.invocationId,
|
|
2776
|
+
startSerial: e.serial
|
|
1987
2777
|
});
|
|
1988
2778
|
}
|
|
1989
2779
|
on(e, t) {
|
|
1990
|
-
if (this._closed) return Ue;
|
|
1991
2780
|
let n = t;
|
|
1992
2781
|
return this._emitter.on(e, n), () => {
|
|
1993
2782
|
this._emitter.off(e, n);
|
|
1994
2783
|
};
|
|
1995
2784
|
}
|
|
1996
|
-
|
|
1997
|
-
|
|
2785
|
+
emitAblyMessage(e) {
|
|
2786
|
+
this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
|
|
2787
|
+
}
|
|
2788
|
+
}, Qt = (e, t) => new Zt(e, t), $t = (e, t) => {
|
|
2789
|
+
for (let n of t) {
|
|
2790
|
+
let t = D(n), i = t[l];
|
|
2791
|
+
if (!i) continue;
|
|
2792
|
+
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";
|
|
2793
|
+
(o || s) && e.startedCodecMessageIds.add(i), (o || u) && e.terminatedCodecMessageIds.add(i), e.startedCodecMessageIds.has(i) && e.terminatedCodecMessageIds.has(i) && e.completedCodecMessageIds.add(i);
|
|
2794
|
+
}
|
|
2795
|
+
}, en = async (e, t, n) => {
|
|
2796
|
+
e.rawMessages.push(...t.items), e.lastAblyPage = t, $t(e, t.items);
|
|
2797
|
+
let r = e.returnedCount + n;
|
|
2798
|
+
for (; e.completedCodecMessageIds.size < r && t.hasNext();) {
|
|
2799
|
+
e.logger.debug("loadHistory.fetchUntilLimit(); fetching next page", {
|
|
2800
|
+
collected: e.rawMessages.length,
|
|
2801
|
+
completed: e.completedCodecMessageIds.size
|
|
2802
|
+
});
|
|
2803
|
+
let n = await t.next();
|
|
2804
|
+
if (!n) break;
|
|
2805
|
+
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, $t(e, n.items);
|
|
1998
2806
|
}
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2807
|
+
}, tn = (e, t) => {
|
|
2808
|
+
let n = e.completedCodecMessageIds.size, r = Math.min(t, Math.max(0, n - e.returnedCount));
|
|
2809
|
+
e.returnedCount += r;
|
|
2810
|
+
let i = n > e.returnedCount, a = e.lastAblyPage?.hasNext() ?? !1, o = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
|
|
2811
|
+
return e.returnedRawCount = e.rawMessages.length, {
|
|
2812
|
+
rawMessages: o,
|
|
2813
|
+
hasNext: () => i || a,
|
|
2814
|
+
next: async () => {
|
|
2815
|
+
if (i) return tn(e, t);
|
|
2816
|
+
if (!a || !e.lastAblyPage) return;
|
|
2817
|
+
let n = await e.lastAblyPage.next();
|
|
2818
|
+
if (n) return await en(e, n, t), tn(e, t);
|
|
2004
2819
|
}
|
|
2005
|
-
|
|
2820
|
+
};
|
|
2821
|
+
}, nn = async (e, t, n) => {
|
|
2822
|
+
let r = t?.limit ?? 100, i = {
|
|
2823
|
+
rawMessages: [],
|
|
2824
|
+
returnedCount: 0,
|
|
2825
|
+
returnedRawCount: 0,
|
|
2826
|
+
lastAblyPage: void 0,
|
|
2827
|
+
startedCodecMessageIds: /* @__PURE__ */ new Set(),
|
|
2828
|
+
terminatedCodecMessageIds: /* @__PURE__ */ new Set(),
|
|
2829
|
+
completedCodecMessageIds: /* @__PURE__ */ new Set(),
|
|
2830
|
+
logger: n
|
|
2831
|
+
};
|
|
2832
|
+
n.trace("loadHistory();", { limit: r });
|
|
2833
|
+
let a = r * 10;
|
|
2834
|
+
return await e.attach(), await en(i, await e.history({
|
|
2835
|
+
untilAttach: !0,
|
|
2836
|
+
limit: a
|
|
2837
|
+
}), r), tn(i, r);
|
|
2838
|
+
}, rn = (e) => Array.isArray(e) ? e : [e], an = 3, on = (e) => ({
|
|
2839
|
+
runId: e.runId,
|
|
2840
|
+
clientId: e.clientId,
|
|
2841
|
+
status: e.status,
|
|
2842
|
+
invocationId: e.invocationId
|
|
2843
|
+
}), sn = class {
|
|
2844
|
+
constructor(e) {
|
|
2845
|
+
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 Q(this._logger), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
|
|
2846
|
+
this._onTreeUpdate();
|
|
2847
|
+
}), this._tree.on("ably-message", (e) => {
|
|
2848
|
+
this._onTreeAblyMessage(e);
|
|
2849
|
+
}), this._tree.on("run", (e) => {
|
|
2850
|
+
this._onTreeRun(e);
|
|
2851
|
+
}), this._tree.on("output", (e) => {
|
|
2852
|
+
this._onTreeOutput(e);
|
|
2853
|
+
}));
|
|
2006
2854
|
}
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
return this._tree.getNodeByKey(t)?.headers;
|
|
2855
|
+
_onTreeOutput(e) {
|
|
2856
|
+
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"));
|
|
2010
2857
|
}
|
|
2011
2858
|
getMessages() {
|
|
2012
|
-
return this.
|
|
2013
|
-
}
|
|
2014
|
-
getMessagesWithHeaders() {
|
|
2015
|
-
return this._getMessagesWithHeaders();
|
|
2016
|
-
}
|
|
2017
|
-
getAblyMessages() {
|
|
2018
|
-
return [...this._ablyMessages];
|
|
2019
|
-
}
|
|
2020
|
-
async history(t) {
|
|
2021
|
-
if (this._closed) throw new e.ErrorInfo("unable to load history; transport is closed", W.TransportClosed, 400);
|
|
2022
|
-
this._logger.trace("ClientTransport.history();", { limit: t?.limit });
|
|
2023
|
-
let n = t?.limit ?? 100, r = new Set(this._tree.flatten().map((e) => this._codec.getMessageKey(e))), i = await Be(this._channel, this._codec, t, this._logger), a = await this._loadUntilVisible(i, n, r);
|
|
2024
|
-
i = a.lastPage;
|
|
2025
|
-
let o = a.newVisible;
|
|
2026
|
-
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
2027
|
-
let s = o.slice(-n), c = o.slice(0, -n);
|
|
2028
|
-
this._releaseWithheld(s);
|
|
2029
|
-
let l = (e) => ({
|
|
2030
|
-
items: e,
|
|
2031
|
-
hasNext: () => c.length > 0 || i.hasNext(),
|
|
2032
|
-
next: async () => {
|
|
2033
|
-
if (c.length > 0) {
|
|
2034
|
-
let e = c.splice(-n, n);
|
|
2035
|
-
return this._releaseWithheld(e), l(e);
|
|
2036
|
-
}
|
|
2037
|
-
if (!i.hasNext()) return;
|
|
2038
|
-
let e = await i.next();
|
|
2039
|
-
if (!e) return;
|
|
2040
|
-
let t = new Set(r);
|
|
2041
|
-
for (let e of this._tree.flatten()) t.add(this._codec.getMessageKey(e));
|
|
2042
|
-
let a = await this._loadUntilVisible(e, n, t);
|
|
2043
|
-
i = a.lastPage;
|
|
2044
|
-
let o = a.newVisible;
|
|
2045
|
-
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
2046
|
-
let s = o.splice(-n, n);
|
|
2047
|
-
if (c.push(...o), this._releaseWithheld(s), s.length !== 0) return l(s);
|
|
2048
|
-
}
|
|
2049
|
-
});
|
|
2050
|
-
return l(s);
|
|
2859
|
+
return this._lastVisibleMessagePairs;
|
|
2051
2860
|
}
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2861
|
+
runs() {
|
|
2862
|
+
return this._cachedNodes.filter((e) => e.kind === "run").map((e) => on(e));
|
|
2863
|
+
}
|
|
2864
|
+
_computeFlatNodes() {
|
|
2865
|
+
let e = this._treeVisibleNodes();
|
|
2866
|
+
return this._withheldRunIds.size === 0 ? e : e.filter((e) => !this._withheldRunIds.has($(e)));
|
|
2867
|
+
}
|
|
2868
|
+
_recomputeAndEmit() {
|
|
2869
|
+
this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update");
|
|
2870
|
+
}
|
|
2871
|
+
_recomputeAndEmitIfChanged() {
|
|
2872
|
+
let e = this._computeFlatNodes();
|
|
2873
|
+
this._visibleChanged(e) && (this._cachedNodes = e, this._updateVisibleSnapshot(e), this._emitter.emit("update"));
|
|
2874
|
+
}
|
|
2875
|
+
_runByCodecMessageId(e) {
|
|
2876
|
+
let t = this._tree.getNodeByCodecMessageId(e);
|
|
2877
|
+
return t?.kind === "run" ? t : void 0;
|
|
2878
|
+
}
|
|
2879
|
+
_extractMessages(e) {
|
|
2880
|
+
let t = [];
|
|
2881
|
+
for (let n of e) for (let e of this._codec.getMessages(n.projection)) t.push(e);
|
|
2882
|
+
return t;
|
|
2883
|
+
}
|
|
2884
|
+
hasOlder() {
|
|
2885
|
+
return this._withheldBuffer.length > 0 || this._hasMoreHistory;
|
|
2886
|
+
}
|
|
2887
|
+
async loadOlder(e = 100) {
|
|
2888
|
+
if (!(this._closed || this._loadingOlder)) {
|
|
2889
|
+
this._loadingOlder = !0, this._logger.trace("DefaultView.loadOlder();", { limit: e });
|
|
2890
|
+
try {
|
|
2891
|
+
if (this._withheldBuffer.length > 0) {
|
|
2892
|
+
let t = this._withheldBuffer.splice(-e, e);
|
|
2893
|
+
this._releaseWithheld(t);
|
|
2894
|
+
return;
|
|
2895
|
+
}
|
|
2896
|
+
if (!this._hasMoreHistory && !this._lastHistoryPage) {
|
|
2897
|
+
await this._loadFirstPage(e);
|
|
2898
|
+
return;
|
|
2899
|
+
}
|
|
2900
|
+
if (!this._hasMoreHistory) return;
|
|
2901
|
+
if (!this._lastHistoryPage?.hasNext()) {
|
|
2902
|
+
this._hasMoreHistory = !1;
|
|
2903
|
+
return;
|
|
2904
|
+
}
|
|
2905
|
+
let t = await this._lastHistoryPage.next();
|
|
2906
|
+
if (this._closed || !t) {
|
|
2907
|
+
t || (this._hasMoreHistory = !1);
|
|
2908
|
+
return;
|
|
2909
|
+
}
|
|
2910
|
+
await this._revealFromPage(t, e);
|
|
2911
|
+
} catch (e) {
|
|
2912
|
+
throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
|
|
2913
|
+
} finally {
|
|
2914
|
+
this._loadingOlder = !1;
|
|
2059
2915
|
}
|
|
2060
|
-
this._channel.unsubscribe(this._onMessage);
|
|
2061
|
-
for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
2062
|
-
this._turnObservers.clear(), this._emitter.off(), this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear(), this._turnClientIds.clear(), this._withheldKeys.clear(), this._ablyMessages.length = 0;
|
|
2063
2916
|
}
|
|
2064
2917
|
}
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
if (
|
|
2069
|
-
|
|
2070
|
-
|
|
2918
|
+
runOf(e) {
|
|
2919
|
+
this._logger.trace("DefaultView.runOf();", { codecMessageId: e });
|
|
2920
|
+
let t = this._tree.getNodeByCodecMessageId(e);
|
|
2921
|
+
if (!t) return;
|
|
2922
|
+
if (t.kind === "run") return on(t);
|
|
2923
|
+
let n = this._selectedReplyRun(t.codecMessageId);
|
|
2924
|
+
return n ? on(n) : void 0;
|
|
2925
|
+
}
|
|
2926
|
+
_selectedReplyRun(e) {
|
|
2927
|
+
let t = this._tree.getReplyRuns(e);
|
|
2928
|
+
if (t.length === 0) return;
|
|
2929
|
+
if (t.length === 1) return t[0];
|
|
2930
|
+
let n = this._tree.getGroupRoot(t[0]?.runId ?? ""), r = this._regenSelections.get(n), i = r && r.kind !== "pending" ? r.selectedRunId : void 0;
|
|
2931
|
+
if (i !== void 0) {
|
|
2932
|
+
let e = t.find((e) => e.runId === i);
|
|
2933
|
+
if (e) return e;
|
|
2071
2934
|
}
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2935
|
+
return t.toSorted((e, t) => (e.startSerial ?? "").localeCompare(t.startSerial ?? "")).at(-1);
|
|
2936
|
+
}
|
|
2937
|
+
run(e) {
|
|
2938
|
+
this._logger.trace("DefaultView.run();", { runId: e });
|
|
2939
|
+
let t = this._tree.getRunNode(e);
|
|
2940
|
+
return t ? on(t) : void 0;
|
|
2941
|
+
}
|
|
2942
|
+
branchSelection(e) {
|
|
2943
|
+
let t = this._resolveMessageBranchPoint(e);
|
|
2944
|
+
if (t) {
|
|
2945
|
+
let e = t.siblings.flatMap((e) => {
|
|
2946
|
+
let t = this._codec.getMessages(e.projection).at(0);
|
|
2947
|
+
return t ? [t.message] : [];
|
|
2948
|
+
});
|
|
2949
|
+
if (e.length > 0) {
|
|
2950
|
+
let n = this._resolveSelectedIndex(t), r = Math.max(0, Math.min(n, e.length - 1)), i = e[r];
|
|
2951
|
+
return {
|
|
2952
|
+
hasSiblings: e.length > 1,
|
|
2953
|
+
siblings: e,
|
|
2954
|
+
index: r,
|
|
2955
|
+
selected: i
|
|
2956
|
+
};
|
|
2087
2957
|
}
|
|
2088
|
-
await t.appendEvent(o);
|
|
2089
2958
|
}
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2959
|
+
let n = this._tree.getNodeByCodecMessageId(e);
|
|
2960
|
+
if (n) {
|
|
2961
|
+
let t = this._codec.getMessages(n.projection).find((t) => t.codecMessageId === e);
|
|
2962
|
+
if (t !== void 0) return {
|
|
2963
|
+
hasSiblings: !1,
|
|
2964
|
+
siblings: [t.message],
|
|
2965
|
+
index: 0,
|
|
2966
|
+
selected: t.message
|
|
2967
|
+
};
|
|
2968
|
+
}
|
|
2969
|
+
return {
|
|
2970
|
+
hasSiblings: !1,
|
|
2971
|
+
siblings: [],
|
|
2972
|
+
index: 0,
|
|
2973
|
+
selected: void 0
|
|
2974
|
+
};
|
|
2104
2975
|
}
|
|
2105
|
-
|
|
2106
|
-
this._logger
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
});
|
|
2110
|
-
let r = n ?? new AbortController(), i = t ?? "";
|
|
2111
|
-
return this._activeTurns.set(e, {
|
|
2112
|
-
controller: r,
|
|
2113
|
-
clientId: i
|
|
2114
|
-
}), await this._channel.publish({
|
|
2115
|
-
name: _,
|
|
2116
|
-
extras: { headers: {
|
|
2117
|
-
[a]: e,
|
|
2118
|
-
[s]: i
|
|
2119
|
-
} }
|
|
2120
|
-
}), this._logger?.debug("DefaultTurnManager.startTurn(); turn started", { turnId: e }), r.signal;
|
|
2121
|
-
}
|
|
2122
|
-
async endTurn(e, t) {
|
|
2123
|
-
this._logger?.trace("DefaultTurnManager.endTurn();", {
|
|
2124
|
-
turnId: e,
|
|
2125
|
-
reason: t
|
|
2126
|
-
});
|
|
2127
|
-
let n = this._activeTurns.get(e)?.clientId ?? "";
|
|
2128
|
-
await this._channel.publish({
|
|
2129
|
-
name: v,
|
|
2130
|
-
extras: { headers: {
|
|
2131
|
-
[a]: e,
|
|
2132
|
-
[s]: n,
|
|
2133
|
-
[h]: t
|
|
2134
|
-
} }
|
|
2135
|
-
}), this._activeTurns.delete(e), this._logger?.debug("DefaultTurnManager.endTurn(); turn ended", {
|
|
2136
|
-
turnId: e,
|
|
2137
|
-
reason: t
|
|
2976
|
+
selectSibling(e, t) {
|
|
2977
|
+
this._logger.trace("DefaultView.selectSibling();", {
|
|
2978
|
+
codecMessageId: e,
|
|
2979
|
+
index: t
|
|
2138
2980
|
});
|
|
2981
|
+
let n = this._resolveMessageBranchPoint(e);
|
|
2982
|
+
if (!n) return;
|
|
2983
|
+
let r = Math.max(0, Math.min(t, n.siblings.length - 1)), i = n.siblings[r];
|
|
2984
|
+
i && (n.kind === "fork-of" ? (this._branchSelections.set(n.groupRoot, {
|
|
2985
|
+
kind: "user",
|
|
2986
|
+
selectedKey: $(i)
|
|
2987
|
+
}), this._logger.debug("DefaultView.selectSibling(); fork-of", {
|
|
2988
|
+
codecMessageId: e,
|
|
2989
|
+
index: r,
|
|
2990
|
+
selectedKey: $(i)
|
|
2991
|
+
})) : (this._regenSelections.set(n.groupRoot, {
|
|
2992
|
+
kind: "user",
|
|
2993
|
+
selectedRunId: $(i)
|
|
2994
|
+
}), this._logger.debug("DefaultView.selectSibling(); regenerate", {
|
|
2995
|
+
codecMessageId: e,
|
|
2996
|
+
index: r,
|
|
2997
|
+
selectedRunId: $(i),
|
|
2998
|
+
groupRoot: n.groupRoot
|
|
2999
|
+
})), this._recomputeAndEmit());
|
|
3000
|
+
}
|
|
3001
|
+
_resolveSelectedIndex(e) {
|
|
3002
|
+
if (e.kind === "fork-of") {
|
|
3003
|
+
let t = this._branchSelections.get(e.groupRoot);
|
|
3004
|
+
if (!t) return e.siblings.length - 1;
|
|
3005
|
+
let n = e.siblings.findIndex((e) => $(e) === t.selectedKey);
|
|
3006
|
+
return n === -1 ? e.siblings.length - 1 : n;
|
|
3007
|
+
}
|
|
3008
|
+
let t = this._regenSelections.get(e.groupRoot);
|
|
3009
|
+
if (!t || t.kind === "pending") return e.siblings.length - 1;
|
|
3010
|
+
let n = e.siblings.findIndex((e) => $(e) === t.selectedRunId);
|
|
3011
|
+
return n === -1 ? e.siblings.length - 1 : n;
|
|
2139
3012
|
}
|
|
2140
|
-
|
|
2141
|
-
|
|
3013
|
+
_resolveMessageBranchPoint(e) {
|
|
3014
|
+
let t = this._tree.getNodeByCodecMessageId(e);
|
|
3015
|
+
if (!t) return;
|
|
3016
|
+
if (t.kind === "input") {
|
|
3017
|
+
let e = this._tree.getSiblingNodes(t.codecMessageId);
|
|
3018
|
+
return e.length > 1 ? {
|
|
3019
|
+
kind: "fork-of",
|
|
3020
|
+
groupRoot: this._tree.getGroupRoot(t.codecMessageId),
|
|
3021
|
+
siblings: e
|
|
3022
|
+
} : void 0;
|
|
3023
|
+
}
|
|
3024
|
+
let n = this._tree.getSiblingNodes(t.runId);
|
|
3025
|
+
if (n.length > 1 && this._codec.getMessages(t.projection).at(0)?.codecMessageId === e) return {
|
|
3026
|
+
kind: "regen",
|
|
3027
|
+
groupRoot: this._tree.getGroupRoot(t.runId),
|
|
3028
|
+
siblings: n
|
|
3029
|
+
};
|
|
2142
3030
|
}
|
|
2143
|
-
|
|
2144
|
-
|
|
3031
|
+
async send(t, n) {
|
|
3032
|
+
if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", W.InvalidArgument, 400);
|
|
3033
|
+
let r = rn(t), i = this._lastVisibleMessagePairs.at(-1)?.codecMessageId, a = await this._sendDelegate(r, n, i);
|
|
3034
|
+
return this._applyForkAutoSelect(a, n), a;
|
|
3035
|
+
}
|
|
3036
|
+
_applyForkAutoSelect(e, t) {
|
|
3037
|
+
if (!t?.forkOf) return;
|
|
3038
|
+
let n = e.optimisticCodecMessageIds.at(0);
|
|
3039
|
+
if (n === void 0) return;
|
|
3040
|
+
let r = this._tree.getGroupRoot(n);
|
|
3041
|
+
this._branchSelections.set(r, {
|
|
3042
|
+
kind: "auto",
|
|
3043
|
+
selectedKey: n
|
|
3044
|
+
}), this._recomputeAndEmit();
|
|
3045
|
+
}
|
|
3046
|
+
_applyRegenerateAutoSelect(e, t) {
|
|
3047
|
+
let n = this._runByCodecMessageId(t);
|
|
3048
|
+
if (!n) return;
|
|
3049
|
+
let r = this._tree.getGroupRoot(n.runId);
|
|
3050
|
+
this._regenSelections.set(r, {
|
|
3051
|
+
kind: "pending",
|
|
3052
|
+
carrierCodecMessageId: e.inputCodecMessageId
|
|
3053
|
+
}), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection", {
|
|
3054
|
+
anchorCodecMessageId: t,
|
|
3055
|
+
groupRoot: r,
|
|
3056
|
+
carrier: e.inputCodecMessageId
|
|
3057
|
+
}), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged();
|
|
3058
|
+
}
|
|
3059
|
+
async regenerate(t, n) {
|
|
3060
|
+
if (this._logger.trace("DefaultView.regenerate();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to regenerate; view is closed", W.InvalidArgument, 400);
|
|
3061
|
+
let r = this._runByCodecMessageId(t);
|
|
3062
|
+
if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, W.InvalidArgument, 400);
|
|
3063
|
+
let i = this._findParentMsgId(r, t);
|
|
3064
|
+
if (!i) throw new e.ErrorInfo(`unable to regenerate; parent user message not found for ${t}`, W.InvalidArgument, 400);
|
|
3065
|
+
let a = t;
|
|
3066
|
+
r.regeneratesCodecMessageId !== void 0 && this._codec.getMessages(r.projection).at(0)?.codecMessageId === t && (a = r.regeneratesCodecMessageId);
|
|
3067
|
+
let o = {
|
|
3068
|
+
...n,
|
|
3069
|
+
parent: i
|
|
3070
|
+
}, s = this._codec.createRegenerate(a, i), c = await this._sendDelegate([s], o, i);
|
|
3071
|
+
return this._applyRegenerateAutoSelect(c, a), c;
|
|
3072
|
+
}
|
|
3073
|
+
async edit(t, n, r) {
|
|
3074
|
+
if (this._logger.trace("DefaultView.edit();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to edit; view is closed", W.InvalidArgument, 400);
|
|
3075
|
+
let i = this._tree.getNodeByCodecMessageId(t);
|
|
3076
|
+
if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, W.InvalidArgument, 400);
|
|
3077
|
+
let a = this._findParentMsgId(i, t);
|
|
3078
|
+
return this.send(n, {
|
|
3079
|
+
...r,
|
|
3080
|
+
forkOf: t,
|
|
3081
|
+
parent: a
|
|
3082
|
+
});
|
|
2145
3083
|
}
|
|
2146
|
-
|
|
2147
|
-
this.
|
|
3084
|
+
_findParentMsgId(e, t) {
|
|
3085
|
+
let n = this._lastVisibleMessagePairs, r = n.findIndex((e) => e.codecMessageId === t);
|
|
3086
|
+
if (r > 0) return n[r - 1]?.codecMessageId;
|
|
3087
|
+
if (r === 0) return;
|
|
3088
|
+
let i = this._codec.getMessages(e.projection), a = i.findIndex((e) => e.codecMessageId === t);
|
|
3089
|
+
if (a > 0) return i[a - 1]?.codecMessageId;
|
|
3090
|
+
if (a === 0 && e.parentCodecMessageId !== void 0) {
|
|
3091
|
+
let t = this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);
|
|
3092
|
+
if (t) return this._codec.getMessages(t.projection).at(-1)?.codecMessageId;
|
|
3093
|
+
}
|
|
2148
3094
|
}
|
|
2149
|
-
|
|
2150
|
-
|
|
3095
|
+
on(e, t) {
|
|
3096
|
+
let n = t;
|
|
3097
|
+
return this._emitter.on(e, n), () => {
|
|
3098
|
+
this._emitter.off(e, n);
|
|
3099
|
+
};
|
|
2151
3100
|
}
|
|
2152
3101
|
close() {
|
|
2153
|
-
this.
|
|
2154
|
-
|
|
2155
|
-
|
|
3102
|
+
if (!this._closed) {
|
|
3103
|
+
this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
|
|
3104
|
+
for (let e of this._unsubs) e();
|
|
3105
|
+
this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._regenSelections.clear(), this._withheldRunIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
|
|
3106
|
+
}
|
|
2156
3107
|
}
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
this.
|
|
2160
|
-
this._handleChannelMessage(e);
|
|
2161
|
-
}, this._attachPromise = this._channel.subscribe(g, this._channelListener).then(() => {}, (t) => {
|
|
2162
|
-
let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`, W.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2163
|
-
this._logger?.error("DefaultServerTransport(); subscribe failed"), this._onError?.(n);
|
|
2164
|
-
}), this._logger?.debug("DefaultServerTransport(); transport created");
|
|
3108
|
+
async _loadFirstPage(e) {
|
|
3109
|
+
let t = e * an, n = await nn(this._channel, { limit: t }, this._logger);
|
|
3110
|
+
this._closed || await this._revealFromPage(n, e);
|
|
2165
3111
|
}
|
|
2166
|
-
|
|
2167
|
-
|
|
3112
|
+
async _revealFromPage(e, t) {
|
|
3113
|
+
let n = new Set(this._treeVisibleNodes().map((e) => $(e))), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
|
|
3114
|
+
this._closed || (this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext(), this._splitReveal(r, t));
|
|
2168
3115
|
}
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
for (let e
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
let n = [...this._registeredTurns.keys()];
|
|
2176
|
-
return e.all ? n : e.own && t ? n.filter((e) => this._registeredTurns.get(e)?.clientId === t) : e.clientId ? n.filter((t) => this._registeredTurns.get(t)?.clientId === e.clientId) : e.turnId && this._registeredTurns.has(e.turnId) ? [e.turnId] : [];
|
|
2177
|
-
}
|
|
2178
|
-
async _handleCancelMessage(t) {
|
|
2179
|
-
let n = b(t), r = {};
|
|
2180
|
-
n["x-ably-cancel-turn-id"] ? r.turnId = n[l] : n["x-ably-cancel-own"] === "true" ? r.own = !0 : n["x-ably-cancel-client-id"] ? r.clientId = n[f] : n["x-ably-cancel-all"] === "true" && (r.all = !0);
|
|
2181
|
-
let i = this._resolveFilter(r, t.clientId);
|
|
2182
|
-
if (i.length === 0) return;
|
|
2183
|
-
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); matched turns", {
|
|
2184
|
-
matchedTurnIds: i,
|
|
2185
|
-
filter: r
|
|
2186
|
-
});
|
|
2187
|
-
let a = /* @__PURE__ */ new Map();
|
|
2188
|
-
for (let e of i) {
|
|
2189
|
-
let t = this._registeredTurns.get(e);
|
|
2190
|
-
a.set(e, t?.clientId ?? "");
|
|
2191
|
-
}
|
|
2192
|
-
let o = {
|
|
2193
|
-
message: t,
|
|
2194
|
-
filter: r,
|
|
2195
|
-
matchedTurnIds: i,
|
|
2196
|
-
turnOwners: a
|
|
2197
|
-
};
|
|
2198
|
-
for (let t of i) {
|
|
2199
|
-
let n = this._registeredTurns.get(t);
|
|
2200
|
-
if (n) try {
|
|
2201
|
-
if (n.onCancel && !await n.onCancel(o)) {
|
|
2202
|
-
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); cancel rejected by onCancel", { turnId: t });
|
|
2203
|
-
continue;
|
|
2204
|
-
}
|
|
2205
|
-
n.controller.abort(), this._logger?.debug("DefaultServerTransport._handleCancelMessage(); turn aborted", { turnId: t });
|
|
2206
|
-
} catch (r) {
|
|
2207
|
-
let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`, W.CancelListenerError, 500, r instanceof e.ErrorInfo ? r : void 0);
|
|
2208
|
-
this._logger?.error("DefaultServerTransport._handleCancelMessage(); onCancel threw", { turnId: t }), (n.onError ?? this._onError)?.(i);
|
|
3116
|
+
_splitReveal(e, t) {
|
|
3117
|
+
let n = 0, r = e.length;
|
|
3118
|
+
for (let i = e.length - 1; i >= 0; i--) {
|
|
3119
|
+
if (e[i]?.kind === "run") {
|
|
3120
|
+
if (n === t) break;
|
|
3121
|
+
n++;
|
|
2209
3122
|
}
|
|
3123
|
+
r = i;
|
|
2210
3124
|
}
|
|
3125
|
+
let i = e.slice(r), a = e.slice(0, r);
|
|
3126
|
+
for (let e of a) this._withheldRunIds.add($(e));
|
|
3127
|
+
this._withheldBuffer.push(...a), this._releaseWithheld(i);
|
|
2211
3128
|
}
|
|
2212
|
-
|
|
3129
|
+
_processHistoryPage(e) {
|
|
3130
|
+
this._processingHistory = !0;
|
|
2213
3131
|
try {
|
|
2214
|
-
t
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, W.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2220
|
-
this._logger?.error("DefaultServerTransport._handleChannelMessage(); subscription error"), this._onError?.(n);
|
|
3132
|
+
let t = this._codec.createDecoder();
|
|
3133
|
+
for (let n of e.rawMessages) Mt(this._tree, t, n);
|
|
3134
|
+
for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
|
|
3135
|
+
} finally {
|
|
3136
|
+
this._processingHistory = !1;
|
|
2221
3137
|
}
|
|
2222
3138
|
}
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
onError: s
|
|
3139
|
+
async _loadUntilVisible(e, t, n) {
|
|
3140
|
+
this._processHistoryPage(e);
|
|
3141
|
+
let r = e, i = () => {
|
|
3142
|
+
let e = 0;
|
|
3143
|
+
for (let t of this._treeVisibleNodes()) t.kind === "run" && !n.has($(t)) && e++;
|
|
3144
|
+
return e;
|
|
2230
3145
|
};
|
|
2231
|
-
|
|
2232
|
-
|
|
3146
|
+
for (; i() < t && r.hasNext();) {
|
|
3147
|
+
let e = await r.next();
|
|
3148
|
+
if (!e || this._closed) break;
|
|
3149
|
+
this._processHistoryPage(e), r = e;
|
|
3150
|
+
}
|
|
2233
3151
|
return {
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
3152
|
+
newVisible: this._treeVisibleNodes().filter((e) => !n.has($(e))),
|
|
3153
|
+
lastPage: r
|
|
3154
|
+
};
|
|
3155
|
+
}
|
|
3156
|
+
_releaseWithheld(e) {
|
|
3157
|
+
for (let t of e) this._withheldRunIds.delete($(t));
|
|
3158
|
+
e.length > 0 && this._recomputeAndEmit();
|
|
3159
|
+
}
|
|
3160
|
+
_updateVisibleSnapshot(e) {
|
|
3161
|
+
let t = e ?? this._cachedNodes;
|
|
3162
|
+
this._lastVisibleNodeKeys = t.map((e) => $(e)), this._lastVisibleNodeKeySet = new Set(this._lastVisibleNodeKeys), this._lastVisibleProjections = t.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(t);
|
|
3163
|
+
}
|
|
3164
|
+
_onTreeUpdate() {
|
|
3165
|
+
this._processingHistory || (this._pinBranchSelections(), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged());
|
|
3166
|
+
}
|
|
3167
|
+
_resolveSelections() {
|
|
3168
|
+
let e = /* @__PURE__ */ new Map();
|
|
3169
|
+
for (let [t, n] of this._branchSelections) e.set(t, n.selectedKey);
|
|
3170
|
+
for (let [t, n] of this._regenSelections) n.kind !== "pending" && e.set(t, n.selectedRunId);
|
|
3171
|
+
return e;
|
|
3172
|
+
}
|
|
3173
|
+
_treeVisibleNodes() {
|
|
3174
|
+
return this._tree.visibleNodes(this._resolveSelections());
|
|
3175
|
+
}
|
|
3176
|
+
_pinBranchSelections() {
|
|
3177
|
+
for (let e of this._lastVisibleNodeKeys) {
|
|
3178
|
+
if (this._tree.getNode(e)?.kind !== "input" || this._tree.getSiblingNodes(e).length <= 1) continue;
|
|
3179
|
+
let t = this._tree.getGroupRoot(e);
|
|
3180
|
+
this._branchSelections.get(t) || this._branchSelections.set(t, {
|
|
3181
|
+
kind: "pinned",
|
|
3182
|
+
selectedKey: e
|
|
3183
|
+
});
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
_resolvePendingRegenSelections() {
|
|
3187
|
+
for (let [e, t] of this._regenSelections) {
|
|
3188
|
+
if (t.kind === "user") continue;
|
|
3189
|
+
let n = this._tree.getSiblingNodes(e).filter((e) => e.kind === "run");
|
|
3190
|
+
if (n.length <= 1) continue;
|
|
3191
|
+
let r = n.at(-1);
|
|
3192
|
+
r && this._regenSelections.set(e, {
|
|
3193
|
+
kind: "auto",
|
|
3194
|
+
selectedRunId: r.runId
|
|
3195
|
+
});
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
_onTreeAblyMessage(e) {
|
|
3199
|
+
let t = D(e), n = t[l], r = t[o];
|
|
3200
|
+
if (!n && !r) {
|
|
3201
|
+
this._emitter.emit("ably-message", e);
|
|
3202
|
+
return;
|
|
3203
|
+
}
|
|
3204
|
+
r && this._lastVisibleNodeKeySet.has(r) && this._emitter.emit("ably-message", e);
|
|
3205
|
+
}
|
|
3206
|
+
_onTreeRun(e) {
|
|
3207
|
+
if (this._lastVisibleNodeKeySet.has(e.runId)) {
|
|
3208
|
+
this._emitter.emit("run", e);
|
|
3209
|
+
return;
|
|
3210
|
+
}
|
|
3211
|
+
e.type === "start" && this._isRunStartVisible(e) && (this._lastVisibleNodeKeySet.add(e.runId), this._emitter.emit("run", e));
|
|
3212
|
+
}
|
|
3213
|
+
_isRunStartVisible(e) {
|
|
3214
|
+
let { parent: t } = e;
|
|
3215
|
+
if (t === void 0) return !0;
|
|
3216
|
+
let n = this._tree.getNodeByCodecMessageId(t);
|
|
3217
|
+
return n ? this._lastVisibleNodeKeySet.has($(n)) : !0;
|
|
3218
|
+
}
|
|
3219
|
+
_visibleChanged(e) {
|
|
3220
|
+
if (e.length !== this._lastVisibleNodeKeys.length) return !0;
|
|
3221
|
+
for (let [t, n] of e.entries()) if ($(n) !== this._lastVisibleNodeKeys[t] || n.projection !== this._lastVisibleProjections[t]) return !0;
|
|
3222
|
+
return !1;
|
|
3223
|
+
}
|
|
3224
|
+
}, cn = (e) => new sn(e), ln = () => {}, un = class {
|
|
3225
|
+
constructor(e) {
|
|
3226
|
+
this._views = /* @__PURE__ */ new Set(), this._state = "ready", this._pendingRunStarts = /* @__PURE__ */ new Map();
|
|
3227
|
+
let t = Tt(e.client, e.codec);
|
|
3228
|
+
if (this._channel = e.client.channels.get(e.channelName, t), this._codec = e.codec, this._clientId = e.clientId, this._logger = (e.logger ?? ut({ logLevel: ct.Silent })).withContext({ component: "ClientSession" }), this._emitter = new Q(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = Qt(this._codec, this._logger), this._view = cn({
|
|
3229
|
+
tree: this._tree,
|
|
3230
|
+
channel: this._channel,
|
|
3231
|
+
codec: this._codec,
|
|
3232
|
+
sendDelegate: this._internalSend.bind(this),
|
|
3233
|
+
logger: this._logger,
|
|
3234
|
+
onClose: () => this._views.delete(this._view)
|
|
3235
|
+
}), 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) {
|
|
3236
|
+
let t;
|
|
3237
|
+
for (let n of e.messages) {
|
|
3238
|
+
let e = crypto.randomUUID(), r = {
|
|
3239
|
+
[l]: e,
|
|
3240
|
+
[f]: "user"
|
|
3241
|
+
};
|
|
3242
|
+
t && (r[p] = t), this._tree.applyMessage({
|
|
3243
|
+
inputs: [this._codec.createUserMessage(n)],
|
|
3244
|
+
outputs: []
|
|
3245
|
+
}, r), t = e;
|
|
3246
|
+
}
|
|
3247
|
+
}
|
|
3248
|
+
this._onMessage = (e) => {
|
|
3249
|
+
this._handleMessage(e);
|
|
3250
|
+
}, this._onChannelStateChange = (e) => {
|
|
3251
|
+
this._handleChannelStateChange(e);
|
|
3252
|
+
}, this._channel.on(this._onChannelStateChange);
|
|
3253
|
+
}
|
|
3254
|
+
connect() {
|
|
3255
|
+
return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", W.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger.trace("DefaultClientSession.connect();"), this._connectPromise = this._channel.subscribe(this._onMessage).then(() => {
|
|
3256
|
+
this._logger.debug("DefaultClientSession.connect(); subscribed and attached");
|
|
3257
|
+
}, (t) => {
|
|
3258
|
+
let n = new e.ErrorInfo(`unable to subscribe to channel; ${t instanceof Error ? t.message : String(t)}`, W.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
3259
|
+
throw this._logger.error("DefaultClientSession.connect(); subscribe failed"), this._emitter.emit("error", n), n;
|
|
3260
|
+
}), this._connectPromise);
|
|
3261
|
+
}
|
|
3262
|
+
async _requireConnected(t) {
|
|
3263
|
+
if (!this._connectPromise) throw new e.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`, W.InvalidArgument, 400);
|
|
3264
|
+
return this._connectPromise;
|
|
3265
|
+
}
|
|
3266
|
+
_handleMessage(t) {
|
|
3267
|
+
if (this._state !== "closed") try {
|
|
3268
|
+
if (t.name === "ai-run-end") {
|
|
3269
|
+
let n = D(t);
|
|
3270
|
+
if ((n["run-reason"] ?? "complete") === "error") {
|
|
3271
|
+
let t = n[v], r = t === void 0 ? NaN : Number(t), i = Number.isFinite(r) ? r : W.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);
|
|
3272
|
+
this._logger.error("ClientSession._handleMessage(); agent error received", {
|
|
3273
|
+
runId: n[o],
|
|
3274
|
+
invocationId: n[s],
|
|
3275
|
+
code: i
|
|
3276
|
+
}), this._emitter.emit("error", l);
|
|
2273
3277
|
}
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
await g;
|
|
2282
|
-
let o = h.getSignal(n), s = h.getClientId(n), u = r?.parent === void 0 ? c ?? void 0 : r.parent ?? void 0, f = Q({
|
|
2283
|
-
role: "assistant",
|
|
2284
|
-
turnId: n,
|
|
2285
|
-
msgId: crypto.randomUUID(),
|
|
2286
|
-
turnClientId: s,
|
|
2287
|
-
parent: u,
|
|
2288
|
-
forkOf: r?.forkOf ?? l
|
|
2289
|
-
}), p = await Ge(t, _.createEncoder(v, {
|
|
2290
|
-
extras: { headers: f },
|
|
2291
|
-
onMessage: i
|
|
2292
|
-
}), o, a, m);
|
|
2293
|
-
return m?.debug("Turn.streamResponse(); stream finished", {
|
|
2294
|
-
turnId: n,
|
|
2295
|
-
reason: p.reason
|
|
2296
|
-
}), p;
|
|
2297
|
-
},
|
|
2298
|
-
end: async (t) => {
|
|
2299
|
-
if (m?.trace("Turn.end();", {
|
|
2300
|
-
turnId: n,
|
|
2301
|
-
reason: t
|
|
2302
|
-
}), !d) throw new e.ErrorInfo(`unable to end turn; start() must be called before end() (turn ${n})`, W.InvalidArgument, 400);
|
|
2303
|
-
if (!f) {
|
|
2304
|
-
f = !0;
|
|
2305
|
-
try {
|
|
2306
|
-
await h.endTurn(n, t);
|
|
2307
|
-
} catch (t) {
|
|
2308
|
-
let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, W.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
2309
|
-
throw m?.error("Turn.end(); failed to publish turn-end", { turnId: n }), s?.(r), r;
|
|
2310
|
-
} finally {
|
|
2311
|
-
y.delete(n);
|
|
2312
|
-
}
|
|
2313
|
-
m?.debug("Turn.end(); turn ended", {
|
|
2314
|
-
turnId: n,
|
|
2315
|
-
reason: t
|
|
2316
|
-
});
|
|
3278
|
+
}
|
|
3279
|
+
let n = Mt(this._tree, this._decoder, t);
|
|
3280
|
+
if (n && (n.type === "start" || n.type === "resume")) {
|
|
3281
|
+
let e = D(t)[_];
|
|
3282
|
+
if (e !== void 0) {
|
|
3283
|
+
let t = this._pendingRunStarts.get(e);
|
|
3284
|
+
t && (this._pendingRunStarts.delete(e), t.resolve(n.runId));
|
|
2317
3285
|
}
|
|
2318
3286
|
}
|
|
3287
|
+
this._tree.emitAblyMessage(t);
|
|
3288
|
+
} catch (t) {
|
|
3289
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
3290
|
+
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, W.SessionSubscriptionError, 500, n));
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
_handleChannelStateChange(t) {
|
|
3294
|
+
if (this._state === "closed") return;
|
|
3295
|
+
let { current: n, resumed: r } = t;
|
|
3296
|
+
if (n === "attached" && !this._hasAttachedOnce) {
|
|
3297
|
+
this._hasAttachedOnce = !0;
|
|
3298
|
+
return;
|
|
3299
|
+
}
|
|
3300
|
+
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
3301
|
+
this._logger.error("ClientSession._handleChannelStateChange(); channel continuity lost", {
|
|
3302
|
+
current: n,
|
|
3303
|
+
resumed: r,
|
|
3304
|
+
previous: t.previous
|
|
3305
|
+
});
|
|
3306
|
+
let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, W.ChannelContinuityLost, 500, t.reason);
|
|
3307
|
+
this._emitter.emit("error", i);
|
|
3308
|
+
}
|
|
3309
|
+
_cleanupFailedSend(e) {
|
|
3310
|
+
for (let t of e) {
|
|
3311
|
+
let e = this._tree.getNodeByCodecMessageId(t);
|
|
3312
|
+
e?.kind === "input" && e.serial === void 0 && this._tree.delete(e.codecMessageId);
|
|
3313
|
+
}
|
|
3314
|
+
}
|
|
3315
|
+
createView() {
|
|
3316
|
+
if (this._state === "closed") throw new e.ErrorInfo("unable to create view; session is closed", W.SessionClosed, 400);
|
|
3317
|
+
this._logger.trace("DefaultClientSession.createView();");
|
|
3318
|
+
let t = cn({
|
|
3319
|
+
tree: this._tree,
|
|
3320
|
+
channel: this._channel,
|
|
3321
|
+
codec: this._codec,
|
|
3322
|
+
sendDelegate: this._internalSend.bind(this),
|
|
3323
|
+
logger: this._logger,
|
|
3324
|
+
onClose: () => this._views.delete(t)
|
|
3325
|
+
});
|
|
3326
|
+
return this._views.add(t), t;
|
|
3327
|
+
}
|
|
3328
|
+
async _internalSend(t, n, r) {
|
|
3329
|
+
if (this._state === "closed" || (await this._requireConnected("send"), this._state === "closed")) throw new e.ErrorInfo("unable to send; session is closed", W.SessionClosed, 400);
|
|
3330
|
+
let i = this._channel.state;
|
|
3331
|
+
if (i !== "attached" && i !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${i}`, W.ChannelNotReady, 400);
|
|
3332
|
+
this._logger.trace("ClientSession._internalSend();");
|
|
3333
|
+
let a = n?.runId !== void 0, o = n?.runId, s;
|
|
3334
|
+
n?.parent === void 0 && !n?.forkOf && (s = r);
|
|
3335
|
+
let c = /* @__PURE__ */ new Set(), l = [];
|
|
3336
|
+
for (let e of t) {
|
|
3337
|
+
let t = crypto.randomUUID(), r = e.codecMessageId ?? crypto.randomUUID();
|
|
3338
|
+
c.add(r);
|
|
3339
|
+
let i = e.kind !== "user-message" && (e.kind === "regenerate" || e.codecMessageId !== void 0), a = e.parent ?? (n?.parent === void 0 ? s : n.parent), u = n?.forkOf, d = e.kind === "regenerate" ? e.target : void 0, f = Et({
|
|
3340
|
+
role: "user",
|
|
3341
|
+
runId: o,
|
|
3342
|
+
codecMessageId: r,
|
|
3343
|
+
runClientId: this._clientId,
|
|
3344
|
+
...a !== void 0 && { parent: a },
|
|
3345
|
+
...u !== void 0 && { forkOf: u },
|
|
3346
|
+
...d !== void 0 && { regenerates: d },
|
|
3347
|
+
inputEventId: t
|
|
3348
|
+
});
|
|
3349
|
+
i || this._tree.applyMessage({
|
|
3350
|
+
inputs: [e],
|
|
3351
|
+
outputs: []
|
|
3352
|
+
}, f), l.push({
|
|
3353
|
+
input: e,
|
|
3354
|
+
codecMessageId: r,
|
|
3355
|
+
inputEventId: t,
|
|
3356
|
+
headers: f,
|
|
3357
|
+
isWireOnly: i
|
|
3358
|
+
}), !i && n?.parent === void 0 && !n?.forkOf && e.parent === void 0 && (s = r);
|
|
3359
|
+
}
|
|
3360
|
+
let u = l.at(-1);
|
|
3361
|
+
if (u === void 0) throw new e.ErrorInfo("unable to send; inputs array is empty (include at least one input)", W.InvalidArgument, 400);
|
|
3362
|
+
let d = u.inputEventId, f = u.codecMessageId, p = new Promise((e, t) => {
|
|
3363
|
+
this._pendingRunStarts.set(f, {
|
|
3364
|
+
resolve: e,
|
|
3365
|
+
reject: t
|
|
3366
|
+
});
|
|
3367
|
+
});
|
|
3368
|
+
return p.catch(() => {}), await (async () => {
|
|
3369
|
+
try {
|
|
3370
|
+
for (let e of l) await this._encoder.publishInput(e.input, {
|
|
3371
|
+
extras: { headers: e.headers },
|
|
3372
|
+
messageId: e.codecMessageId,
|
|
3373
|
+
...this._clientId !== void 0 && { clientId: this._clientId }
|
|
3374
|
+
});
|
|
3375
|
+
} catch (t) {
|
|
3376
|
+
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 ? W.InsufficientCapability : W.SessionSendFailed, r ? 401 : 500, n);
|
|
3377
|
+
throw this._emitter.emit("error", i), this._pendingRunStarts.delete(f), a || this._cleanupFailedSend([...c]), i;
|
|
3378
|
+
}
|
|
3379
|
+
})(), {
|
|
3380
|
+
inputCodecMessageId: f,
|
|
3381
|
+
runId: p,
|
|
3382
|
+
inputEventId: d,
|
|
3383
|
+
cancel: async () => {
|
|
3384
|
+
await this._publishCancel({
|
|
3385
|
+
inputCodecMessageId: f,
|
|
3386
|
+
...o !== void 0 && { runId: o }
|
|
3387
|
+
});
|
|
3388
|
+
},
|
|
3389
|
+
optimisticCodecMessageIds: [...c],
|
|
3390
|
+
toInvocation: () => qt.fromJSON({
|
|
3391
|
+
inputEventId: d,
|
|
3392
|
+
sessionName: this._channel.name
|
|
3393
|
+
})
|
|
3394
|
+
};
|
|
3395
|
+
}
|
|
3396
|
+
async cancel(e) {
|
|
3397
|
+
return this._publishCancel({ runId: e });
|
|
3398
|
+
}
|
|
3399
|
+
async _publishCancel(e) {
|
|
3400
|
+
if (this._state === "closed" || (await this._requireConnected("cancel"), this._state === "closed")) return;
|
|
3401
|
+
this._logger.debug("ClientSession._publishCancel();", {
|
|
3402
|
+
runId: e.runId,
|
|
3403
|
+
inputCodecMessageId: e.inputCodecMessageId
|
|
3404
|
+
});
|
|
3405
|
+
let t = { [c]: crypto.randomUUID() };
|
|
3406
|
+
e.runId !== void 0 && (t[o] = e.runId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), await this._channel.publish({
|
|
3407
|
+
name: y,
|
|
3408
|
+
extras: { ai: { transport: t } }
|
|
3409
|
+
});
|
|
3410
|
+
}
|
|
3411
|
+
on(e, t) {
|
|
3412
|
+
if (this._state === "closed") return ln;
|
|
3413
|
+
let n = t;
|
|
3414
|
+
return this._emitter.on(e, n), () => {
|
|
3415
|
+
this._emitter.off(e, n);
|
|
2319
3416
|
};
|
|
2320
3417
|
}
|
|
2321
|
-
|
|
3418
|
+
async close() {
|
|
3419
|
+
if (this._state !== "closed") {
|
|
3420
|
+
this._state = "closed", this._logger.info("ClientSession.close();"), this._connectPromise && this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange), this._emitter.off();
|
|
3421
|
+
for (let e of this._views) e.close();
|
|
3422
|
+
if (this._views.clear(), this._pendingRunStarts.size > 0) {
|
|
3423
|
+
let t = new e.ErrorInfo("unable to await run-start; session closed", W.SessionClosed, 400);
|
|
3424
|
+
for (let e of this._pendingRunStarts.values()) e.reject(t);
|
|
3425
|
+
this._pendingRunStarts.clear();
|
|
3426
|
+
}
|
|
3427
|
+
try {
|
|
3428
|
+
await this._encoder.close();
|
|
3429
|
+
} catch {}
|
|
3430
|
+
if (this._connectPromise) try {
|
|
3431
|
+
await this._channel.detach();
|
|
3432
|
+
} catch (e) {
|
|
3433
|
+
this._logger.debug("ClientSession.close(); channel detach failed", { error: e });
|
|
3434
|
+
}
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
3437
|
+
}, dn = (e) => new un(e), fn = (e) => dn({
|
|
2322
3438
|
...e,
|
|
2323
|
-
codec:
|
|
2324
|
-
}),
|
|
3439
|
+
codec: Z
|
|
3440
|
+
}), pn = (e) => Kt({
|
|
2325
3441
|
...e,
|
|
2326
|
-
codec:
|
|
2327
|
-
})
|
|
3442
|
+
codec: Z
|
|
3443
|
+
}), mn = async (e, t) => {
|
|
3444
|
+
if (e.reason !== "complete") return Promise.resolve(t).catch(() => {}), e.reason;
|
|
3445
|
+
try {
|
|
3446
|
+
return await t === "tool-calls" ? "suspend" : "complete";
|
|
3447
|
+
} catch (e) {
|
|
3448
|
+
return hn(e) ? "cancelled" : "error";
|
|
3449
|
+
}
|
|
3450
|
+
}, hn = (e) => typeof e != "object" || !e ? !1 : e.name === "AbortError";
|
|
2328
3451
|
//#endregion
|
|
2329
|
-
export {
|
|
3452
|
+
export { Z as UIMessageCodec, pn as createAgentSession, xt as createChatTransport, fn as createClientSession, mn as vercelRunOutcome };
|
|
2330
3453
|
|
|
2331
3454
|
//# sourceMappingURL=ably-ai-transport-vercel.js.map
|