@charivo/core 0.25.0 → 0.27.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/dist/index.js CHANGED
@@ -1,12 +1,17 @@
1
1
  // src/bus.ts
2
2
  var EventBus = class {
3
- listeners = {};
3
+ // Object.create(null), not {}: EventMap is open to declaration merging, so
4
+ // an augmented event may be named after an Object.prototype member
5
+ // ("constructor", "toString", ...). On a prototype-backed store those keys
6
+ // inherit a truthy value, so `??=` skips the array init and on()/emit()
7
+ // throw. A null-prototype store has no inherited keys.
8
+ listeners = /* @__PURE__ */ Object.create(null);
4
9
  on(event, listener) {
5
10
  this.listeners[event] ??= [];
6
11
  this.listeners[event].push(listener);
7
12
  }
8
13
  emit(event, data) {
9
- this.listeners[event]?.forEach((listener) => {
14
+ [...this.listeners[event] ?? []].forEach((listener) => {
10
15
  try {
11
16
  listener(data);
12
17
  } catch (error) {
@@ -28,7 +33,7 @@ var EventBus = class {
28
33
  }
29
34
  }
30
35
  clear() {
31
- this.listeners = {};
36
+ this.listeners = /* @__PURE__ */ Object.create(null);
32
37
  }
33
38
  };
34
39
 
@@ -525,6 +530,83 @@ function snapshotToolResult(result, toolName, toolLabel = "Tool") {
525
530
  return { serialized, snapshot: parsed };
526
531
  }
527
532
 
533
+ // src/fetch-with-timeout.ts
534
+ var DEFAULT_FETCH_TIMEOUT_MS = 3e4;
535
+ function isAbortError(error) {
536
+ return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
537
+ }
538
+ function fetchWithTimeout(input, init, options, consumeBody) {
539
+ const {
540
+ timeoutMessage,
541
+ failureMessage = "Request failed",
542
+ timeoutMs = DEFAULT_FETCH_TIMEOUT_MS,
543
+ signal,
544
+ mapError
545
+ } = options;
546
+ const controller = new AbortController();
547
+ let abortSource = null;
548
+ const onExternalAbort = () => {
549
+ if (abortSource === null) {
550
+ abortSource = "external";
551
+ }
552
+ controller.abort(signal.reason);
553
+ };
554
+ if (signal?.aborted) {
555
+ abortSource = "external";
556
+ controller.abort(signal.reason);
557
+ } else {
558
+ signal?.addEventListener("abort", onExternalAbort);
559
+ }
560
+ const timeoutId = setTimeout(() => {
561
+ if (abortSource === null) {
562
+ abortSource = "timeout";
563
+ }
564
+ controller.abort();
565
+ }, timeoutMs);
566
+ const cleanup = () => {
567
+ clearTimeout(timeoutId);
568
+ signal?.removeEventListener("abort", onExternalAbort);
569
+ };
570
+ const classifyAbort = (error) => {
571
+ if (abortSource === "external" && (error === signal?.reason || isAbortError(error))) {
572
+ return { matched: true, value: error };
573
+ }
574
+ if (abortSource === "timeout" && isAbortError(error)) {
575
+ return {
576
+ matched: true,
577
+ value: new CharivoTimeoutError(timeoutMessage, { cause: error })
578
+ };
579
+ }
580
+ return { matched: false };
581
+ };
582
+ return fetch(input, { ...init, signal: controller.signal }).then(
583
+ (response) => {
584
+ if (!consumeBody) {
585
+ cleanup();
586
+ return response;
587
+ }
588
+ return Promise.resolve().then(() => consumeBody(response)).then(
589
+ (result) => {
590
+ cleanup();
591
+ return result;
592
+ },
593
+ (error) => {
594
+ cleanup();
595
+ const classified = classifyAbort(error);
596
+ throw classified.matched ? classified.value : error;
597
+ }
598
+ );
599
+ },
600
+ (error) => {
601
+ cleanup();
602
+ const classified = classifyAbort(error);
603
+ throw classified.matched ? classified.value : mapError?.(error) ?? new CharivoTransportError(failureMessage, {
604
+ cause: error instanceof Error ? error : void 0
605
+ });
606
+ }
607
+ );
608
+ }
609
+
528
610
  // src/index.ts
529
611
  var Charivo = class {
530
612
  eventBus;
@@ -663,7 +745,7 @@ var Charivo = class {
663
745
  this.messageSeq += 1;
664
746
  return `${Date.now()}-${this.messageSeq}`;
665
747
  }
666
- /** A turn is live only while it is the newest one. */
748
+ /** A turn is live only while it still owns the current epoch. */
667
749
  isStale(turn) {
668
750
  return this.turnEpoch !== turn.epoch;
669
751
  }
@@ -724,7 +806,11 @@ var Charivo = class {
724
806
  * Latest-wins: a newer call supersedes the in-flight turn, which then
725
807
  * resolves without performing any further turn-scoped effect or emitting
726
808
  * any further turn-scoped event. Its user message is retained regardless of
727
- * the phase the supersession lands in.
809
+ * the phase the supersession lands in. Supersession also aborts the turn's
810
+ * LLM request through the turn's own `AbortSignal`, so a client that honors
811
+ * it stops waiting on the provider; one that ignores it settles late and
812
+ * the turn merely goes quiet once it resumes. {@link Charivo.interrupt}
813
+ * cancels an in-flight turn the same way, without a successor taking over.
728
814
  */
729
815
  async userSay(content) {
730
816
  const userMessage = {
@@ -737,7 +823,8 @@ var Charivo = class {
737
823
  this.turnEpoch += 1;
738
824
  const turn = {
739
825
  epoch: this.turnEpoch,
740
- userMessageId: userMessage.id
826
+ userMessageId: userMessage.id,
827
+ abortController: new AbortController()
741
828
  };
742
829
  const superseded = this.activeTurn;
743
830
  this.activeTurn = turn;
@@ -747,6 +834,7 @@ var Charivo = class {
747
834
  this.eventBus.emit("message:sent", { message: userMessage });
748
835
  this.flushSupersededEntries();
749
836
  if (superseded) {
837
+ superseded.abortController.abort();
750
838
  this.eventBus.emit("turn:cancelled", {
751
839
  userMessageId: superseded.userMessageId
752
840
  });
@@ -800,7 +888,8 @@ var Charivo = class {
800
888
  }
801
889
  response = await generatingManager.generateResponse(userMessage, {
802
890
  callerOwnsHistory: true,
803
- isCancelled: () => this.isStale(turn)
891
+ isCancelled: () => this.isStale(turn),
892
+ signal: turn.abortController.signal
804
893
  });
805
894
  } catch (error) {
806
895
  if (this.isStale(turn)) {
@@ -867,6 +956,7 @@ var Charivo = class {
867
956
  return;
868
957
  }
869
958
  if (this.ttsManager) {
959
+ const speakingManager = this.ttsManager;
870
960
  try {
871
961
  this.eventBus.emit("tts:start", {
872
962
  text: response,
@@ -881,7 +971,8 @@ var Charivo = class {
881
971
  volume: this.character.voice.volume,
882
972
  voice: this.character.voice.voiceId
883
973
  } : void 0;
884
- await this.ttsManager.speak(response, ttsOptions);
974
+ turn.speakingTTSManager = speakingManager;
975
+ await speakingManager.speak(response, ttsOptions);
885
976
  if (this.isStale(turn)) {
886
977
  return;
887
978
  }
@@ -902,6 +993,48 @@ var Charivo = class {
902
993
  }
903
994
  }
904
995
  }
996
+ /**
997
+ * Cut off the in-progress turn and its speech now.
998
+ *
999
+ * The cascade counterpart of `RealtimeManager.interrupt()`: the live turn's
1000
+ * LLM request is aborted, the turn performs and emits nothing further, and
1001
+ * the TTS manager it is speaking on is stopped — the exact manager it handed
1002
+ * the reply to, which a mid-turn `attachTTS()` may since have replaced.
1003
+ * Resolving means that stop has completed, so no audio from the interrupted
1004
+ * turn starts afterwards. The interrupted `userSay()` **resolves**, and the
1005
+ * turn is announced as `turn:cancelled`, exactly as a supersession is.
1006
+ *
1007
+ * Unlike the realtime version, which requires an active, connected session,
1008
+ * this has no precondition: with no turn in flight it still stops the
1009
+ * attached TTS manager, resolves, and emits nothing.
1010
+ *
1011
+ * Realtime mode is not covered — this does not delegate to the realtime
1012
+ * manager. Use `getRealtimeManager()?.interrupt()` there.
1013
+ */
1014
+ async interrupt() {
1015
+ const interrupted = this.activeTurn;
1016
+ if (interrupted) {
1017
+ this.turnEpoch += 1;
1018
+ this.activeTurn = void 0;
1019
+ this.flushSupersededEntries();
1020
+ interrupted.abortController.abort();
1021
+ this.eventBus.emit("turn:cancelled", {
1022
+ userMessageId: interrupted.userMessageId
1023
+ });
1024
+ }
1025
+ const stopTarget = interrupted?.speakingTTSManager ?? this.ttsManager;
1026
+ if (stopTarget) {
1027
+ try {
1028
+ await stopTarget.stop();
1029
+ } catch (error) {
1030
+ throw toCharivoError(
1031
+ "provider",
1032
+ error,
1033
+ "Failed to stop TTS during interrupt"
1034
+ );
1035
+ }
1036
+ }
1037
+ }
905
1038
  /**
906
1039
  * Clear the conversation history from the LLM manager.
907
1040
  */
@@ -934,6 +1067,18 @@ var Charivo = class {
934
1067
  getRenderManager() {
935
1068
  return this.renderManager;
936
1069
  }
1070
+ /**
1071
+ * Get the current TTS manager instance.
1072
+ */
1073
+ getTTSManager() {
1074
+ return this.ttsManager;
1075
+ }
1076
+ /**
1077
+ * Get the current LLM manager instance.
1078
+ */
1079
+ getLLMManager() {
1080
+ return this.llmManager;
1081
+ }
937
1082
  /**
938
1083
  * Attach a Realtime manager to handle real-time conversation.
939
1084
  * Automatically connects the event emitter and enables Realtime mode.
@@ -1058,7 +1203,29 @@ var Charivo = class {
1058
1203
  }
1059
1204
  }
1060
1205
  };
1206
+ function createCharivo(options = {}) {
1207
+ const charivo = new Charivo();
1208
+ if (options.renderer) {
1209
+ charivo.attachRenderer(options.renderer);
1210
+ }
1211
+ if (options.llm) {
1212
+ charivo.attachLLM(options.llm);
1213
+ }
1214
+ if (options.tts) {
1215
+ charivo.attachTTS(options.tts);
1216
+ }
1217
+ if (options.stt) {
1218
+ charivo.attachSTT(options.stt);
1219
+ }
1220
+ if (options.realtime) {
1221
+ charivo.attachRealtime(options.realtime);
1222
+ }
1223
+ if (options.character) {
1224
+ charivo.setCharacter(options.character);
1225
+ }
1226
+ return charivo;
1227
+ }
1061
1228
 
1062
- export { Charivo, CharivoDisposeError, CharivoError, CharivoProviderError, CharivoStateError, CharivoTimeoutError, CharivoTransportError, OPENAI_REALTIME_ADAPTER, OPENAI_REALTIME_AGENTS_ADAPTER, assertToolResultObject, createLipSyncAnalyzer, createToolFailureOutput, createToolRegistry, getErrorMessage, isCharivoError, snapshotToolResult, subscribeBrowserLifecycle, toCharivoError, validateToolArguments, withToolTimeout };
1229
+ export { Charivo, CharivoDisposeError, CharivoError, CharivoProviderError, CharivoStateError, CharivoTimeoutError, CharivoTransportError, DEFAULT_FETCH_TIMEOUT_MS, OPENAI_REALTIME_ADAPTER, OPENAI_REALTIME_AGENTS_ADAPTER, assertToolResultObject, createCharivo, createLipSyncAnalyzer, createToolFailureOutput, createToolRegistry, fetchWithTimeout, getErrorMessage, isCharivoError, snapshotToolResult, subscribeBrowserLifecycle, toCharivoError, validateToolArguments, withToolTimeout };
1063
1230
  //# sourceMappingURL=index.js.map
1064
1231
  //# sourceMappingURL=index.js.map