@dajiaoai/algeo-sdk 2.7.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -6
- package/dist/algeo-sdk.cjs.js +324 -34
- package/dist/algeo-sdk.esm.js +324 -34
- package/dist/algeo-sdk.umd.js +4880 -4590
- package/dist/embedded-editor.d.ts +17 -3
- package/dist/embedded-target.d.ts +3 -2
- package/dist/index.d.ts +1 -1
- package/dist/shared.d.ts +34 -4
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -118,6 +118,7 @@ const editor = await createEditor(document.getElementById('editor-root'), {
|
|
|
118
118
|
algebraPanel: false,
|
|
119
119
|
docPanel: false,
|
|
120
120
|
helpEntry: false,
|
|
121
|
+
aiChatPanel: true,
|
|
121
122
|
},
|
|
122
123
|
});
|
|
123
124
|
|
|
@@ -157,10 +158,39 @@ editor.on('save', async (event) => {
|
|
|
157
158
|
|
|
158
159
|
console.log('用户点击保存按钮且宿主返回成功后的完整内容', event.content);
|
|
159
160
|
});
|
|
161
|
+
|
|
162
|
+
editor.on('aiRequest', async ({ payload, signal }) => {
|
|
163
|
+
// 接入方自行进行后端鉴权
|
|
164
|
+
const response = await fetch('/api/xxxx', {
|
|
165
|
+
method: 'POST',
|
|
166
|
+
credentials: 'include',
|
|
167
|
+
headers: {
|
|
168
|
+
'Content-Type': 'application/json',
|
|
169
|
+
Accept: 'text/event-stream',
|
|
170
|
+
},
|
|
171
|
+
body: JSON.stringify(payload),
|
|
172
|
+
signal,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
if (!response.ok || !response.body) {
|
|
176
|
+
throw new Error(`AI 请求失败:${response.status}`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
await editor.ai.consumeStream({
|
|
180
|
+
stream: response.body,
|
|
181
|
+
signal,
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
editor.on('aiCancel', ({ runId, reason }) => {
|
|
186
|
+
console.log('用户取消 AI 生成', runId, reason);
|
|
187
|
+
});
|
|
160
188
|
```
|
|
161
189
|
|
|
162
190
|
编辑器内嵌页点击保存按钮时,会触发 `editor.on('save', listener)` 的请求阶段监听器。只有宿主返回 `{ status: 'success' }` 后,iframe 才会展示成功态,并向外触发 `save` 的成功阶段事件。
|
|
163
191
|
|
|
192
|
+
开启 `ui.aiChatPanel` 后,iframe 内的 AI 对话请求会通过 `editor.on('aiRequest', listener)` 交给宿主处理。宿主完成登录、权限、额度等业务校验后,将后端返回的大角几何标准 SSE 流传给 `editor.ai.consumeStream()` 即可。
|
|
193
|
+
|
|
164
194
|
如需通过统一入口分发模式,也可以使用 `create`:
|
|
165
195
|
|
|
166
196
|
```javascript
|
|
@@ -261,6 +291,18 @@ type AlgeoCreateOptions =
|
|
|
261
291
|
| `initialContent` | `FileContentLatest` | - | 初始化后自动注入的文件内容 |
|
|
262
292
|
| `ui` | `Partial<AlgeoEditorUiConfig>` | - | 编辑器 UI 开关配置 |
|
|
263
293
|
|
|
294
|
+
**AlgeoEditorUiConfig:**
|
|
295
|
+
|
|
296
|
+
| 属性 | 类型 | 默认值 | 说明 |
|
|
297
|
+
| -------------- | --------- | ------- | -------------------- |
|
|
298
|
+
| `navbar` | `boolean` | - | 是否展示顶部导航栏 |
|
|
299
|
+
| `slidePanel` | `boolean` | - | 是否展示画板列表 |
|
|
300
|
+
| `toolboxPanel` | `boolean` | - | 是否展示工具栏 |
|
|
301
|
+
| `algebraPanel` | `boolean` | - | 是否展示代数面板 |
|
|
302
|
+
| `docPanel` | `boolean` | - | 是否展示文档面板 |
|
|
303
|
+
| `helpEntry` | `boolean` | - | 是否展示帮助入口 |
|
|
304
|
+
| `aiChatPanel` | `boolean` | `false` | 是否展示 AI 对话面板 |
|
|
305
|
+
|
|
264
306
|
**AlgeoPresentationCreateOptions:**
|
|
265
307
|
|
|
266
308
|
| 属性 | 类型 | 默认值 | 说明 |
|
|
@@ -413,6 +455,7 @@ interface FileContent {
|
|
|
413
455
|
| `slides` | `SlidesApi` | 多画板管理能力 |
|
|
414
456
|
| `history` | `HistoryApi` | 历史记录能力 |
|
|
415
457
|
| `mode` | `ModeApi` | 编辑器展示模式控制 |
|
|
458
|
+
| `ai` | `AiApi` | AI 对话流式响应透传能力 |
|
|
416
459
|
|
|
417
460
|
#### `editor.document`
|
|
418
461
|
|
|
@@ -455,16 +498,25 @@ interface FileContent {
|
|
|
455
498
|
| `getUiConfig()` | 获取当前 UI 配置 |
|
|
456
499
|
| `setUiConfig(config)` | 更新 UI 配置 |
|
|
457
500
|
|
|
501
|
+
#### `editor.ai`
|
|
502
|
+
|
|
503
|
+
| 方法 | 说明 |
|
|
504
|
+
| ------------------- | ------------------------------------------------------------------- |
|
|
505
|
+
| `consumeStream()` | 消费接入方后端返回的大角几何标准 SSE 流,并实时转发给 iframe |
|
|
506
|
+
| `pushStreamEvent()` | 高级接口;接入方已自行解析 SSE 或使用非标准传输时,手动推送流式事件 |
|
|
507
|
+
|
|
458
508
|
#### 编辑器事件
|
|
459
509
|
|
|
460
510
|
`editor.on(event, listener)` 当前支持以下事件:
|
|
461
511
|
|
|
462
|
-
| 事件名 | 事件数据 | 说明
|
|
463
|
-
| --------------- | ---------------------------------------------------------- |
|
|
464
|
-
| `ready` | `{ type: 'ready', mode, version }` | iframe 初始化完成
|
|
465
|
-
| `contentChange` | `{ type: 'contentChange', source
|
|
466
|
-
| `slideChange` | `{ type: 'slideChange', index }` | 用户在 iframe 内切换画板后回传当前索引
|
|
467
|
-
| `save` | `{ type: 'save', stage: 'request' \| 'success', content }` | `stage: 'request'` 时用于宿主处理保存,`stage: 'success'` 时表示保存成功后的通知
|
|
512
|
+
| 事件名 | 事件数据 | 说明 |
|
|
513
|
+
| --------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------- |
|
|
514
|
+
| `ready` | `{ type: 'ready', mode, version }` | iframe 初始化完成 |
|
|
515
|
+
| `contentChange` | `{ type: 'contentChange', source, content }` | 用户、AI 或 SDK 加载内容后回传完整 `FileContentLatest` |
|
|
516
|
+
| `slideChange` | `{ type: 'slideChange', index }` | 用户在 iframe 内切换画板后回传当前索引 |
|
|
517
|
+
| `save` | `{ type: 'save', stage: 'request' \| 'success', content }` | `stage: 'request'` 时用于宿主处理保存,`stage: 'success'` 时表示保存成功后的通知 |
|
|
518
|
+
| `aiRequest` | `{ type: 'aiRequest', payload, signal }` | iframe 发起 AI 请求,宿主应调用自有后端并将响应流交给 `editor.ai.consumeStream()` |
|
|
519
|
+
| `aiCancel` | `{ type: 'aiCancel', runId, reason }` | 用户停止生成、新请求替代旧请求或 editor 销毁时触发 |
|
|
468
520
|
|
|
469
521
|
#### 事件与销毁
|
|
470
522
|
|
package/dist/algeo-sdk.cjs.js
CHANGED
|
@@ -1,32 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
// src/embed.ts
|
|
4
|
-
var EMBED_ERROR_CODES = {
|
|
5
|
-
LOAD_SHARE_FAILED: "EMBED_LOAD_SHARE_FAILED",
|
|
6
|
-
LOAD_FILE_FAILED: "EMBED_LOAD_FILE_FAILED",
|
|
7
|
-
APPLY_CONTENT_FAILED: "EMBED_APPLY_CONTENT_FAILED",
|
|
8
|
-
SWITCH_SLIDE_FAILED: "EMBED_SWITCH_SLIDE_FAILED",
|
|
9
|
-
INVALID_SLIDE_INDEX: "EMBED_INVALID_SLIDE_INDEX",
|
|
10
|
-
GET_SLIDE_COUNT_FAILED: "EMBED_GET_SLIDE_COUNT_FAILED",
|
|
11
|
-
INVALID_REPL_COMMAND: "EMBED_INVALID_REPL_COMMAND",
|
|
12
|
-
REPL_EXECUTE_FAILED: "EMBED_REPL_EXECUTE_FAILED",
|
|
13
|
-
UNKNOWN_METHOD: "EMBED_UNKNOWN_METHOD",
|
|
14
|
-
UNKNOWN_ERROR: "EMBED_UNKNOWN_ERROR",
|
|
15
|
-
MISSING_APP_ID: "EMBED_MISSING_APP_ID",
|
|
16
|
-
BAD_REQUEST: "EMBED_BAD_REQUEST",
|
|
17
|
-
IFRAME_NOT_READY: "EMBED_IFRAME_NOT_READY",
|
|
18
|
-
TIMEOUT: "EMBED_TIMEOUT",
|
|
19
|
-
DESTROYED: "EMBED_DESTROYED"
|
|
20
|
-
};
|
|
21
|
-
var AlgeoError = class extends Error {
|
|
22
|
-
constructor(message, code, details) {
|
|
23
|
-
super(message);
|
|
24
|
-
this.code = code;
|
|
25
|
-
this.details = details;
|
|
26
|
-
this.name = "AlgeoError";
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
|
|
30
3
|
var util;
|
|
31
4
|
(function (util) {
|
|
32
5
|
util.assertEqual = (_) => { };
|
|
@@ -3856,7 +3829,7 @@ const unknownType = ZodUnknown.create;
|
|
|
3856
3829
|
ZodNever.create;
|
|
3857
3830
|
const arrayType = ZodArray.create;
|
|
3858
3831
|
const objectType = ZodObject.create;
|
|
3859
|
-
ZodUnion.create;
|
|
3832
|
+
const unionType = ZodUnion.create;
|
|
3860
3833
|
ZodIntersection.create;
|
|
3861
3834
|
const tupleType = ZodTuple.create;
|
|
3862
3835
|
const recordType = ZodRecord.create;
|
|
@@ -3866,6 +3839,66 @@ ZodPromise.create;
|
|
|
3866
3839
|
ZodOptional.create;
|
|
3867
3840
|
ZodNullable.create;
|
|
3868
3841
|
|
|
3842
|
+
// src/embed.ts
|
|
3843
|
+
var EMBED_ERROR_CODES = {
|
|
3844
|
+
LOAD_SHARE_FAILED: "EMBED_LOAD_SHARE_FAILED",
|
|
3845
|
+
LOAD_FILE_FAILED: "EMBED_LOAD_FILE_FAILED",
|
|
3846
|
+
APPLY_CONTENT_FAILED: "EMBED_APPLY_CONTENT_FAILED",
|
|
3847
|
+
SWITCH_SLIDE_FAILED: "EMBED_SWITCH_SLIDE_FAILED",
|
|
3848
|
+
INVALID_SLIDE_INDEX: "EMBED_INVALID_SLIDE_INDEX",
|
|
3849
|
+
GET_SLIDE_COUNT_FAILED: "EMBED_GET_SLIDE_COUNT_FAILED",
|
|
3850
|
+
INVALID_REPL_COMMAND: "EMBED_INVALID_REPL_COMMAND",
|
|
3851
|
+
REPL_EXECUTE_FAILED: "EMBED_REPL_EXECUTE_FAILED",
|
|
3852
|
+
UNKNOWN_METHOD: "EMBED_UNKNOWN_METHOD",
|
|
3853
|
+
UNKNOWN_ERROR: "EMBED_UNKNOWN_ERROR",
|
|
3854
|
+
MISSING_APP_ID: "EMBED_MISSING_APP_ID",
|
|
3855
|
+
BAD_REQUEST: "EMBED_BAD_REQUEST",
|
|
3856
|
+
IFRAME_NOT_READY: "EMBED_IFRAME_NOT_READY",
|
|
3857
|
+
TIMEOUT: "EMBED_TIMEOUT",
|
|
3858
|
+
DESTROYED: "EMBED_DESTROYED"
|
|
3859
|
+
};
|
|
3860
|
+
var AlgeoError = class extends Error {
|
|
3861
|
+
constructor(message, code, details) {
|
|
3862
|
+
super(message);
|
|
3863
|
+
this.code = code;
|
|
3864
|
+
this.details = details;
|
|
3865
|
+
this.name = "AlgeoError";
|
|
3866
|
+
}
|
|
3867
|
+
};
|
|
3868
|
+
var openAiChatMessageV1Schema = objectType({
|
|
3869
|
+
role: stringType(),
|
|
3870
|
+
content: unionType([
|
|
3871
|
+
stringType(),
|
|
3872
|
+
arrayType(
|
|
3873
|
+
objectType({
|
|
3874
|
+
type: stringType()
|
|
3875
|
+
}).passthrough()
|
|
3876
|
+
)
|
|
3877
|
+
]),
|
|
3878
|
+
name: stringType().optional()
|
|
3879
|
+
}).passthrough();
|
|
3880
|
+
objectType({
|
|
3881
|
+
model_id: stringType(),
|
|
3882
|
+
messages: arrayType(unionType([openAiChatMessageV1Schema, recordType(unknownType())])),
|
|
3883
|
+
extra_openai_params: recordType(unknownType()).optional()
|
|
3884
|
+
});
|
|
3885
|
+
objectType({
|
|
3886
|
+
id: stringType(),
|
|
3887
|
+
model: stringType(),
|
|
3888
|
+
call_ids: arrayType(stringType()).optional()
|
|
3889
|
+
});
|
|
3890
|
+
recordType(unknownType());
|
|
3891
|
+
var aiRawSseEventV1Schema = objectType({
|
|
3892
|
+
type: literalType("raw"),
|
|
3893
|
+
runId: stringType(),
|
|
3894
|
+
event: stringType(),
|
|
3895
|
+
data: recordType(unknownType())
|
|
3896
|
+
});
|
|
3897
|
+
var aiStreamEventV1Schema = aiRawSseEventV1Schema;
|
|
3898
|
+
function safeParseAiStreamEventV1(input) {
|
|
3899
|
+
return aiStreamEventV1Schema.safeParse(input);
|
|
3900
|
+
}
|
|
3901
|
+
|
|
3869
3902
|
// src/schema.ts
|
|
3870
3903
|
var shareOptionsSchema = objectType({
|
|
3871
3904
|
showAiTranscript: booleanType().optional(),
|
|
@@ -3978,7 +4011,7 @@ function convertToLatest(content) {
|
|
|
3978
4011
|
}
|
|
3979
4012
|
|
|
3980
4013
|
/** SDK 版本号,构建时由 rollup 注入 */
|
|
3981
|
-
const VERSION = '2.
|
|
4014
|
+
const VERSION = '2.8.0';
|
|
3982
4015
|
const DEFAULT_EMBED_BASE = 'https://dajiaoai.com';
|
|
3983
4016
|
const DEFAULT_PRESENTATION_PATH = '/e';
|
|
3984
4017
|
const DEFAULT_EDITOR_PATH = '/embed/edit';
|
|
@@ -4008,6 +4041,15 @@ function isSaveRequestMessage(msg) {
|
|
|
4008
4041
|
typeof msg.requestId === 'string' &&
|
|
4009
4042
|
typeof msg.content === 'object');
|
|
4010
4043
|
}
|
|
4044
|
+
function isAiRequestMessage(msg) {
|
|
4045
|
+
return (typeof msg === 'object' &&
|
|
4046
|
+
msg !== null &&
|
|
4047
|
+
'type' in msg &&
|
|
4048
|
+
msg.type === 'aiRequest' &&
|
|
4049
|
+
typeof msg.requestId === 'string' &&
|
|
4050
|
+
typeof msg.payload === 'object' &&
|
|
4051
|
+
msg.payload !== null);
|
|
4052
|
+
}
|
|
4011
4053
|
function isEmbedEventMessage(msg) {
|
|
4012
4054
|
if (typeof msg !== 'object' || msg == null || !('type' in msg)) {
|
|
4013
4055
|
return false;
|
|
@@ -4027,6 +4069,12 @@ function isEmbedEventMessage(msg) {
|
|
|
4027
4069
|
if (type === 'contentChange') {
|
|
4028
4070
|
return true;
|
|
4029
4071
|
}
|
|
4072
|
+
if (type === 'aiCancel') {
|
|
4073
|
+
const runId = msg.runId;
|
|
4074
|
+
const reason = msg.reason;
|
|
4075
|
+
return ((runId === null || typeof runId === 'string') &&
|
|
4076
|
+
(reason === 'user' || reason === 'superseded' || reason === 'destroyed'));
|
|
4077
|
+
}
|
|
4030
4078
|
return false;
|
|
4031
4079
|
}
|
|
4032
4080
|
function normalizeBaseUrl(baseUrl) {
|
|
@@ -4198,7 +4246,7 @@ class EmbeddedTarget {
|
|
|
4198
4246
|
pending.reject(new AlgeoError(err?.message ?? '未知错误', err?.code ?? EMBED_ERROR_CODES.UNKNOWN_ERROR, err?.details));
|
|
4199
4247
|
return;
|
|
4200
4248
|
}
|
|
4201
|
-
if (isSaveRequestMessage(data) &&
|
|
4249
|
+
if ((isSaveRequestMessage(data) || isAiRequestMessage(data)) &&
|
|
4202
4250
|
this.handleRequestMessage(data, iframe.contentWindow)) {
|
|
4203
4251
|
return;
|
|
4204
4252
|
}
|
|
@@ -4241,6 +4289,12 @@ class EmbeddedTarget {
|
|
|
4241
4289
|
}, timeoutMs);
|
|
4242
4290
|
});
|
|
4243
4291
|
}
|
|
4292
|
+
postEvent(type, payload = {}) {
|
|
4293
|
+
if (this.destroyed || !this._ready) {
|
|
4294
|
+
return;
|
|
4295
|
+
}
|
|
4296
|
+
this.iframe?.contentWindow?.postMessage({ type, ...payload }, '*');
|
|
4297
|
+
}
|
|
4244
4298
|
async destroy() {
|
|
4245
4299
|
if (this.destroyed) {
|
|
4246
4300
|
return;
|
|
@@ -4413,6 +4467,14 @@ class EmbeddedEditor extends EmbeddedTarget {
|
|
|
4413
4467
|
};
|
|
4414
4468
|
},
|
|
4415
4469
|
};
|
|
4470
|
+
this.ai = {
|
|
4471
|
+
consumeStream: async ({ stream, signal }) => {
|
|
4472
|
+
await this.consumeAiStream(stream, signal);
|
|
4473
|
+
},
|
|
4474
|
+
pushStreamEvent: (event) => {
|
|
4475
|
+
this.pushAiStreamEvent(event);
|
|
4476
|
+
},
|
|
4477
|
+
};
|
|
4416
4478
|
}
|
|
4417
4479
|
async initialize(options = {}, baseUrl) {
|
|
4418
4480
|
if (!options.auth?.appId?.trim()) {
|
|
@@ -4449,16 +4511,29 @@ class EmbeddedEditor extends EmbeddedTarget {
|
|
|
4449
4511
|
this.currentSlideIndex = event.index;
|
|
4450
4512
|
return;
|
|
4451
4513
|
}
|
|
4514
|
+
if (event.type === 'aiCancel') {
|
|
4515
|
+
event.runId = this.activeAiRun?.runId ?? event.runId;
|
|
4516
|
+
this.cancelActiveAi(event.reason, false);
|
|
4517
|
+
return;
|
|
4518
|
+
}
|
|
4452
4519
|
this.currentContent = event.content;
|
|
4453
4520
|
this.slideCount = event.content.slides.length;
|
|
4454
4521
|
this.currentSlideIndex = Math.min(this.currentSlideIndex, Math.max(this.slideCount - 1, 0));
|
|
4455
4522
|
}
|
|
4456
4523
|
handleRequestMessage(message, sourceWindow) {
|
|
4457
|
-
if (message.type
|
|
4458
|
-
|
|
4524
|
+
if (message.type === 'save') {
|
|
4525
|
+
void this.handleSaveRequest(message, sourceWindow);
|
|
4526
|
+
return true;
|
|
4459
4527
|
}
|
|
4460
|
-
|
|
4461
|
-
|
|
4528
|
+
if (message.type === 'aiRequest') {
|
|
4529
|
+
void this.handleAiRequest(message, sourceWindow);
|
|
4530
|
+
return true;
|
|
4531
|
+
}
|
|
4532
|
+
return false;
|
|
4533
|
+
}
|
|
4534
|
+
async destroy() {
|
|
4535
|
+
this.cancelActiveAi('destroyed', true);
|
|
4536
|
+
await super.destroy();
|
|
4462
4537
|
}
|
|
4463
4538
|
async loadContent(content, source) {
|
|
4464
4539
|
await this.post('loadContent', { content });
|
|
@@ -4509,6 +4584,221 @@ class EmbeddedEditor extends EmbeddedTarget {
|
|
|
4509
4584
|
});
|
|
4510
4585
|
}
|
|
4511
4586
|
}
|
|
4587
|
+
async handleAiRequest(message, sourceWindow) {
|
|
4588
|
+
const respond = (payload) => {
|
|
4589
|
+
sourceWindow.postMessage(payload, '*');
|
|
4590
|
+
};
|
|
4591
|
+
const listeners = this.getListeners('aiRequest');
|
|
4592
|
+
if (listeners.length === 0) {
|
|
4593
|
+
respond({
|
|
4594
|
+
type: 'response',
|
|
4595
|
+
requestId: message.requestId,
|
|
4596
|
+
success: false,
|
|
4597
|
+
error: {
|
|
4598
|
+
code: EMBED_ERROR_CODES.BAD_REQUEST,
|
|
4599
|
+
message: '宿主未配置 aiRequest 事件处理器',
|
|
4600
|
+
},
|
|
4601
|
+
});
|
|
4602
|
+
return;
|
|
4603
|
+
}
|
|
4604
|
+
this.cancelActiveAi('superseded', true);
|
|
4605
|
+
const controller = new AbortController();
|
|
4606
|
+
this.activeAiRun = {
|
|
4607
|
+
controller,
|
|
4608
|
+
requestId: message.requestId,
|
|
4609
|
+
runId: null,
|
|
4610
|
+
};
|
|
4611
|
+
const requestEvent = {
|
|
4612
|
+
type: 'aiRequest',
|
|
4613
|
+
payload: message.payload,
|
|
4614
|
+
signal: controller.signal,
|
|
4615
|
+
};
|
|
4616
|
+
try {
|
|
4617
|
+
for (const listener of listeners) {
|
|
4618
|
+
await listener(requestEvent);
|
|
4619
|
+
}
|
|
4620
|
+
if (this.activeAiRun?.requestId === message.requestId) {
|
|
4621
|
+
this.activeAiRun = undefined;
|
|
4622
|
+
}
|
|
4623
|
+
respond({
|
|
4624
|
+
type: 'response',
|
|
4625
|
+
requestId: message.requestId,
|
|
4626
|
+
success: true,
|
|
4627
|
+
result: { success: true },
|
|
4628
|
+
});
|
|
4629
|
+
}
|
|
4630
|
+
catch (error) {
|
|
4631
|
+
if (this.activeAiRun?.requestId === message.requestId) {
|
|
4632
|
+
this.activeAiRun = undefined;
|
|
4633
|
+
}
|
|
4634
|
+
respond({
|
|
4635
|
+
type: 'response',
|
|
4636
|
+
requestId: message.requestId,
|
|
4637
|
+
success: false,
|
|
4638
|
+
error: {
|
|
4639
|
+
code: controller.signal.aborted
|
|
4640
|
+
? EMBED_ERROR_CODES.BAD_REQUEST
|
|
4641
|
+
: EMBED_ERROR_CODES.UNKNOWN_ERROR,
|
|
4642
|
+
message: error instanceof Error ? error.message : String(error),
|
|
4643
|
+
},
|
|
4644
|
+
});
|
|
4645
|
+
}
|
|
4646
|
+
}
|
|
4647
|
+
cancelActiveAi(reason, shouldEmit) {
|
|
4648
|
+
const activeRun = this.activeAiRun;
|
|
4649
|
+
if (!activeRun) {
|
|
4650
|
+
return;
|
|
4651
|
+
}
|
|
4652
|
+
this.activeAiRun = undefined;
|
|
4653
|
+
activeRun.controller.abort();
|
|
4654
|
+
if (shouldEmit) {
|
|
4655
|
+
this.emit('aiCancel', {
|
|
4656
|
+
type: 'aiCancel',
|
|
4657
|
+
runId: activeRun.runId,
|
|
4658
|
+
reason,
|
|
4659
|
+
});
|
|
4660
|
+
}
|
|
4661
|
+
}
|
|
4662
|
+
async consumeAiStream(stream, signal) {
|
|
4663
|
+
const reader = stream.getReader();
|
|
4664
|
+
const decoder = new TextDecoder();
|
|
4665
|
+
let buffer = '';
|
|
4666
|
+
let completed = false;
|
|
4667
|
+
const abortReader = () => {
|
|
4668
|
+
void reader.cancel();
|
|
4669
|
+
};
|
|
4670
|
+
if (signal?.aborted) {
|
|
4671
|
+
await reader.cancel();
|
|
4672
|
+
return;
|
|
4673
|
+
}
|
|
4674
|
+
signal?.addEventListener('abort', abortReader, { once: true });
|
|
4675
|
+
try {
|
|
4676
|
+
while (!completed) {
|
|
4677
|
+
const { done, value } = await reader.read();
|
|
4678
|
+
if (signal?.aborted) {
|
|
4679
|
+
throw new DOMException('AI 请求已取消', 'AbortError');
|
|
4680
|
+
}
|
|
4681
|
+
if (done) {
|
|
4682
|
+
break;
|
|
4683
|
+
}
|
|
4684
|
+
buffer += decoder.decode(value, { stream: true });
|
|
4685
|
+
const result = this.drainAiSseBuffer(buffer);
|
|
4686
|
+
buffer = result.rest;
|
|
4687
|
+
completed = result.completed;
|
|
4688
|
+
}
|
|
4689
|
+
buffer += decoder.decode();
|
|
4690
|
+
if (signal?.aborted) {
|
|
4691
|
+
throw new DOMException('AI 请求已取消', 'AbortError');
|
|
4692
|
+
}
|
|
4693
|
+
if (!completed && buffer.trim()) {
|
|
4694
|
+
completed = this.pushAiSseFrame(buffer);
|
|
4695
|
+
}
|
|
4696
|
+
}
|
|
4697
|
+
finally {
|
|
4698
|
+
signal?.removeEventListener('abort', abortReader);
|
|
4699
|
+
reader.releaseLock();
|
|
4700
|
+
}
|
|
4701
|
+
}
|
|
4702
|
+
drainAiSseBuffer(buffer) {
|
|
4703
|
+
let rest = buffer;
|
|
4704
|
+
let completed = false;
|
|
4705
|
+
while (!completed) {
|
|
4706
|
+
const normalized = rest.replace(/\r\n/g, '\n');
|
|
4707
|
+
const index = normalized.indexOf('\n\n');
|
|
4708
|
+
if (index < 0) {
|
|
4709
|
+
break;
|
|
4710
|
+
}
|
|
4711
|
+
const frame = normalized.slice(0, index);
|
|
4712
|
+
rest = normalized.slice(index + 2);
|
|
4713
|
+
completed = this.pushAiSseFrame(frame);
|
|
4714
|
+
}
|
|
4715
|
+
return { rest, completed };
|
|
4716
|
+
}
|
|
4717
|
+
pushAiSseFrame(frame) {
|
|
4718
|
+
const event = this.parseAiSseFrame(frame);
|
|
4719
|
+
if (!event) {
|
|
4720
|
+
return false;
|
|
4721
|
+
}
|
|
4722
|
+
this.pushAiStreamEvent(event);
|
|
4723
|
+
return this.isAiSseTerminalEvent(event);
|
|
4724
|
+
}
|
|
4725
|
+
parseAiSseFrame(frame) {
|
|
4726
|
+
let eventType = 'message';
|
|
4727
|
+
const dataLines = [];
|
|
4728
|
+
for (const line of frame.split(/\r?\n/)) {
|
|
4729
|
+
if (!line || line.startsWith(':')) {
|
|
4730
|
+
continue;
|
|
4731
|
+
}
|
|
4732
|
+
const separatorIndex = line.indexOf(':');
|
|
4733
|
+
const field = separatorIndex >= 0 ? line.slice(0, separatorIndex) : line;
|
|
4734
|
+
const rawValue = separatorIndex >= 0 ? line.slice(separatorIndex + 1) : '';
|
|
4735
|
+
const value = rawValue.startsWith(' ') ? rawValue.slice(1) : rawValue;
|
|
4736
|
+
if (field === 'event') {
|
|
4737
|
+
eventType = value;
|
|
4738
|
+
}
|
|
4739
|
+
else if (field === 'data') {
|
|
4740
|
+
dataLines.push(value);
|
|
4741
|
+
}
|
|
4742
|
+
}
|
|
4743
|
+
if (dataLines.length === 0) {
|
|
4744
|
+
return null;
|
|
4745
|
+
}
|
|
4746
|
+
const data = JSON.parse(dataLines.join('\n'));
|
|
4747
|
+
return {
|
|
4748
|
+
type: 'raw',
|
|
4749
|
+
runId: this.getAiSseRunId(data),
|
|
4750
|
+
event: eventType,
|
|
4751
|
+
data,
|
|
4752
|
+
};
|
|
4753
|
+
}
|
|
4754
|
+
getAiSseRunId(data) {
|
|
4755
|
+
const response = this.asRecord(data.response);
|
|
4756
|
+
const explicitRunId = data.run_id ?? data.runId;
|
|
4757
|
+
if (typeof explicitRunId === 'string' && explicitRunId) {
|
|
4758
|
+
this.setActiveAiRunId(explicitRunId);
|
|
4759
|
+
return explicitRunId;
|
|
4760
|
+
}
|
|
4761
|
+
if (this.activeAiRun?.runId) {
|
|
4762
|
+
return this.activeAiRun.runId;
|
|
4763
|
+
}
|
|
4764
|
+
if (typeof response?.id === 'string' && response.id) {
|
|
4765
|
+
this.setActiveAiRunId(response.id);
|
|
4766
|
+
return response.id;
|
|
4767
|
+
}
|
|
4768
|
+
const generatedRunId = `run_${Date.now()}`;
|
|
4769
|
+
this.setActiveAiRunId(generatedRunId);
|
|
4770
|
+
return generatedRunId;
|
|
4771
|
+
}
|
|
4772
|
+
asRecord(value) {
|
|
4773
|
+
return value && typeof value === 'object'
|
|
4774
|
+
? value
|
|
4775
|
+
: undefined;
|
|
4776
|
+
}
|
|
4777
|
+
isAiSseTerminalEvent(event) {
|
|
4778
|
+
const type = typeof event.data.type === 'string' ? event.data.type : event.event;
|
|
4779
|
+
return (type === 'response.completed' ||
|
|
4780
|
+
type === 'response.failed' ||
|
|
4781
|
+
type === 'response.incomplete' ||
|
|
4782
|
+
type === 'error' ||
|
|
4783
|
+
type === 'run.cancelled');
|
|
4784
|
+
}
|
|
4785
|
+
pushAiStreamEvent(event) {
|
|
4786
|
+
const parsedEvent = safeParseAiStreamEventV1(event);
|
|
4787
|
+
if (!parsedEvent.success) {
|
|
4788
|
+
throw new AlgeoError('Invalid AI stream event', EMBED_ERROR_CODES.BAD_REQUEST, parsedEvent.error);
|
|
4789
|
+
}
|
|
4790
|
+
const streamEvent = parsedEvent.data;
|
|
4791
|
+
this.setActiveAiRunId(streamEvent.runId);
|
|
4792
|
+
this.postEvent('aiStreamEvent', { event: streamEvent });
|
|
4793
|
+
if (this.isAiSseTerminalEvent(streamEvent)) {
|
|
4794
|
+
this.activeAiRun = undefined;
|
|
4795
|
+
}
|
|
4796
|
+
}
|
|
4797
|
+
setActiveAiRunId(runId) {
|
|
4798
|
+
if (this.activeAiRun) {
|
|
4799
|
+
this.activeAiRun.runId = runId;
|
|
4800
|
+
}
|
|
4801
|
+
}
|
|
4512
4802
|
async resolveSaveResult(content) {
|
|
4513
4803
|
const requestEvent = {
|
|
4514
4804
|
type: 'save',
|