@charivo/core 0.23.0 → 0.24.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 CHANGED
@@ -85,13 +85,114 @@ releases any held expression, without destroying the manager, so it remains
85
85
  reusable. Calling `attachRenderer(newManager)` automatically disconnects the
86
86
  previously-attached manager before wiring the new one.
87
87
 
88
- `userSay(text)` stops any TTS still playing from a previous turn before
89
- generating a response, so — for sequential turns — the new turn's own
90
- audio/expression events can't be undone by the previous turn's speech ending;
91
- overlapping/concurrent `userSay(text)` calls are not serialized and can still
92
- interleave. A failure during that stop doesn't abort the turn — it's
93
- surfaced via `tts:error`, like other non-fatal TTS failures during
94
- `userSay(text)`.
88
+ `userSay(text)` is **latest-wins**: a newer call supersedes the turn still in
89
+ flight, so only the newest turn goes on to speak. It still stops any TTS
90
+ playing from a previous turn before generating a response, so the new turn's
91
+ own audio/expression events can't be undone by the previous turn's speech
92
+ ending. A failure during that stop doesn't abort the turn — it's surfaced via
93
+ `tts:error`, like other non-fatal TTS failures during `userSay(text)`.
94
+
95
+ The superseded call **resolves**; it never rejects, and once superseded it
96
+ does no further work for that turn and emits no further events for it, beyond
97
+ finishing the bookkeeping of its own entry (see Ordering below) and reporting
98
+ the outcome of a tool handler that had already started: that handler's
99
+ `tool:result`/`tool:error` still fires, because it reports work that genuinely
100
+ happened, so `turn:cancelled` is not an event barrier. Projections still stop,
101
+ and no new tool work or request starts.
102
+ `turn:cancelled` (`{ userMessageId }`) fires exactly once for it, and
103
+ supersession by a newer `userSay(text)` is its only cause. What the superseded
104
+ turn leaves behind is its **user message**: it is retained no matter which
105
+ phase the cancellation landed in, always ordered ahead of the superseding
106
+ turn's own message, and from then on it is an ordinary history entry subject
107
+ to normal `maxHistoryTurns` eviction. Input the LLM manager refuses to store —
108
+ empty content, exactly as today — is never stored. The unspoken reply is
109
+ dropped.
110
+
111
+ A reply reaches history only at the **presentation boundary**: after its own
112
+ character message has rendered (immediately, when no renderer is attached) and
113
+ before playback would begin. It commits there even with no TTS manager
114
+ attached — the boundary is presentation, not playback. So a turn superseded
115
+ while generating, while emitting `message:received`/`character:speak`, or
116
+ while rendering its reply never commits that reply, while a reply that is
117
+ already speaking when the next turn arrives stays in history in full.
118
+ (Truncating it to what was actually heard needs word-level playback alignment
119
+ Charivo doesn't have; that's a follow-up, not a guarantee.)
120
+
121
+ Where the history writes happen: a live turn writes its own user message at
122
+ the LLM step — the point where it reads the attached manager and character,
123
+ exactly as today — so a turn that completes or fails without ever reaching an
124
+ attached manager and character writes nothing at all. A turn superseded before
125
+ that point has its message written by the **next** `userSay(text)`, in call
126
+ order, ahead of that turn's own message. `attachLLM(...)` and
127
+ `setCharacter(...)` write no history, so `getHistory()` does not change at
128
+ attachment, and `dispose()` discards whatever is still unwritten.
129
+
130
+ Ordering:
131
+
132
+ - History order is call order, at any reentrancy depth — including a turn
133
+ started synchronously from inside a `message:sent` listener.
134
+ - The `message:sent` carrying an id always precedes any `turn:cancelled`
135
+ carrying that id.
136
+ - A turn superseded during its own entry still emits its `message:sent`, still
137
+ announces its predecessor's cancellation, and still keeps its user message:
138
+ those steps run to completion before the turn checks whether it is still the
139
+ live one.
140
+ - `turn:cancelled` is a per-turn fact, not an ordered log. A listener that
141
+ starts a turn from inside an event can observe an inner turn's cancellation
142
+ before an outer turn's; each superseded turn is still announced exactly once.
143
+ - `message:sent` is now emitted **before** the pre-turn TTS stop rather than
144
+ after it. The stop targets the TTS manager attached when `userSay(text)` was
145
+ called, so a `message:sent` listener that calls `attachTTS(...)` or
146
+ `detachTTS()` does not change which audio is stopped — it governs that
147
+ turn's playback only, exactly as before.
148
+
149
+ Failures on a **live** turn behave as they did, with one deliberate
150
+ divergence:
151
+
152
+ - A generation failure rejects and rolls the turn's user message back,
153
+ restoring what that write evicted at the history bound (unless history has
154
+ been written again meanwhile, which the rollback deliberately doesn't
155
+ undo). It rolls back only the manager the turn actually wrote into, even if
156
+ a different one was attached in the meantime.
157
+ - A failure before the LLM step — a rejected user-message render — has written
158
+ nothing yet, so there is nothing to roll back.
159
+ - A **character-render failure now rejects without committing the reply**,
160
+ where previously the reply was already in history by then. The turn's user
161
+ message stays. This is the one intentional change on the failure paths.
162
+ - Playback failures stay non-fatal: `tts:error`, then resolve, with the
163
+ committed reply left in history.
164
+ - A **superseded** turn never rolls back and never emits an error event on any
165
+ of these paths.
166
+
167
+ A tool handler that has already started runs to completion, and cancellation
168
+ does not undo its side effects. What stops is new work. `Charivo` hands the
169
+ manager a cancellation predicate, and the built-in `@charivo/llm` manager
170
+ checks it in four places: before each further tool call, between a call's
171
+ `tool:call` emission and its handler, before each follow-up request, and on
172
+ every projected emission. A custom `LLMManager` should honor the same four
173
+ checkpoints, since only the manager can enforce them. That is also why
174
+ `tool:call` records an *attempted, dispatched* call, and can be the last event
175
+ for a call whose handler was skipped, while `tool:result`/`tool:error` report
176
+ a handler that actually ran. The superseded turn's in-flight LLM request is
177
+ abandoned but keeps running; request-level `AbortSignal` threading is a
178
+ follow-up. There is
179
+ no guard interval either — a stray duplicate send is indistinguishable from a
180
+ deliberate rapid correction, so debouncing belongs in the input layer.
181
+
182
+ Nothing else cancels a turn: `setCharacter(...)`, `attachLLM(...)`,
183
+ `detachLLM(...)`, `clearHistory()` and `dispose()` neither cancel an in-flight
184
+ turn nor move the point at which a turn reads the manager or the character.
185
+ Message validation is unchanged — `userSay("")` still emits `message:sent`,
186
+ still runs the pre-turn stop and renders the user message, and still rejects
187
+ with `CharivoStateError` from the LLM step (and still resolves when no manager
188
+ and character are attached) — and an empty assistant reply is still stored,
189
+ presented, and spoken exactly as before.
190
+
191
+ The realtime path deliberately keeps the opposite contract:
192
+ `RealtimeManager.sendMessage(...)` rejects while a response is in progress and
193
+ requires an explicit `interrupt()`, because the transport allows one active
194
+ response at a time. The divergence is intentional, not an inconsistency to
195
+ normalize.
95
196
 
