@qfei-design/make-ai-assistant 0.2.9 → 0.2.11

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.
Files changed (38) hide show
  1. package/PUBLIC_API.md +17 -23
  2. package/README.md +12 -24
  3. package/capabilities.json +36 -9
  4. package/dist/conversation-CZfbgCXd.js +1111 -0
  5. package/dist/conversation-Cvh-IVRV.cjs +1 -0
  6. package/dist/core/conversation-management.d.ts +212 -0
  7. package/dist/core/conversation.d.ts +34 -2
  8. package/dist/core/index.d.ts +2 -0
  9. package/dist/core/response-state.d.ts +8 -0
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.mjs +4 -4
  12. package/dist/make-app/protocol.d.ts +27 -0
  13. package/dist/make-app/stream.d.ts +20 -0
  14. package/dist/make-app.cjs +1 -1
  15. package/dist/make-app.d.ts +46 -11
  16. package/dist/make-app.mjs +698 -259
  17. package/dist/make-console.cjs +1 -1
  18. package/dist/make-console.mjs +1 -1
  19. package/dist/react/conversation-controls.d.ts +20 -0
  20. package/dist/react/use-attachments.d.ts +33 -0
  21. package/dist/react/use-conversation-manager.d.ts +35 -0
  22. package/dist/react.cjs +4 -4
  23. package/dist/react.mjs +2000 -845
  24. package/dist/sse.cjs +1 -1
  25. package/dist/sse.mjs +1 -1
  26. package/dist/styles.css +428 -13
  27. package/docs/backend-contract.md +8 -21
  28. package/docs/make-app-integration.md +80 -0
  29. package/examples/make-app/README.md +11 -0
  30. package/examples/make-app/index.html +5 -0
  31. package/examples/make-app/main.tsx +34 -0
  32. package/examples/make-app/style.css +4 -0
  33. package/examples/make-app/transport.ts +163 -0
  34. package/examples/make-app/vite.config.ts +7 -0
  35. package/package.json +10 -2
  36. package/recipes.json +36 -13
  37. package/dist/conversation-B7eGUXi-.js +0 -727
  38. package/dist/conversation-Cv1wdvCR.cjs +0 -1
