@siact/sime-x-vue 0.0.10 → 0.0.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.
@@ -1,1003 +1,809 @@
1
- import { inject, defineComponent, shallowRef, provide, renderSlot, computed, openBlock, createBlock, Transition, withCtx, createElementBlock, normalizeClass, createElementVNode, toDisplayString, createVNode, createCommentVNode, ref, onBeforeUnmount, reactive, watch, normalizeStyle, withModifiers, nextTick, unref, Fragment, renderList } from 'vue';
2
- import { HostBridge } from '@siact/sime-bridge';
3
- import { WakeWordDetectorStandalone, SpeechSynthesizerStandalone, SpeechTranscriberStandalone } from 'web-voice-kit';
1
+ import { defineComponent, ref, reactive, computed, watch, onMounted, openBlock, createElementBlock, normalizeClass, createElementVNode, toDisplayString, withModifiers, withDirectives, vModelText, Fragment, renderList, createCommentVNode, unref, createVNode, Transition, withCtx, nextTick, inject, shallowRef, provide, renderSlot, onBeforeUnmount, normalizeStyle } from 'vue';
2
+ import { Chat } from '@ai-sdk/vue';
3
+ import { DefaultChatTransport } from 'ai';
4
+ import { SpeechSynthesizerStandalone, WakeWordDetectorStandalone, SpeechTranscriberStandalone } from 'web-voice-kit';
4
5
 