96
197
  The current render-manager contract is explicit: a `RenderManager` must expose
97
198
  `setEventBus(eventBus)` and `disconnect()` so the core can connect and cleanly
@@ -196,6 +297,7 @@ Important event names include:
196
297
 
197
298
  - `message:sent`
198
299
  - `message:received`
300
+ - `turn:cancelled`
199
301
  - `character:speak`
200
302
  - `tts:start`
201
303
  - `tts:end`
package/dist/index.cjs CHANGED
@@ -537,6 +537,10 @@ var Charivo = class {
537
537
  realtimeManager;
538
538
  character;
539
539
  isRealtimeMode = false;
540
+ turnEpoch = 0;
541
+ activeTurn;
542
+ turnQueue = [];
543
+ messageSeq = 0;
540
544
  constructor() {
541
545
  this.eventBus = new EventBus();
542
546
  }
@@ -653,83 +657,250 @@ var Charivo = class {
653
657
  }
654
658
  }
655
659
  /**
656
- * Process a user message and generate a character response.
657
- * Orchestrates the full conversation flow: rendering, LLM generation, and TTS playback.
660
+ * Ids are for observability only, so a timestamp plus a per-instance
661
+ * counter is enough: same-millisecond turns no longer collide, which
662
+ * matters because turn:cancelled names its turn by user message id.
658
663
  */
