@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.
@@ -1,30 +1,3 @@
1
- // src/embed.ts
2
- var EMBED_ERROR_CODES = {
3
- LOAD_SHARE_FAILED: "EMBED_LOAD_SHARE_FAILED",
4
- LOAD_FILE_FAILED: "EMBED_LOAD_FILE_FAILED",
5
- APPLY_CONTENT_FAILED: "EMBED_APPLY_CONTENT_FAILED",
6
- SWITCH_SLIDE_FAILED: "EMBED_SWITCH_SLIDE_FAILED",
7
- INVALID_SLIDE_INDEX: "EMBED_INVALID_SLIDE_INDEX",
8
- GET_SLIDE_COUNT_FAILED: "EMBED_GET_SLIDE_COUNT_FAILED",
9
- INVALID_REPL_COMMAND: "EMBED_INVALID_REPL_COMMAND",
10
- REPL_EXECUTE_FAILED: "EMBED_REPL_EXECUTE_FAILED",
11
- UNKNOWN_METHOD: "EMBED_UNKNOWN_METHOD",
12
- UNKNOWN_ERROR: "EMBED_UNKNOWN_ERROR",
13
- MISSING_APP_ID: "EMBED_MISSING_APP_ID",
14
- BAD_REQUEST: "EMBED_BAD_REQUEST",
15
- IFRAME_NOT_READY: "EMBED_IFRAME_NOT_READY",
16
- TIMEOUT: "EMBED_TIMEOUT",
17
- DESTROYED: "EMBED_DESTROYED"
18
- };
19
- var AlgeoError = class extends Error {
20
- constructor(message, code, details) {
21
- super(message);
22
- this.code = code;
23
- this.details = details;
24
- this.name = "AlgeoError";
25
- }
26
- };
27
-
28
1
  var util;