5
- const AiChatbotXKey = Symbol("sime-x");
6
- function injectStrict(key, defaultValue, treatDefaultAsFactory) {
7
- let result;
8
- if (defaultValue === void 0) {
9
- result = inject(key);
10
- } else if (treatDefaultAsFactory === true) {
11
- result = inject(key, defaultValue, true);
12
- } else {
13
- result = inject(key, defaultValue, false);
14
- }
15
- if (!result) {
16
- throw new Error(`Could not resolve ${key.description}`);
17
- }
18
- return result;
6
+ function createAgentChatTransport(options) {
7
+ const { api, projectId, getCommands, headers: extraHeaders, body: extraBody } = options;
8
+ return new DefaultChatTransport({
9
+ api,
10
+ headers: extraHeaders,
11
+ prepareSendMessagesRequest({ messages }) {
12
+ const lastUserMessage = findLastUserMessage(messages);
13
+ const input = lastUserMessage ? lastUserMessage.parts.filter((p) => p.type === "text").map((p) => p.text).join("") : "";
14
+ const historyMessages = buildHistoryMessages(messages, lastUserMessage?.id);
15
+ const resolvedExtraBody = typeof extraBody === "function" ? extraBody() : extraBody || {};
16
+ return {
17
+ body: {
18
+ input,
19
+ projectId: projectId || "",
20
+ messages: historyMessages.length > 0 ? historyMessages : void 0,
21
+ ...resolvedExtraBody
22
+ }
23
+ };
24
+ }
25
+ });
19
26
  }
20
-
21
- var clientCommandKey = /* @__PURE__ */ ((clientCommandKey2) => {
22
- clientCommandKey2["SET_THEME"] = "SiMeAgent_setTheme";
23
- clientCommandKey2["APPEND_MESSAGE"] = "SiMeAgent_appendMessage";
24
- clientCommandKey2["WAKE"] = "SiMeAgent_wake";
25
- clientCommandKey2["TRANSITION"] = "SiMeAgent_transition";
26
- clientCommandKey2["TRANSITION_END"] = "SiMeAgent_transition_end";
27
- clientCommandKey2["START_NEW_CONVERSATION"] = "SiMeAgent_startNewConversation";
28
- clientCommandKey2["RECOGNITION"] = "SiMeAgent_recognition";
29
- return clientCommandKey2;
30
- })(clientCommandKey || {});
31
-
32
- const _sfc_main$4 = /* @__PURE__ */ defineComponent({
33
- __name: "sime-provider",
34
- props: {
35
- project: {},
36
- description: {},
37
- debug: { type: Boolean },
38
- chatbotUrl: {},
39
- appId: {},
40
- appToken: {},
41
- voiceConfig: {}
42
- },
43
- setup(__props) {
44
- const props = __props;
45
- const hostBridge = shallowRef(new HostBridge({ debug: false }));
46
- const startListeningRef = shallowRef(async () => {
47
- });
48
- const stopListeningRef = shallowRef(async () => {
49
- });
50
- const stopBroadcastRef = shallowRef(async () => {
51
- });
52
- const toggleCollapseRef = shallowRef(async () => {
53
- });
54
- const openDialogRef = shallowRef(async () => {
55
- });
56
- const closeDialogRef = shallowRef(async () => {
57
- });
58
- provide(AiChatbotXKey, {
59
- chatbotUrl: () => props.chatbotUrl,
60
- appId: () => props.appId,
61
- appToken: () => props.appToken,
62
- voiceConfig: () => props.voiceConfig || { appId: "", apiKey: "", websocketUrl: "" },
63
- startListening: () => startListeningRef.value(),
64
- stopListening: () => stopListeningRef.value(),
65
- stopBroadcast: () => stopBroadcastRef.value(),
66
- toggleCollapse: () => toggleCollapseRef.value(),
67
- openDialog: () => openDialogRef.value(),
68
- closeDialog: () => closeDialogRef.value(),
69
- registerVoiceMethods: (methods) => {
70
- startListeningRef.value = methods.start;
71
- stopListeningRef.value = methods.stop;
72
- if (methods.stopBroadcast) stopBroadcastRef.value = methods.stopBroadcast;
73
- toggleCollapseRef.value = methods.toggleCollapse;
74
- openDialogRef.value = methods.openDialog;
75
- closeDialogRef.value = methods.closeDialog;
76
- },
77
- clientCommand: () => hostBridge.value.clientCommands(),
78
- hostCommads: () => hostBridge.value.hostCommands(),
79
- registerCommand: (cmd) => {
80
- hostBridge.value.registerCommand(cmd);
81
- },
82
- unregisterCommand: (name) => {
83
- hostBridge.value.unregisterCommand(name);
84
- },
85
- async appendMessage(message) {
86
- await hostBridge.value.executeClientCommand(clientCommandKey.APPEND_MESSAGE, [message]);
87
- },
88
- async setTheme(theme) {
89
- await hostBridge.value.executeClientCommand(clientCommandKey.SET_THEME, [theme]);
90
- },
91
- async weak() {
92
- await hostBridge.value.executeClientCommand(clientCommandKey.WAKE);
93
- },
94
- async startNewConversation() {
95
- await hostBridge.value.executeClientCommand(clientCommandKey.START_NEW_CONVERSATION);
96
- },
97
- setIframeElement(iframe) {
98
- hostBridge.value.setIframe(iframe);
99
- },
100
- async recognition(message, commands) {
101
- return await hostBridge.value.executeClientCommand(clientCommandKey.RECOGNITION, [message, commands]);
102
- },
103
- async executeCommand(commandName, args = []) {
104
- return await hostBridge.value.executeCommand(commandName, args);
27
+ class AgentChatTransport extends DefaultChatTransport {
28
+ agentOptions;
29
+ constructor(options) {
30
+ const { api, headers: extraHeaders, body: extraBody, projectId } = options;
31
+ super({
32
+ api,
33
+ headers: extraHeaders,
34
+ prepareSendMessagesRequest({ messages }) {
35
+ const lastUserMessage = findLastUserMessage(messages);
36
+ const input = lastUserMessage ? lastUserMessage.parts.filter((p) => p.type === "text").map((p) => p.text).join("") : "";
37
+ const historyMessages = buildHistoryMessages(messages, lastUserMessage?.id);
38
+ const resolvedExtraBody = typeof extraBody === "function" ? extraBody() : extraBody || {};
39
+ return {
40
+ body: {
41
+ input,
42
+ projectId: projectId || "",
43
+ messages: historyMessages.length > 0 ? historyMessages : void 0,
44
+ ...resolvedExtraBody
45
+ }
46
+ };
105
47
  }
106
48
  });
107
- return (_ctx, _cache) => {
108
- return renderSlot(_ctx.$slots, "default");
109
- };
49
+ this.agentOptions = options;
110
50
  }
111
- });
112
-
113
- const _hoisted_1$3 = { class: "content-container" };
114
- const _hoisted_2$3 = { class: "status-header" };
115
- const _hoisted_3$2 = { class: "status-text" };
116
- const _hoisted_4$2 = {
117
- key: 0,
118
- class: "transcription-content"
119
- };
120
- const _hoisted_5$2 = {
121
- key: 1,
122
- class: "placeholder-text"
123
- };
124
- const _sfc_main$3 = /* @__PURE__ */ defineComponent({
125
- __name: "voice-status",
126
- props: {
127
- status: {},
128
- transcriptionText: {},
129
- isTranscribing: { type: Boolean }
130
- },
131
- setup(__props) {
132
- const props = __props;
133
- const currentMode = computed(() => {
134
- if (props.isTranscribing) return "mode-transcribing";
135
- if (props.status === "wake") return "mode-wake";
136
- return "mode-standby";
137
- });
138
- const statusLabel = computed(() => {
139
- if (props.isTranscribing) return "正在聆听您的问题...";
140
- if (props.status === "wake") return "您好,有什么可以帮助您的吗?";
141
- return "Standby";
142
- });
143
- return (_ctx, _cache) => {
144
- return openBlock(), createBlock(Transition, { name: "voice-panel" }, {
145
- default: withCtx(() => [
146
- __props.status === "wake" || __props.isTranscribing ? (openBlock(), createElementBlock("div", {
147
- key: 0,
148
- class: normalizeClass(["voice-status-wrapper", currentMode.value])
149
- }, [
150
- _cache[0] || (_cache[0] = createElementVNode("div", { class: "indicator-container" }, [
151
- createElementVNode("div", { class: "ambient-glow" }),
152
- createElementVNode("div", { class: "ripple-layer" }, [
153
- createElementVNode("div", { class: "ripple delay-1" }),
154
- createElementVNode("div", { class: "ripple delay-2" }),
155
- createElementVNode("div", { class: "ripple delay-3" })
156
- ]),
157
- createElementVNode("div", { class: "icon-core" }, [
158
- createElementVNode("svg", {
159
- class: "mic-icon",
160
- viewBox: "0 0 24 24",
161
- fill: "none",
162
- stroke: "currentColor",
163
- "stroke-width": "2",
164
- "stroke-linecap": "round",
165
- "stroke-linejoin": "round"
166
- }, [
167
- createElementVNode("rect", {
168
- x: "9",
169
- y: "2",
170
- width: "6",
171
- height: "12",
172
- rx: "3",
173
- class: "mic-capsule"
174
- }),
175
- createElementVNode("path", {
176
- d: "M5 10C5 13.866 8.13401 17 12 17C15.866 17 19 13.866 19 10",
177
- class: "mic-stand"
178
- }),
179
- createElementVNode("path", {
180
- d: "M12 17V21M8 21H16",
181
- class: "mic-base"
182
- })
183
- ])
184
- ])
185
- ], -1)),
186
- createElementVNode("div", _hoisted_1$3, [
187
- createElementVNode("div", _hoisted_2$3, [
188
- createElementVNode("span", _hoisted_3$2, toDisplayString(statusLabel.value), 1)
189
- ]),
190
- createElementVNode("div", {
191
- class: normalizeClass(["text-window", { "has-text": !!__props.transcriptionText }])
192
- }, [
193
- createVNode(Transition, {
194
- name: "fade-slide",
195
- mode: "out-in"
196
- }, {
197
- default: withCtx(() => [
198
- __props.transcriptionText ? (openBlock(), createElementBlock("p", _hoisted_4$2, toDisplayString(__props.transcriptionText), 1)) : __props.status === "wake" ? (openBlock(), createElementBlock("p", _hoisted_5$2, "Listening...")) : createCommentVNode("", true)
199
- ]),
200
- _: 1
201
- })
202
- ], 2)
203
- ])
204
- ], 2)) : createCommentVNode("", true)
205
- ]),
206
- _: 1
207
- });
208
- };
209
- }
210
- });
211
-
212
- const _export_sfc = (sfc, props) => {
213
- const target = sfc.__vccOpts || sfc;
214
- for (const [key, val] of props) {
215
- target[key] = val;
216
- }
217
- return target;
218
- };
219
-
220
- const VoiceStatus = /* @__PURE__ */ _export_sfc(_sfc_main$3, [["__scopeId", "data-v-c9fa6caf"]]);
221
-
222
- const _hoisted_1$2 = {
223
- key: 0,
224
- class: "execution-bubble"
225
- };
226
- const _hoisted_2$2 = { class: "exec-text" };
227
- const _sfc_main$2 = /* @__PURE__ */ defineComponent({
228
- __name: "execution-status",
229
- props: {
230
- visible: { type: Boolean },
231
- text: {}
232
- },
233
- setup(__props) {
234
- return (_ctx, _cache) => {
235
- return openBlock(), createBlock(Transition, { name: "exec-bubble" }, {
236
- default: withCtx(() => [
237
- __props.visible ? (openBlock(), createElementBlock("div", _hoisted_1$2, [
238
- createElementVNode("span", _hoisted_2$2, toDisplayString(__props.text || "执行中"), 1),
239
- _cache[0] || (_cache[0] = createElementVNode("div", { class: "loading-dots" }, [
240
- createElementVNode("span", { class: "dot" }),
241
- createElementVNode("span", { class: "dot" }),
242
- createElementVNode("span", { class: "dot" })
243
- ], -1))
244
- ])) : createCommentVNode("", true)
245
- ]),
246
- _: 1
247
- });
248
- };
249
- }
250
- });
251
-
252
- const ExecutionStatus = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["__scopeId", "data-v-8244ff0d"]]);
253
-
254
- const ensureMicrophonePermission = async () => {
255
- if (typeof navigator === "undefined" || typeof window === "undefined") {
256
- console.log("当前环境不支持麦克风访问");
257
- return false;
258
- }
259
- if (!navigator.mediaDevices?.getUserMedia || !navigator.mediaDevices?.enumerateDevices) {
260
- console.log("当前环境不支持麦克风访问");
261
- return false;
262
- }
263
- try {
264
- const devices = await navigator.mediaDevices.enumerateDevices();
265
- const audioInputDevices = devices.filter((device) => device.kind === "audioinput");
266
- if (audioInputDevices.length === 0) {
267
- console.log("未检测到麦克风设备,请连接麦克风后重试。");
268
- return false;
269
- }
270
- if ("permissions" in navigator && navigator.permissions?.query) {
51
+ async sendMessages(options) {
52
+ if (this.agentOptions.getCommands) {
271
53
  try {
272
- const status = await navigator.permissions.query({ name: "microphone" });
273
- if (status.state === "denied") {
274
- console.log("麦克风权限被禁用,请在浏览器设置中开启。");
275
- return false;
54
+ const commands = await this.agentOptions.getCommands();
55
+ if (commands && commands.length > 0) {
56
+ options.body = {
57
+ ...options.body || {},
58
+ commands
59
+ };
276
60
  }
277
- } catch (e) {
278
- console.warn("Permission query not supported:", e);
61
+ } catch {
279
62
  }
280
63
  }
281
- let stream = null;
282
- try {
283
- stream = await navigator.mediaDevices.getUserMedia({
284
- audio: {
285
- echoCancellation: true,
286
- noiseSuppression: true,
287
- autoGainControl: true
288
- }
289
- });
290
- const audioTracks = stream.getAudioTracks();
291
- if (audioTracks.length === 0) {
292
- console.log("无法获取麦克风音频轨道。");
293
- return false;
294
- }
295
- const activeTrack = audioTracks[0];
296
- if (!activeTrack.enabled || activeTrack.readyState !== "live") {
297
- console.log("麦克风设备不可用,请检查设备连接。");
298
- return false;
299
- }
300
- return true;
301
- } finally {
302
- if (stream) {
303
- stream.getTracks().forEach((track) => track.stop());
304
- }
64
+ return super.sendMessages(options);
65
+ }
66
+ }
67
+ function findLastUserMessage(messages) {
68
+ for (let i = messages.length - 1; i >= 0; i--) {
69
+ if (messages[i].role === "user") {
70
+ return messages[i];
305
71
  }
306
- } catch (error) {
307
- console.error("Microphone permission check failed", error);
308
- if (error.name === "NotFoundError" || error.name === "DevicesNotFoundError") {
309
- console.log("未检测到麦克风设备,请连接麦克风后重试。");
310
- } else if (error.name === "NotAllowedError" || error.name === "PermissionDeniedError") {
311
- console.log("麦克风权限被拒绝,请在浏览器设置中允许访问。");
312
- } else if (error.name === "NotReadableError" || error.name === "TrackStartError") {
313
- console.log("麦克风被其他应用占用或无法访问。");
314
- } else {
315
- console.log("无法访问麦克风,请检查设备连接和浏览器权限。");
72
+ }
73
+ return void 0;
74
+ }
75
+ function buildHistoryMessages(messages, excludeId) {
76
+ const history = [];
77
+ for (const msg of messages) {
78
+ if (msg.id === excludeId) continue;
79
+ if (msg.role !== "user" && msg.role !== "assistant") continue;
80
+ const textContent = msg.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
81
+ if (textContent.trim()) {
82
+ history.push({
83
+ role: msg.role,
84
+ content: textContent
85
+ });
316
86
  }
317
- return false;
318
87
  }
319
- };
88
+ return history;
89
+ }
320
90
 
321
- const _hoisted_1$1 = ["data-theme"];
322
- const _hoisted_2$1 = { class: "fab-avatar-wrapper" };
323
- const _hoisted_3$1 = ["src"];
324
- const _hoisted_4$1 = { class: "header-left" };
325
- const _hoisted_5$1 = { class: "logo-icon" };
326
- const _hoisted_6$1 = ["src"];
327
- const _hoisted_7$1 = { class: "title" };
328
- const _hoisted_8$1 = { class: "actions" };
329
- const _hoisted_9$1 = ["title"];
330
- const _hoisted_10$1 = {
91
+ const _hoisted_1$1 = {
92
+ key: 0,
93
+ class: "ai-chat__welcome"
94
+ };
95
+ const _hoisted_2$1 = { class: "ai-chat__welcome-header" };
96
+ const _hoisted_3$1 = { class: "ai-chat__welcome-title" };
97
+ const _hoisted_4$1 = { class: "ai-chat__welcome-desc" };
98
+ const _hoisted_5$1 = { class: "ai-chat__input-area" };
99
+ const _hoisted_6$1 = { class: "ai-chat__input-wrapper" };
100
+ const _hoisted_7$1 = ["disabled"];
101
+ const _hoisted_8$1 = {
331
102
  key: 0,
332
- class: "voice-indicator"
103
+ class: "ai-chat__suggestions"
333
104
  };
334
- const _hoisted_11$1 = ["title"];
335
- const _hoisted_12$1 = ["title"];
105
+ const _hoisted_9$1 = ["onClick"];
106
+ const _hoisted_10$1 = { class: "ai-chat__messages-inner" };
107
+ const _hoisted_11$1 = { class: "ai-chat__message-content" };
108
+ const _hoisted_12$1 = ["innerHTML"];
336
109
  const _hoisted_13$1 = {
337
- width: "16",
338
- height: "16",
110
+ key: 1,
111
+ class: "ai-chat__reasoning"
112
+ };
113
+ const _hoisted_14 = ["onClick"];
114
+ const _hoisted_15 = {
115
+ key: 0,
116
+ class: "ai-chat__reasoning-streaming"
117
+ };
118
+ const _hoisted_16 = {
119
+ key: 0,
120
+ class: "ai-chat__reasoning-content"
121
+ };
122
+ const _hoisted_17 = {
123
+ key: 2,
124
+ class: "ai-chat__tool"
125
+ };
126
+ const _hoisted_18 = { class: "ai-chat__tool-icon" };
127
+ const _hoisted_19 = {
128
+ key: 0,
129
+ class: "ai-chat__tool-spinner",
130
+ width: "14",
131
+ height: "14",
339
132
  viewBox: "0 0 24 24",
340
133
  fill: "none"
341
134
  };
342
- const _hoisted_14 = ["d"];
343
- const _hoisted_15 = ["src"];
344
- const FAB_SAFE_GAP = 24;
345
- const _sfc_main$1 = /* @__PURE__ */ defineComponent({
346
- __name: "sime-x",
135
+ const _hoisted_20 = {
136
+ key: 1,
137
+ width: "14",
138
+ height: "14",
139
+ viewBox: "0 0 24 24",
140
+ fill: "none"
141
+ };
142
+ const _hoisted_21 = {
143
+ key: 2,
144
+ width: "14",
145
+ height: "14",
146
+ viewBox: "0 0 24 24",
147
+ fill: "none"
148
+ };
149
+ const _hoisted_22 = { class: "ai-chat__tool-name" };
150
+ const _hoisted_23 = {
151
+ key: 0,
152
+ class: "ai-chat__message-actions"
153
+ };
154
+ const _hoisted_24 = ["onClick"];
155
+ const _hoisted_25 = ["onClick"];
156
+ const _hoisted_26 = {
157
+ key: 0,
158
+ width: "12",
159
+ height: "12",
160
+ viewBox: "0 0 24 24",
161
+ fill: "none",
162
+ stroke: "currentColor",
163
+ "stroke-width": "2",
164
+ "stroke-linecap": "round",
165
+ "stroke-linejoin": "round"
166
+ };
167
+ const _hoisted_27 = {
168
+ key: 1,
169
+ width: "12",
170
+ height: "12",
171
+ viewBox: "0 0 24 24",
172
+ fill: "none",
173
+ stroke: "currentColor",
174
+ "stroke-width": "2",
175
+ "stroke-linecap": "round",
176
+ "stroke-linejoin": "round"
177
+ };
178
+ const _hoisted_28 = {
179
+ key: 0,
180
+ class: "ai-chat__thinking"
181
+ };
182
+ const _hoisted_29 = {
183
+ key: 0,
184
+ class: "ai-chat__input-area ai-chat__input-area--bottom"
185
+ };
186
+ const _hoisted_30 = { class: "ai-chat__input-wrapper" };
187
+ const _hoisted_31 = ["disabled"];
188
+ const _sfc_main$2 = /* @__PURE__ */ defineComponent({
189
+ __name: "ai-chat",
347
190
  props: {
348
- xLogo: {},
349
- xSize: {},
350
- xTitle: {},
351
- xTheme: {},
352
- xDialogSize: {},
353
- wakeWords: {},
354
- modelPath: {}
191
+ api: {},
192
+ projectId: {},
193
+ isReadonly: { type: Boolean, default: false },
194
+ welcomeTitle: { default: "你好,有什么可以帮助你的吗?" },
195
+ welcomeDescription: { default: "我可以帮你回答问题、分析数据、生成报告等。" },
196
+ suggestions: { default: () => [] },
197
+ fullWidth: { type: Boolean, default: false },
198
+ toolNames: { default: () => ({}) },
199
+ transportOptions: {},
200
+ headers: {},
201
+ body: {}
355
202
  },
356
- emits: ["start-transcribing", "stop-transcribing", "wakeUp"],
357
- setup(__props, { emit: __emit }) {
203
+ emits: ["error", "finish"],
204
+ setup(__props, { expose: __expose, emit: __emit }) {
205
+ const toolDisplayNames = {
206
+ generateReport: "生成报告",
207
+ searchKnowledge: "知识库检索",
208
+ resolveInstanceTargets: "解析实例目标",
209
+ getHistoryMetrics: "历史数据查询",
210
+ getRealtimeMetrics: "实时数据查询",
211
+ queryBitableData: "多维表格查询",
212
+ searchUser: "搜索用户",
213
+ createBitableRecord: "创建表格记录",
214
+ timeTool: "时间工具",
215
+ loadSkill: "加载技能",
216
+ executeCommand: "执行命令",
217
+ dataAnalyzer: "数据分析",
218
+ dataPredictor: "数据预测"
219
+ };
358
220
  const props = __props;
359
221
  const emit = __emit;
360
- const aiChatbotX = injectStrict(AiChatbotXKey);
361
- const chatbotUrl = ref("");
362
- const voiceStatus = ref("standby");
363
- const wakeAnimating = ref(false);
364
- const wakeResponses = ["在呢", "在的", "我在", "您好", "在呢,请说"];
365
- const transcriptionText = ref("");
366
- const isTranscribing = ref(false);
367
- const isProcessing = ref(false);
368
- const visible = ref(false);
369
- const isCollapsed = ref(false);
370
- const fabRef = ref(null);
371
- const positionReady = ref(false);
372
- let detector = null;
373
- const isInitializing = ref(false);
374
- const initError = ref("");
375
- const getSystemTheme = () => {
376
- return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
377
- };
378
- const currentTheme = ref(props.xTheme === "system" ? getSystemTheme() : props.xTheme || "light");
379
- const cycleTheme = async () => {
380
- currentTheme.value = currentTheme.value === "light" ? "dark" : "light";
381
- aiChatbotX.setTheme(currentTheme.value);
382
- };
383
- const startNewConversation = () => {
384
- aiChatbotX.startNewConversation();
385
- };
386
- const themeTooltip = computed(() => currentTheme.value === "light" ? "切换到深色模式" : "切换到浅色模式");
387
- const voiceButtonTooltip = computed(() => {
388
- if (isInitializing.value) return "初始化中...";
389
- if (initError.value) return `错误: ${initError.value}`;
390
- switch (voiceStatus.value) {
391
- case "standby":
392
- return "开启语音监听";
393
- case "listening":
394
- return "监听中,等待唤醒词...";
395
- case "wake":
396
- return "已唤醒!";
397
- default:
398
- return "语音监听";
222
+ const transport = new AgentChatTransport({
223
+ api: props.api,
224
+ projectId: props.projectId,
225
+ headers: props.headers,
226
+ body: props.body,
227
+ ...props.transportOptions
228
+ });
229
+ const chat = new Chat({
230
+ transport,
231
+ onError: (error) => {
232
+ console.error("[AiChat] error:", error);
233
+ emit("error", error instanceof Error ? error : new Error(String(error)));
234
+ },
235
+ onFinish: ({ message }) => {
236
+ emit("finish", message);
399
237
  }
400
238
  });
401
- if (props.xTheme === "system") {
402
- const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
403
- const handleThemeChange = (e) => {
404
- currentTheme.value = e.matches ? "dark" : "light";
405
- };
406
- mediaQuery.addEventListener("change", handleThemeChange);
407
- onBeforeUnmount(() => {
408
- mediaQuery.removeEventListener("change", handleThemeChange);
239
+ const inputText = ref("");
240
+ const textareaRef = ref(null);
241
+ const messagesContainerRef = ref(null);
242
+ const showScrollButton = ref(false);
243
+ const copiedId = ref(null);
244
+ const reasoningOpen = reactive({});
245
+ const isEmpty = computed(() => chat.messages.length === 0);
246
+ const isLoading = computed(() => chat.status === "streaming" || chat.status === "submitted");
247
+ const scrollToBottom = () => {
248
+ nextTick(() => {
249
+ const el = messagesContainerRef.value;
250
+ if (el) {
251
+ el.scrollTop = el.scrollHeight;
252
+ }
409
253
  });
410
- }
411
- const initVoiceDetector = () => {
412
- if (detector || isInitializing.value) return;
413
- isInitializing.value = true;
414
- initError.value = "";
415
- if (!props.modelPath) {
416
- initError.value = "未提供语音模型文件";
417
- isInitializing.value = false;
418
- return;
419
- }
420
- try {
421
- detector = new WakeWordDetectorStandalone({
422
- modelPath: props.modelPath,
423
- sampleRate: 16e3,
424
- usePartial: true,
425
- autoReset: {
426
- enabled: true,
427
- resetDelayMs: 5e3
428
- }
429
- });
430
- const wakeWords = props.wakeWords || ["你好", "您好"];
431
- detector.setWakeWords(wakeWords);
432
- detector.onWake(() => {
433
- console.log("[VoiceDetector] 检测到唤醒词");
434
- wakeAnimating.value = true;
435
- playWakeResponse();
436
- emit("wakeUp", true);
437
- aiChatbotX.weak();
438
- aiChatbotX.openDialog();
439
- setTimeout(() => {
440
- wakeAnimating.value = false;
441
- }, 1500);
442
- voiceStatus.value = "listening";
443
- });
444
- detector.onError((error) => {
445
- console.error("[VoiceDetector] 错误:", error);
446
- initError.value = error.message;
447
- voiceStatus.value = "standby";
448
- isTranscribing.value = false;
449
- if (error.message.includes("permission")) {
450
- transcriptionText.value = "需要麦克风权限";
451
- } else if (error.message.includes("model")) {
452
- transcriptionText.value = "模型加载失败";
453
- } else {
454
- transcriptionText.value = "初始化失败";
455
- }
456
- setTimeout(() => {
457
- transcriptionText.value = "";
458
- }, 3e3);
459
- });
460
- console.log("[VoiceDetector] 初始化成功");
461
- } catch (error) {
462
- console.error("[VoiceDetector] 初始化失败:", error);
463
- initError.value = error instanceof Error ? error.message : "初始化失败";
464
- voiceStatus.value = "standby";
465
- isTranscribing.value = false;
466
- } finally {
467
- isInitializing.value = false;
468
- }
469
254
  };
470
- const playWakeResponse = () => {
471
- try {
472
- if (typeof window === "undefined" || !window.speechSynthesis) {
473
- console.warn("[TTS] SpeechSynthesis API 不可用");
474
- return;
255
+ const handleScroll = () => {
256
+ const el = messagesContainerRef.value;
257
+ if (!el) return;
258
+ const threshold = 100;
259
+ showScrollButton.value = el.scrollHeight - el.scrollTop - el.clientHeight > threshold;
260
+ };
261
+ watch(
262
+ () => chat.messages.length,
263
+ () => {
264
+ if (!showScrollButton.value) {
265
+ scrollToBottom();
475
266
  }
476
- const text = wakeResponses[Math.floor(Math.random() * wakeResponses.length)];
477
- const utterance = new SpeechSynthesisUtterance(text);
478
- utterance.lang = "zh-CN";
479
- utterance.rate = 1;
480
- utterance.pitch = 0.8;
481
- utterance.volume = 0.9;
482
- const voices = window.speechSynthesis.getVoices();
483
- const maleVoice = voices.find((v) => v.lang.startsWith("zh") && /male|男/i.test(v.name));
484
- const zhVoice = maleVoice || voices.find((v) => v.lang.startsWith("zh"));
485
- if (zhVoice) {
486
- utterance.voice = zhVoice;
267
+ }
268
+ );
269
+ watch(
270
+ () => {
271
+ const msgs = chat.messages;
272
+ if (msgs.length === 0) return "";
273
+ const last = msgs[msgs.length - 1];
274
+ return last.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
275
+ },
276
+ () => {
277
+ if (!showScrollButton.value) {
278
+ scrollToBottom();
487
279
  }
488
- window.speechSynthesis.speak(utterance);
489
- } catch (error) {
490
- console.error("[TTS] 播报失败:", error);
491
280
  }
281
+ );
282
+ const autoResize = () => {
283
+ const el = textareaRef.value;
284
+ if (!el) return;
285
+ el.style.height = "auto";
286
+ el.style.height = `${Math.min(el.scrollHeight, 200)}px`;
492
287
  };
493
- const stopTranscribing = async () => {
494
- };
495
- const toggleVoiceMode = async (targetState) => {
496
- const permission = await ensureMicrophonePermission();
497
- if (!permission) return;
498
- if (isInitializing.value) return;
499
- if (!detector) {
500
- await initVoiceDetector();
501
- if (!detector) return;
288
+ const handleKeydown = (e) => {
289
+ if (e.key === "Enter" && !e.shiftKey) {
290
+ e.preventDefault();
291
+ handleSubmit();
502
292
  }
503
- const isCurrentlyListening = voiceStatus.value === "listening";
504
- const shouldStart = targetState !== void 0 ? targetState : !isCurrentlyListening;
505
- if (shouldStart === isCurrentlyListening) return;
506
- try {
507
- if (shouldStart) {
508
- console.log("[VoiceDetector] 强制/自动启动监听...");
509
- await detector.start();
510
- voiceStatus.value = "listening";
511
- transcriptionText.value = "";
512
- isTranscribing.value = false;
513
- } else {
514
- console.log("[VoiceDetector] 强制/自动停止监听...");
515
- await detector.stop();
516
- stopTranscribing();
517
- voiceStatus.value = "standby";
518
- transcriptionText.value = "";
519
- isTranscribing.value = false;
293
+ };
294
+ const handleSubmit = () => {
295
+ const text = inputText.value.trim();
296
+ if (!text || isLoading.value) return;
297
+ chat.sendMessage({ text });
298
+ inputText.value = "";
299
+ nextTick(() => {
300
+ if (textareaRef.value) {
301
+ textareaRef.value.style.height = "auto";
520
302
  }
521
- } catch (error) {
522
- console.error("[VoiceDetector] 操作失败:", error);
523
- voiceStatus.value = "standby";
524
- transcriptionText.value = "操作失败";
525
- isTranscribing.value = false;
526
- setTimeout(() => {
527
- transcriptionText.value = "";
528
- }, 2e3);
529
- }
303
+ });
530
304
  };
531
- const position = reactive({ x: 0, y: 0 });
532
- const containerWidth = ref(props.xDialogSize?.width || 420);
533
- const containerHeight = ref(props.xDialogSize?.height || 600);
534
- const isFirstOpen = ref(true);
535
- const validatePosition = (x, y, width, height) => {
536
- const margin = 20;
537
- const viewportWidth = window.innerWidth;
538
- const viewportHeight = window.innerHeight;
539
- const maxX = viewportWidth - width - margin;
540
- const maxY = viewportHeight - height - margin;
541
- return {
542
- x: Math.max(margin, Math.min(x, maxX)),
543
- y: Math.max(margin, Math.min(y, maxY))
544
- };
305
+ const handleSuggestionClick = (suggestion) => {
306
+ chat.sendMessage({ text: suggestion });
545
307
  };
546
- const getOverlapArea = (rectA, rectB) => {
547
- const overlapX = Math.max(0, Math.min(rectA.right, rectB.right) - Math.max(rectA.left, rectB.left));
548
- const overlapY = Math.max(0, Math.min(rectA.bottom, rectB.bottom) - Math.max(rectA.top, rectB.top));
549
- return overlapX * overlapY;
308
+ const handleStop = () => {
309
+ chat.stop();
550
310
  };
551
- const keepDistanceFromFab = (x, y, width, height) => {
552
- if (!fabRef.value) return { x, y };
553
- const fabRect = fabRef.value.getBoundingClientRect();
554
- const safeFabRect = {
555
- left: fabRect.left - FAB_SAFE_GAP,
556
- right: fabRect.right + FAB_SAFE_GAP,
557
- top: fabRect.top - FAB_SAFE_GAP,
558
- bottom: fabRect.bottom + FAB_SAFE_GAP
559
- };
560
- const candidates = [
561
- { x, y },
562
- { x: safeFabRect.left - width - FAB_SAFE_GAP, y },
563
- { x: safeFabRect.right + FAB_SAFE_GAP, y },
564
- { x, y: safeFabRect.top - height - FAB_SAFE_GAP },
565
- { x, y: safeFabRect.bottom + FAB_SAFE_GAP }
566
- ];
567
- let best = validatePosition(candidates[0].x, candidates[0].y, width, height);
568
- let bestOverlap = getOverlapArea(
569
- { left: best.x, right: best.x + width, top: best.y, bottom: best.y + height },
570
- safeFabRect
571
- );
572
- for (let i = 1; i < candidates.length; i++) {
573
- const validated = validatePosition(candidates[i].x, candidates[i].y, width, height);
574
- const overlap = getOverlapArea(
575
- { left: validated.x, right: validated.x + width, top: validated.y, bottom: validated.y + height },
576
- safeFabRect
577
- );
578
- if (overlap < bestOverlap) {
579
- best = validated;
580
- bestOverlap = overlap;
581
- if (overlap === 0) break;
311
+ const handleRegenerate = (assistantMessageId) => {
312
+ const msgs = chat.messages;
313
+ const index = msgs.findIndex((m) => m.id === assistantMessageId);
314
+ if (index <= 0) return;
315
+ let userMsg = null;
316
+ for (let i = index - 1; i >= 0; i--) {
317
+ if (msgs[i].role === "user") {
318
+ userMsg = msgs[i];
319
+ break;
582
320
  }
583
321
  }
584
- return best;
322
+ if (!userMsg) return;
323
+ const userText = userMsg.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
324
+ chat.messages = msgs.slice(0, msgs.indexOf(userMsg));
325
+ nextTick(() => {
326
+ chat.sendMessage({ text: userText });
327
+ });
585
328
  };
586
- const calculateInitialPosition = () => {
587
- if (!fabRef.value) return;
588
- const fabRect = fabRef.value.getBoundingClientRect();
589
- const dialogWidth = containerWidth.value;
590
- const dialogHeight = containerHeight.value;
591
- const viewportWidth = window.innerWidth;
592
- const viewportHeight = window.innerHeight;
593
- const margin = 20;
594
- const minMargin = 20;
595
- let x = 0;
596
- let y = 0;
597
- const leftX = fabRect.left - dialogWidth - margin;
598
- if (leftX >= minMargin) {
599
- x = leftX;
600
- y = fabRect.top;
601
- if (y + dialogHeight > viewportHeight - minMargin) {
602
- y = viewportHeight - dialogHeight - minMargin;
603
- }
604
- if (y < minMargin) {
605
- y = minMargin;
606
- }
607
- } else {
608
- const rightX = fabRect.right + margin;
609
- if (rightX + dialogWidth <= viewportWidth - minMargin) {
610
- x = rightX;
611
- y = fabRect.top;
612
- if (y + dialogHeight > viewportHeight - minMargin) {
613
- y = viewportHeight - dialogHeight - minMargin;
614
- }
615
- if (y < minMargin) {
616
- y = minMargin;
617
- }
618
- } else {
619
- x = (viewportWidth - dialogWidth) / 2;
620
- const aboveY = fabRect.top - dialogHeight - margin;
621
- if (aboveY >= minMargin) {
622
- y = aboveY;
623
- } else {
624
- const belowY = fabRect.bottom + margin;
625
- if (belowY + dialogHeight <= viewportHeight - minMargin) {
626
- y = belowY;
627
- } else {
628
- y = (viewportHeight - dialogHeight) / 2;
629
- }
630
- }
631
- }
329
+ const handleCopy = async (message) => {
330
+ const text = message.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
331
+ try {
332
+ await navigator.clipboard.writeText(text);
333
+ copiedId.value = message.id;
334
+ setTimeout(() => {
335
+ copiedId.value = null;
336
+ }, 2e3);
337
+ } catch {
338
+ console.error("Failed to copy");
632
339
  }
633
- const validated = validatePosition(x, y, dialogWidth, dialogHeight);
634
- const separated = keepDistanceFromFab(validated.x, validated.y, dialogWidth, dialogHeight);
635
- position.x = separated.x;
636
- position.y = separated.y;
637
340
  };
638
- const toggleCollapse = async () => {
639
- isCollapsed.value = !isCollapsed.value;
640
- nextTick(() => {
641
- const currentHeight = isCollapsed.value ? 60 : containerHeight.value;
642
- const validated = validatePosition(position.x, position.y, containerWidth.value, currentHeight);
643
- const separated = keepDistanceFromFab(validated.x, validated.y, containerWidth.value, currentHeight);
644
- position.x = separated.x;
645
- position.y = separated.y;
646
- });
341
+ const isToolPart = (part) => {
342
+ return typeof part.type === "string" && part.type.startsWith("tool-");
647
343
  };
648
- const drag = reactive({
649
- isDragging: false,
650
- startX: 0,
651
- startY: 0,
652
- offsetX: 0,
653
- offsetY: 0
654
- });
655
- const startDrag = (e) => {
656
- drag.isDragging = true;
657
- drag.startX = e.clientX;
658
- drag.startY = e.clientY;
659
- drag.offsetX = position.x;
660
- drag.offsetY = position.y;
661
- document.addEventListener("mousemove", onDrag);
662
- document.addEventListener("mouseup", stopDrag);
344
+ const isToolLoading = (part) => {
345
+ return part.state === "partial-call" || part.state === "call" || part.state === "input-streaming" || part.state === "input-available";
663
346
  };
664
- const onDrag = (e) => {
665
- if (!drag.isDragging) return;
666
- const newX = drag.offsetX + (e.clientX - drag.startX);
667
- const newY = drag.offsetY + (e.clientY - drag.startY);
668
- const validated = validatePosition(newX, newY, containerWidth.value, isCollapsed.value ? 60 : containerHeight.value);
669
- position.x = validated.x;
670
- position.y = validated.y;
347
+ const isToolDone = (part) => {
348
+ return part.state === "result" || part.state === "output-available";
671
349
  };
672
- const stopDrag = () => {
673
- drag.isDragging = false;
674
- document.removeEventListener("mousemove", onDrag);
675
- document.removeEventListener("mouseup", stopDrag);
350
+ const isToolError = (part) => {
351
+ return part.state === "error" || part.state === "output-error";
676
352
  };
677
- const toggleDialog = async (state) => {
678
- if (state) {
679
- visible.value = true;
680
- positionReady.value = false;
681
- emit("wakeUp", true);
682
- await nextTick();
683
- if (isFirstOpen.value) {
684
- calculateInitialPosition();
685
- isFirstOpen.value = false;
686
- } else {
687
- const validated = validatePosition(
688
- position.x,
689
- position.y,
690
- containerWidth.value,
691
- isCollapsed.value ? 60 : containerHeight.value
692
- );
693
- const separated = keepDistanceFromFab(
694
- validated.x,
695
- validated.y,
696
- containerWidth.value,
697
- isCollapsed.value ? 60 : containerHeight.value
698
- );
699
- position.x = separated.x;
700
- position.y = separated.y;
701
- }
702
- await nextTick();
703
- positionReady.value = true;
704
- } else {
705
- positionReady.value = false;
706
- visible.value = false;
707
- isCollapsed.value = false;
708
- emit("wakeUp", false);
709
- }
353
+ const getToolName = (part) => {
354
+ return part.toolName || part.type?.replace("tool-", "") || "unknown";
710
355
  };
711
- const handleIframeLoad = async (event) => {
712
- aiChatbotX.setIframeElement(event.target);
713
- aiChatbotX.setTheme(currentTheme.value);
356
+ const getToolDisplayName = (name) => {
357
+ return props.toolNames?.[name] || toolDisplayNames[name] || name;
714
358
  };
715
- watch(
716
- () => [aiChatbotX.chatbotUrl()],
717
- ([url]) => {
718
- console.log("[AiChatbotX] 初始化", url);
719
- if (url) {
720
- chatbotUrl.value = `${url}/app/${aiChatbotX.appId()}?token=${aiChatbotX.appToken()}`;
721
- }
722
- },
723
- { immediate: true }
724
- );
725
- onBeforeUnmount(async () => {
726
- if (detector) {
727
- try {
728
- if (detector.isActive()) {
729
- await detector.stop();
730
- }
731
- detector = null;
732
- } catch (error) {
733
- console.error("[VoiceDetector] 清理失败:", error);
734
- }
735
- }
736
- });
737
- aiChatbotX?.registerVoiceMethods({
738
- start: () => toggleVoiceMode(true),
739
- stop: () => toggleVoiceMode(false),
740
- openDialog: () => toggleDialog(true),
741
- closeDialog: () => toggleDialog(false),
742
- toggleCollapse: () => toggleCollapse()
743
- });
744
- return (_ctx, _cache) => {
745
- return openBlock(), createElementBlock("div", {
746
- class: "sime-x",
747
- "data-theme": currentTheme.value
748
- }, [
749
- createVNode(Transition, { name: "fade" }, {
750
- default: withCtx(() => [
751
- createElementVNode("div", {
752
- ref_key: "fabRef",
753
- ref: fabRef,
754
- class: "assistant-fab",
755
- onClick: _cache[0] || (_cache[0] = ($event) => toggleDialog(!visible.value))
756
- }, [
757
- !isProcessing.value ? (openBlock(), createBlock(VoiceStatus, {
758
- key: 0,
759
- class: "voice-status",
760
- status: voiceStatus.value,
761
- "transcription-text": transcriptionText.value,
762
- "is-transcribing": isTranscribing.value,
763
- style: { "width": "480px" }
764
- }, null, 8, ["status", "transcription-text", "is-transcribing"])) : (openBlock(), createBlock(ExecutionStatus, {
765
- key: 1,
766
- class: "voice-status",
767
- visible: isProcessing.value,
768
- text: transcriptionText.value
769
- }, null, 8, ["visible", "text"])),
770
- createElementVNode("div", _hoisted_2$1, [
771
- createElementVNode("img", {
772
- src: __props.xLogo ? __props.xLogo : "/sime.png",
773
- alt: "assistant",
774
- style: normalizeStyle({
775
- width: __props.xSize?.width + "px"
776
- })
777
- }, null, 12, _hoisted_3$1),
778
- createVNode(Transition, { name: "indicator-fade" }, {
779
- default: withCtx(() => [
780
- voiceStatus.value === "listening" ? (openBlock(), createElementBlock("div", {
781
- key: 0,
782
- class: normalizeClass(["listening-badge", { "wake-active": wakeAnimating.value }])
783
- }, [..._cache[3] || (_cache[3] = [
784
- createElementVNode("div", { class: "listening-waves" }, [
785
- createElementVNode("div", { class: "wave wave-1" }),
786
- createElementVNode("div", { class: "wave wave-2" }),
787
- createElementVNode("div", { class: "wave wave-3" })
788
- ], -1),
789
- createElementVNode("div", { class: "listening-icon" }, [
790
- createElementVNode("svg", {
791
- width: "24",
792
- height: "24",
793
- viewBox: "0 0 24 24",
794
- fill: "none"
795
- }, [
796
- createElementVNode("path", {
797
- d: "M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z",
798
- fill: "currentColor"
799
- }),
800
- createElementVNode("path", {
801
- d: "M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5",
802
- stroke: "currentColor",
803
- "stroke-width": "2",
804
- "stroke-linecap": "round"
805
- })
806
- ])
807
- ], -1)
808
- ])], 2)) : createCommentVNode("", true)
809
- ]),
810
- _: 1
811
- })
812
- ]),
813
- createElementVNode("div", {
814
- class: normalizeClass(["fab-pulse", { active: voiceStatus.value === "listening" }])
815
- }, null, 2)
816
- ], 512)
359
+ const isStreamingMessage = (messageId) => {
360
+ if (chat.status !== "streaming" && chat.status !== "submitted") return false;
361
+ const msgs = chat.messages;
362
+ return msgs.length > 0 && msgs[msgs.length - 1].id === messageId;
363
+ };
364
+ const toggleReasoning = (messageId) => {
365
+ reasoningOpen[messageId] = !reasoningOpen[messageId];
366
+ };
367
+ const renderMarkdown = (text) => {
368
+ if (!text) return "";
369
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>").replace(/\*(.*?)\*/g, "<em>$1</em>").replace(/`([^`]+)`/g, "<code>$1</code>").replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>').replace(/\n/g, "<br/>");
370
+ };
371
+ onMounted(() => {
372
+ autoResize();
373
+ });
374
+ __expose({
375
+ chat,
376
+ sendMessage: (text) => chat.sendMessage({ text }),
377
+ clearMessages: () => {
378
+ chat.messages = [];
379
+ },
380
+ stop: () => chat.stop()
381
+ });
382
+ return (_ctx, _cache) => {
383
+ return openBlock(), createElementBlock("div", {
384
+ class: normalizeClass(["ai-chat", { "ai-chat--full-width": __props.fullWidth }])
385
+ }, [
386
+ isEmpty.value ? (openBlock(), createElementBlock("div", _hoisted_1$1, [
387
+ createElementVNode("div", _hoisted_2$1, [
388
+ createElementVNode("h1", _hoisted_3$1, toDisplayString(__props.welcomeTitle), 1),
389
+ createElementVNode("p", _hoisted_4$1, toDisplayString(__props.welcomeDescription), 1)
817
390
  ]),
818
- _: 1
819
- }),
820
- createVNode(Transition, { name: "dialog-fade" }, {
821
- default: withCtx(() => [
822
- createElementVNode("div", {
823
- ref: "dialogRef",
824
- class: normalizeClass(["x-dialog-container", {
825
- collapsed: isCollapsed.value,
826
- "is-hidden": !visible.value,
827
- "position-ready": positionReady.value
828
- }]),
829
- style: normalizeStyle({
830
- width: containerWidth.value + "px",
831
- height: isCollapsed.value ? "auto" : containerHeight.value + "px",
832
- border: currentTheme.value === "light" && !isCollapsed.value ? "1px solid var(--border-color)" : "none",
833
- "--dialog-x": position.x + "px",
834
- "--dialog-y": position.y + "px"
835
- }),
836
- onMousedown: startDrag
391
+ createElementVNode("div", _hoisted_5$1, [
392
+ createElementVNode("form", {
393
+ class: "ai-chat__form",
394
+ onSubmit: withModifiers(handleSubmit, ["prevent"])
837
395
  }, [
838
- createElementVNode("div", {
839
- class: "x-dialog-header",
840
- onMousedown: withModifiers(startDrag, ["stop"])
841
- }, [
842
- createElementVNode("div", _hoisted_4$1, [
843
- createElementVNode("div", _hoisted_5$1, [
844
- createElementVNode("img", {
845
- src: __props.xLogo ? __props.xLogo : "/sime.png",
846
- alt: "assistant",
847
- class: "logo"
848
- }, null, 8, _hoisted_6$1)
849
- ]),
850
- createElementVNode("span", _hoisted_7$1, toDisplayString(__props.xTitle), 1)
396
+ createElementVNode("div", _hoisted_6$1, [
397
+ withDirectives(createElementVNode("textarea", {
398
+ ref_key: "textareaRef",
399
+ ref: textareaRef,
400
+ "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => inputText.value = $event),
401
+ class: "ai-chat__textarea",
402
+ placeholder: "发送消息...",
403
+ rows: "1",
404
+ onKeydown: handleKeydown,
405
+ onInput: autoResize
406
+ }, null, 544), [
407
+ [vModelText, inputText.value]
851
408
  ]),
852
- createElementVNode("div", _hoisted_8$1, [
853
- createElementVNode("button", {
854
- class: "action-btn theme-btn",
855
- title: "开启新对话",
856
- onClick: startNewConversation
857
- }, [..._cache[4] || (_cache[4] = [
858
- createElementVNode("svg", {
859
- width: "16",
860
- height: "16",
861
- viewBox: "0 0 24 24",
862
- fill: "none"
863
- }, [
864
- createElementVNode("path", {
865
- d: "M12 5v14M5 12h14",
866
- stroke: "currentColor",
867
- "stroke-width": "2",
868
- "stroke-linecap": "round"
869
- })
870
- ], -1)
871
- ])]),
872
- createElementVNode("button", {
873
- class: normalizeClass(["action-btn theme-btn", {
874
- active: voiceStatus.value !== "standby",
875
- listening: voiceStatus.value === "listening",
876
- woke: voiceStatus.value === "wake"
877
- }]),
878
- onClick: _cache[1] || (_cache[1] = withModifiers(() => toggleVoiceMode(), ["stop"])),
879
- title: voiceButtonTooltip.value
409
+ createElementVNode("button", {
410
+ type: "submit",
411
+ class: "ai-chat__send-btn",
412
+ disabled: !inputText.value.trim() || isLoading.value
413
+ }, [..._cache[2] || (_cache[2] = [
414
+ createElementVNode("svg", {
415
+ width: "16",
416
+ height: "16",
417
+ viewBox: "0 0 24 24",
418
+ fill: "none",
419
+ stroke: "currentColor",
420
+ "stroke-width": "2",
421
+ "stroke-linecap": "round",
422
+ "stroke-linejoin": "round"
880
423
  }, [
881
- _cache[5] || (_cache[5] = createElementVNode("svg", {
882
- width: "16",
883
- height: "16",
884
- viewBox: "0 0 24 24",
885
- fill: "none"
424
+ createElementVNode("line", {
425
+ x1: "22",
426
+ y1: "2",
427
+ x2: "11",
428
+ y2: "13"
429
+ }),
430
+ createElementVNode("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
431
+ ], -1)
432
+ ])], 8, _hoisted_7$1)
433
+ ])
434
+ ], 32),
435
+ __props.suggestions.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_8$1, [
436
+ (openBlock(true), createElementBlock(Fragment, null, renderList(__props.suggestions, (suggestion) => {
437
+ return openBlock(), createElementBlock("button", {
438
+ key: suggestion,
439
+ class: "ai-chat__suggestion",
440
+ onClick: ($event) => handleSuggestionClick(suggestion)
441
+ }, toDisplayString(suggestion), 9, _hoisted_9$1);
442
+ }), 128))
443
+ ])) : createCommentVNode("", true)
444
+ ])
445
+ ])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
446
+ createElementVNode("div", {
447
+ ref_key: "messagesContainerRef",
448
+ ref: messagesContainerRef,
449
+ class: "ai-chat__messages",
450
+ onScroll: handleScroll
451
+ }, [
452
+ createElementVNode("div", _hoisted_10$1, [
453
+ (openBlock(true), createElementBlock(Fragment, null, renderList(unref(chat).messages, (message) => {
454
+ return openBlock(), createElementBlock("div", {
455
+ key: message.id,
456
+ class: "ai-chat__message-group"
457
+ }, [
458
+ (openBlock(true), createElementBlock(Fragment, null, renderList(message.parts, (part, partIndex) => {
459
+ return openBlock(), createElementBlock(Fragment, {
460
+ key: `${message.id}-${partIndex}`
886
461
  }, [
887
- createElementVNode("path", {
888
- d: "M12 15C13.6569 15 15 13.6569 15 12V7C15 5.34315 13.6569 4 12 4C10.3431 4 9 5.34315 9 7V12C9 13.6569 10.3431 15 12 15Z",
889
- stroke: "currentColor",
890
- "stroke-width": "2",
891
- "stroke-linecap": "round",
892
- "stroke-linejoin": "round"
893
- }),
894
- createElementVNode("path", {
895
- d: "M18 11C18 14.3137 15.3137 17 12 17C8.68629 17 6 14.3137 6 11",
896
- stroke: "currentColor",
897
- "stroke-width": "2",
898
- "stroke-linecap": "round",
899
- "stroke-linejoin": "round"
900
- }),
901
- createElementVNode("path", {
902
- d: "M12 19V17",
903
- stroke: "currentColor",
904
- "stroke-width": "2",
905
- "stroke-linecap": "round",
906
- "stroke-linejoin": "round"
907
- }),
908
- createElementVNode("path", {
909
- d: "M9 21H15",
462
+ part.type === "text" ? (openBlock(), createElementBlock("div", {
463
+ key: 0,
464
+ class: normalizeClass(["ai-chat__message", `ai-chat__message--${message.role}`])
465
+ }, [
466
+ createElementVNode("div", _hoisted_11$1, [
467
+ createElementVNode("div", {
468
+ class: "ai-chat__message-text",
469
+ innerHTML: renderMarkdown(part.text)
470
+ }, null, 8, _hoisted_12$1)
471
+ ])
472
+ ], 2)) : part.type === "reasoning" ? (openBlock(), createElementBlock("div", _hoisted_13$1, [
473
+ createElementVNode("button", {
474
+ class: "ai-chat__reasoning-trigger",
475
+ onClick: ($event) => toggleReasoning(message.id)
476
+ }, [
477
+ (openBlock(), createElementBlock("svg", {
478
+ class: normalizeClass(["ai-chat__reasoning-icon", { "ai-chat__reasoning-icon--open": reasoningOpen[message.id] }]),
479
+ width: "12",
480
+ height: "12",
481
+ viewBox: "0 0 24 24",
482
+ fill: "none",
483
+ stroke: "currentColor",
484
+ "stroke-width": "2"
485
+ }, [..._cache[3] || (_cache[3] = [
486
+ createElementVNode("polyline", { points: "9 18 15 12 9 6" }, null, -1)
487
+ ])], 2)),
488
+ _cache[4] || (_cache[4] = createElementVNode("span", null, "思考过程", -1)),
489
+ isStreamingMessage(message.id) && partIndex === message.parts.length - 1 ? (openBlock(), createElementBlock("span", _hoisted_15)) : createCommentVNode("", true)
490
+ ], 8, _hoisted_14),
491
+ reasoningOpen[message.id] ? (openBlock(), createElementBlock("div", _hoisted_16, toDisplayString(part.text), 1)) : createCommentVNode("", true)
492
+ ])) : isToolPart(part) ? (openBlock(), createElementBlock("div", _hoisted_17, [
493
+ createElementVNode("div", {
494
+ class: normalizeClass(["ai-chat__tool-step", {
495
+ "ai-chat__tool-step--loading": isToolLoading(part),
496
+ "ai-chat__tool-step--done": isToolDone(part),
497
+ "ai-chat__tool-step--error": isToolError(part)
498
+ }])
499
+ }, [
500
+ createElementVNode("span", _hoisted_18, [
501
+ isToolLoading(part) ? (openBlock(), createElementBlock("svg", _hoisted_19, [..._cache[5] || (_cache[5] = [
502
+ createElementVNode("circle", {
503
+ cx: "12",
504
+ cy: "12",
505
+ r: "10",
506
+ stroke: "currentColor",
507
+ "stroke-width": "2.5",
508
+ "stroke-linecap": "round",
509
+ "stroke-dasharray": "31.4 31.4"
510
+ }, null, -1)
511
+ ])])) : isToolDone(part) ? (openBlock(), createElementBlock("svg", _hoisted_20, [..._cache[6] || (_cache[6] = [
512
+ createElementVNode("path", {
513
+ d: "M20 6L9 17l-5-5",
514
+ stroke: "currentColor",
515
+ "stroke-width": "2.5",
516
+ "stroke-linecap": "round",
517
+ "stroke-linejoin": "round"
518
+ }, null, -1)
519
+ ])])) : isToolError(part) ? (openBlock(), createElementBlock("svg", _hoisted_21, [..._cache[7] || (_cache[7] = [
520
+ createElementVNode("circle", {
521
+ cx: "12",
522
+ cy: "12",
523
+ r: "10",
524
+ stroke: "currentColor",
525
+ "stroke-width": "2"
526
+ }, null, -1),
527
+ createElementVNode("path", {
528
+ d: "M15 9l-6 6M9 9l6 6",
529
+ stroke: "currentColor",
530
+ "stroke-width": "2",
531
+ "stroke-linecap": "round"
532
+ }, null, -1)
533
+ ])])) : createCommentVNode("", true)
534
+ ]),
535
+ createElementVNode("span", _hoisted_22, toDisplayString(getToolDisplayName(getToolName(part))), 1)
536
+ ], 2)
537
+ ])) : createCommentVNode("", true)
538
+ ], 64);
539
+ }), 128)),
540
+ message.role === "assistant" && !isStreamingMessage(message.id) ? (openBlock(), createElementBlock("div", _hoisted_23, [
541
+ createElementVNode("button", {
542
+ class: "ai-chat__action-btn",
543
+ title: "重新生成",
544
+ onClick: ($event) => handleRegenerate(message.id)
545
+ }, [..._cache[8] || (_cache[8] = [
546
+ createElementVNode("svg", {
547
+ width: "12",
548
+ height: "12",
549
+ viewBox: "0 0 24 24",
550
+ fill: "none",
910
551
  stroke: "currentColor",
911
552
  "stroke-width": "2",
912
553
  "stroke-linecap": "round",
913
554
  "stroke-linejoin": "round"
914
- })
915
- ], -1)),
916
- voiceStatus.value !== "standby" ? (openBlock(), createElementBlock("span", _hoisted_10$1)) : createCommentVNode("", true)
917
- ], 10, _hoisted_9$1),
918
- createElementVNode("button", {
919
- class: "action-btn theme-btn",
920
- onClick: withModifiers(cycleTheme, ["stop"]),
921
- title: themeTooltip.value
922
- }, [..._cache[6] || (_cache[6] = [
923
- createElementVNode("svg", {
924
- width: "16",
925
- height: "16",
926
- viewBox: "0 0 24 24",
927
- fill: "none"
555
+ }, [
556
+ createElementVNode("polyline", { points: "23 4 23 10 17 10" }),
557
+ createElementVNode("polyline", { points: "1 20 1 14 7 14" }),
558
+ createElementVNode("path", { d: "M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" })
559
+ ], -1)
560
+ ])], 8, _hoisted_24),
561
+ createElementVNode("button", {
562
+ class: "ai-chat__action-btn",
563
+ title: "复制",
564
+ onClick: ($event) => handleCopy(message)
928
565
  }, [
929
- createElementVNode("circle", {
930
- cx: "12",
931
- cy: "12",
932
- r: "7",
933
- stroke: "currentColor",
934
- "stroke-width": "2"
935
- }),
936
- createElementVNode("path", {
937
- d: "M12 5A7 7 0 1 1 12 19",
938
- fill: "currentColor"
939
- })
940
- ], -1)
941
- ])], 8, _hoisted_11$1),
942
- createElementVNode("button", {
943
- class: "action-btn collapse-btn",
944
- onClick: withModifiers(toggleCollapse, ["stop"]),
945
- title: isCollapsed.value ? "展开" : "折叠"
566
+ !copiedId.value || copiedId.value !== message.id ? (openBlock(), createElementBlock("svg", _hoisted_26, [..._cache[9] || (_cache[9] = [
567
+ createElementVNode("rect", {
568
+ x: "9",
569
+ y: "9",
570
+ width: "13",
571
+ height: "13",
572
+ rx: "2",
573
+ ry: "2"
574
+ }, null, -1),
575
+ createElementVNode("path", { d: "M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" }, null, -1)
576
+ ])])) : (openBlock(), createElementBlock("svg", _hoisted_27, [..._cache[10] || (_cache[10] = [
577
+ createElementVNode("polyline", { points: "20 6 9 17 4 12" }, null, -1)
578
+ ])]))
579
+ ], 8, _hoisted_25)
580
+ ])) : createCommentVNode("", true)
581
+ ]);
582
+ }), 128)),
583
+ unref(chat).status === "submitted" ? (openBlock(), createElementBlock("div", _hoisted_28, [..._cache[11] || (_cache[11] = [
584
+ createElementVNode("div", { class: "ai-chat__thinking-dots" }, [
585
+ createElementVNode("span"),
586
+ createElementVNode("span"),
587
+ createElementVNode("span")
588
+ ], -1)
589
+ ])])) : createCommentVNode("", true)
590
+ ])
591
+ ], 544),
592
+ createVNode(Transition, { name: "fade" }, {
593
+ default: withCtx(() => [
594
+ showScrollButton.value ? (openBlock(), createElementBlock("button", {
595
+ key: 0,
596
+ class: "ai-chat__scroll-btn",
597
+ onClick: scrollToBottom
598
+ }, [..._cache[12] || (_cache[12] = [
599
+ createElementVNode("svg", {
600
+ width: "16",
601
+ height: "16",
602
+ viewBox: "0 0 24 24",
603
+ fill: "none",
604
+ stroke: "currentColor",
605
+ "stroke-width": "2",
606
+ "stroke-linecap": "round",
607
+ "stroke-linejoin": "round"
608
+ }, [
609
+ createElementVNode("polyline", { points: "6 9 12 15 18 9" })
610
+ ], -1)
611
+ ])])) : createCommentVNode("", true)
612
+ ]),
613
+ _: 1
614
+ }),
615
+ !__props.isReadonly ? (openBlock(), createElementBlock("div", _hoisted_29, [
616
+ createElementVNode("form", {
617
+ class: "ai-chat__form",
618
+ onSubmit: withModifiers(handleSubmit, ["prevent"])
619
+ }, [
620
+ createElementVNode("div", _hoisted_30, [
621
+ withDirectives(createElementVNode("textarea", {
622
+ ref_key: "textareaRef",
623
+ ref: textareaRef,
624
+ "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => inputText.value = $event),
625
+ class: "ai-chat__textarea",
626
+ placeholder: "发送消息...",
627
+ rows: "1",
628
+ onKeydown: handleKeydown,
629
+ onInput: autoResize
630
+ }, null, 544), [
631
+ [vModelText, inputText.value]
632
+ ]),
633
+ unref(chat).status === "streaming" || unref(chat).status === "submitted" ? (openBlock(), createElementBlock("button", {
634
+ key: 0,
635
+ type: "button",
636
+ class: "ai-chat__stop-btn",
637
+ onClick: handleStop
638
+ }, [..._cache[13] || (_cache[13] = [
639
+ createElementVNode("svg", {
640
+ width: "14",
641
+ height: "14",
642
+ viewBox: "0 0 24 24",
643
+ fill: "currentColor"
946
644
  }, [
947
- (openBlock(), createElementBlock("svg", _hoisted_13$1, [
948
- createElementVNode("path", {
949
- d: isCollapsed.value ? "M18 15L12 9L6 15" : "M6 9L12 15L18 9",
950
- stroke: "currentColor",
951
- "stroke-width": "2",
952
- "stroke-linecap": "round",
953
- "stroke-linejoin": "round"
954
- }, null, 8, _hoisted_14)
955
- ]))
956
- ], 8, _hoisted_12$1),
957
- createElementVNode("button", {
958
- class: "action-btn minimize-btn",
959
- onClick: _cache[2] || (_cache[2] = withModifiers(($event) => toggleDialog(false), ["stop"])),
960
- title: "最小化"
961
- }, [..._cache[7] || (_cache[7] = [
962
- createElementVNode("svg", {
963
- width: "16",
964
- height: "16",
965
- viewBox: "0 0 24 24",
966
- fill: "none"
967
- }, [
968
- createElementVNode("path", {
969
- d: "M5 12H19",
970
- stroke: "currentColor",
971
- "stroke-width": "2",
972
- "stroke-linecap": "round"
973
- })
974
- ], -1)
975
- ])])
976
- ])
977
- ], 32),
978
- createElementVNode("div", {
979
- class: normalizeClass(["x-dialog-content", { "is-hidden": isCollapsed.value }]),
980
- style: normalizeStyle({ opacity: isCollapsed.value ? 0 : 1 })
981
- }, [
982
- createElementVNode("iframe", {
983
- ref: "iframeRef",
984
- src: chatbotUrl.value,
985
- class: "x-iframe",
986
- allow: "microphone *; storage-access *; camera *",
987
- frameborder: "0",
988
- onLoad: handleIframeLoad
989
- }, null, 40, _hoisted_15)
990
- ], 6)
991
- ], 38)
992
- ]),
993
- _: 1
994
- })
995
- ], 8, _hoisted_1$1);
645
+ createElementVNode("rect", {
646
+ x: "6",
647
+ y: "6",
648
+ width: "12",
649
+ height: "12",
650
+ rx: "2"
651
+ })
652
+ ], -1)
653
+ ])])) : (openBlock(), createElementBlock("button", {
654
+ key: 1,
655
+ type: "submit",
656
+ class: "ai-chat__send-btn",
657
+ disabled: !inputText.value.trim()
658
+ }, [..._cache[14] || (_cache[14] = [
659
+ createElementVNode("svg", {
660
+ width: "16",
661
+ height: "16",
662
+ viewBox: "0 0 24 24",
663
+ fill: "none",
664
+ stroke: "currentColor",
665
+ "stroke-width": "2",
666
+ "stroke-linecap": "round",
667
+ "stroke-linejoin": "round"
668
+ }, [
669
+ createElementVNode("line", {
670
+ x1: "22",
671
+ y1: "2",
672
+ x2: "11",
673
+ y2: "13"
674
+ }),
675
+ createElementVNode("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
676
+ ], -1)
677
+ ])], 8, _hoisted_31))
678
+ ])
679
+ ], 32)
680
+ ])) : createCommentVNode("", true)
681
+ ], 64))
682
+ ], 2);
996
683
  };
997
684
  }
998
685
  });
999
686
 
1000
- const simeX = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["__scopeId", "data-v-91f104d1"]]);
687
+ const _export_sfc = (sfc, props) => {
688
+ const target = sfc.__vccOpts || sfc;
689
+ for (const [key, val] of props) {
690
+ target[key] = val;
691
+ }
692
+ return target;
693
+ };
694
+
695
+ const aiChat = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["__scopeId", "data-v-958fd919"]]);
696
+
697
+ class CommandManager {
698
+ commands = /* @__PURE__ */ new Map();
699
+ debug;
700
+ constructor(options = {}) {
701
+ this.debug = options.debug ?? false;
702
+ }
703
+ registerCommand(command) {
704
+ this.commands.set(command.name, command);
705
+ this.log("注册命令", `${command.name}: ${command.description}`);
706
+ }
707
+ unregisterCommand(name) {
708
+ const deleted = this.commands.delete(name);
709
+ if (deleted) {
710
+ this.log("命令已注销", name);
711
+ }
712
+ }
713
+ async executeCommand(command, args = []) {
714
+ const commandDef = this.commands.get(command);
715
+ if (!commandDef) {
716
+ throw new Error(`命令 "${command}" 未找到`);
717
+ }
718
+ this.log("执行命令", command, args);
719
+ return await commandDef.handler(...args);
720
+ }
721
+ getCommands() {
722
+ return Array.from(this.commands.values()).map((cmd) => ({
723
+ name: cmd.name,
724
+ description: cmd.description,
725
+ parameters: cmd.parameters
726
+ }));
727
+ }
728
+ hasCommand(name) {
729
+ return this.commands.has(name);
730
+ }
731
+ clear() {
732
+ this.commands.clear();
733
+ this.log("", "所有命令已清空");
734
+ }
735
+ log(prefix, msg, ...args) {
736
+ (/* @__PURE__ */ new Date()).toLocaleTimeString([], {
737
+ hour: "2-digit",
738
+ minute: "2-digit",
739
+ second: "2-digit"
740
+ });
741
+ console.log(
742
+ `%c ${prefix}`,
743
+ "background:#7c3aed;color:white;padding:2px 6px;border-radius:3px 0 0 3px;font-weight:bold;",
744
+ `${msg}`
745
+ );
746
+ if (args.length > 0) {
747
+ console.log(...args);
748
+ }
749
+ }
750
+ }
751
+
752
+ const AiChatbotXKey = Symbol("sime-x");
753
+ function injectStrict(key, defaultValue, treatDefaultAsFactory) {
754
+ let result;
755
+ if (defaultValue === void 0) {
756
+ result = inject(key);
757
+ } else if (treatDefaultAsFactory === true) {
758
+ result = inject(key, defaultValue, true);
759
+ } else {
760
+ result = inject(key, defaultValue, false);
761
+ }
762
+ if (!result) {
763
+ throw new Error(`Could not resolve ${key.description}`);
764
+ }
765
+ return result;
766
+ }
767
+
768
+ const _sfc_main$1 = /* @__PURE__ */ defineComponent({
769
+ __name: "sime-provider",
770
+ props: {
771
+ project: {},
772
+ description: {},
773
+ debug: { type: Boolean },
774
+ chatbotUrl: {},
775
+ appId: {},
776
+ appToken: {}
777
+ },
778
+ setup(__props) {
779
+ const props = __props;
780
+ const commandManager = shallowRef(new CommandManager({ debug: props.debug ?? false }));
781
+ const stopBroadcastRef = shallowRef(async () => {
782
+ });
783
+ provide(AiChatbotXKey, {
784
+ chatbotUrl: () => props.chatbotUrl,
785
+ appId: () => props.appId,
786
+ appToken: () => props.appToken,
787
+ stopBroadcast: () => stopBroadcastRef.value(),
788
+ registerVoiceMethods: (methods) => {
789
+ if (methods.stopBroadcast) stopBroadcastRef.value = methods.stopBroadcast;
790
+ },
791
+ getCommads: async () => commandManager.value.getCommands(),
792
+ registerCommand: (cmd) => {
793
+ commandManager.value.registerCommand(cmd);
794
+ },
795
+ unregisterCommand: (name) => {
796
+ commandManager.value.unregisterCommand(name);
797
+ },
798
+ async executeCommand(commandName, args = []) {
799
+ return await commandManager.value.executeCommand(commandName, args);
800
+ }
801
+ });
802
+ return (_ctx, _cache) => {
803
+ return renderSlot(_ctx.$slots, "default");
804
+ };
805
+ }
806
+ });
1001
807
 
1002
808
  function useTTS(getVoiceConfig) {
1003
809
  const isSpeaking = ref(false);
@@ -1236,6 +1042,73 @@ function useBubble(options = {}) {
1236
1042
  };
1237
1043
  }
1238
1044
 
1045
+ const ensureMicrophonePermission = async () => {
1046
+ if (typeof navigator === "undefined" || typeof window === "undefined") {
1047
+ console.log("当前环境不支持麦克风访问");
1048
+ return false;
1049
+ }
1050
+ if (!navigator.mediaDevices?.getUserMedia || !navigator.mediaDevices?.enumerateDevices) {
1051
+ console.log("当前环境不支持麦克风访问");
1052
+ return false;
1053
+ }
1054
+ try {
1055
+ const devices = await navigator.mediaDevices.enumerateDevices();
1056
+ const audioInputDevices = devices.filter((device) => device.kind === "audioinput");
1057
+ if (audioInputDevices.length === 0) {
1058
+ console.log("未检测到麦克风设备,请连接麦克风后重试。");
1059
+ return false;
1060
+ }
1061
+ if ("permissions" in navigator && navigator.permissions?.query) {
1062
+ try {
1063
+ const status = await navigator.permissions.query({ name: "microphone" });
1064
+ if (status.state === "denied") {
1065
+ console.log("麦克风权限被禁用,请在浏览器设置中开启。");
1066
+ return false;
1067
+ }
1068
+ } catch (e) {
1069
+ console.warn("Permission query not supported:", e);
1070
+ }
1071
+ }
1072
+ let stream = null;
1073
+ try {
1074
+ stream = await navigator.mediaDevices.getUserMedia({
1075
+ audio: {
1076
+ echoCancellation: true,
1077
+ noiseSuppression: true,
1078
+ autoGainControl: true
1079
+ }
1080
+ });
1081
+ const audioTracks = stream.getAudioTracks();
1082
+ if (audioTracks.length === 0) {
1083
+ console.log("无法获取麦克风音频轨道。");
1084
+ return false;
1085
+ }
1086
+ const activeTrack = audioTracks[0];
1087
+ if (!activeTrack.enabled || activeTrack.readyState !== "live") {
1088
+ console.log("麦克风设备不可用,请检查设备连接。");
1089
+ return false;
1090
+ }
1091
+ return true;
1092
+ } finally {
1093
+ if (stream) {
1094
+ stream.getTracks().forEach((track) => track.stop());
1095
+ }
1096
+ }
1097
+ } catch (error) {
1098
+ console.error("Microphone permission check failed", error);
1099
+ if (error.name === "NotFoundError" || error.name === "DevicesNotFoundError") {
1100
+ console.log("未检测到麦克风设备,请连接麦克风后重试。");
1101
+ } else if (error.name === "NotAllowedError" || error.name === "PermissionDeniedError") {
1102
+ console.log("麦克风权限被拒绝,请在浏览器设置中允许访问。");
1103
+ } else if (error.name === "NotReadableError" || error.name === "TrackStartError") {
1104
+ console.log("麦克风被其他应用占用或无法访问。");
1105
+ } else {
1106
+ console.log("无法访问麦克风,请检查设备连接和浏览器权限。");
1107
+ }
1108
+ return false;
1109
+ }
1110
+ };
1111
+
1239
1112
  function useVoiceRecognition(options) {
1240
1113
  const voiceStatus = ref("standby");
1241
1114
  const isTranscribing = ref(false);
@@ -1461,7 +1334,8 @@ function processUIMessageStreamEvent(payload, callbacks) {
1461
1334
  callbacks.onFinish?.(parsed);
1462
1335
  break;
1463
1336
  case "error":
1464
- callbacks.onError?.(parsed.errorText || parsed.error || "Unknown error");
1337
+ case "tool-output-error":
1338
+ callbacks.onError?.(parsed.errorText || parsed.error || "Unknown error", parsed);
1465
1339
  break;
1466
1340
  case "start":
1467
1341
  case "text-start":
@@ -1720,7 +1594,16 @@ async function parseDataStreamToMessage(response, onUpdate) {
1720
1594
  }
1721
1595
  emitUpdate();
1722
1596
  },
1723
- onError(error) {
1597
+ onError(error, data) {
1598
+ const toolCallId = data?.toolCallId;
1599
+ if (toolCallId) {
1600
+ toolCalls.delete(toolCallId);
1601
+ const idx = findToolPartIndex(toolCallId);
1602
+ if (idx !== -1) {
1603
+ parts.splice(idx, 1);
1604
+ emitUpdate();
1605
+ }
1606
+ }
1724
1607
  console.error("[DataStreamParser] stream error:", error);
1725
1608
  },
1726
1609
  onStepFinish(_data) {
@@ -1790,20 +1673,28 @@ function useAgentInvoke(options) {
1790
1673
  currentToolParts.value = [];
1791
1674
  executingTools.value = /* @__PURE__ */ new Set();
1792
1675
  };
1676
+ const extractExecutableCommands = (payload) => {
1677
+ if (!payload || typeof payload !== "object") return [];
1678
+ const commands = payload.commands;
1679
+ if (!Array.isArray(commands) || commands.length === 0) return [];
1680
+ return commands.filter((cmd) => cmd && typeof cmd === "object" && typeof cmd.name === "string" && cmd.name.trim()).map((cmd) => ({
1681
+ name: cmd.name,
1682
+ args: Array.isArray(cmd.args) ? cmd.args : []
1683
+ }));
1684
+ };
1793
1685
  const executeHostCommands = async (toolCallId, result) => {
1794
- if (!result || typeof result !== "object") return;
1795
- const commands = result.commands;
1796
- if (!Array.isArray(commands) || commands.length === 0) return;
1686
+ const commands = extractExecutableCommands(result);
1687
+ if (commands.length === 0) return false;
1797
1688
  try {
1798
1689
  executingTools.value = /* @__PURE__ */ new Set([...executingTools.value, toolCallId]);
1799
1690
  for (const cmd of commands) {
1800
- const args = Array.isArray(cmd.args) ? cmd.args : [];
1801
1691
  try {
1802
- await aiChatbotX.executeCommand(cmd.name, args);
1692
+ await aiChatbotX.executeCommand(cmd.name, cmd.args);
1803
1693
  } catch (cmdErr) {
1804
1694
  console.error(`[AgentInvoke] 执行命令 ${cmd.name} 失败:`, cmdErr);
1805
1695
  }
1806
1696
  }
1697
+ return true;
1807
1698
  } finally {
1808
1699
  const next = new Set(executingTools.value);
1809
1700
  next.delete(toolCallId);
@@ -1837,8 +1728,9 @@ function useAgentInvoke(options) {
1837
1728
  bubble.open();
1838
1729
  let prevTextLength = 0;
1839
1730
  const processedToolResults = /* @__PURE__ */ new Set();
1731
+ const processingToolResults = /* @__PURE__ */ new Set();
1840
1732
  abortController = new AbortController();
1841
- const commands = await aiChatbotX.hostCommads();
1733
+ const commands = await aiChatbotX.getCommads();
1842
1734
  conversationHistory.value.length > 0 ? [...conversationHistory.value] : void 0;
1843
1735
  try {
1844
1736
  const response = await fetch(options.endpoint.value, {
@@ -1874,7 +1766,8 @@ function useAgentInvoke(options) {
1874
1766
  };
1875
1767
  currentToolParts.value = [...currentToolParts.value, toolPart];
1876
1768
  if (tr.toolName === "executeCommand") {
1877
- executeHostCommands(toolPart.toolCallId, tr.result);
1769
+ console.log("executeCommand", tr.result);
1770
+ void executeHostCommands(toolPart.toolCallId, tr.result);
1878
1771
  }
1879
1772
  }
1880
1773
  }
@@ -1891,13 +1784,23 @@ function useAgentInvoke(options) {
1891
1784
  );
1892
1785
  currentToolParts.value = toolParts;
1893
1786
  for (const part of toolParts) {
1894
- if (part.toolName === "executeCommand" && !processedToolResults.has(part.toolCallId)) {
1787
+ if (part.toolName === "executeCommand" && !processedToolResults.has(part.toolCallId) && !processingToolResults.has(part.toolCallId)) {
1895
1788
  if (part.type === "tool-call" && part.state === "call" && part.args) {
1896
- processedToolResults.add(part.toolCallId);
1897
- executeHostCommands(part.toolCallId, part.args);
1789
+ processingToolResults.add(part.toolCallId);
1790
+ void executeHostCommands(part.toolCallId, part.args).then((executed) => {
1791
+ if (executed) {
1792
+ processedToolResults.add(part.toolCallId);
1793
+ }
1794
+ processingToolResults.delete(part.toolCallId);
1795
+ });
1898
1796
  } else if (part.type === "tool-result" && part.result) {
1899
- processedToolResults.add(part.toolCallId);
1900
- executeHostCommands(part.toolCallId, part.result);
1797
+ processingToolResults.add(part.toolCallId);
1798
+ void executeHostCommands(part.toolCallId, part.result).then((executed) => {
1799
+ if (executed) {
1800
+ processedToolResults.add(part.toolCallId);
1801
+ }
1802
+ processingToolResults.delete(part.toolCallId);
1803
+ });
1901
1804
  }
1902
1805
  }
1903
1806
  }
@@ -2018,11 +1921,7 @@ const _sfc_main = /* @__PURE__ */ defineComponent({
2018
1921
  const aiChatbotX = injectStrict(AiChatbotXKey);
2019
1922
  const getVoiceConfig = () => {
2020
1923
  if (props.voiceConfig) return props.voiceConfig;
2021
- try {
2022
- return aiChatbotX.voiceConfig();
2023
- } catch {
2024
- return null;
2025
- }
1924
+ return null;
2026
1925
  };
2027
1926
  const endpoint = computed(() => {
2028
1927
  return props.invokeUrl || "http://localhost:3001/agent/zyy55sw40nrl801056m0o/stream-invoke";
@@ -2091,12 +1990,7 @@ const _sfc_main = /* @__PURE__ */ defineComponent({
2091
1990
  const { voiceStatus, transcriptionText, wakeAnimating, isTranscribing } = voice;
2092
1991
  const { isInvoking, currentTextContent, currentToolParts, executingTools, hasAnyContent, toolDisplayName } = agent;
2093
1992
  aiChatbotX?.registerVoiceMethods({
2094
- start: () => toggleVoiceMode(true),
2095
- stop: () => toggleVoiceMode(false),
2096
- stopBroadcast: async () => interruptCurrentResponse(),
2097
- openDialog: async () => Promise.resolve(),
2098
- closeDialog: async () => Promise.resolve(),
2099
- toggleCollapse: async () => Promise.resolve()
1993
+ stopBroadcast: async () => interruptCurrentResponse()
2100
1994
  });
2101
1995
  onBeforeUnmount(async () => {
2102
1996
  bubble.destroy();
@@ -2235,7 +2129,18 @@ const _sfc_main = /* @__PURE__ */ defineComponent({
2235
2129
  }
2236
2130
  });
2237
2131
 
2238
- const voiceAssistant = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-77c6ae95"]]);
2132
+ const voiceAssistant = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-fda883a9"]]);
2133
+
2134
+ var clientCommandKey = /* @__PURE__ */ ((clientCommandKey2) => {
2135
+ clientCommandKey2["SET_THEME"] = "SiMeAgent_setTheme";
2136
+ clientCommandKey2["APPEND_MESSAGE"] = "SiMeAgent_appendMessage";
2137
+ clientCommandKey2["WAKE"] = "SiMeAgent_wake";
2138
+ clientCommandKey2["TRANSITION"] = "SiMeAgent_transition";
2139
+ clientCommandKey2["TRANSITION_END"] = "SiMeAgent_transition_end";
2140
+ clientCommandKey2["START_NEW_CONVERSATION"] = "SiMeAgent_startNewConversation";
2141
+ clientCommandKey2["RECOGNITION"] = "SiMeAgent_recognition";
2142
+ return clientCommandKey2;
2143
+ })(clientCommandKey || {});
2239
2144
 
2240
- export { _sfc_main$4 as AiChatbotProvider, voiceAssistant as AiChatbotVoiceAssistant, simeX as AiChatbotX, AiChatbotXKey, clientCommandKey, injectStrict };
2145
+ export { AgentChatTransport, aiChat as AiChat, _sfc_main$1 as AiChatbotProvider, voiceAssistant as AiChatbotVoiceAssistant, AiChatbotXKey, clientCommandKey, createAgentChatTransport, injectStrict };
2241
2146
  //# sourceMappingURL=sime-x-vue.mjs.map