package/dist/make-app.mjs CHANGED
@@ -1,288 +1,727 @@
1
- import { DEFAULT_MAX_SSE_EVENT_CHARACTERS as m } from "./sse.mjs";
2
- import { M as A, c as u } from "./conversation-B7eGUXi-.js";
3
- const v = 100, k = {
4
- AI_AGENT_UNAVAILABLE: "当前 App 尚未配置可用的 AI 助手。",
5
- AI_APP_UNAVAILABLE: "当前 App 暂不可用。",
6
- AI_AUTH_EXPIRED: "登录已失效,请重新登录。",
7
- AI_AUTH_REQUIRED: "登录已失效,请重新登录。",
8
- AI_FORBIDDEN: "当前账号无权使用该 AI 助手。",
9
- AI_RUN_FAILED: "本次 AI 处理失败,请重试。",
10
- AI_UPSTREAM_ERROR: "AI 服务暂时不可用,请稍后重试。"
11
- }, y = (e) => typeof e == "object" && e !== null && !Array.isArray(e), h = (e, a, i = A.identifierCharacters) => {
12
- if (typeof e != "string" || !e.trim() || u(e, i) > i)
13
- throw new Error(`Invalid Make App assistant response: ${a}`);
14
- return e;
15
- }, M = (e) => {
16
- if (!y(e))
17
- throw new Error("Invalid Make App assistant response: locate");
18
- return { chatId: h(e.chatId, "chatId") };
19
- }, _ = (e) => {
20
- if (!y(e))
21
- throw new Error("Invalid Make App assistant response: send");
22
- const a = e.acceptedCursor;
23
- if (!Number.isSafeInteger(a) || Number(a) < 0)
24
- throw new Error("Invalid Make App assistant response: acceptedCursor");
1
+ import { p as w, a as q, b as g, d as A, e as m, f as C, g as L, h as N, i as U, j as z, k as x, l as P, m as H } from "./conversation-CZfbgCXd.js";
2
+ const b = (t) => {
3
+ const o = g(t, 36);
4
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
5
+ o
6
+ ))
7
+ throw new Error("Invalid Make App request: UUID");
8
+ return o;
9
+ }, T = (t) => {
10
+ const o = g(t, 512, !0);
11
+ if (new TextEncoder().encode(o).length > 512 || /[\r\n/\\]/.test(o))
12
+ throw new Error("Invalid Make App request: filename");
13
+ return o;
14
+ }, M = (t, o, a) => {
15
+ const d = A(t);
16
+ if (N(d, [
17
+ "chatId",
18
+ "appKey",
19
+ "agentId",
20
+ "title",
21
+ "status",
22
+ "revision",
23
+ "pinned",
24
+ "pinnedAt",
25
+ "createdAt",
26
+ "lastActivityAt"
27
+ ]), d.appKey !== o.appKey || d.agentId !== o.agentId || a && d.chatId !== a || !["active", "deleted"].includes(String(d.status)))
28
+ throw new Error("Invalid Make App response: chat scope");
25
29
  return {
26
- acceptedCursor: a,
27
- chatId: h(e.chatId, "chatId"),
28
- responseId: h(e.responseId, "responseId")
30
+ chatId: w(d.chatId),
31
+ appKey: o.appKey,
32
+ agentId: o.agentId,
33
+ title: g(d.title, 255, !0),
34
+ status: d.status,
35
+ revision: m(d.revision, 1),
36
+ pinned: U(d.pinned),
37
+ pinnedAt: d.pinnedAt == null ? null : g(d.pinnedAt, 64),
38
+ createdAt: g(d.createdAt, 64),
39
+ lastActivityAt: g(d.lastActivityAt, 64)
29
40
  };
30
- }, S = (e, a, i) => {
31
- if (!y(e) || !Array.isArray(e.messages) || e.messages.length > i)
32
- throw new Error("Invalid Make App assistant response: history");
33
- const c = /* @__PURE__ */ new Set();
34
- let o = 0;
35
- const t = e.messages.map((s) => {
36
- if (!y(s))
37
- throw new Error("Invalid Make App assistant response: history message");
38
- if (s.role !== "user" && s.role !== "assistant")
39
- throw new Error("Invalid Make App assistant response: history role");
40
- const r = s.role;
41
- if (!Number.isSafeInteger(s.cursor) || Number(s.cursor) < 0)
42
- throw new Error("Invalid Make App assistant response: history cursor");
43
- const p = `history-${a}-${String(s.cursor)}`;
44
- if (c.has(p))
45
- throw new Error("Invalid Make App assistant response: duplicate history cursor");
46
- c.add(p);
47
- const d = h(
48
- s.text,
49
- "history text",
50
- A.messageCharacters
41
+ }, j = (t, o) => {
42
+ const a = A(t), d = C(a.chats, 100).map(
43
+ (h) => M(h, o)
44
+ );
45
+ if (new Set(d.map((h) => h.chatId)).size !== d.length)
46
+ throw new Error("Invalid Make App response: duplicate chat");
47
+ const c = g(a.nextCursor, 8192, !0), u = U(a.hasMore);
48
+ if (u !== !!c)
49
+ throw new Error("Invalid Make App response: chat cursor");
50
+ return { chats: d, nextCursor: c, hasMore: u };
51
+ }, J = (t, o, a) => {
52
+ const d = A(t), c = m(d.nextCursor, -1), u = U(d.hasMore);
53
+ if (c < a || u && c <= a)
54
+ throw new Error(
55
+ "Invalid Make App response: history cursor did not advance"
51
56
  );
52
- if (o += u(
53
- d,
54
- A.historyCharacters - o
55
- ), o > A.historyCharacters)
56
- throw new Error("Invalid Make App assistant response: history text budget");
57
+ let h = 0, p = a;
58
+ const v = /* @__PURE__ */ new Set(), I = C(d.messages, 200).map((E) => {
59
+ const y = A(E);
60
+ if (y.role !== "user" && y.role !== "assistant")
61
+ throw new Error("Invalid Make App response: history role");
62
+ const f = m(y.cursor);
63
+ if (f <= p || f > c)
64
+ throw new Error("Invalid Make App response: history order");
65
+ p = f;
66
+ const s = y.messageId !== void 0, e = s ? w(y.messageId) : `history-${o}-${f}`;
67
+ if (v.has(e))
68
+ throw new Error("Invalid Make App response: duplicate message");
69
+ v.add(e);
70
+ const r = g(y.text, 1e5, !0);
71
+ if (h += [...r].length, h > 1e6)
72
+ throw new Error("Invalid Make App response: history budget");
57
73
  return {
58
- id: p,
59
- role: r,
60
- content: d,
61
- artifacts: []
74
+ id: e,
75
+ role: y.role,
76
+ content: r,
77
+ persistent: s,
78
+ cursor: f,
79
+ createdAt: g(y.createdAt, 64),
80
+ ...y.responseId === void 0 ? {} : { responseId: w(y.responseId) },
81
+ ...y.parts === void 0 ? {} : { parts: q(y.parts) },
82
+ ...y.feedback === void 0 ? {} : { feedback: z(y.feedback) }
62
83
  };
63
84
  });
64
- return { threadId: a, messages: t };
65
- }, R = () => {
66
- const e = [], a = [];
67
- return { next: () => {
68
- const o = e.shift();
69
- return o ? Promise.resolve(o) : new Promise((t) => a.push(t));
70
- }, push: (o) => {
71
- const t = a.shift();
72
- t ? t(o) : e.push(o);
73
- } };
74
- }, b = (e, a) => {
75
- if (u(e.data, a) > a)
76
- throw new Error("Make App assistant SSE event exceeds maxEventCharacters");
77
- try {
78
- const i = JSON.parse(e.data);
79
- if (!y(i)) throw new Error("invalid data");
80
- return i;
81
- } catch {
82
- throw new Error("Invalid Make App assistant SSE JSON");
83
- }
84
- }, g = () => new DOMException("Aborted", "AbortError"), I = (e) => {
85
- if (e?.aborted) throw g();
86
- }, C = async function* (e, a) {
87
- const i = `assistant:${e.responseId}`;
88
- I(a?.signal), yield {
89
- type: "message.start",
90
- runId: e.responseId,
91
- messageId: i
85
+ return { threadId: o, messages: I, nextCursor: c, hasMore: u };
86
+ }, K = (t, o) => {
87
+ const a = L(t);
88
+ if (a.chatId !== o.chatId || a.responseId !== o.responseId)
89
+ throw new Error("Invalid Make App response: response scope");
90
+ return a;
91
+ }, S = (t, o) => {
92
+ const a = A(t);
93
+ if (!["uploading", "ready", "cancelled"].includes(String(a.status)) || o && a.id !== o)
94
+ throw new Error("Invalid Make App response: upload");
95
+ const d = m(a.sizeBytes, 0, 64 << 20), c = m(a.partSize, 1 << 20, 1 << 20), u = C(a.completedParts, 64).map(
96
+ (p) => m(p, 0, Math.max(0, Math.ceil(d / c) - 1))
97
+ );
98
+ if (new Set(u).size !== u.length)
99
+ throw new Error("Invalid Make App response: repeated upload part");
100
+ const h = {
101
+ id: w(a.id),
102
+ status: a.status,
103
+ name: T(a.name),
104
+ contentType: g(a.contentType, 256),
105
+ sizeBytes: d,
106
+ partSize: c,
107
+ completedParts: u
92
108
  };
93
- const c = R(), o = e.eventSourceFactory({
94
- chatId: e.chatId,
95
- responseId: e.responseId,
96
- cursor: "0-0"
97
- }, { withCredentials: !0 });
98
- let t = !1;
99
- const s = (n) => {
100
- t || (t = !0, c.push(n));
101
- }, r = /* @__PURE__ */ new Map(), p = (n, l) => {
102
- const f = (E) => {
103
- if (!t)
104
- try {
105
- l(b(E, e.maxEventCharacters));
106
- } catch (w) {
107
- s({ type: "error", error: w });
108
- }
109
+ if (h.status === "ready") {
110
+ const p = A(a.content);
111
+ if (p.kind !== "reference" || p.sizeBytes !== d || !/^[0-9a-f]{64}$/.test(String(p.digestSha256)))
112
+ throw new Error("Invalid Make App response: content receipt");
113
+ h.content = {
114
+ kind: "reference",
115
+ contentRef: w(p.contentRef),
116
+ sizeBytes: d,
117
+ digestSha256: String(p.digestSha256)
109
118
  };
110
- r.set(n, f), o.addEventListener(n, f);
119
+ }
120
+ return h;
121
+ }, Q = (t) => {
122
+ const o = w(t.threadId), a = b(t.message.id);
123
+ let d, c;
124
+ if (t.message.parts !== void 0) {
125
+ const u = q(t.message.parts);
126
+ if (!u.length) throw new Error("Invalid Make App request: empty parts");
127
+ const h = /* @__PURE__ */ new Set();
128
+ for (const p of u) {
129
+ const v = b(p.id);
130
+ if (h.has(v))
131
+ throw new Error("Invalid Make App request: duplicate part");
132
+ if (h.add(v), p.kind !== "text") {
133
+ p.name !== void 0 && T(p.name);
134
+ const I = p.media.contentType;
135
+ if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(I) || p.kind !== "file" && (!I.startsWith(`${p.kind}/`) || I === "image/svg+xml"))
136
+ throw new Error("Invalid Make App request: media type");
137
+ }
138
+ }
139
+ if (c = u.filter((p) => p.kind === "text").map((p) => p.text).join(""), !c.trim() && u.every((p) => p.kind === "text"))
140
+ throw new Error("Invalid Make App request: empty input");
141
+ d = { chatId: o, messageId: a, parts: u };
142
+ } else
143
+ c = g(t.message.content, 8192), d = { chatId: o, messageId: a, text: c };
144
+ if (new TextEncoder().encode(c).length > 8192 || new TextEncoder().encode(JSON.stringify(d)).length > 65536)
145
+ throw new Error(
146
+ "输入内容过长,请控制在 8 KiB 文本和 32 个附件/文本片段以内"
147
+ );
148
+ return d;
149
+ }, W = () => {
150
+ const t = [];
151
+ let o, a = !1, d;
152
+ return {
153
+ push(c) {
154
+ if (!a)
155
+ if (o) {
156
+ const u = o;
157
+ o = void 0, u.resolve({ done: !1, value: c });
158
+ } else t.length >= 4096 ? this.fail(new Error("响应事件积压超过限制,请恢复对话")) : t.push(c);
159
+ },
160
+ fail(c) {
161
+ d = c, a = !0, t.length = 0, o?.reject(c), o = void 0;
162
+ },
163
+ close() {
164
+ a = !0, t.length = 0, o?.resolve({ done: !0, value: void 0 }), o = void 0;
165
+ },
166
+ next() {
167
+ return d ? Promise.reject(d) : t.length ? Promise.resolve({ done: !1, value: t.shift() }) : a ? Promise.resolve({ done: !0, value: void 0 }) : new Promise((c, u) => {
168
+ o = { resolve: c, reject: u };
169
+ });
170
+ }
111
171
  };
112
- p("run.started", () => {
113
- c.push({
114
- type: "event",
115
- event: {
116
- type: "run.progress",
117
- runId: e.responseId,
118
- message: "正在分析"
172
+ }, D = (t, o) => new Promise((a) => {
173
+ if (o?.aborted) {
174
+ a();
175
+ return;
176
+ }
177
+ const d = () => {
178
+ clearTimeout(c), o?.removeEventListener("abort", d), a();
179
+ }, c = setTimeout(d, t);
180
+ o?.addEventListener("abort", d, { once: !0 });
181
+ }), _ = (t) => {
182
+ if (!/^\d{1,20}-\d{1,20}$/.test(t))
183
+ throw new Error("Invalid Make App response: stream cursor");
184
+ return t.split("-").map(BigInt);
185
+ }, X = (t, o) => {
186
+ const [a, d] = _(t), [c, u] = _(o);
187
+ return a > c || a === c && d > u;
188
+ }, O = (t) => {
189
+ const o = t;
190
+ return [400, 401, 403, 404].includes(o?.status ?? o?.response?.status ?? 0) || [
191
+ "AI_FORBIDDEN",
192
+ "AI_AUTH_REQUIRED",
193
+ "AI_AUTH_EXPIRED",
194
+ "AI_NOT_FOUND",
195
+ "AI_RESPONSE_NOT_FOUND"
196
+ ].includes(o?.code ?? "") || t instanceof Error && t.message.startsWith("Invalid ");
197
+ }, G = [
198
+ "response.subscribed",
199
+ "response.state",
200
+ "response.output_item.added",
201
+ "response.output_text.delta",
202
+ "response.output_item.done",
203
+ "response.reset",
204
+ "response.snapshot",
205
+ "response.completed",
206
+ "response.failed",
207
+ "response.cancelled"
208
+ ];
209
+ async function* V(t, o, a) {
210
+ if (a?.aborted) return;
211
+ let d = t.cursor ?? "0-0";
212
+ _(d);
213
+ let c = 0, u = !1, h = 0;
214
+ const p = /* @__PURE__ */ new Map();
215
+ yield {
216
+ type: "response.state",
217
+ chatId: t.chatId,
218
+ responseId: t.responseId,
219
+ status: "queued"
220
+ };
221
+ async function* v(I, E) {
222
+ if (I === "completed") {
223
+ let y = t.historyCursor ?? -1, f = 0;
224
+ const s = [];
225
+ let e = !0;
226
+ for (; e && !a?.aborted; ) {
227
+ if (++f > 200)
228
+ throw new Error("历史恢复超过单次预算,请继续加载历史");
229
+ const r = await o.loadHistory(t, y, a);
230
+ for (const n of r.messages)
231
+ if (n.responseId === t.responseId && n.role === "assistant" && n.persistent) {
232
+ const { artifacts: i, ...l } = n;
233
+ s.push(H(l));
234
+ }
235
+ if (e = r.hasMore ?? !1, e && (r.nextCursor ?? -1) <= y)
236
+ throw new Error("Invalid Make App response: history cursor");
237
+ y = r.nextCursor ?? y;
119
238
  }
120
- });
121
- }), p("response.progress", (n) => {
122
- c.push({
123
- type: "event",
124
- event: {
125
- type: "run.progress",
126
- runId: e.responseId,
127
- message: h(
128
- n.message,
129
- "progress message",
130
- A.messageCharacters
131
- )
239
+ if (a?.aborted) return;
240
+ if (!s.length)
241
+ throw new Error("回答已完成,历史尚未同步,请恢复对话");
242
+ yield {
243
+ type: "response.reconciled",
244
+ chatId: t.chatId,
245
+ responseId: t.responseId,
246
+ messages: s
247
+ };
248
+ }
249
+ yield {
250
+ type: "response.terminal",
251
+ chatId: t.chatId,
252
+ responseId: t.responseId,
253
+ status: I,
254
+ ...E ? { code: E } : {}
255
+ };
256
+ }
257
+ for (; !a?.aborted; ) {
258
+ if (c > 3) {
259
+ if (++h > 600) throw new Error("响应连接中断,请恢复对话");
260
+ let n;
261
+ try {
262
+ n = await o.getResponse(t, a);
263
+ } catch (i) {
264
+ if (a?.aborted) return;
265
+ if (O(i)) throw i;
132
266
  }
133
- });
134
- }), p("response.delta", (n) => {
135
- if (typeof n.text != "string")
136
- throw new Error("Invalid Make App assistant response: delta text");
137
- c.push({
138
- type: "event",
139
- event: { type: "message.delta", messageId: i, delta: n.text }
140
- });
141
- }), p("response.message", (n) => {
142
- c.push({
143
- type: "event",
144
- event: {
145
- type: "message.replace",
146
- messageId: i,
147
- content: h(
148
- n.text,
149
- "message text",
150
- A.messageCharacters
151
- )
267
+ if (n && (yield { type: "response.snapshot", snapshot: n }, x(n.status))) {
268
+ yield* v(
269
+ n.status
270
+ );
271
+ return;
152
272
  }
273
+ await D(Math.max(1e3, o.reconnectDelayMs), a);
274
+ continue;
275
+ }
276
+ const I = W();
277
+ let E = 0, y = !1;
278
+ const f = o.eventSourceFactory(
279
+ { chatId: t.chatId, responseId: t.responseId, cursor: d },
280
+ { withCredentials: !0 }
281
+ ), s = G.map((n) => {
282
+ const i = (l) => {
283
+ if (!(y || a?.aborted)) {
284
+ if (l.data.length > o.maxEventCharacters * 2 || [...l.data].length > o.maxEventCharacters || E + l.data.length > 4e6) {
285
+ y = !0, f.close(), I.fail(
286
+ new Error(
287
+ "Make App assistant SSE event exceeds maxEventCharacters"
288
+ )
289
+ );
290
+ return;
291
+ }
292
+ E += l.data.length, I.push({ name: n, raw: l.data, id: l.lastEventId });
293
+ }
294
+ };
295
+ return f.addEventListener(n, i), { name: n, listener: i };
153
296
  });
154
- }), p("response.completed", () => {
155
- c.push({
156
- type: "event",
157
- event: { type: "message.complete", messageId: i }
158
- }), c.push({
159
- type: "event",
160
- event: {
161
- type: "run.complete",
162
- runId: e.responseId,
163
- threadId: e.chatId
164
- }
165
- }), s({ type: "done" });
166
- }), p("response.failed", (n) => {
167
- const l = h(n.code, "failure code");
168
- s({
169
- type: "event",
170
- event: {
171
- type: "error",
172
- code: l,
173
- message: k[l] ?? "本次 AI 处理失败,请重试。",
174
- retryable: ![
175
- "AI_AUTH_REQUIRED",
176
- "AI_AUTH_EXPIRED",
177
- "AI_FORBIDDEN",
178
- "AI_APP_UNAVAILABLE",
179
- "AI_AGENT_UNAVAILABLE"
180
- ].includes(l),
181
- requestId: e.responseId
297
+ f.onerror = () => {
298
+ !y && !a?.aborted && (y = !0, f.close(), I.push({ reconnect: !0 }));
299
+ };
300
+ const e = () => {
301
+ y = !0, f.close(), I.close();
302
+ };
303
+ a?.addEventListener("abort", e, { once: !0 }), a?.aborted && e();
304
+ try {
305
+ for (; !a?.aborted; ) {
306
+ const n = await I.next();
307
+ if (n.done) return;
308
+ const i = n.value;
309
+ if ("reconnect" in i) break;
310
+ if (E -= i.raw.length, i.id && !X(i.id, d)) {
311
+ if (p.has(i.id) && p.get(i.id) !== i.raw)
312
+ throw new Error(
313
+ "Invalid Make App response: conflicting stream replay"
314
+ );
315
+ continue;
316
+ }
317
+ const l = A(JSON.parse(i.raw));
318
+ if (w(l.responseId) !== t.responseId)
319
+ throw new Error("Invalid Make App response: stream scope");
320
+ if (i.name !== "response.subscribed") {
321
+ if (i.name === "response.reset") {
322
+ u = !0;
323
+ continue;
324
+ }
325
+ if (i.name === "response.snapshot") {
326
+ const k = K(l, t);
327
+ if (yield { type: "response.snapshot", snapshot: k }, x(k.status)) {
328
+ yield* v(
329
+ k.status
330
+ );
331
+ return;
332
+ }
333
+ } else if (i.name === "response.completed" || i.name === "response.cancelled") {
334
+ yield* v(
335
+ i.name === "response.completed" ? "completed" : "cancelled"
336
+ );
337
+ return;
338
+ } else if (i.name === "response.failed") {
339
+ if (l.code === "AI_UPSTREAM_ERROR") {
340
+ y = !0, f.close();
341
+ break;
342
+ }
343
+ if (l.code === "AI_FORBIDDEN" || l.code === "AI_AUTH_EXPIRED")
344
+ throw Object.assign(new Error("当前身份无法继续读取响应"), {
345
+ code: l.code,
346
+ status: l.code === "AI_FORBIDDEN" ? 403 : 401
347
+ });
348
+ yield* v(
349
+ "failed",
350
+ typeof l.code == "string" ? l.code : void 0
351
+ );
352
+ return;
353
+ } else i.name === "response.state" ? yield P({
354
+ type: i.name,
355
+ chatId: t.chatId,
356
+ ...l
357
+ }) : u || (yield P({ type: i.name, ...l }));
358
+ i.id && (d = i.id, p.set(i.id, i.raw), p.size > 512 && p.delete(p.keys().next().value));
359
+ }
182
360
  }
183
- });
184
- }), o.onerror = () => {
185
- t || o.readyState !== void 0 && o.readyState !== 2 || s({ type: "error", error: new Error("Make App assistant SSE disconnected") });
186
- };
187
- const d = () => s({ type: "error", error: g() });
188
- a?.signal?.addEventListener("abort", d, { once: !0 }), a?.signal?.aborted && d();
189
- try {
190
- for (; ; ) {
191
- const n = await c.next();
192
- if (n.type === "done") return;
193
- if (n.type === "error") throw n.error;
194
- if (yield n.event, n.event.type === "error") return;
361
+ } finally {
362
+ f.onerror = null, f.close(), I.close();
363
+ for (const { name: n, listener: i } of s)
364
+ f.removeEventListener(n, i);
365
+ a?.removeEventListener("abort", e);
366
+ }
367
+ if (a?.aborted || (c += 1, console.info("[make-ai-assistant] response reconnect", {
368
+ attempt: c
369
+ }), await D(
370
+ Math.min(o.reconnectDelayMs * 2 ** (c - 1), 5e3),
371
+ a
372
+ ), a?.aborted)) return;
373
+ let r;
374
+ try {
375
+ r = await o.getResponse(t, a);
376
+ } catch (n) {
377
+ if (a?.aborted) return;
378
+ if (O(n)) throw n;
195
379
  }
196
- } finally {
197
- t = !0, a?.signal?.removeEventListener("abort", d), o.onerror = null;
198
- for (const [n, l] of r)
199
- o.removeEventListener(n, l);
200
- o.close();
380
+ if (r && x(r.status)) {
381
+ yield { type: "response.snapshot", snapshot: r }, yield* v(r.status);
382
+ return;
383
+ }
384
+ u && (c = 4);
201
385
  }
202
- }, T = (e) => {
203
- const a = e.eventSourceFactory, i = e.historyLimit ?? v, c = e.maxEventCharacters ?? m;
204
- if (!Number.isInteger(i) || i < 1 || i > 100)
205
- throw new Error("historyLimit must be an integer between 1 and 100");
206
- if (!Number.isInteger(c) || c <= 0)
207
- throw new Error("maxEventCharacters must be a positive integer");
208
- const o = async (t, s) => {
209
- I(s?.signal), console.info("[make-ai-assistant] Make App chat locate start", {
210
- appId: t.app.id
211
- });
212
- const { chatId: r } = M(await e.locateChat(t, {
213
- signal: s?.signal
214
- }));
215
- return I(s?.signal), console.info("[make-ai-assistant] Make App chat locate success", {
216
- appId: t.app.id
217
- }), r;
386
+ }
387
+ const B = () => Object.assign(new Error("Operation aborted"), { name: "AbortError" }), F = (t) => {
388
+ if (t?.aborted) throw B();
389
+ }, Z = (t) => {
390
+ const o = m(t.historyLimit ?? 100, 1, 200), a = m(
391
+ t.maxEventCharacters ?? 1e6,
392
+ 1,
393
+ 4e6
394
+ ), d = m(
395
+ t.reconnectDelayMs ?? 500,
396
+ 1,
397
+ 3e4
398
+ ), c = (s) => {
399
+ const e = t.resolveScope(s);
400
+ return {
401
+ appKey: w(e.appKey),
402
+ agentId: w(e.agentId),
403
+ identityKey: w(e.identityKey)
404
+ };
405
+ }, u = (s) => {
406
+ const e = c(s);
407
+ return `${e.identityKey}\0${e.appKey}\0${e.agentId}`;
408
+ }, h = async (s, e, r, n) => {
409
+ F(n);
410
+ const i = u(s);
411
+ console.info("[make-ai-assistant] Make App operation start", { operation: e });
412
+ try {
413
+ const l = await r();
414
+ if (F(n), i !== u(s)) throw B();
415
+ return l;
416
+ } catch (l) {
417
+ throw console.warn("[make-ai-assistant] Make App operation failed", {
418
+ operation: e,
419
+ errorType: l instanceof Error ? l.name : typeof l
420
+ }), l;
421
+ }
422
+ }, p = (s) => ({
423
+ chatId: w(s.chatId)
424
+ }), v = (s) => ({
425
+ ...p(s),
426
+ responseId: w(s.responseId)
427
+ }), I = (s) => ({
428
+ ...p(s),
429
+ uploadId: w(s.uploadId)
430
+ }), E = async (s, e, r, n) => h(
431
+ s,
432
+ "loadHistory",
433
+ async () => J(
434
+ await t.loadHistory(
435
+ {
436
+ chatId: w(e),
437
+ cursor: m(r, -1),
438
+ limit: o
439
+ },
440
+ { signal: n }
441
+ ),
442
+ e,
443
+ r
444
+ ),
445
+ n
446
+ ), y = async (s, e, r) => h(
447
+ s,
448
+ "getResponse",
449
+ async () => K(
450
+ await t.getResponse(v(e), { signal: r }),
451
+ e
452
+ ),
453
+ r
454
+ ), f = (s, e, r) => {
455
+ const n = u(s), i = r?.signal;
456
+ return (async function* () {
457
+ for await (const l of V(
458
+ e,
459
+ {
460
+ eventSourceFactory: t.eventSourceFactory,
461
+ getResponse: (k, R) => y(s, k, R),
462
+ loadHistory: (k, R, $) => E(s, k.chatId, R, $),
463
+ maxEventCharacters: a,
464
+ reconnectDelayMs: d
465
+ },
466
+ i
467
+ )) {
468
+ if (i?.aborted || n !== u(s)) return;
469
+ yield l;
470
+ }
471
+ })();
218
472
  };
219
473
  return {
220
474
  features: {
221
475
  history: !0,
222
- newConversation: !1,
476
+ newConversation: !0,
477
+ remoteCancellation: !0,
223
478
  regeneration: !1,
224
- remoteCancellation: !1
479
+ conversationManagement: !0,
480
+ feedback: !0,
481
+ attachments: !0,
482
+ modelInputKinds: t.modelInputKinds ?? ["text"]
225
483
  },
226
- async loadConversation(t, s) {
227
- console.info("[make-ai-assistant] Make App history load start", {
228
- appId: t.app.id
229
- });
230
- try {
231
- I(s?.signal);
232
- const r = await o(t, s), p = await e.loadHistory(
233
- { chatId: r, cursor: -1, limit: i },
234
- { signal: s?.signal }
484
+ scopeKey: u,
485
+ listAgents: (s, e) => h(
486
+ s,
487
+ "listAgents",
488
+ async () => {
489
+ const r = c(s), n = A(
490
+ await t.listAgents(
491
+ { appKey: r.appKey },
492
+ { signal: e?.signal }
493
+ )
235
494
  );
236
- I(s?.signal);
237
- const d = S(p, r, i);
238
- return console.info("[make-ai-assistant] Make App history load success", {
239
- appId: t.app.id,
240
- messageCount: d.messages.length
241
- }), d;
242
- } catch (r) {
243
- throw (s?.signal?.aborted ? console.info : console.error)(
244
- s?.signal?.aborted ? "[make-ai-assistant] Make App history load cancelled" : "[make-ai-assistant] Make App history load failed",
245
- {
246
- appId: t.app.id,
247
- errorType: r instanceof Error ? r.name : typeof r
248
- }
249
- ), r;
250
- }
251
- },
252
- async *run(t, s) {
253
- console.info("[make-ai-assistant] Make App run start", {
254
- appId: t.context.app.id
255
- });
256
- try {
257
- I(s?.signal);
258
- const r = await o(t.context, s), p = _(await e.sendMessage({
259
- chatId: r,
260
- messageId: t.message.id,
261
- text: t.message.content
262
- }, { signal: s?.signal }));
263
- if (I(s?.signal), p.chatId !== r)
264
- throw new Error("Invalid Make App assistant response: chatId mismatch");
265
- for await (const d of C({
266
- chatId: r,
267
- responseId: p.responseId,
268
- eventSourceFactory: a,
269
- maxEventCharacters: c
270
- }, s))
271
- yield d;
272
- console.info("[make-ai-assistant] Make App run complete", {
273
- appId: t.context.app.id
495
+ return C(n.agents, 1e3).map((i) => {
496
+ const l = A(i);
497
+ if (l.appKey !== r.appKey)
498
+ throw new Error("Invalid Make App response: agent scope");
499
+ return {
500
+ agentId: w(l.agentId),
501
+ appKey: r.appKey,
502
+ name: g(l.name)
503
+ };
274
504
  });
275
- } catch (r) {
276
- throw s?.signal?.aborted ? console.info("[make-ai-assistant] Make App run cancelled", {
277
- appId: t.context.app.id
278
- }) : console.error("[make-ai-assistant] Make App run failed", {
279
- appId: t.context.app.id,
280
- errorType: r instanceof Error ? r.name : typeof r
281
- }), r;
282
- }
505
+ },
506
+ e?.signal
507
+ ),
508
+ listConversations: (s, e, r) => h(
509
+ s,
510
+ "listChats",
511
+ async () => {
512
+ const { appKey: n, agentId: i } = c(s);
513
+ return j(
514
+ await t.listChats(
515
+ {
516
+ appKey: n,
517
+ agentId: i,
518
+ ...e?.cursor ? { cursor: g(e.cursor, 8192) } : {},
519
+ limit: m(e?.limit ?? 50, 1, 100)
520
+ },
521
+ { signal: r?.signal }
522
+ ),
523
+ { appKey: n, agentId: i }
524
+ );
525
+ },
526
+ r?.signal
527
+ ),
528
+ createConversation: (s, e, r) => h(
529
+ s,
530
+ "createChat",
531
+ async () => {
532
+ const { appKey: n, agentId: i } = c(s), l = {
533
+ appKey: n,
534
+ agentId: i,
535
+ requestId: b(e.requestId),
536
+ ...e.title === void 0 ? {} : { title: g(e.title.trim(), 255) }
537
+ };
538
+ return M(
539
+ await t.createChat(l, { signal: r?.signal }),
540
+ { appKey: n, agentId: i }
541
+ );
542
+ },
543
+ r?.signal
544
+ ),
545
+ getConversation: (s, e, r) => h(
546
+ s,
547
+ "getChat",
548
+ async () => M(
549
+ await t.getChat(p(e), { signal: r?.signal }),
550
+ c(s),
551
+ e.chatId
552
+ ),
553
+ r?.signal
554
+ ),
555
+ updateConversation: (s, e, r) => h(
556
+ s,
557
+ "updateChat",
558
+ async () => {
559
+ const n = {
560
+ ...p(e),
561
+ expectedRevision: m(e.expectedRevision, 1)
562
+ };
563
+ if (e.title !== void 0 && (n.title = g(e.title.trim(), 255)), e.pinned !== void 0) {
564
+ if (typeof e.pinned != "boolean")
565
+ throw new Error("Invalid Make App request: pinned");
566
+ n.pinned = e.pinned;
567
+ }
568
+ if (n.title === void 0 && n.pinned === void 0)
569
+ throw new Error("Invalid Make App request: empty patch");
570
+ return M(
571
+ await t.updateChat(n, { signal: r?.signal }),
572
+ c(s),
573
+ e.chatId
574
+ );
575
+ },
576
+ r?.signal
577
+ ),
578
+ deleteConversation: (s, e, r) => h(
579
+ s,
580
+ "deleteChat",
581
+ () => t.deleteChat(
582
+ {
583
+ ...p(e),
584
+ expectedRevision: m(e.expectedRevision, 1)
585
+ },
586
+ { signal: r?.signal }
587
+ ),
588
+ r?.signal
589
+ ),
590
+ loadConversation: async (s, e) => e?.threadId ? E(s, e.threadId, e.cursor ?? -1, e.signal) : { messages: [] },
591
+ getResponse: (s, e, r) => y(s, e, r?.signal),
592
+ cancelResponse: (s, e, r) => h(
593
+ s,
594
+ "cancelResponse",
595
+ async () => K(
596
+ await t.cancelResponse(v(e), {
597
+ signal: r?.signal
598
+ }),
599
+ e
600
+ ),
601
+ r?.signal
602
+ ),
603
+ setFeedback: (s, e, r) => h(
604
+ s,
605
+ "setFeedback",
606
+ async () => {
607
+ if (!["like", "dislike", "none"].includes(e.rating))
608
+ throw new Error("Invalid Make App request: rating");
609
+ const n = g(e.reason ?? "", 128, !0).trim(), i = g(e.comment ?? "", 4e3, !0).trim();
610
+ if (e.rating !== "dislike" && (n || i))
611
+ throw new Error("Invalid Make App request: feedback detail");
612
+ return z(
613
+ await t.setFeedback(
614
+ {
615
+ ...p(e),
616
+ messageId: w(e.messageId),
617
+ requestId: b(e.requestId),
618
+ rating: e.rating,
619
+ ...n ? { reason: n } : {},
620
+ ...i ? { comment: i } : {}
621
+ },
622
+ { signal: r?.signal }
623
+ )
624
+ );
625
+ },
626
+ r?.signal
627
+ ),
628
+ startUpload: (s, e, r) => h(
629
+ s,
630
+ "startUpload",
631
+ async () => S(
632
+ await t.startUpload(
633
+ {
634
+ ...p(e),
635
+ fileId: b(e.fileId),
636
+ name: T(e.name),
637
+ contentType: g(e.contentType, 256),
638
+ sizeBytes: m(e.sizeBytes, 0, 64 << 20),
639
+ ...e.digestSha256 ? { digestSha256: g(e.digestSha256, 64) } : {}
640
+ },
641
+ { signal: r?.signal }
642
+ )
643
+ ),
644
+ r?.signal
645
+ ),
646
+ getUpload: (s, e, r) => h(
647
+ s,
648
+ "getUpload",
649
+ async () => S(
650
+ await t.getUpload(I(e), { signal: r?.signal }),
651
+ e.uploadId
652
+ ),
653
+ r?.signal
654
+ ),
655
+ uploadPart: (s, e, r) => h(
656
+ s,
657
+ "uploadPart",
658
+ () => {
659
+ if (!(e.bytes instanceof Uint8Array) || e.bytes.byteLength > 1 << 20)
660
+ throw new Error("Invalid Make App request: upload bytes");
661
+ return t.uploadPart(
662
+ {
663
+ ...I(e),
664
+ part: m(e.part, 0, 63),
665
+ bytes: e.bytes
666
+ },
667
+ { signal: r?.signal }
668
+ );
669
+ },
670
+ r?.signal
671
+ ),
672
+ completeUpload: (s, e, r) => h(
673
+ s,
674
+ "completeUpload",
675
+ async () => S(
676
+ await t.completeUpload(I(e), {
677
+ signal: r?.signal
678
+ }),
679
+ e.uploadId
680
+ ),
681
+ r?.signal
682
+ ),
683
+ readContent: (s, e, r) => h(
684
+ s,
685
+ "readContent",
686
+ async () => {
687
+ const n = await t.readContent(
688
+ { ...p(e), contentRef: w(e.contentRef) },
689
+ { signal: r?.signal }
690
+ );
691
+ if (!(n instanceof Uint8Array) || n.byteLength > 64 << 20)
692
+ throw new Error("Invalid Make App response: content bytes");
693
+ return n;
694
+ },
695
+ r?.signal
696
+ ),
697
+ watchResponse: f,
698
+ async *run(s, e) {
699
+ if (e?.signal?.aborted) return;
700
+ const r = Q(s), n = await h(
701
+ s.context,
702
+ "sendMessage",
703
+ async () => A(
704
+ await t.sendMessage(r, { signal: e?.signal })
705
+ ),
706
+ e?.signal
707
+ );
708
+ if (n.chatId !== r.chatId)
709
+ throw new Error("Invalid Make App response: accepted chat");
710
+ const i = w(n.responseId), l = m(n.acceptedCursor);
711
+ yield {
712
+ type: "response.accepted",
713
+ chatId: r.chatId,
714
+ responseId: i,
715
+ messageId: r.messageId,
716
+ acceptedCursor: l
717
+ }, yield* f(
718
+ s.context,
719
+ { chatId: r.chatId, responseId: i, historyCursor: l },
720
+ e
721
+ );
283
722
  }
284
723
  };
285
724
  };
286
725
  export {
287
- T as createMakeAppAssistantTransport
726
+ Z as createMakeAppAssistantTransport
288
727
  };