659
- async userSay(content) {
660
- if (this.ttsManager) {
664
+ nextMessageId() {
665
+ this.messageSeq += 1;
666
+ return `${Date.now()}-${this.messageSeq}`;
667
+ }
668
+ /** A turn is live only while it is the newest one. */
669
+ isStale(turn) {
670
+ return this.turnEpoch !== turn.epoch;
671
+ }
672
+ removeQueueEntry(entry) {
673
+ const index = this.turnQueue.indexOf(entry);
674
+ if (index !== -1) {
675
+ this.turnQueue.splice(index, 1);
676
+ }
677
+ }
678
+ /**
679
+ * Head-first drain shared by both flushes, so history order is call order at
680
+ * any reentrancy depth. Both return immediately on an in-progress head.
681
+ *
682
+ * With `requester` null this is flush-superseded: it writes entries whose
683
+ * owner is no longer the active turn, stops at the first entry the active
684
+ * turn owns, and swallows rejections. With a requester it is flush-through:
685
+ * it writes older entries first, then the requester's own entry, recording
686
+ * that write's rollback handle and propagating a rejection of that entry
687
+ * alone.
688
+ */
689
+ writeQueuedEntries(manager, requester) {
690
+ while (this.turnQueue.length > 0) {
691
+ const head = this.turnQueue[0];
692
+ if (head.inProgress) {
693
+ return;
694
+ }
695
+ const isOwnEntry = head.turn === requester;
696
+ if (!isOwnEntry && head.turn === this.activeTurn) {
697
+ return;
698
+ }
699
+ head.inProgress = true;
661
700
  try {
662
- await this.ttsManager.stop();
701
+ const handle = manager.addToHistory(head.message);
702
+ this.removeQueueEntry(head);
703
+ if (isOwnEntry) {
704
+ head.turn.rollback = { manager, handle };
705
+ return;
706
+ }
663
707
  } catch (error) {
664
- const typedError = toCharivoError("provider", error);
665
- this.eventBus.emit("tts:error", { error: typedError });
708
+ this.removeQueueEntry(head);
709
+ if (isOwnEntry) {
710
+ throw error;
711
+ }
666
712
  }
667
713
  }
714
+ }
715
+ /** Entry-block flush: drains the superseded backlog into the live manager. */
716
+ flushSupersededEntries() {
717
+ if (!this.llmManager || !this.character) {
718
+ return;
719
+ }
720
+ this.writeQueuedEntries(this.llmManager, null);
721
+ }
722
+ /**
723
+ * Process a user message and generate a character response.
724
+ * Orchestrates the full conversation flow: rendering, LLM generation, and TTS playback.
725
+ *
726
+ * Latest-wins: a newer call supersedes the in-flight turn, which then
727
+ * resolves without performing any further turn-scoped effect or emitting
728
+ * any further turn-scoped event. Its user message is retained regardless of
729
+ * the phase the supersession lands in.
730
+ */
731
+ async userSay(content) {
668
732
  const userMessage = {
669
- id: Date.now().toString(),
733
+ id: this.nextMessageId(),
670
734
  content,
671
735
  timestamp: /* @__PURE__ */ new Date(),
672
736
  type: "user"
673
737
  };
674
- this.eventBus.emit("message:sent", { message: userMessage });
675
- if (this.renderManager) {
676
- try {
677
- await this.renderManager.render(userMessage);
678
- } catch (error) {
679
- throw toCharivoError("state", error, "Failed to render user message");
738
+ const entryTTSManager = this.ttsManager;
739
+ this.turnEpoch += 1;
740
+ const turn = {
741
+ epoch: this.turnEpoch,
742
+ userMessageId: userMessage.id
743
+ };
744
+ const superseded = this.activeTurn;
745
+ this.activeTurn = turn;
746
+ const entry = { message: userMessage, turn, inProgress: false };
747
+ this.turnQueue.push(entry);
748
+ try {
749
+ this.eventBus.emit("message:sent", { message: userMessage });
750
+ this.flushSupersededEntries();
751
+ if (superseded) {
752
+ this.eventBus.emit("turn:cancelled", {
753
+ userMessageId: superseded.userMessageId
754
+ });
755
+ }
756
+ if (this.isStale(turn)) {
757
+ return;
758
+ }
759
+ if (entryTTSManager) {
760
+ try {
761
+ await entryTTSManager.stop();
762
+ } catch (error) {
763
+ if (this.isStale(turn)) {
764
+ return;
765
+ }
766
+ const typedError = toCharivoError("provider", error);
767
+ this.eventBus.emit("tts:error", { error: typedError });
768
+ }
769
+ if (this.isStale(turn)) {
770
+ return;
771
+ }
680
772
  }
681
- }
682
- if (this.llmManager && this.character) {
683
- const response = await this.llmManager.generateResponse(userMessage).catch(
684
- (error) => Promise.reject(
685
- toCharivoError(
686
- "provider",
687
- error,
688
- "Failed to generate a character response"
689
- )
690
- )
691
- );
692
- const characterMessage = {
693
- id: Date.now().toString() + "_response",
694
- content: response,
695
- timestamp: /* @__PURE__ */ new Date(),
696
- characterId: this.character.id,
697
- type: "character"
698
- };
699
- this.eventBus.emit("message:received", { message: characterMessage });
700
- this.eventBus.emit("character:speak", {
701
- character: this.character,
702
- text: response
703
- });
704
773
  if (this.renderManager) {
705
774
  try {
706
- await this.renderManager.render(characterMessage, this.character);
775
+ await this.renderManager.render(userMessage);
707
776
  } catch (error) {
777
+ if (this.isStale(turn)) {
778
+ return;
779
+ }
780
+ throw toCharivoError("state", error, "Failed to render user message");
781
+ }
782
+ if (this.isStale(turn)) {
783
+ return;
784
+ }
785
+ }
786
+ if (this.llmManager && this.character) {
787
+ const generatingManager = this.llmManager;
788
+ let response;
789
+ try {
790
+ for (; ; ) {
791
+ this.writeQueuedEntries(generatingManager, turn);
792
+ if (!this.turnQueue.includes(entry)) {
793
+ break;
794
+ }
795
+ await Promise.resolve();
796
+ if (this.isStale(turn)) {
797
+ return;
798
+ }
799
+ }
800
+ if (this.isStale(turn)) {
801
+ return;
802
+ }
803
+ response = await generatingManager.generateResponse(userMessage, {
804
+ callerOwnsHistory: true,
805
+ isCancelled: () => this.isStale(turn)
806
+ });
807
+ } catch (error) {
808
+ if (this.isStale(turn)) {
809
+ return;
810
+ }
811
+ turn.rollback?.handle();
708
812
  throw toCharivoError(
709
- "state",
813
+ "provider",
710
814
  error,
711
- "Failed to render character response"
815
+ "Failed to generate a character response"
712
816
  );
713
817
  }
714
- }
715
- if (this.ttsManager) {
818
+ if (this.isStale(turn)) {
819
+ return;
820
+ }
821
+ const characterMessage = {
822
+ id: this.nextMessageId() + "_response",
823
+ content: response,
824
+ timestamp: /* @__PURE__ */ new Date(),
825
+ characterId: this.character.id,
826
+ type: "character"
827
+ };
828
+ this.eventBus.emit("message:received", { message: characterMessage });
829
+ if (this.isStale(turn)) {
830
+ return;
831
+ }
832
+ this.eventBus.emit("character:speak", {
833
+ character: this.character,
834
+ text: response
835
+ });
836
+ if (this.isStale(turn)) {
837
+ return;
838
+ }
839
+ if (this.renderManager) {
840
+ try {
841
+ await this.renderManager.render(characterMessage, this.character);
842
+ } catch (error) {
843
+ if (this.isStale(turn)) {
844
+ return;
845
+ }
846
+ throw toCharivoError(
847
+ "state",
848
+ error,
849
+ "Failed to render character response"
850
+ );
851
+ }
852
+ if (this.isStale(turn)) {
853
+ return;
854
+ }
855
+ }
716
856
  try {
717
- this.eventBus.emit("tts:start", {
718
- text: response,
719
- characterId: this.character.id
720
- });
721
- const ttsOptions = this.character.voice ? {
722
- rate: this.character.voice.rate,
723
- pitch: this.character.voice.pitch,
724
- volume: this.character.voice.volume,
725
- voice: this.character.voice.voiceId
726
- } : void 0;
727
- await this.ttsManager.speak(response, ttsOptions);
728
- this.eventBus.emit("tts:end", { characterId: this.character.id });
857
+ generatingManager.addToHistory(characterMessage);
729
858
  } catch (error) {
730
- const typedError = toCharivoError("provider", error);
731
- this.eventBus.emit("tts:error", { error: typedError });
859
+ if (this.isStale(turn)) {
860
+ return;
861
+ }
862
+ throw toCharivoError(
863
+ "provider",
864
+ error,
865
+ "Failed to generate a character response"
866
+ );
867
+ }
868
+ if (this.isStale(turn)) {
869
+ return;
732
870
  }
871
+ if (this.ttsManager) {
872
+ try {
873
+ this.eventBus.emit("tts:start", {
874
+ text: response,
875
+ characterId: this.character.id
876
+ });
877
+ if (this.isStale(turn)) {
878
+ return;
879
+ }
880
+ const ttsOptions = this.character.voice ? {
881
+ rate: this.character.voice.rate,
882
+ pitch: this.character.voice.pitch,
883
+ volume: this.character.voice.volume,
884
+ voice: this.character.voice.voiceId
885
+ } : void 0;
886
+ await this.ttsManager.speak(response, ttsOptions);
887
+ if (this.isStale(turn)) {
888
+ return;
889
+ }
890
+ this.eventBus.emit("tts:end", { characterId: this.character.id });
891
+ } catch (error) {
892
+ if (this.isStale(turn)) {
893
+ return;
894
+ }
895
+ const typedError = toCharivoError("provider", error);
896
+ this.eventBus.emit("tts:error", { error: typedError });
897
+ }
898
+ }
899
+ }
900
+ } finally {
901
+ if (!this.isStale(turn)) {
902
+ this.removeQueueEntry(entry);
903
+ this.activeTurn = void 0;
733
904
  }
734
905
  }
735
906
  }
@@ -879,6 +1050,7 @@ var Charivo = class {
879
1050
  this.renderManager = void 0;
880
1051
  this.character = void 0;
881
1052
  this.isRealtimeMode = false;
1053
+ this.turnQueue.length = 0;
882
1054
  this.eventBus.clear();
883
1055
  return this.finishDispose(firstError);
884
1056
  }