29
2
  (function (util) {
30
3
  util.assertEqual = (_) => { };
@@ -3854,7 +3827,7 @@ const unknownType = ZodUnknown.create;
3854
3827
  ZodNever.create;
3855
3828
  const arrayType = ZodArray.create;
3856
3829
  const objectType = ZodObject.create;
3857
- ZodUnion.create;
3830
+ const unionType = ZodUnion.create;
3858
3831
  ZodIntersection.create;
3859
3832
  const tupleType = ZodTuple.create;
3860
3833
  const recordType = ZodRecord.create;
@@ -3864,6 +3837,66 @@ ZodPromise.create;
3864
3837
  ZodOptional.create;
3865
3838
  ZodNullable.create;
3866
3839
 
3840
+ // src/embed.ts
3841
+ var EMBED_ERROR_CODES = {
3842
+ LOAD_SHARE_FAILED: "EMBED_LOAD_SHARE_FAILED",
3843
+ LOAD_FILE_FAILED: "EMBED_LOAD_FILE_FAILED",
3844
+ APPLY_CONTENT_FAILED: "EMBED_APPLY_CONTENT_FAILED",
3845
+ SWITCH_SLIDE_FAILED: "EMBED_SWITCH_SLIDE_FAILED",
3846
+ INVALID_SLIDE_INDEX: "EMBED_INVALID_SLIDE_INDEX",
3847
+ GET_SLIDE_COUNT_FAILED: "EMBED_GET_SLIDE_COUNT_FAILED",
3848
+ INVALID_REPL_COMMAND: "EMBED_INVALID_REPL_COMMAND",
3849
+ REPL_EXECUTE_FAILED: "EMBED_REPL_EXECUTE_FAILED",
3850
+ UNKNOWN_METHOD: "EMBED_UNKNOWN_METHOD",
3851
+ UNKNOWN_ERROR: "EMBED_UNKNOWN_ERROR",
3852
+ MISSING_APP_ID: "EMBED_MISSING_APP_ID",
3853
+ BAD_REQUEST: "EMBED_BAD_REQUEST",
3854
+ IFRAME_NOT_READY: "EMBED_IFRAME_NOT_READY",
3855
+ TIMEOUT: "EMBED_TIMEOUT",
3856
+ DESTROYED: "EMBED_DESTROYED"
3857
+ };
3858
+ var AlgeoError = class extends Error {
3859
+ constructor(message, code, details) {
3860
+ super(message);
3861
+ this.code = code;
3862
+ this.details = details;
3863
+ this.name = "AlgeoError";
3864
+ }
3865
+ };
3866
+ var openAiChatMessageV1Schema = objectType({
3867
+ role: stringType(),
3868
+ content: unionType([
3869
+ stringType(),
3870
+ arrayType(
3871
+ objectType({
3872
+ type: stringType()
3873
+ }).passthrough()
3874
+ )
3875
+ ]),
3876
+ name: stringType().optional()
3877
+ }).passthrough();
3878
+ objectType({
3879
+ model_id: stringType(),
3880
+ messages: arrayType(unionType([openAiChatMessageV1Schema, recordType(unknownType())])),
3881
+ extra_openai_params: recordType(unknownType()).optional()
3882
+ });
3883
+ objectType({
3884
+ id: stringType(),
3885
+ model: stringType(),
3886
+ call_ids: arrayType(stringType()).optional()
3887
+ });
3888
+ recordType(unknownType());
3889
+ var aiRawSseEventV1Schema = objectType({
3890
+ type: literalType("raw"),
3891
+ runId: stringType(),
3892
+ event: stringType(),
3893
+ data: recordType(unknownType())
3894
+ });
3895
+ var aiStreamEventV1Schema = aiRawSseEventV1Schema;
3896
+ function safeParseAiStreamEventV1(input) {
3897
+ return aiStreamEventV1Schema.safeParse(input);
3898
+ }
3899
+
3867
3900
  // src/schema.ts
3868
3901
  var shareOptionsSchema = objectType({
3869
3902
  showAiTranscript: booleanType().optional(),
@@ -3976,7 +4009,7 @@ function convertToLatest(content) {
3976
4009
  }
3977
4010
 
3978
4011
  /** SDK 版本号,构建时由 rollup 注入 */
3979
- const VERSION = '2.7.0';
4012
+ const VERSION = '2.8.0';
3980
4013
  const DEFAULT_EMBED_BASE = 'https://dajiaoai.com';
3981
4014
  const DEFAULT_PRESENTATION_PATH = '/e';
3982
4015
  const DEFAULT_EDITOR_PATH = '/embed/edit';
@@ -4006,6 +4039,15 @@ function isSaveRequestMessage(msg) {
4006
4039
  typeof msg.requestId === 'string' &&
4007
4040
  typeof msg.content === 'object');
4008
4041
  }
4042
+ function isAiRequestMessage(msg) {
4043
+ return (typeof msg === 'object' &&
4044
+ msg !== null &&
4045
+ 'type' in msg &&
4046
+ msg.type === 'aiRequest' &&
4047
+ typeof msg.requestId === 'string' &&
4048
+ typeof msg.payload === 'object' &&
4049
+ msg.payload !== null);
4050
+ }
4009
4051
  function isEmbedEventMessage(msg) {
4010
4052
  if (typeof msg !== 'object' || msg == null || !('type' in msg)) {
4011
4053
  return false;
@@ -4025,6 +4067,12 @@ function isEmbedEventMessage(msg) {
4025
4067
  if (type === 'contentChange') {
4026
4068
  return true;
4027
4069
  }
4070
+ if (type === 'aiCancel') {
4071
+ const runId = msg.runId;
4072
+ const reason = msg.reason;
4073
+ return ((runId === null || typeof runId === 'string') &&
4074
+ (reason === 'user' || reason === 'superseded' || reason === 'destroyed'));
4075
+ }
4028
4076
  return false;
4029
4077
  }
4030
4078
  function normalizeBaseUrl(baseUrl) {
@@ -4196,7 +4244,7 @@ class EmbeddedTarget {
4196
4244
  pending.reject(new AlgeoError(err?.message ?? '未知错误', err?.code ?? EMBED_ERROR_CODES.UNKNOWN_ERROR, err?.details));
4197
4245
  return;
4198
4246
  }
4199
- if (isSaveRequestMessage(data) &&
4247
+ if ((isSaveRequestMessage(data) || isAiRequestMessage(data)) &&
4200
4248
  this.handleRequestMessage(data, iframe.contentWindow)) {
4201
4249
  return;
4202
4250
  }
@@ -4239,6 +4287,12 @@ class EmbeddedTarget {
4239
4287
  }, timeoutMs);
4240
4288
  });
4241
4289
  }
4290
+ postEvent(type, payload = {}) {
4291
+ if (this.destroyed || !this._ready) {
4292
+ return;
4293
+ }
4294
+ this.iframe?.contentWindow?.postMessage({ type, ...payload }, '*');
4295
+ }
4242
4296
  async destroy() {
4243
4297
  if (this.destroyed) {
4244
4298
  return;
@@ -4411,6 +4465,14 @@ class EmbeddedEditor extends EmbeddedTarget {
4411
4465
  };
4412
4466
  },
4413
4467
  };
4468
+ this.ai = {
4469
+ consumeStream: async ({ stream, signal }) => {
4470
+ await this.consumeAiStream(stream, signal);
4471
+ },
4472
+ pushStreamEvent: (event) => {
4473
+ this.pushAiStreamEvent(event);
4474
+ },
4475
+ };
4414
4476
  }
4415
4477
  async initialize(options = {}, baseUrl) {
4416
4478
  if (!options.auth?.appId?.trim()) {
@@ -4447,16 +4509,29 @@ class EmbeddedEditor extends EmbeddedTarget {
4447
4509
  this.currentSlideIndex = event.index;
4448
4510
  return;
4449
4511
  }
4512
+ if (event.type === 'aiCancel') {
4513
+ event.runId = this.activeAiRun?.runId ?? event.runId;
4514
+ this.cancelActiveAi(event.reason, false);
4515
+ return;
4516
+ }
4450
4517
  this.currentContent = event.content;
4451
4518
  this.slideCount = event.content.slides.length;
4452
4519
  this.currentSlideIndex = Math.min(this.currentSlideIndex, Math.max(this.slideCount - 1, 0));
4453
4520
  }
4454
4521
  handleRequestMessage(message, sourceWindow) {
4455
- if (message.type !== 'save') {
4456
- return false;
4522
+ if (message.type === 'save') {
4523
+ void this.handleSaveRequest(message, sourceWindow);
4524
+ return true;
4457
4525
  }
4458
- void this.handleSaveRequest(message, sourceWindow);
4459
- return true;
4526
+ if (message.type === 'aiRequest') {
4527
+ void this.handleAiRequest(message, sourceWindow);
4528
+ return true;
4529
+ }
4530
+ return false;
4531
+ }
4532
+ async destroy() {
4533
+ this.cancelActiveAi('destroyed', true);
4534
+ await super.destroy();
4460
4535
  }
4461
4536
  async loadContent(content, source) {
4462
4537
  await this.post('loadContent', { content });
@@ -4507,6 +4582,221 @@ class EmbeddedEditor extends EmbeddedTarget {
4507
4582
  });
4508
4583
  }
4509
4584
  }
4585
+ async handleAiRequest(message, sourceWindow) {
4586
+ const respond = (payload) => {
4587
+ sourceWindow.postMessage(payload, '*');
4588
+ };
4589
+ const listeners = this.getListeners('aiRequest');
4590
+ if (listeners.length === 0) {
4591
+ respond({
4592
+ type: 'response',
4593
+ requestId: message.requestId,
4594
+ success: false,
4595
+ error: {
4596
+ code: EMBED_ERROR_CODES.BAD_REQUEST,
4597
+ message: '宿主未配置 aiRequest 事件处理器',
4598
+ },
4599
+ });
4600
+ return;
4601
+ }
4602
+ this.cancelActiveAi('superseded', true);
4603
+ const controller = new AbortController();
4604
+ this.activeAiRun = {
4605
+ controller,
4606
+ requestId: message.requestId,
4607
+ runId: null,
4608
+ };
4609
+ const requestEvent = {
4610
+ type: 'aiRequest',
4611
+ payload: message.payload,
4612
+ signal: controller.signal,
4613
+ };
4614
+ try {
4615
+ for (const listener of listeners) {
4616
+ await listener(requestEvent);
4617
+ }
4618
+ if (this.activeAiRun?.requestId === message.requestId) {
4619
+ this.activeAiRun = undefined;
4620
+ }
4621
+ respond({
4622
+ type: 'response',
4623
+ requestId: message.requestId,
4624
+ success: true,
4625
+ result: { success: true },
4626
+ });
4627
+ }
4628
+ catch (error) {
4629
+ if (this.activeAiRun?.requestId === message.requestId) {
4630
+ this.activeAiRun = undefined;
4631
+ }
4632
+ respond({
4633
+ type: 'response',
4634
+ requestId: message.requestId,
4635
+ success: false,
4636
+ error: {
4637
+ code: controller.signal.aborted
4638
+ ? EMBED_ERROR_CODES.BAD_REQUEST
4639
+ : EMBED_ERROR_CODES.UNKNOWN_ERROR,
4640
+ message: error instanceof Error ? error.message : String(error),
4641
+ },
4642
+ });
4643
+ }
4644
+ }
4645
+ cancelActiveAi(reason, shouldEmit) {
4646
+ const activeRun = this.activeAiRun;
4647
+ if (!activeRun) {
4648
+ return;
4649
+ }
4650
+ this.activeAiRun = undefined;
4651
+ activeRun.controller.abort();
4652
+ if (shouldEmit) {
4653
+ this.emit('aiCancel', {
4654
+ type: 'aiCancel',
4655
+ runId: activeRun.runId,
4656
+ reason,
4657
+ });
4658
+ }
4659
+ }
4660
+ async consumeAiStream(stream, signal) {
4661
+ const reader = stream.getReader();
4662
+ const decoder = new TextDecoder();
4663
+ let buffer = '';
4664
+ let completed = false;
4665
+ const abortReader = () => {
4666
+ void reader.cancel();
4667
+ };
4668
+ if (signal?.aborted) {
4669
+ await reader.cancel();
4670
+ return;
4671
+ }
4672
+ signal?.addEventListener('abort', abortReader, { once: true });
4673
+ try {
4674
+ while (!completed) {
4675
+ const { done, value } = await reader.read();
4676
+ if (signal?.aborted) {
4677
+ throw new DOMException('AI 请求已取消', 'AbortError');
4678
+ }
4679
+ if (done) {
4680
+ break;
4681
+ }
4682
+ buffer += decoder.decode(value, { stream: true });
4683
+ const result = this.drainAiSseBuffer(buffer);
4684
+ buffer = result.rest;
4685
+ completed = result.completed;
4686
+ }
4687
+ buffer += decoder.decode();
4688
+ if (signal?.aborted) {
4689
+ throw new DOMException('AI 请求已取消', 'AbortError');
4690
+ }
4691
+ if (!completed && buffer.trim()) {
4692
+ completed = this.pushAiSseFrame(buffer);
4693
+ }
4694
+ }
4695
+ finally {
4696
+ signal?.removeEventListener('abort', abortReader);
4697
+ reader.releaseLock();
4698
+ }
4699
+ }
4700
+ drainAiSseBuffer(buffer) {
4701
+ let rest = buffer;
4702
+ let completed = false;
4703
+ while (!completed) {
4704
+ const normalized = rest.replace(/\r\n/g, '\n');
4705
+ const index = normalized.indexOf('\n\n');
4706
+ if (index < 0) {
4707
+ break;
4708
+ }
4709
+ const frame = normalized.slice(0, index);
4710
+ rest = normalized.slice(index + 2);
4711
+ completed = this.pushAiSseFrame(frame);
4712
+ }
4713
+ return { rest, completed };
4714
+ }
4715
+ pushAiSseFrame(frame) {
4716
+ const event = this.parseAiSseFrame(frame);
4717
+ if (!event) {
4718
+ return false;
4719
+ }
4720
+ this.pushAiStreamEvent(event);
4721
+ return this.isAiSseTerminalEvent(event);
4722
+ }
4723
+ parseAiSseFrame(frame) {
4724
+ let eventType = 'message';
4725
+ const dataLines = [];
4726
+ for (const line of frame.split(/\r?\n/)) {
4727
+ if (!line || line.startsWith(':')) {
4728
+ continue;
4729
+ }
4730
+ const separatorIndex = line.indexOf(':');
4731
+ const field = separatorIndex >= 0 ? line.slice(0, separatorIndex) : line;
4732
+ const rawValue = separatorIndex >= 0 ? line.slice(separatorIndex + 1) : '';
4733
+ const value = rawValue.startsWith(' ') ? rawValue.slice(1) : rawValue;
4734
+ if (field === 'event') {
4735
+ eventType = value;
4736
+ }
4737
+ else if (field === 'data') {
4738
+ dataLines.push(value);
4739
+ }
4740
+ }
4741
+ if (dataLines.length === 0) {
4742
+ return null;
4743
+ }
4744
+ const data = JSON.parse(dataLines.join('\n'));
4745
+ return {
4746
+ type: 'raw',
4747
+ runId: this.getAiSseRunId(data),
4748
+ event: eventType,
4749
+ data,
4750
+ };
4751
+ }
4752
+ getAiSseRunId(data) {
4753
+ const response = this.asRecord(data.response);
4754
+ const explicitRunId = data.run_id ?? data.runId;
4755
+ if (typeof explicitRunId === 'string' && explicitRunId) {
4756
+ this.setActiveAiRunId(explicitRunId);
4757
+ return explicitRunId;
4758
+ }
4759
+ if (this.activeAiRun?.runId) {
4760
+ return this.activeAiRun.runId;
4761
+ }
4762
+ if (typeof response?.id === 'string' && response.id) {
4763
+ this.setActiveAiRunId(response.id);
4764
+ return response.id;
4765
+ }
4766
+ const generatedRunId = `run_${Date.now()}`;
4767
+ this.setActiveAiRunId(generatedRunId);
4768
+ return generatedRunId;
4769
+ }
4770
+ asRecord(value) {
4771
+ return value && typeof value === 'object'
4772
+ ? value
4773
+ : undefined;
4774
+ }
4775
+ isAiSseTerminalEvent(event) {
4776
+ const type = typeof event.data.type === 'string' ? event.data.type : event.event;
4777
+ return (type === 'response.completed' ||
4778
+ type === 'response.failed' ||
4779
+ type === 'response.incomplete' ||
4780
+ type === 'error' ||
4781
+ type === 'run.cancelled');
4782
+ }
4783
+ pushAiStreamEvent(event) {
4784
+ const parsedEvent = safeParseAiStreamEventV1(event);
4785
+ if (!parsedEvent.success) {
4786
+ throw new AlgeoError('Invalid AI stream event', EMBED_ERROR_CODES.BAD_REQUEST, parsedEvent.error);
4787
+ }
4788
+ const streamEvent = parsedEvent.data;
4789
+ this.setActiveAiRunId(streamEvent.runId);
4790
+ this.postEvent('aiStreamEvent', { event: streamEvent });
4791
+ if (this.isAiSseTerminalEvent(streamEvent)) {
4792
+ this.activeAiRun = undefined;
4793
+ }
4794
+ }
4795
+ setActiveAiRunId(runId) {
4796
+ if (this.activeAiRun) {
4797
+ this.activeAiRun.runId = runId;
4798
+ }
4799
+ }
4510
4800
  async resolveSaveResult(content) {
4511
4801
  const requestEvent = {
4512
4802
  type: 'save',