@qfei-design/make-ai-assistant 0.1.0 → 0.1.2
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/PUBLIC_API.md +63 -4
- package/README.md +61 -4
- package/capabilities.json +18 -0
- package/dist/conversation-Dy2Sghjv.js +684 -0
- package/dist/conversation-Yku9Lzj_.cjs +1 -0
- package/dist/core/conversation.d.ts +30 -1
- package/dist/core/types.d.ts +3 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/make-app.cjs +1 -0
- package/dist/make-app.d.ts +36 -0
- package/dist/make-app.mjs +287 -0
- package/dist/make-console.cjs +1 -0
- package/dist/make-console.d.ts +58 -0
- package/dist/make-console.mjs +366 -0
- package/dist/react.cjs +1 -1
- package/dist/react.mjs +384 -326
- package/dist/sse.cjs +1 -1
- package/dist/sse.mjs +1 -1
- package/dist/styles.css +29 -0
- package/docs/backend-contract.md +52 -3
- package/package.ai.json +9 -5
- package/package.json +11 -1
- package/recipes.json +36 -0
- package/dist/conversation-B5kECJz8.js +0 -595
- package/dist/conversation-DpYszfVd.cjs +0 -1
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { DEFAULT_MAX_SSE_EVENT_CHARACTERS as N } from "./sse.mjs";
|
|
2
|
+
import { c as D, M as m } from "./conversation-Dy2Sghjv.js";
|
|
3
|
+
const _ = 4e3, U = 200, P = 30, K = 1e3, F = {
|
|
4
|
+
AI_AGENT_UNAVAILABLE: "当前应用没有可用 Agent。",
|
|
5
|
+
AI_AUTH_EXPIRED: "登录已失效,请重新登录。",
|
|
6
|
+
AI_AUTH_REQUIRED: "登录已失效,请重新登录。",
|
|
7
|
+
AI_FORBIDDEN: "当前账号无权使用该 AI 助手。",
|
|
8
|
+
AI_RUN_FAILED: "本次 AI 处理失败,请重试。",
|
|
9
|
+
AI_UPSTREAM_ERROR: "AI 服务暂时不可用,请稍后重试。"
|
|
10
|
+
}, q = /* @__PURE__ */ new Set([
|
|
11
|
+
"AI_AGENT_UNAVAILABLE",
|
|
12
|
+
"AI_AUTH_EXPIRED",
|
|
13
|
+
"AI_AUTH_REQUIRED",
|
|
14
|
+
"AI_FORBIDDEN"
|
|
15
|
+
]), E = (e) => typeof e == "object" && e !== null && !Array.isArray(e), y = (e, t, n = m.identifierCharacters) => {
|
|
16
|
+
if (typeof e != "string" || !e.trim() || D(e, n) > n)
|
|
17
|
+
throw new Error(`Invalid Make Console assistant response: ${t}`);
|
|
18
|
+
return e;
|
|
19
|
+
}, k = (e, t) => {
|
|
20
|
+
if (!(e == null || e === ""))
|
|
21
|
+
return y(e, t);
|
|
22
|
+
}, C = (e, t) => {
|
|
23
|
+
if (!Number.isSafeInteger(e) || Number(e) < 0)
|
|
24
|
+
throw new Error(`Invalid Make Console assistant response: ${t}`);
|
|
25
|
+
return Number(e);
|
|
26
|
+
}, S = () => new DOMException("Aborted", "AbortError"), u = (e) => {
|
|
27
|
+
if (e?.aborted) throw S();
|
|
28
|
+
}, H = (e, t) => (u(t), e === 0 ? Promise.resolve() : new Promise((n, i) => {
|
|
29
|
+
const f = setTimeout(() => {
|
|
30
|
+
t?.removeEventListener("abort", I), n();
|
|
31
|
+
}, e), I = () => {
|
|
32
|
+
clearTimeout(f), t?.removeEventListener("abort", I), i(S());
|
|
33
|
+
};
|
|
34
|
+
t?.addEventListener("abort", I, { once: !0 });
|
|
35
|
+
})), $ = (e) => {
|
|
36
|
+
if (!E(e) || !Array.isArray(e.agents) || e.agents.length > 1e3)
|
|
37
|
+
throw new Error("Invalid Make Console assistant response: agents");
|
|
38
|
+
const t = /* @__PURE__ */ new Set();
|
|
39
|
+
return e.agents.map((n) => {
|
|
40
|
+
if (!E(n))
|
|
41
|
+
throw new Error("Invalid Make Console assistant response: agent");
|
|
42
|
+
const i = y(n.agentID, "agentID");
|
|
43
|
+
if (t.has(i))
|
|
44
|
+
throw new Error("Invalid Make Console assistant response: duplicate agentID");
|
|
45
|
+
return t.add(i), {
|
|
46
|
+
agentID: i,
|
|
47
|
+
...typeof n.name == "string" && n.name.trim() ? { name: y(n.name, "agent name") } : {},
|
|
48
|
+
status: y(n.status, "agent status")
|
|
49
|
+
};
|
|
50
|
+
});
|
|
51
|
+
}, B = (e) => {
|
|
52
|
+
if (!E(e))
|
|
53
|
+
throw new Error("Invalid Make Console assistant response: session");
|
|
54
|
+
return {
|
|
55
|
+
nextSeq: C(e.nextSeq, "nextSeq"),
|
|
56
|
+
sessionID: y(e.sessionID, "sessionID")
|
|
57
|
+
};
|
|
58
|
+
}, G = (e) => {
|
|
59
|
+
if (!E(e))
|
|
60
|
+
throw new Error("Invalid Make Console assistant response: sent message");
|
|
61
|
+
const t = k(e.runID, "runID"), n = k(e.mergedInto, "mergedInto");
|
|
62
|
+
if (t && n)
|
|
63
|
+
throw new Error("Invalid Make Console assistant response: multiple Run IDs");
|
|
64
|
+
return {
|
|
65
|
+
effectiveRunID: t ?? n,
|
|
66
|
+
seq: C(e.seq, "seq"),
|
|
67
|
+
sessionID: y(e.sessionID, "sessionID")
|
|
68
|
+
};
|
|
69
|
+
}, V = (e) => {
|
|
70
|
+
if (!E(e) || !Array.isArray(e.blocks) || e.blocks.length > 1e3)
|
|
71
|
+
throw new Error("Invalid Make Console assistant response: payload blocks");
|
|
72
|
+
let t = "";
|
|
73
|
+
for (const n of e.blocks)
|
|
74
|
+
if (!(!E(n) || n.kind !== "text" || typeof n.text != "string") && (t += n.text, D(t, m.messageCharacters) > m.messageCharacters))
|
|
75
|
+
throw new Error("Invalid Make Console assistant response: message text budget");
|
|
76
|
+
return y(
|
|
77
|
+
t,
|
|
78
|
+
"message text",
|
|
79
|
+
m.messageCharacters
|
|
80
|
+
);
|
|
81
|
+
}, x = (e, t) => {
|
|
82
|
+
if (!Array.isArray(e) || e.length > t)
|
|
83
|
+
throw new Error("Invalid Make Console assistant response: durable events");
|
|
84
|
+
const n = /* @__PURE__ */ new Set();
|
|
85
|
+
return e.flatMap((i) => {
|
|
86
|
+
if (!E(i))
|
|
87
|
+
throw new Error("Invalid Make Console assistant response: durable event");
|
|
88
|
+
const c = C(i.seq, "event seq");
|
|
89
|
+
if (n.has(c))
|
|
90
|
+
throw new Error("Invalid Make Console assistant response: duplicate event seq");
|
|
91
|
+
n.add(c);
|
|
92
|
+
const f = typeof i.type == "string" ? i.type : "", I = E(i.actor) && typeof i.actor.kind == "string" ? i.actor.kind : "";
|
|
93
|
+
return !(f === "user_message") && !(f === "message" && I === "agent") ? [] : [{
|
|
94
|
+
actorKind: I,
|
|
95
|
+
content: V(i.payload),
|
|
96
|
+
runID: k(i.runID, "event runID"),
|
|
97
|
+
seq: c,
|
|
98
|
+
type: f
|
|
99
|
+
}];
|
|
100
|
+
});
|
|
101
|
+
}, X = (e, t, n) => {
|
|
102
|
+
const i = x(e, n);
|
|
103
|
+
let c = 0;
|
|
104
|
+
return { messages: i.map((I) => {
|
|
105
|
+
if (c += D(
|
|
106
|
+
I.content,
|
|
107
|
+
m.historyCharacters - c
|
|
108
|
+
), c > m.historyCharacters)
|
|
109
|
+
throw new Error("Invalid Make Console assistant response: history text budget");
|
|
110
|
+
return {
|
|
111
|
+
artifacts: [],
|
|
112
|
+
content: I.content,
|
|
113
|
+
id: `console-${t}-${String(I.seq)}`,
|
|
114
|
+
role: I.type === "user_message" ? "user" : "assistant"
|
|
115
|
+
};
|
|
116
|
+
}), threadId: t };
|
|
117
|
+
}, Q = () => {
|
|
118
|
+
const e = [], t = [];
|
|
119
|
+
return { next: () => {
|
|
120
|
+
const c = e.shift();
|
|
121
|
+
return c ? Promise.resolve(c) : new Promise((f) => t.push(f));
|
|
122
|
+
}, push: (c) => {
|
|
123
|
+
const f = t.shift();
|
|
124
|
+
f ? f(c) : e.push(c);
|
|
125
|
+
} };
|
|
126
|
+
}, J = (e, t) => {
|
|
127
|
+
if (D(e.data, t) > t)
|
|
128
|
+
throw new Error("Make Console assistant SSE event exceeds maxEventCharacters");
|
|
129
|
+
try {
|
|
130
|
+
const n = JSON.parse(e.data);
|
|
131
|
+
if (!E(n)) throw new Error("invalid data");
|
|
132
|
+
return n;
|
|
133
|
+
} catch {
|
|
134
|
+
throw new Error("Invalid Make Console assistant SSE JSON");
|
|
135
|
+
}
|
|
136
|
+
}, T = (e, t) => {
|
|
137
|
+
if (!Number.isInteger(e) || e < 1)
|
|
138
|
+
throw new Error(`${t} must be a positive integer`);
|
|
139
|
+
}, Y = (e, t, n) => x(e, t).find(
|
|
140
|
+
(c) => c.type === "message" && c.actorKind === "agent" && (n === void 0 || c.runID === n)
|
|
141
|
+
), W = (e) => {
|
|
142
|
+
const t = e.historyLimit ?? U, n = e.maxEventCharacters ?? N, i = e.maxPollingAttempts ?? P, c = e.pollIntervalMs ?? K, f = e.wait ?? H;
|
|
143
|
+
if (!Number.isInteger(t) || t < 1 || t > 200)
|
|
144
|
+
throw new Error("historyLimit must be an integer between 1 and 200");
|
|
145
|
+
if (T(n, "maxEventCharacters"), T(i, "maxPollingAttempts"), !Number.isInteger(c) || c < 0)
|
|
146
|
+
throw new Error("pollIntervalMs must be a non-negative integer");
|
|
147
|
+
const I = async (s, r) => {
|
|
148
|
+
u(r?.signal), console.info("[make-ai-assistant] Make Console Agent lookup start", {
|
|
149
|
+
appId: s.app.id
|
|
150
|
+
});
|
|
151
|
+
const a = $(await e.listAgents(
|
|
152
|
+
{ appKey: s.app.id },
|
|
153
|
+
{ signal: r?.signal }
|
|
154
|
+
));
|
|
155
|
+
u(r?.signal);
|
|
156
|
+
const l = a.filter((g) => g.status === "enabled"), p = e.selectAgent ? e.selectAgent(l, s) : l[0]?.agentID, d = l.find((g) => g.agentID === p);
|
|
157
|
+
if (!d) throw new Error("当前应用没有可用 Agent");
|
|
158
|
+
return console.info("[make-ai-assistant] Make Console Agent lookup success", {
|
|
159
|
+
appId: s.app.id,
|
|
160
|
+
enabledAgentCount: l.length
|
|
161
|
+
}), d;
|
|
162
|
+
}, M = async (s, r, a) => (u(a?.signal), B(await e.getOrCreateSession(
|
|
163
|
+
{ agentID: r, appKey: s.app.id },
|
|
164
|
+
{ signal: a?.signal }
|
|
165
|
+
))), v = async (s) => {
|
|
166
|
+
for (let r = 1; r <= i; r += 1) {
|
|
167
|
+
u(s.signal);
|
|
168
|
+
const a = await e.loadEvents({
|
|
169
|
+
agentID: s.agentID,
|
|
170
|
+
appKey: s.appKey,
|
|
171
|
+
from: s.from,
|
|
172
|
+
limit: t,
|
|
173
|
+
sessionID: s.sessionID
|
|
174
|
+
}, { signal: s.signal });
|
|
175
|
+
u(s.signal);
|
|
176
|
+
const l = Y(
|
|
177
|
+
a,
|
|
178
|
+
t,
|
|
179
|
+
s.effectiveRunID
|
|
180
|
+
);
|
|
181
|
+
if (l) return l;
|
|
182
|
+
r < i && await f(c, s.signal);
|
|
183
|
+
}
|
|
184
|
+
throw new Error("Make Console assistant durable response unavailable");
|
|
185
|
+
}, L = async function* (s) {
|
|
186
|
+
u(s.signal);
|
|
187
|
+
const r = Q(), a = e.eventSourceFactory({
|
|
188
|
+
agentID: s.agentID,
|
|
189
|
+
appKey: s.appKey,
|
|
190
|
+
cursor: "0-0",
|
|
191
|
+
runID: s.effectiveRunID,
|
|
192
|
+
sessionID: s.sessionID
|
|
193
|
+
}, { withCredentials: !0 });
|
|
194
|
+
let l = !1;
|
|
195
|
+
const p = (o) => {
|
|
196
|
+
l || (l = !0, r.push(o));
|
|
197
|
+
}, d = /* @__PURE__ */ new Map(), g = (o, h) => {
|
|
198
|
+
const A = (b) => {
|
|
199
|
+
if (!l)
|
|
200
|
+
try {
|
|
201
|
+
h(J(b, n), b);
|
|
202
|
+
} catch (R) {
|
|
203
|
+
p({ type: "error", error: R });
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
d.set(o, A), a.addEventListener(o, A);
|
|
207
|
+
};
|
|
208
|
+
g("ready", (o) => {
|
|
209
|
+
if (typeof o.after != "string")
|
|
210
|
+
throw new Error("Invalid Make Console assistant response: ready cursor");
|
|
211
|
+
}), g("run-output", (o) => {
|
|
212
|
+
if (y(o.runID, "SSE runID") !== s.effectiveRunID)
|
|
213
|
+
throw new Error("Invalid Make Console assistant response: SSE runID mismatch");
|
|
214
|
+
C(o.sequence, "SSE sequence");
|
|
215
|
+
const h = y(o.type, "SSE output type");
|
|
216
|
+
if (h === "output_text.delta") {
|
|
217
|
+
if (typeof o.delta != "string")
|
|
218
|
+
throw new Error("Invalid Make Console assistant response: SSE delta");
|
|
219
|
+
r.push({
|
|
220
|
+
type: "event",
|
|
221
|
+
event: {
|
|
222
|
+
type: "message.delta",
|
|
223
|
+
messageId: s.messageId,
|
|
224
|
+
delta: o.delta
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
} else h === "response.completed" ? p({ type: "completed" }) : h === "response.failed" && p({
|
|
228
|
+
type: "failed",
|
|
229
|
+
code: y(o.failureCode, "failureCode")
|
|
230
|
+
});
|
|
231
|
+
}), g("fallback", (o) => {
|
|
232
|
+
if (o.reason !== "stream_unavailable")
|
|
233
|
+
throw new Error("Invalid Make Console assistant response: fallback reason");
|
|
234
|
+
p({ type: "fallback" });
|
|
235
|
+
}), a.onerror = () => {
|
|
236
|
+
l || a.readyState !== void 0 && a.readyState !== 2 || p({
|
|
237
|
+
type: "error",
|
|
238
|
+
error: new Error("Make Console assistant SSE disconnected")
|
|
239
|
+
});
|
|
240
|
+
};
|
|
241
|
+
const w = () => p({ type: "error", error: S() });
|
|
242
|
+
s.signal?.addEventListener("abort", w, { once: !0 }), s.signal?.aborted && w();
|
|
243
|
+
try {
|
|
244
|
+
for (; ; ) {
|
|
245
|
+
const o = await r.next();
|
|
246
|
+
if (o.type === "event")
|
|
247
|
+
yield o.event;
|
|
248
|
+
else {
|
|
249
|
+
if (o.type === "completed" || o.type === "fallback")
|
|
250
|
+
return o.type;
|
|
251
|
+
if (o.type === "failed")
|
|
252
|
+
return yield {
|
|
253
|
+
type: "error",
|
|
254
|
+
code: o.code,
|
|
255
|
+
message: F[o.code] ?? "本次 AI 处理失败,请重试。",
|
|
256
|
+
retryable: !q.has(o.code),
|
|
257
|
+
requestId: s.effectiveRunID
|
|
258
|
+
}, "failed";
|
|
259
|
+
throw o.error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
} finally {
|
|
263
|
+
l = !0, s.signal?.removeEventListener("abort", w), a.onerror = null;
|
|
264
|
+
for (const [o, h] of d)
|
|
265
|
+
a.removeEventListener(o, h);
|
|
266
|
+
a.close();
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
return {
|
|
270
|
+
features: {
|
|
271
|
+
history: !0,
|
|
272
|
+
newConversation: !1,
|
|
273
|
+
remoteCancellation: !1
|
|
274
|
+
},
|
|
275
|
+
async loadConversation(s, r) {
|
|
276
|
+
console.info("[make-ai-assistant] Make Console history load start", {
|
|
277
|
+
appId: s.app.id
|
|
278
|
+
});
|
|
279
|
+
try {
|
|
280
|
+
const a = await I(s, r), l = await M(s, a.agentID, r), p = Math.max(0, l.nextSeq - t), d = await e.loadEvents({
|
|
281
|
+
agentID: a.agentID,
|
|
282
|
+
appKey: s.app.id,
|
|
283
|
+
from: p,
|
|
284
|
+
limit: t,
|
|
285
|
+
sessionID: l.sessionID
|
|
286
|
+
}, { signal: r?.signal });
|
|
287
|
+
u(r?.signal);
|
|
288
|
+
const g = X(d, l.sessionID, t);
|
|
289
|
+
return console.info("[make-ai-assistant] Make Console history load success", {
|
|
290
|
+
appId: s.app.id,
|
|
291
|
+
messageCount: g.messages.length
|
|
292
|
+
}), g;
|
|
293
|
+
} catch (a) {
|
|
294
|
+
throw (r?.signal?.aborted ? console.info : console.error)(
|
|
295
|
+
r?.signal?.aborted ? "[make-ai-assistant] Make Console history load cancelled" : "[make-ai-assistant] Make Console history load failed",
|
|
296
|
+
{
|
|
297
|
+
appId: s.app.id,
|
|
298
|
+
errorType: a instanceof Error ? a.name : typeof a
|
|
299
|
+
}
|
|
300
|
+
), a;
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
async *run(s, r) {
|
|
304
|
+
console.info("[make-ai-assistant] Make Console run start", {
|
|
305
|
+
appId: s.context.app.id
|
|
306
|
+
});
|
|
307
|
+
try {
|
|
308
|
+
const a = s.message.content.trim();
|
|
309
|
+
if (!a || D(a, _) > _)
|
|
310
|
+
throw new Error(
|
|
311
|
+
a ? "Console 消息不能超过 4000 个字符" : "Console 消息不能为空"
|
|
312
|
+
);
|
|
313
|
+
const l = await I(s.context, r), p = await M(
|
|
314
|
+
s.context,
|
|
315
|
+
l.agentID,
|
|
316
|
+
r
|
|
317
|
+
);
|
|
318
|
+
u(r?.signal);
|
|
319
|
+
const d = G(await e.sendMessage({
|
|
320
|
+
agentID: l.agentID,
|
|
321
|
+
appKey: s.context.app.id,
|
|
322
|
+
text: a
|
|
323
|
+
}, { signal: r?.signal }));
|
|
324
|
+
if (u(r?.signal), d.sessionID !== p.sessionID)
|
|
325
|
+
throw new Error("Invalid Make Console assistant response: sessionID mismatch");
|
|
326
|
+
const g = d.effectiveRunID ?? `${d.sessionID}:${String(d.seq)}`, w = `assistant:${g}`;
|
|
327
|
+
if (yield { type: "message.start", runId: g, messageId: w }, d.effectiveRunID) {
|
|
328
|
+
const A = yield* L({
|
|
329
|
+
agentID: l.agentID,
|
|
330
|
+
appKey: s.context.app.id,
|
|
331
|
+
effectiveRunID: d.effectiveRunID,
|
|
332
|
+
messageId: w,
|
|
333
|
+
sessionID: d.sessionID,
|
|
334
|
+
signal: r?.signal
|
|
335
|
+
});
|
|
336
|
+
if (A === "failed") return;
|
|
337
|
+
A === "fallback" && console.info("[make-ai-assistant] Make Console SSE fallback", {
|
|
338
|
+
appId: s.context.app.id
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
const o = await v({
|
|
342
|
+
agentID: l.agentID,
|
|
343
|
+
appKey: s.context.app.id,
|
|
344
|
+
effectiveRunID: d.effectiveRunID,
|
|
345
|
+
from: d.seq + 1,
|
|
346
|
+
sessionID: d.sessionID,
|
|
347
|
+
signal: r?.signal
|
|
348
|
+
});
|
|
349
|
+
yield { type: "message.replace", messageId: w, content: o.content }, yield { type: "message.complete", messageId: w }, yield { type: "run.complete", runId: g, threadId: d.sessionID }, console.info("[make-ai-assistant] Make Console run complete", {
|
|
350
|
+
appId: s.context.app.id
|
|
351
|
+
});
|
|
352
|
+
} catch (a) {
|
|
353
|
+
throw r?.signal?.aborted ? console.info("[make-ai-assistant] Make Console run cancelled", {
|
|
354
|
+
appId: s.context.app.id
|
|
355
|
+
}) : console.error("[make-ai-assistant] Make Console run failed", {
|
|
356
|
+
appId: s.context.app.id,
|
|
357
|
+
errorType: a instanceof Error ? a.name : typeof a
|
|
358
|
+
}), a;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
};
|
|
363
|
+
export {
|
|
364
|
+
_ as MAKE_CONSOLE_MESSAGE_CHARACTERS,
|
|
365
|
+
W as createMakeConsoleAssistantTransport
|
|
366
|
+
};
|
package/dist/react.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),y=require("./index.cjs"),h=require("react"),c=require("./conversation-DpYszfVd.cjs");function W({artifact:a,context:t,fallback:s,onAction:o,onActionError:n,registry:r}){const m=y.resolveArtifactTemplate(r,a,t);if(!m)return s?s(a):e.jsxs("section",{className:"make-ai-artifact make-ai-artifact--unsupported",role:"status",children:[e.jsx("strong",{children:"暂不支持展示此结果"}),e.jsxs("span",{children:["结果类型:",a.kind]})]});const u={context:t,onAction:o,onActionError:n};return m.template.render(a,t,u)}const v=(a,t,s)=>{if(a==null||a==="")return"—";if(typeof a=="boolean")return a?"是":"否";if(typeof a!="number")return`${a}${t?.unit??""}`;const o=t?.precision,n={maximumFractionDigits:o??2,minimumFractionDigits:o};t?.style==="currency"&&t.currency?(n.style="currency",n.currency=t.currency):t?.style==="percent"&&(n.style="percent");try{const r=t?.style==="percent"?a/100:a;return`${new Intl.NumberFormat(s,n).format(r)}${t?.unit??""}`}catch{return`${a}${t?.unit??""}`}},X=a=>{let t=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const o of a)t=Math.min(t,o),s=Math.max(s,o);return Number.isFinite(t)&&Number.isFinite(s)?{min:t,max:s}:{min:0,max:0}},ee=(a,t,s)=>{if(!s.onAction)return;const o=r=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:a.id,artifactId:t.artifact.id,errorType:r instanceof Error?r.name:typeof r,intent:a.intent})},n=r=>{if(s.onActionError){try{Promise.resolve(s.onActionError(r,a,t)).catch(o)}catch(m){o(m)}return}console.error("[make-ai-assistant] host action failed",{actionId:a.id,artifactId:t.artifact.id,errorType:r instanceof Error?r.name:typeof r,intent:a.intent})};try{Promise.resolve(s.onAction(a,t)).catch(n)}catch(r){n(r)}},R=(a,t)=>a.actions?.length&&t.onAction?e.jsx("div",{className:"make-ai-artifact__actions",children:a.actions.map(s=>e.jsxs("button",{className:`make-ai-artifact__action make-ai-artifact__action--${s.appearance??"link"}`,type:"button",onClick:()=>ee(s,{artifact:a,context:t.context},t),children:[s.label,e.jsx("span",{"aria-hidden":"true",children:"→"})]},s.id))}):null,C=(a,t,s="")=>e.jsxs("section",{"aria-label":a.title??`${a.kind} result`,className:`make-ai-artifact ${s}`.trim(),"data-artifact-density":a.presentation?.density,"data-artifact-kind":a.kind,children:[a.title?e.jsx("h4",{className:"make-ai-artifact__title",children:a.title}):null,a.summary?e.jsx("p",{className:"make-ai-artifact__summary",children:a.summary}):null,t]}),de=({artifact:a,renderContext:t})=>{const s=a.data.delta,o=s?v(s.value,s.format==="percent"?{style:"percent"}:void 0,t.context.locale):void 0;return C(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__metric-value",children:v(a.data.value,a.data.format,t.context.locale)}),s?e.jsxs("div",{className:`make-ai-artifact__delta make-ai-artifact__delta--${s.direction??"flat"}`,children:[e.jsx("span",{"aria-hidden":"true",children:s.direction==="up"?"↗":s.direction==="down"?"↘":"→"}),e.jsx("span",{children:o}),s.label?e.jsx("span",{children:s.label}):null]}):null,a.data.context?e.jsx("p",{className:"make-ai-artifact__context",children:a.data.context}):null,R(a,t)]}),"make-ai-artifact--metric")},me=({artifact:a,renderContext:t})=>C(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__comparison",children:a.data.items.map(s=>e.jsxs("div",{className:"make-ai-artifact__comparison-item",children:[e.jsx("span",{children:s.label}),e.jsx("strong",{children:v(s.value,s.format,t.context.locale)}),s.hint?e.jsx("small",{children:s.hint}):null]},s.id))}),R(a,t)]}),"make-ai-artifact--comparison"),ue=({artifact:a,renderContext:t})=>{const s=a.data.series.flatMap(m=>m.points.map(u=>u.y)),{max:o,min:n}=X(s),r=o-n||1;return C(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__trend",children:a.data.series.map(m=>e.jsxs("div",{className:"make-ai-artifact__trend-series",children:[e.jsx("div",{className:"make-ai-artifact__trend-label",children:m.label}),e.jsx("div",{className:"make-ai-artifact__trend-bars",children:m.points.map((u,g)=>{const f=18+(u.y-n)/r*70;return e.jsxs("div",{className:"make-ai-artifact__trend-point",children:[e.jsx("span",{"aria-label":`${u.x}: ${v(u.y,m.format,t.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${f}%`},title:`${u.x}: ${v(u.y,m.format,t.context.locale)}`}),e.jsx("small",{children:u.x})]},`${u.x}-${g}`)})})]},m.id))}),R(a,t)]}),"make-ai-artifact--trend")},pe=({artifact:a,renderContext:t})=>{const{max:s}=X(a.data.items.map(n=>Math.abs(n.value))),o=Math.max(s,1);return C(a,e.jsxs(e.Fragment,{children:[e.jsx("ol",{className:"make-ai-artifact__ranking",children:a.data.items.map((n,r)=>e.jsxs("li",{children:[e.jsx("span",{className:"make-ai-artifact__rank",children:r+1}),e.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[e.jsx("span",{children:n.label}),n.description?e.jsx("small",{children:n.description}):null]}),e.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.abs(n.value)/o*100}%`}})}),e.jsx("strong",{children:v(n.value,n.format,t.context.locale)})]},n.id))}),R(a,t)]}),"make-ai-artifact--ranking")},he=(a,t)=>t.action??{id:`open-${t.id}`,label:t.title??t.id,intent:"open-record",target:{entityKey:a.data.entity.key,recordId:t.id}},fe=({artifact:a,renderContext:t})=>C(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__record-list",children:a.data.records.length===0?e.jsx("p",{className:"make-ai-artifact__empty",children:"没有符合条件的记录"}):a.data.records.map(s=>{const o=he(a,s),n=e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:s.title??s.id}),e.jsx("span",{className:"make-ai-artifact__record-values",children:a.data.columns.map(r=>e.jsxs("span",{children:[e.jsx("small",{children:r.label}),v(s.values[r.key],r.format,t.context.locale)]},r.key))}),t.onAction?e.jsx("span",{"aria-hidden":"true",children:"›"}):null]});return t.onAction?e.jsx("button",{className:"make-ai-artifact__record",type:"button",onClick:()=>ee(o,{artifact:a,context:t.context},t),children:n},s.id):e.jsx("div",{className:"make-ai-artifact__record",children:n},s.id)})}),a.data.total!==void 0?e.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",a.data.total," 条"]}):null,R(a,t)]}),"make-ai-artifact--record-list"),_e=({artifact:a,renderContext:t})=>C(a,e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`make-ai-artifact__notice make-ai-artifact__notice--${a.data.tone}`,children:[e.jsx("span",{"aria-hidden":"true",children:a.data.tone==="success"?"✓":a.data.tone==="warning"?"!":a.data.tone==="danger"?"×":"i"}),e.jsx("p",{children:a.data.body})]}),R(a,t)]}),"make-ai-artifact--notice"),S=(a,t,s)=>({id:a,kinds:[t],priority:0,render:s}),Ae=[S("platform.metric.default","metric",(a,t,s)=>e.jsx(de,{artifact:a,renderContext:s})),S("platform.comparison.default","comparison",(a,t,s)=>e.jsx(me,{artifact:a,renderContext:s})),S("platform.trend.default","trend",(a,t,s)=>e.jsx(ue,{artifact:a,renderContext:s})),S("platform.ranking.default","ranking",(a,t,s)=>e.jsx(pe,{artifact:a,renderContext:s})),S("platform.record-list.default","record-list",(a,t,s)=>e.jsx(fe,{artifact:a,renderContext:s})),S("platform.notice.default","notice",(a,t,s)=>e.jsx(_e,{artifact:a,renderContext:s}))],ae=y.createArtifactTemplateRegistry(Ae).templates,te=(a=ae)=>y.createArtifactTemplateRegistry(a),xe=a=>`${a}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`;class p extends Error{}const Q=a=>{try{const t=a?.return?.();if(!t)return;Promise.resolve(t).catch(s=>{console.error("[make-ai-assistant] transport iterator close failed",{errorType:s instanceof Error?s.name:typeof s})})}catch(t){console.error("[make-ai-assistant] transport iterator close failed",{errorType:t instanceof Error?t.name:typeof t})}},se=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 2.8c.5 4.4 2.8 6.8 7.2 7.2-4.4.5-6.8 2.8-7.2 7.2-.5-4.4-2.8-6.8-7.2-7.2 4.4-.5 6.8-2.8 7.2-7.2Z"}),e.jsx("path",{d:"M18.3 16.1c.2 1.8 1.2 2.8 3 3-1.8.2-2.8 1.2-3 3-.2-1.8-1.2-2.8-3-3 1.8-.2 2.8-1.2 3-3Z"})]}),je=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),Ie=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),ke=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"m4 4 17 8-17 8 3-8-3-8Z"}),e.jsx("path",{d:"M7 12h14"})]}),B=()=>e.jsx("span",{className:"make-ai-assistant__avatar","aria-hidden":"true",children:e.jsx(se,{})}),ve=(a,t,s,o,n)=>a.messages.map(r=>e.jsxs("article",{className:`make-ai-assistant__message make-ai-assistant__message--${r.role}`,children:[r.role==="assistant"?e.jsx(B,{}):null,e.jsxs("div",{className:"make-ai-assistant__message-stack",children:[r.content?e.jsx("div",{className:"make-ai-assistant__bubble",children:r.content}):r.status==="streaming"?e.jsxs("div",{className:"make-ai-assistant__typing","aria-label":"AI 正在思考",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):null,r.artifacts.map(m=>e.jsx(W,{artifact:m,context:t,onAction:o,onActionError:n,registry:s},m.id))]})]},r.id));function re({context:a,onAction:t,onActionError:s,onClose:o,onNewConversation:n,registry:r,subtitle:m,suggestions:u=[],title:g="Make AI 助手",transport:f}){const[j,b]=h.useState(""),[d,I]=h.useState(c.createAssistantConversationState),[$,F]=h.useState(void 0),T=h.useRef(void 0),E=h.useRef(void 0),M=h.useRef(0),P=h.useRef(null),D=h.useRef(!0),U=h.useMemo(()=>r??te(),[r]),q=i=>{M.current+=1;const A=T.current,k=E.current?.iterator;return T.current=void 0,E.current=void 0,!A&&!k?!1:(console.info("[make-ai-assistant] local run cancellation requested",{reason:i}),A?.abort(),Q(k),!0)};h.useEffect(()=>()=>{q("unmount")},[]),h.useEffect(()=>{const i=P.current;if(!i||!D.current)return;const A=requestAnimationFrame(()=>{if(!D.current)return;const k=d.status==="streaming"||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";typeof i.scrollTo=="function"?i.scrollTo({top:i.scrollHeight,behavior:k}):i.scrollTop=i.scrollHeight});return()=>cancelAnimationFrame(A)},[d.messages,d.status]);const ne=()=>{const i=P.current;i&&(D.current=i.scrollHeight-i.scrollTop-i.clientHeight<=48)},H=async i=>{const A=i.trim();if(!A||d.status==="streaming"||T.current)return;if(c.countCodePointsUpTo(A,c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){F(`输入内容过长,请控制在 ${c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const k={id:xe("user"),content:A},O=new AbortController,w=M.current+1;M.current=w,T.current=O,F(void 0),b(""),I(x=>c.appendUserMessage(x,k));try{let x=!1,_,Z=0,Y=0,K=0;const z=new Set,G=new Set([...d.messages.map(L=>L.id),k.id]),V=new Set,J=f.run({threadId:d.threadId,message:k,context:a,capabilities:y.createArtifactCapabilities(U)},{signal:O.signal})[Symbol.asyncIterator]();for(E.current={iterator:J,requestVersion:w};;){const L=await J.next();if(M.current!==w||L.done)break;let l;try{l=c.parseAssistantEvent(L.value)}catch(N){throw new p(N instanceof Error?N.message:"Invalid assistant event")}if(l.type==="message.start"){if(_!==void 0&&_!==l.runId)throw new p("AI 助手响应 run id 不一致");if(_??=l.runId,Y+=1,Y>c.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new p("AI 助手单次响应消息数量超过限制");if(G.has(l.messageId))throw new p("AI 助手响应包含重复的 message id");G.add(l.messageId),V.add(l.messageId)}if(l.type==="message.delta"){if(!V.has(l.messageId))throw new p("AI 助手响应事件顺序无效");const N=c.countCodePointsUpTo(l.delta,c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-K);if(K+N>c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new p("AI 助手响应文本超过大小限制");if(K+=N,K>c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new p("AI 助手响应文本超过大小限制")}if(l.type==="artifact"){if(!V.has(l.messageId))throw new p("AI 助手响应事件顺序无效");if(Z+=1,Z>c.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new p("AI 助手单次响应 Artifact 数量超过限制");if(z.has(l.artifact.id))throw new p("AI 助手响应包含重复的 Artifact id");z.add(l.artifact.id)}if(l.type==="message.complete"&&!V.delete(l.messageId))throw new p("AI 助手响应事件顺序无效");if(l.type==="run.complete"&&_!==void 0&&_!==l.runId)throw new p("AI 助手响应 run id 不一致");if(l.type==="run.cancelled"&&l.runId!==void 0&&_!==void 0&&_!==l.runId)throw new p("AI 助手响应 run id 不一致");if(I(N=>c.reduceAssistantEvent(N,l)),l.type==="error"||l.type==="run.cancelled"||l.type==="run.complete"){x=!0;break}}if(!x)throw new p("AI 助手流式响应在终止事件前结束")}catch(x){if(M.current!==w)return;if(O.signal.aborted){I(_=>c.reduceAssistantEvent(_,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:x instanceof Error?x.name:typeof x}),I(_=>c.reduceAssistantEvent(_,{type:"error",code:"TRANSPORT_ERROR",message:x instanceof p?x.message:"连接失败,请重试",retryable:!0}))}finally{M.current===w&&T.current===O&&(T.current=void 0),E.current?.requestVersion===w&&(Q(E.current.iterator),E.current=void 0)}},ie=i=>{i.preventDefault(),H(j)},ce=i=>{i.key==="Enter"&&!i.shiftKey&&!i.nativeEvent.isComposing&&(i.preventDefault(),H(j))},oe=()=>{q("stop")&&I(i=>c.reduceAssistantEvent(i,{type:"run.cancelled"}))},le=()=>{q("new-conversation"),b(""),F(void 0),I(c.createAssistantConversationState()),n?.()};return e.jsxs("section",{className:"make-ai-assistant make-ai-assistant__panel",children:[e.jsxs("header",{className:"make-ai-assistant__header",children:[e.jsx(B,{}),e.jsxs("div",{children:[e.jsx("h2",{children:g}),e.jsxs("p",{children:[e.jsx("span",{className:"make-ai-assistant__online-dot"}),m??a.app.name??"当前应用"]})]}),e.jsxs("div",{className:"make-ai-assistant__header-actions",children:[e.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:le,children:e.jsx(Ie,{})}),o?e.jsx("button",{"aria-label":"关闭 Make AI 助手",className:"make-ai-assistant__icon-button",type:"button",onClick:o,children:e.jsx(je,{})}):null]})]}),e.jsxs("div",{className:"make-ai-assistant__privacy-note",role:"note",children:[e.jsx("span",{"aria-hidden":"true",children:"◇"}),"当前页面上下文会随请求发送,数据权限以宿主服务端校验结果为准"]}),e.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite",ref:P,onScroll:ne,children:[d.messages.length===0?e.jsxs("div",{className:"make-ai-assistant__empty",children:[e.jsx(B,{}),e.jsx("h3",{children:"有什么可以帮你?"}),e.jsx("p",{children:"我会结合当前 App 和页面上下文理解问题,并用适合的方式展示结果。"})]}):ve(d,a,U,t,s),d.error?e.jsxs("div",{className:"make-ai-assistant__error",role:"alert",children:[e.jsx("strong",{children:"暂时无法完成"}),e.jsx("span",{children:d.error.message})]}):null]}),e.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[u.length>0&&d.messages.length===0?e.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:u.map((i,A)=>e.jsx("button",{type:"button",onClick:()=>{H(i)},children:i},`${A}-${i}`))}):null,e.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:ie,children:[e.jsx("textarea",{"aria-label":"向 Make AI 助手提问","aria-describedby":$?"make-ai-composer-error":void 0,"aria-invalid":$?!0:void 0,autoFocus:!0,disabled:d.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,rows:2,value:j,onChange:i=>{b(i.currentTarget.value),F(void 0)},onKeyDown:ce}),d.status==="streaming"?e.jsx("button",{"aria-label":"停止生成",className:"make-ai-assistant__send make-ai-assistant__send--stop",type:"button",onClick:oe,children:e.jsx("span",{"aria-hidden":"true"})}):e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:!j.trim(),type:"submit",children:e.jsx(ke,{})})]}),$?e.jsx("p",{id:"make-ai-composer-error",role:"alert",children:$}):null,e.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function ye({defaultOpen:a=!1,hideLauncher:t=!1,launcher:s,onOpenChange:o,open:n,...r}){const[m,u]=h.useState(a),g=h.useRef(null),f=n??m,j=d=>{n===void 0&&u(d),o?.(d),d||requestAnimationFrame(()=>g.current?.focus())},b=()=>j(!f);return h.useEffect(()=>{if(!f)return;const d=I=>{I.key==="Escape"&&(j(!1),requestAnimationFrame(()=>g.current?.focus()))};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[o,f]),e.jsxs("div",{className:"make-ai-assistant","data-open":f||void 0,children:[!t&&(!f||s)?s?s({open:f,toggle:b}):e.jsxs("button",{"aria-label":f?"关闭 Make AI 助手":"打开 Make AI 助手","aria-expanded":f,className:"make-ai-assistant__launcher",ref:g,type:"button",onClick:b,children:[e.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),e.jsx(se,{})]}):null,f?e.jsx("aside",{"aria-label":"Make AI 助手","aria-modal":"false",className:"make-ai-assistant__drawer",role:"dialog",children:e.jsx(re,{...r,onClose:()=>j(!1)})}):null]})}exports.createArtifactCapabilities=y.createArtifactCapabilities;exports.createArtifactTemplateRegistry=y.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=y.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=y.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=c.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=c.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=c.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=c.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=c.appendUserMessage;exports.createAssistantConversationState=c.createAssistantConversationState;exports.parseArtifact=c.parseArtifact;exports.parseAssistantEvent=c.parseAssistantEvent;exports.reduceAssistantEvent=c.reduceAssistantEvent;exports.validateArtifact=c.validateArtifact;exports.ArtifactRenderer=W;exports.AssistantPanel=re;exports.MakeAiAssistant=ye;exports.createPlatformArtifactRegistry=te;exports.formatArtifactValue=v;exports.platformArtifactTemplates=ae;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),N=require("./index.cjs"),p=require("react"),c=require("./conversation-Yku9Lzj_.cjs");function ne({artifact:a,context:t,fallback:s,onAction:l,onActionError:o,registry:n}){const m=N.resolveArtifactTemplate(n,a,t);if(!m)return s?s(a):e.jsxs("section",{className:"make-ai-artifact make-ai-artifact--unsupported",role:"status",children:[e.jsx("strong",{children:"暂不支持展示此结果"}),e.jsxs("span",{children:["结果类型:",a.kind]})]});const f={context:t,onAction:l,onActionError:o};return m.template.render(a,t,f)}const y=(a,t,s)=>{if(a==null||a==="")return"—";if(typeof a=="boolean")return a?"是":"否";if(typeof a!="number")return`${a}${t?.unit??""}`;const l=t?.precision,o={maximumFractionDigits:l??2,minimumFractionDigits:l};t?.style==="currency"&&t.currency?(o.style="currency",o.currency=t.currency):t?.style==="percent"&&(o.style="percent");try{const n=t?.style==="percent"?a/100:a;return`${new Intl.NumberFormat(s,o).format(n)}${t?.unit??""}`}catch{return`${a}${t?.unit??""}`}},re=a=>{let t=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const l of a)t=Math.min(t,l),s=Math.max(s,l);return Number.isFinite(t)&&Number.isFinite(s)?{min:t,max:s}:{min:0,max:0}},ie=(a,t,s)=>{if(!s.onAction)return;const l=n=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:a.id,artifactId:t.artifact.id,errorType:n instanceof Error?n.name:typeof n,intent:a.intent})},o=n=>{if(s.onActionError){try{Promise.resolve(s.onActionError(n,a,t)).catch(l)}catch(m){l(m)}return}console.error("[make-ai-assistant] host action failed",{actionId:a.id,artifactId:t.artifact.id,errorType:n instanceof Error?n.name:typeof n,intent:a.intent})};try{Promise.resolve(s.onAction(a,t)).catch(o)}catch(n){o(n)}},O=(a,t)=>a.actions?.length&&t.onAction?e.jsx("div",{className:"make-ai-artifact__actions",children:a.actions.map(s=>e.jsxs("button",{className:`make-ai-artifact__action make-ai-artifact__action--${s.appearance??"link"}`,type:"button",onClick:()=>ie(s,{artifact:a,context:t.context},t),children:[s.label,e.jsx("span",{"aria-hidden":"true",children:"→"})]},s.id))}):null,F=(a,t,s="")=>e.jsxs("section",{"aria-label":a.title??`${a.kind} result`,className:`make-ai-artifact ${s}`.trim(),"data-artifact-density":a.presentation?.density,"data-artifact-kind":a.kind,children:[a.title?e.jsx("h4",{className:"make-ai-artifact__title",children:a.title}):null,a.summary?e.jsx("p",{className:"make-ai-artifact__summary",children:a.summary}):null,t]}),Ie=({artifact:a,renderContext:t})=>{const s=a.data.delta,l=s?y(s.value,s.format==="percent"?{style:"percent"}:void 0,t.context.locale):void 0;return F(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__metric-value",children:y(a.data.value,a.data.format,t.context.locale)}),s?e.jsxs("div",{className:`make-ai-artifact__delta make-ai-artifact__delta--${s.direction??"flat"}`,children:[e.jsx("span",{"aria-hidden":"true",children:s.direction==="up"?"↗":s.direction==="down"?"↘":"→"}),e.jsx("span",{children:l}),s.label?e.jsx("span",{children:s.label}):null]}):null,a.data.context?e.jsx("p",{className:"make-ai-artifact__context",children:a.data.context}):null,O(a,t)]}),"make-ai-artifact--metric")},je=({artifact:a,renderContext:t})=>F(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__comparison",children:a.data.items.map(s=>e.jsxs("div",{className:"make-ai-artifact__comparison-item",children:[e.jsx("span",{children:s.label}),e.jsx("strong",{children:y(s.value,s.format,t.context.locale)}),s.hint?e.jsx("small",{children:s.hint}):null]},s.id))}),O(a,t)]}),"make-ai-artifact--comparison"),ve=({artifact:a,renderContext:t})=>{const s=a.data.series.flatMap(m=>m.points.map(f=>f.y)),{max:l,min:o}=re(s),n=l-o||1;return F(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__trend",children:a.data.series.map(m=>e.jsxs("div",{className:"make-ai-artifact__trend-series",children:[e.jsx("div",{className:"make-ai-artifact__trend-label",children:m.label}),e.jsx("div",{className:"make-ai-artifact__trend-bars",children:m.points.map((f,b)=>{const u=18+(f.y-o)/n*70;return e.jsxs("div",{className:"make-ai-artifact__trend-point",children:[e.jsx("span",{"aria-label":`${f.x}: ${y(f.y,m.format,t.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${u}%`},title:`${f.x}: ${y(f.y,m.format,t.context.locale)}`}),e.jsx("small",{children:f.x})]},`${f.x}-${b}`)})})]},m.id))}),O(a,t)]}),"make-ai-artifact--trend")},ge=({artifact:a,renderContext:t})=>{const{max:s}=re(a.data.items.map(o=>Math.abs(o.value))),l=Math.max(s,1);return F(a,e.jsxs(e.Fragment,{children:[e.jsx("ol",{className:"make-ai-artifact__ranking",children:a.data.items.map((o,n)=>e.jsxs("li",{children:[e.jsx("span",{className:"make-ai-artifact__rank",children:n+1}),e.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[e.jsx("span",{children:o.label}),o.description?e.jsx("small",{children:o.description}):null]}),e.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.abs(o.value)/l*100}%`}})}),e.jsx("strong",{children:y(o.value,o.format,t.context.locale)})]},o.id))}),O(a,t)]}),"make-ai-artifact--ranking")},ke=(a,t)=>t.action??{id:`open-${t.id}`,label:t.title??t.id,intent:"open-record",target:{entityKey:a.data.entity.key,recordId:t.id}},ye=({artifact:a,renderContext:t})=>F(a,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__record-list",children:a.data.records.length===0?e.jsx("p",{className:"make-ai-artifact__empty",children:"没有符合条件的记录"}):a.data.records.map(s=>{const l=ke(a,s),o=e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:s.title??s.id}),e.jsx("span",{className:"make-ai-artifact__record-values",children:a.data.columns.map(n=>e.jsxs("span",{children:[e.jsx("small",{children:n.label}),y(s.values[n.key],n.format,t.context.locale)]},n.key))}),t.onAction?e.jsx("span",{"aria-hidden":"true",children:"›"}):null]});return t.onAction?e.jsx("button",{className:"make-ai-artifact__record",type:"button",onClick:()=>ie(l,{artifact:a,context:t.context},t),children:o},s.id):e.jsx("div",{className:"make-ai-artifact__record",children:o},s.id)})}),a.data.total!==void 0?e.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",a.data.total," 条"]}):null,O(a,t)]}),"make-ai-artifact--record-list"),Ne=({artifact:a,renderContext:t})=>F(a,e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`make-ai-artifact__notice make-ai-artifact__notice--${a.data.tone}`,children:[e.jsx("span",{"aria-hidden":"true",children:a.data.tone==="success"?"✓":a.data.tone==="warning"?"!":a.data.tone==="danger"?"×":"i"}),e.jsx("p",{children:a.data.body})]}),O(a,t)]}),"make-ai-artifact--notice"),$=(a,t,s)=>({id:a,kinds:[t],priority:0,render:s}),be=[$("platform.metric.default","metric",(a,t,s)=>e.jsx(Ie,{artifact:a,renderContext:s})),$("platform.comparison.default","comparison",(a,t,s)=>e.jsx(je,{artifact:a,renderContext:s})),$("platform.trend.default","trend",(a,t,s)=>e.jsx(ve,{artifact:a,renderContext:s})),$("platform.ranking.default","ranking",(a,t,s)=>e.jsx(ge,{artifact:a,renderContext:s})),$("platform.record-list.default","record-list",(a,t,s)=>e.jsx(ye,{artifact:a,renderContext:s})),$("platform.notice.default","notice",(a,t,s)=>e.jsx(Ne,{artifact:a,renderContext:s}))],oe=N.createArtifactTemplateRegistry(be).templates,ce=(a=oe)=>N.createArtifactTemplateRegistry(a),Te=a=>`${a}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`;class h extends Error{}const se=a=>{try{const t=a?.return?.();if(!t)return;Promise.resolve(t).catch(s=>{console.error("[make-ai-assistant] transport iterator close failed",{errorType:s instanceof Error?s.name:typeof s})})}catch(t){console.error("[make-ai-assistant] transport iterator close failed",{errorType:t instanceof Error?t.name:typeof t})}},le=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 2.8c.5 4.4 2.8 6.8 7.2 7.2-4.4.5-6.8 2.8-7.2 7.2-.5-4.4-2.8-6.8-7.2-7.2 4.4-.5 6.8-2.8 7.2-7.2Z"}),e.jsx("path",{d:"M18.3 16.1c.2 1.8 1.2 2.8 3 3-1.8.2-2.8 1.2-3 3-.2-1.8-1.2-2.8-3-3 1.8-.2 2.8-1.2 3-3Z"})]}),Ee=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),Me=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),we=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"m4 4 17 8-17 8 3-8-3-8Z"}),e.jsx("path",{d:"M7 12h14"})]}),D=()=>e.jsx("span",{className:"make-ai-assistant__avatar","aria-hidden":"true",children:e.jsx(le,{})}),Se=(a,t,s,l,o)=>a.messages.map(n=>e.jsxs("article",{className:`make-ai-assistant__message make-ai-assistant__message--${n.role}`,children:[n.role==="assistant"?e.jsx(D,{}):null,e.jsxs("div",{className:"make-ai-assistant__message-stack",children:[n.content?e.jsx("div",{className:"make-ai-assistant__bubble",children:n.content}):n.status==="streaming"?e.jsxs("div",{className:"make-ai-assistant__typing","aria-label":"AI 正在思考",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):null,n.artifacts.map(m=>e.jsx(ne,{artifact:m,context:t,onAction:l,onActionError:o,registry:s},m.id))]})]},n.id));function de({context:a,onAction:t,onActionError:s,onClose:l,onNewConversation:o,registry:n,subtitle:m,suggestions:f=[],title:b="Make AI 助手",transport:u}){const[g,T]=p.useState(""),[d,j]=p.useState(c.createAssistantConversationState),[q,K]=p.useState(void 0),[me,ue]=p.useState(0),[E,H]=p.useState(()=>u.loadConversation?"loading":"ready"),M=p.useRef(void 0),w=p.useRef(void 0),S=p.useRef(0),Z=p.useRef(null),z=p.useRef(!0),G=p.useRef(a.app.id),J=p.useMemo(()=>n??ce(),[n]),U=i=>{const x=M.current,A=w.current?.iterator;return!x&&!A?!1:(S.current+=1,M.current=void 0,w.current=void 0,console.info("[make-ai-assistant] local run cancellation requested",{reason:i}),x?.abort(),se(A),!0)};p.useEffect(()=>()=>{U("unmount")},[]),p.useEffect(()=>{const i=u.loadConversation,x=G.current!==a.app.id;if(G.current=a.app.id,U("reinitialize"),x&&(T(""),z.current=!0),K(void 0),j(c.createAssistantConversationState()),!i){H("ready");return}const A=new AbortController;return H("loading"),console.info("[make-ai-assistant] conversation load start",{appId:a.app.id}),i.call(u,a,{signal:A.signal}).then(I=>{A.signal.aborted||(j(c.createAssistantConversationState(I)),H("ready"),console.info("[make-ai-assistant] conversation load success",{appId:a.app.id,messageCount:I.messages.length}))}).catch(I=>{A.signal.aborted||(console.error("[make-ai-assistant] conversation load failed",{appId:a.app.id,errorType:I instanceof Error?I.name:typeof I}),H("error"))}),()=>A.abort()},[a.app.id,me,u]),p.useEffect(()=>{const i=Z.current;if(!i||!z.current)return;const x=requestAnimationFrame(()=>{if(!z.current)return;const A=d.status==="streaming"||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";typeof i.scrollTo=="function"?i.scrollTo({top:i.scrollHeight,behavior:A}):i.scrollTop=i.scrollHeight});return()=>cancelAnimationFrame(x)},[d.messages,d.status]);const pe=()=>{const i=Z.current;i&&(z.current=i.scrollHeight-i.scrollTop-i.clientHeight<=48)},Y=async i=>{const x=i.trim();if(!x||E!=="ready"||d.status==="streaming"||M.current)return;if(c.countCodePointsUpTo(x,c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){K(`输入内容过长,请控制在 ${c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const A={id:Te("user"),content:x},I=new AbortController,C=S.current+1;S.current=C,M.current=I,K(void 0),T(""),j(v=>c.appendUserMessage(v,A));try{let v=!1,_,Q=0,W=0,V=0;const L=new Map,X=new Set,ee=new Set([...d.messages.map(B=>B.id),A.id]),P=new Set,ae=u.run({threadId:d.threadId,message:A,context:a,capabilities:N.createArtifactCapabilities(J)},{signal:I.signal})[Symbol.asyncIterator]();for(w.current={iterator:ae,requestVersion:C};;){const B=await ae.next();if(S.current!==C||B.done)break;let r;try{r=c.parseAssistantEvent(B.value)}catch(k){throw new h(k instanceof Error?k.message:"Invalid assistant event")}if(r.type==="message.start"){if(_!==void 0&&_!==r.runId)throw new h("AI 助手响应 run id 不一致");if(_??=r.runId,W+=1,W>c.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new h("AI 助手单次响应消息数量超过限制");if(ee.has(r.messageId))throw new h("AI 助手响应包含重复的 message id");ee.add(r.messageId),P.add(r.messageId),L.set(r.messageId,0)}if(r.type==="message.delta"){if(!P.has(r.messageId))throw new h("AI 助手响应事件顺序无效");const k=L.get(r.messageId)??0,R=c.countCodePointsUpTo(r.delta,c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-V);if(V+R>c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new h("AI 助手响应文本超过大小限制");V+=R,L.set(r.messageId,k+R)}if(r.type==="message.replace"){if(!P.has(r.messageId))throw new h("AI 助手响应事件顺序无效");const k=L.get(r.messageId)??0,R=c.countCodePointsUpTo(r.content,c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters),te=V-k+R;if(te>c.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new h("AI 助手响应文本超过大小限制");V=te,L.set(r.messageId,R)}if(r.type==="run.progress"){if(_!==void 0&&_!==r.runId)throw new h("AI 助手响应 run id 不一致");_??=r.runId}if(r.type==="artifact"){if(!P.has(r.messageId))throw new h("AI 助手响应事件顺序无效");if(Q+=1,Q>c.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new h("AI 助手单次响应 Artifact 数量超过限制");if(X.has(r.artifact.id))throw new h("AI 助手响应包含重复的 Artifact id");X.add(r.artifact.id)}if(r.type==="message.complete"&&!P.delete(r.messageId))throw new h("AI 助手响应事件顺序无效");if(r.type==="run.complete"&&_!==void 0&&_!==r.runId)throw new h("AI 助手响应 run id 不一致");if(r.type==="run.cancelled"&&r.runId!==void 0&&_!==void 0&&_!==r.runId)throw new h("AI 助手响应 run id 不一致");if(j(k=>c.reduceAssistantEvent(k,r)),r.type==="error"||r.type==="run.cancelled"||r.type==="run.complete"){v=!0;break}}if(!v)throw new h("AI 助手流式响应在终止事件前结束")}catch(v){if(S.current!==C)return;if(I.signal.aborted){j(_=>c.reduceAssistantEvent(_,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:v instanceof Error?v.name:typeof v}),j(_=>c.reduceAssistantEvent(_,{type:"error",code:"TRANSPORT_ERROR",message:v instanceof h?v.message:"连接失败,请重试",retryable:!0}))}finally{S.current===C&&M.current===I&&(M.current=void 0),w.current?.requestVersion===C&&(se(w.current.iterator),w.current=void 0)}},he=i=>{i.preventDefault(),Y(g)},fe=i=>{i.key==="Enter"&&!i.shiftKey&&!i.nativeEvent.isComposing&&(i.preventDefault(),Y(g))},_e=()=>{U("stop")&&j(i=>c.reduceAssistantEvent(i,{type:"run.cancelled"}))},Ae=()=>{U("new-conversation"),T(""),K(void 0),j(c.createAssistantConversationState()),o?.()},xe=u.features?.remoteCancellation===!1?"停止接收":"停止生成";return e.jsxs("section",{className:"make-ai-assistant make-ai-assistant__panel",children:[e.jsxs("header",{className:"make-ai-assistant__header",children:[e.jsx(D,{}),e.jsxs("div",{children:[e.jsx("h2",{children:b}),e.jsxs("p",{children:[e.jsx("span",{className:"make-ai-assistant__online-dot"}),m??a.app.name??"当前应用"]})]}),e.jsxs("div",{className:"make-ai-assistant__header-actions",children:[u.features?.newConversation!==!1?e.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:Ae,children:e.jsx(Me,{})}):null,l?e.jsx("button",{"aria-label":"关闭 Make AI 助手",className:"make-ai-assistant__icon-button",type:"button",onClick:l,children:e.jsx(Ee,{})}):null]})]}),e.jsxs("div",{className:"make-ai-assistant__privacy-note",role:"note",children:[e.jsx("span",{"aria-hidden":"true",children:"◇"}),"当前页面上下文会随请求发送,数据权限以宿主服务端校验结果为准"]}),e.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite",ref:Z,onScroll:pe,children:[E==="loading"?e.jsxs("div",{className:"make-ai-assistant__empty",role:"status",children:[e.jsx(D,{}),e.jsx("h3",{children:"正在恢复对话"}),e.jsx("p",{children:"正在读取当前 App 的历史消息…"})]}):E==="error"?e.jsxs("div",{className:"make-ai-assistant__empty",role:"alert",children:[e.jsx(D,{}),e.jsx("h3",{children:"暂时无法加载对话"}),e.jsx("p",{children:"请检查网络后重试。"}),e.jsx("button",{className:"make-ai-assistant__retry",type:"button",onClick:()=>ue(i=>i+1),children:"重新加载"})]}):d.messages.length===0?e.jsxs("div",{className:"make-ai-assistant__empty",children:[e.jsx(D,{}),e.jsx("h3",{children:"有什么可以帮你?"}),e.jsx("p",{children:"我会结合当前 App 和页面上下文理解问题,并用适合的方式展示结果。"})]}):Se(d,a,J,t,s),d.progress?e.jsxs("div",{className:"make-ai-assistant__progress",role:"status",children:[e.jsx("span",{"aria-hidden":"true"}),d.progress.message]}):null,d.error?e.jsxs("div",{className:"make-ai-assistant__error",role:"alert",children:[e.jsx("strong",{children:"暂时无法完成"}),e.jsx("span",{children:d.error.message})]}):null]}),e.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[E==="ready"&&f.length>0&&d.messages.length===0?e.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:f.map((i,x)=>e.jsx("button",{type:"button",onClick:()=>{Y(i)},children:i},`${x}-${i}`))}):null,e.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:he,children:[e.jsx("textarea",{"aria-label":"向 Make AI 助手提问","aria-describedby":q?"make-ai-composer-error":void 0,"aria-invalid":q?!0:void 0,autoFocus:!0,disabled:E!=="ready"||d.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,rows:2,value:g,onChange:i=>{T(i.currentTarget.value),K(void 0)},onKeyDown:fe}),d.status==="streaming"?e.jsx("button",{"aria-label":xe,className:"make-ai-assistant__send make-ai-assistant__send--stop",type:"button",onClick:_e,children:e.jsx("span",{"aria-hidden":"true"})}):e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:E!=="ready"||!g.trim(),type:"submit",children:e.jsx(we,{})})]}),q?e.jsx("p",{id:"make-ai-composer-error",role:"alert",children:q}):null,e.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function Ce({defaultOpen:a=!1,hideLauncher:t=!1,launcher:s,onOpenChange:l,open:o,...n}){const[m,f]=p.useState(a),b=p.useRef(null),u=o??m,g=d=>{o===void 0&&f(d),l?.(d),d||requestAnimationFrame(()=>b.current?.focus())},T=()=>g(!u);return p.useEffect(()=>{if(!u)return;const d=j=>{j.key==="Escape"&&(g(!1),requestAnimationFrame(()=>b.current?.focus()))};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[l,u]),e.jsxs("div",{className:"make-ai-assistant","data-open":u||void 0,children:[!t&&(!u||s)?s?s({open:u,toggle:T}):e.jsxs("button",{"aria-label":u?"关闭 Make AI 助手":"打开 Make AI 助手","aria-expanded":u,className:"make-ai-assistant__launcher",ref:b,type:"button",onClick:T,children:[e.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),e.jsx(le,{})]}):null,u?e.jsx("aside",{"aria-label":"Make AI 助手","aria-modal":"false",className:"make-ai-assistant__drawer",role:"dialog",children:e.jsx(de,{...n,onClose:()=>g(!1)})}):null]})}exports.createArtifactCapabilities=N.createArtifactCapabilities;exports.createArtifactTemplateRegistry=N.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=N.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=N.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=c.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=c.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=c.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=c.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=c.appendUserMessage;exports.createAssistantConversationState=c.createAssistantConversationState;exports.parseArtifact=c.parseArtifact;exports.parseAssistantEvent=c.parseAssistantEvent;exports.reduceAssistantEvent=c.reduceAssistantEvent;exports.validateArtifact=c.validateArtifact;exports.ArtifactRenderer=ne;exports.AssistantPanel=de;exports.MakeAiAssistant=Ce;exports.createPlatformArtifactRegistry=ce;exports.formatArtifactValue=y;exports.platformArtifactTemplates=oe;
|