@vellumai/assistant 0.10.8-dev.202607151848.d3cec7b → 0.10.8-dev.202607151931.db21e87

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.8-dev.202607151848.d3cec7b",
3
+ "version": "0.10.8-dev.202607151931.db21e87",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -39,6 +39,7 @@ import {
39
39
  getCachedUserTools,
40
40
  getUserHooksFor,
41
41
  populateCacheAtBoot,
42
+ reconcilePluginSourcesNow,
42
43
  resetPluginCacheForTests,
43
44
  } from "../plugins/mtime-cache.js";
44
45
  import { getSourceVersionsPath } from "../plugins/source-versions.js";
@@ -721,6 +722,66 @@ describe("plugin runtime activation", () => {
721
722
  ).toBe(true);
722
723
  });
723
724
 
725
+ test("reconcilePluginSourcesNow brings a freshly installed plugin up immediately, without the sentinel", async () => {
726
+ await populateCacheAtBoot(); // empty plugins dir
727
+ expect(getAllToolDefinitions().some((t) => t.name === "eager-tool")).toBe(
728
+ false,
729
+ );
730
+
731
+ const dir = freshPluginDir("eager-plugin");
732
+ writePackageJson(dir, { ...SIMPLE_PKG, name: "eager-plugin" });
733
+ writeTool(dir, "eager-tool", TOOL_SRC("eager-tool"));
734
+ const initMarker = join(ROOT, "eager-init.log");
735
+ writeMarkerHook(dir, "init", initMarker, "init");
736
+
737
+ // Deliberately do NOT publish through the watcher and do NOT dispatch a
738
+ // hook — this is the imperative install path: the plugin's files land on
739
+ // disk and the daemon is told to bring it up right now.
740
+ await reconcilePluginSourcesNow();
741
+ await loadPluginTools();
742
+
743
+ expect(getAllToolDefinitions().some((t) => t.name === "eager-tool")).toBe(
744
+ true,
745
+ );
746
+ // init ran exactly once, as part of the reconcile — not at a later turn.
747
+ expect(readFileSync(initMarker, "utf8").trim().split("\n")).toHaveLength(1);
748
+
749
+ // Calling it again (e.g. the monitor's later sentinel publish, or a
750
+ // redundant poke) is a no-op — the plugin is already up.
751
+ await reconcilePluginSourcesNow();
752
+ expect(readFileSync(initMarker, "utf8").trim().split("\n")).toHaveLength(1);
753
+ });
754
+
755
+ test("reconcilePluginSourcesNow deactivates a removed plugin without re-running shutdown", async () => {
756
+ await populateCacheAtBoot(); // empty plugins dir
757
+
758
+ const dir = freshPluginDir("teardown-plugin");
759
+ writePackageJson(dir, { ...SIMPLE_PKG, name: "teardown-plugin" });
760
+ writeTool(dir, "teardown-tool", TOOL_SRC("teardown-tool"));
761
+ const shutdownMarker = join(ROOT, "teardown-shutdown.log");
762
+ writeMarkerHook(dir, "shutdown", shutdownMarker, "bye");
763
+
764
+ await reconcilePluginSourcesNow();
765
+ await loadPluginTools();
766
+ expect(
767
+ getAllToolDefinitions().some((t) => t.name === "teardown-tool"),
768
+ ).toBe(true);
769
+
770
+ // This is the daemon uninstall route's teardown path: the managed uninstall
771
+ // runs `shutdown` itself (while the files are present) and removes the
772
+ // directory, then reconciles. The reconcile here only mirrors the removal —
773
+ // it drops the plugin's tools/hooks but must NOT run `shutdown` a second
774
+ // time (the removal reason carries no shutdown).
775
+ rmSync(dir, { recursive: true, force: true });
776
+ await reconcilePluginSourcesNow();
777
+ await loadPluginTools();
778
+
779
+ expect(
780
+ getAllToolDefinitions().some((t) => t.name === "teardown-tool"),
781
+ ).toBe(false);
782
+ expect(existsSync(shutdownMarker)).toBe(false);
783
+ });
784
+
724
785
  test("activation is idempotent — republishing without changes does not re-run init", async () => {
725
786
  const dir = freshPluginDir("idem-plugin");
726
787
  writePackageJson(dir, { ...SIMPLE_PKG, name: "idem-plugin" });
@@ -10,6 +10,7 @@ import { createRequire } from "node:module";
10
10
 
11
11
  import type { Command } from "commander";
12
12
 
13
+ import { cliIpcCall } from "../../ipc/cli-client.js";
13
14
  import { yellow } from "../lib/cli-colors.js";
14
15
  import { applyCommandHelp, subcommand } from "../lib/cli-command-help.js";
15
16
  import { confirmPrompt } from "../lib/confirm-prompt.js";
@@ -569,7 +570,32 @@ export function registerPluginsCommand(program: Command): void {
569
570
  return;
570
571
  }
571
572
  }
572
- const result = await libs.uninstall.uninstallPlugin({ name });
573
+ // Prefer the daemon: it runs the plugin's `shutdown` hook and drops
574
+ // the plugin's tools/hooks in the main process — symmetric to how
575
+ // install runs `init` there. Fall back to a local uninstall only
576
+ // when the daemon is unreachable (a transport error carries no
577
+ // `statusCode`); an operator can still uninstall while it's stopped,
578
+ // and `shutdown` then runs in this process, the only one available.
579
+ const daemon = await cliIpcCall<{ name: string; target: string }>(
580
+ "plugins_uninstall",
581
+ { pathParams: { name } },
582
+ );
583
+ let result: { name: string; target: string };
584
+ if (daemon.ok && daemon.result) {
585
+ result = daemon.result;
586
+ } else if (daemon.statusCode === undefined) {
587
+ log.debug(
588
+ { name, error: daemon.error },
589
+ "uninstall could not reach the daemon; running shutdown + removal locally",
590
+ );
591
+ result = await libs.uninstall.uninstallPlugin({ name });
592
+ } else {
593
+ // The daemon reached a decision (not installed, bad name, …);
594
+ // surface it rather than silently retrying locally.
595
+ console.error(daemon.error ?? "Plugin uninstall failed.");
596
+ process.exitCode = 1;
597
+ return;
598
+ }
573
599
  log.info(
574
600
  { name: result.name, target: result.target },
575
601
  "external plugin uninstalled",
@@ -408,6 +408,20 @@
408
408
  "license": "MIT",
409
409
  "icon": "🧪"
410
410
  },
411
+ {
412
+ "name": "virlo",
413
+ "source": {
414
+ "source": "github",
415
+ "repo": "Virlo-AI/virlo-integrations",
416
+ "path": "integrations/vellum",
417
+ "ref": "e398cfd8a48316b9378e08efe4b42ad3dc42197e"
418
+ },
419
+ "description": "Real-time short-form video intelligence across TikTok, YouTube Shorts, and Instagram Reels, powered by Virlo Content Research Agents.",
420
+ "category": "marketing",
421
+ "homepage": "https://github.com/Virlo-AI/virlo-integrations/tree/main/integrations/vellum",
422
+ "license": "MIT",
423
+ "icon": "📱"
424
+ },
411
425
  {
412
426
  "name": "writing-coach",
413
427
  "source": {
@@ -417,8 +417,8 @@ describe("LiveVoiceSession server VAD", () => {
417
417
  await waitFor(() => releaseDeltaSend !== undefined);
418
418
  await waitFor(() => streamTtsAudio.mock.calls.length === 1);
419
419
 
420
- // User speaks while the tts_audio frame is queued but unsent: no audio
421
- // has reached the client, so the turn must not be treated as audible.
420
+ // A short blip while the tts_audio frame is queued but unsent: the
421
+ // sustained-speech guard is not met, so nothing cancels yet.
422
422
  await session.handleBinaryAudio(LOUD_CHUNK);
423
423
  await flushAsyncCallbacks();
424
424
  expect(countType(frames, "turn_cancelled")).toBe(0);
@@ -445,7 +445,7 @@ describe("LiveVoiceSession server VAD", () => {
445
445
  await waitFor(() => abort.mock.calls.length === 1);
446
446
  });
447
447
 
448
- test("speech while the turn is still thinking emits speech_started but does not cancel", async () => {
448
+ test("sustained speech while the turn is still thinking aborts the pre-TTS turn", async () => {
449
449
  let callbacks: VoiceTurnCallbacks | undefined;
450
450
  const abort = mock();
451
451
  const startVoiceTurn = mock(async (options: VoiceTurnOptions) => {
@@ -466,11 +466,226 @@ describe("LiveVoiceSession server VAD", () => {
466
466
  await session.handleBinaryAudio(LOUD_CHUNK);
467
467
  await waitFor(() => frames.some((frame) => frame.type === "thinking"));
468
468
 
469
- // No TTS audio has been forwarded yet — the turn is still "thinking".
469
+ // No assistant_text_delta yet — the turn is still pre-TTS "thinking".
470
+ // Sustained speech over the unspoken reply meets the barge-in guard and
471
+ // cancels the in-flight turn before it ever starts talking (JARVIS-1266).
472
+ await session.handleBinaryAudio(SUSTAINED_LOUD_CHUNK);
473
+ await waitFor(() =>
474
+ frames.some((frame) => frame.type === "turn_cancelled"),
475
+ );
476
+
477
+ const types = frameTypes(frames);
478
+ const bargeInSpeechStartedIndex = types.lastIndexOf("speech_started");
479
+ const turnCancelledIndex = types.indexOf("turn_cancelled");
480
+ expect(bargeInSpeechStartedIndex).toBeGreaterThan(-1);
481
+ expect(bargeInSpeechStartedIndex).toBeLessThan(turnCancelledIndex);
482
+ expect(countType(frames, "turn_cancelled")).toBe(1);
483
+ expect(frames[turnCancelledIndex]).toMatchObject({
484
+ type: "turn_cancelled",
485
+ turnId: "live-turn-1",
486
+ });
487
+ await waitFor(() => abort.mock.calls.length === 1);
488
+
489
+ // The aborted thinking turn never produced audio and never completes:
490
+ // no orphaned/late assistant response lands after the interrupt.
491
+ expect(countType(frames, "tts_audio")).toBe(0);
492
+ expect(
493
+ frames.some(
494
+ (frame) => frame.type === "tts_done" && frame.turnId === "live-turn-1",
495
+ ),
496
+ ).toBe(false);
497
+
498
+ // The barge-in speech was captured from onset into the next utterance,
499
+ // which starts its own turn. Exactly one startVoiceTurn per real utterance
500
+ // (the bridge emits one user_message_echo per call) — no double echo.
501
+ await waitFor(() => startVoiceTurn.mock.calls.length === 2);
502
+ expect(startVoiceTurn.mock.calls[1]?.[0]).toMatchObject({
503
+ content: "second question",
504
+ });
505
+ expect(countType(frames, "utterance_end")).toBe(2);
506
+ });
507
+
508
+ test("a late assistant_text_delta after a thinking barge-in never reaches the client", async () => {
509
+ let callbacks: VoiceTurnCallbacks | undefined;
510
+ const abort = mock();
511
+ const startVoiceTurn = mock(async (options: VoiceTurnOptions) => {
512
+ callbacks ??= options.callbacks;
513
+ return { turnId: "bridge-turn", abort };
514
+ });
515
+ let releaseTurnCancelled: (() => void) | undefined;
516
+ const { frames, session } = createHarness({
517
+ finals: ["first question", "second question"],
518
+ startVoiceTurn,
519
+ // Suspend the async barge-in teardown at the turn_cancelled send so the
520
+ // aborted turn stays non-finalized — the exact window a late model delta
521
+ // could race into before cancelAssistantTurn finishes.
522
+ holdSendFrame: (payload) => {
523
+ if (payload.type !== "turn_cancelled" || releaseTurnCancelled) {
524
+ return null;
525
+ }
526
+ return new Promise<void>((resolve) => {
527
+ releaseTurnCancelled = resolve;
528
+ });
529
+ },
530
+ });
531
+
532
+ await session.start();
533
+ await session.handleBinaryAudio(LOUD_CHUNK);
534
+ await waitFor(() => callbacks !== undefined);
535
+
536
+ // Barge in while thinking; teardown blocks on the held turn_cancelled, so
537
+ // the turn is aborted but not yet finalized.
538
+ await session.handleBinaryAudio(SUSTAINED_LOUD_CHUNK);
539
+ await waitFor(() => releaseTurnCancelled !== undefined);
540
+
541
+ // A first assistant_text_delta lands in that window — fenced on the abort
542
+ // signal, it must not be forwarded to the client.
543
+ callbacks?.assistant_text_delta?.(makeTextDelta("stale thinking reply"));
544
+ await flushAsyncCallbacks();
545
+ expect(countType(frames, "assistant_text_delta")).toBe(0);
546
+
547
+ releaseTurnCancelled?.();
548
+ await waitFor(() =>
549
+ frames.some((frame) => frame.type === "turn_cancelled"),
550
+ );
551
+ expect(countType(frames, "assistant_text_delta")).toBe(0);
552
+ });
553
+
554
+ test("a queued assistant_text_delta is dropped at send time once a thinking barge-in aborts", async () => {
555
+ let callbacks: VoiceTurnCallbacks | undefined;
556
+ const abort = mock();
557
+ const startVoiceTurn = mock(async (options: VoiceTurnOptions) => {
558
+ callbacks ??= options.callbacks;
559
+ return { turnId: "bridge-turn", abort };
560
+ });
561
+ let releaseFirstDelta: (() => void) | undefined;
562
+ // No TTS streamer: the turn emits text but never leaves the pre-TTS phase.
563
+ const { frames, session } = createHarness({
564
+ finals: ["first question", "second question"],
565
+ startVoiceTurn,
566
+ streamTtsAudio: null,
567
+ // Hold the first assistant_text_delta's transport write so the second
568
+ // one sits queued behind it (a backed-up outbound queue).
569
+ holdSendFrame: (payload) => {
570
+ if (
571
+ payload.type !== "assistant_text_delta" ||
572
+ releaseFirstDelta !== undefined
573
+ ) {
574
+ return null;
575
+ }
576
+ return new Promise<void>((resolve) => {
577
+ releaseFirstDelta = resolve;
578
+ });
579
+ },
580
+ });
581
+
582
+ await session.start();
583
+ await session.handleBinaryAudio(LOUD_CHUNK);
584
+ await waitFor(() => callbacks !== undefined);
585
+
586
+ // First delta passes shouldSend, then blocks in the transport; the second
587
+ // is enqueued behind it and has not yet been send-time checked.
588
+ callbacks?.assistant_text_delta?.(makeTextDelta("early reply"));
589
+ await waitFor(() => releaseFirstDelta !== undefined);
590
+ callbacks?.assistant_text_delta?.(makeTextDelta("leaked tail"));
591
+
592
+ // Barge in while both deltas are queued: the turn aborts before the second
593
+ // delta drains.
594
+ await session.handleBinaryAudio(SUSTAINED_LOUD_CHUNK);
595
+ await flushAsyncCallbacks();
596
+
597
+ // Release the queue: the first (already-committed) delta writes, but the
598
+ // second must be dropped by the send-time guard — no cancelled-reply text
599
+ // leaks after the abort.
600
+ releaseFirstDelta?.();
601
+ await waitFor(() =>
602
+ frames.some((frame) => frame.type === "turn_cancelled"),
603
+ );
604
+ expect(countType(frames, "assistant_text_delta")).toBe(1);
605
+ expect(
606
+ frames.some(
607
+ (frame) =>
608
+ frame.type === "assistant_text_delta" && frame.text === "leaked tail",
609
+ ),
610
+ ).toBe(false);
611
+ });
612
+
613
+ test("a thinking barge-in that rejects the pending turn start emits no error frame", async () => {
614
+ // startVoiceTurn hangs like a real turn waiting for the conversation lock
615
+ // and rejects when the turn's signal aborts (the waitForIdle behavior), so
616
+ // the turn is still "thinking" with no handle when barge-in hits.
617
+ const startVoiceTurn: LiveVoiceTurnStarter = async (options) => {
618
+ await new Promise<void>((_resolve, reject) => {
619
+ const fail = () =>
620
+ reject(new Error("turn aborted while waiting for the lock"));
621
+ if (options.signal?.aborted) {
622
+ fail();
623
+ return;
624
+ }
625
+ options.signal?.addEventListener("abort", fail, { once: true });
626
+ });
627
+ return { turnId: "bridge-turn", abort: mock() };
628
+ };
629
+ let releaseTurnCancelled: (() => void) | undefined;
630
+ const { frames, session } = createHarness({
631
+ finals: ["first question", "second question"],
632
+ startVoiceTurn,
633
+ holdSendFrame: (payload) => {
634
+ if (payload.type !== "turn_cancelled" || releaseTurnCancelled) {
635
+ return null;
636
+ }
637
+ return new Promise<void>((resolve) => {
638
+ releaseTurnCancelled = resolve;
639
+ });
640
+ },
641
+ });
642
+
643
+ await session.start();
644
+ await session.handleBinaryAudio(LOUD_CHUNK);
645
+ await waitFor(() => frames.some((frame) => frame.type === "thinking"));
646
+
647
+ // Barge in while the turn's start is still pending on the lock: the abort
648
+ // rejects startVoiceTurn, whose catch must treat the aborted turn as dead
649
+ // rather than surface a stray error frame while teardown is in flight.
650
+ await session.handleBinaryAudio(SUSTAINED_LOUD_CHUNK);
651
+ await waitFor(() => releaseTurnCancelled !== undefined);
652
+ await flushAsyncCallbacks();
653
+ expect(countType(frames, "error")).toBe(0);
654
+
655
+ releaseTurnCancelled?.();
656
+ await waitFor(() =>
657
+ frames.some((frame) => frame.type === "turn_cancelled"),
658
+ );
659
+ expect(countType(frames, "error")).toBe(0);
660
+ });
661
+
662
+ test("a brief blip while thinking arms the guard but does not cancel", async () => {
663
+ let callbacks: VoiceTurnCallbacks | undefined;
664
+ const abort = mock();
665
+ const startVoiceTurn = mock(async (options: VoiceTurnOptions) => {
666
+ callbacks ??= options.callbacks;
667
+ return { turnId: "bridge-turn", abort };
668
+ });
669
+ const streamTtsAudio = mock(async (options: LiveVoiceTtsOptions) => {
670
+ options.onAudioChunk(makeTtsChunk("assistant audio"));
671
+ return makeTtsResult("assistant audio");
672
+ });
673
+ const { frames, session } = createHarness({
674
+ finals: ["first question", "second question"],
675
+ startVoiceTurn,
676
+ streamTtsAudio,
677
+ });
678
+
679
+ await session.start();
680
+ await session.handleBinaryAudio(LOUD_CHUNK);
681
+ await waitFor(() => frames.some((frame) => frame.type === "thinking"));
682
+
683
+ // A short blip (well under bargeInMinSpeechMs) while the turn is still
684
+ // "thinking": the sustained-speech guard arms but does not trip, so a
685
+ // cough or noise cannot kill the in-flight agent loop.
470
686
  await session.handleBinaryAudio(LOUD_CHUNK);
471
687
  await flushAsyncCallbacks();
472
688
 
473
- expect(countType(frames, "speech_started")).toBe(2);
474
689
  expect(countType(frames, "turn_cancelled")).toBe(0);
475
690
  expect(abort).not.toHaveBeenCalled();
476
691
 
@@ -483,6 +698,7 @@ describe("LiveVoiceSession server VAD", () => {
483
698
  ),
484
699
  );
485
700
  expect(countType(frames, "turn_cancelled")).toBe(0);
701
+ expect(abort).not.toHaveBeenCalled();
486
702
  });
487
703
 
488
704
  test("runs two VAD turns back-to-back on one session", async () => {
@@ -269,8 +269,8 @@ interface ActiveAssistantTurn {
269
269
  handle: VoiceTurnHandle | null;
270
270
  assistantCompleted: boolean;
271
271
  ttsDone: boolean;
272
- // A tts_audio frame actually went out to the client — the barge-in gate:
273
- // speech only cancels a turn that has audibly started speaking.
272
+ // A tts_audio frame actually went out to the client — latches on the first
273
+ // forwarded chunk so the firstTtsAudio metric is marked exactly once per turn.
274
274
  ttsAudioStarted: boolean;
275
275
  finalized: boolean;
276
276
  // Triage-and-escalate (Voice Mode): the front-door leg emitted [ESCALATE]
@@ -926,12 +926,14 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
926
926
  }
927
927
 
928
928
  // VAD speech onset. Contract: speech_started tells the client to flush
929
- // tail playback immediately; barge-in then cancels the active turn only
930
- // once its first tts_audio chunk was forwarded — speech during a pre-TTS
931
- // "thinking" turn never kills the unspoken reply. While a turn is audibly
932
- // speaking, both are deferred behind the sustained-speech guard so a
933
- // cough or noise blip cannot kill the reply; onset while listening keeps
934
- // the instant speech_started (turn-taking latency is untouched).
929
+ // tail playback immediately; barge-in then cancels any in-flight,
930
+ // non-finalized turn — including a pre-TTS "thinking" turn whose reply is
931
+ // still being generated, so a user can cut in before the assistant starts
932
+ // talking (JARVIS-1266). Speaking over a thinking or audibly speaking turn
933
+ // is deferred behind the same sustained-speech guard, so a cough or noise
934
+ // blip cannot kill an unspoken reply or clip a spoken one; sustained speech
935
+ // aborts the turn. Onset while listening keeps the instant speech_started
936
+ // (turn-taking latency is untouched).
935
937
  private handleVadSpeechStart(): void {
936
938
  if (this.isClosed || this.state === "failed") {
937
939
  return;
@@ -940,25 +942,27 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
940
942
  this.vadSpeechStartPending = true;
941
943
 
942
944
  const turn = this.activeAssistantTurn;
943
- const speakingTurn =
944
- turn && !turn.finalized && turn.ttsAudioStarted ? turn : null;
945
+ // Any in-flight, non-finalized turn is interruptible, whether it is still
946
+ // "thinking" (pre-TTS) or audibly speaking, so a user can cut in before the
947
+ // assistant starts talking.
948
+ const bargeableTurn = turn && !turn.finalized ? turn : null;
945
949
  // The client can still be draining audible playback after tts_done
946
950
  // (the turn is already cleared server-side) — that tail deserves the
947
951
  // same guard, or a noise blip clips the reply's last words.
948
952
  const drainingPlayback = Date.now() < this.assistantPlaybackTailUntilMs;
949
953
 
950
- if ((speakingTurn || drainingPlayback) && this.bargeInMinSpeechMs > 0) {
954
+ if ((bargeableTurn || drainingPlayback) && this.bargeInMinSpeechMs > 0) {
951
955
  // Onset audio keeps flowing into the cycle/pre-roll while the guard
952
956
  // accumulates (trackBargeInGuard), so no speech is lost either way.
953
- this.pendingBargeIn = { turn: speakingTurn, speechMs: 0 };
957
+ this.pendingBargeIn = { turn: bargeableTurn, speechMs: 0 };
954
958
  return;
955
959
  }
956
960
 
957
961
  this.pendingBargeIn = null;
958
962
  this.assistantPlaybackTailUntilMs = 0;
959
963
  void this.sendFrame({ type: "speech_started" });
960
- if (speakingTurn) {
961
- this.bargeIn(speakingTurn);
964
+ if (bargeableTurn) {
965
+ this.bargeIn(bargeableTurn);
962
966
  }
963
967
  }
964
968
 
@@ -1730,7 +1734,14 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1730
1734
  return;
1731
1735
  }
1732
1736
  this.markFirstAssistantDelta(utterance, turnId);
1733
- void this.sendFrame({ type: "assistant_text_delta", text: chunk });
1737
+ // Same send-time abort gate as the default-leg delta path: a front-door
1738
+ // delta queued behind a backed-up outbound frame must not be written
1739
+ // once barge-in aborts the turn. Escalation aborts the front-door handle,
1740
+ // not this turn's controller, so legitimate front-door text still sends.
1741
+ void this.sendFrame(
1742
+ { type: "assistant_text_delta", text: chunk },
1743
+ () => !activeTurn.abortController.signal.aborted && !this.isClosed,
1744
+ );
1734
1745
  this.bufferAssistantTextForTts(token, chunk);
1735
1746
  };
1736
1747
 
@@ -1804,10 +1815,21 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1804
1815
  return;
1805
1816
  }
1806
1817
  this.markFirstAssistantDelta(utterance, turnId);
1807
- void this.sendFrame({
1808
- type: "assistant_text_delta",
1809
- text: msg.text,
1810
- });
1818
+ void this.sendFrame(
1819
+ {
1820
+ type: "assistant_text_delta",
1821
+ text: msg.text,
1822
+ },
1823
+ // Re-check at send time (mirrors the tts_audio path): a delta
1824
+ // already queued behind a backed-up outbound frame must not be
1825
+ // written once barge-in has aborted the turn, or the cancelled
1826
+ // reply's text leaks ahead of turn_cancelled. Key off this turn's
1827
+ // own abort signal — a normal message_complete finalizes and
1828
+ // clears activeAssistantTurn while trailing deltas may still be
1829
+ // draining, so an activeAssistantTurn-based guard would drop them.
1830
+ () =>
1831
+ !activeTurn.abortController.signal.aborted && !this.isClosed,
1832
+ );
1811
1833
  this.bufferAssistantTextForTts(token, msg.text);
1812
1834
  },
1813
1835
  message_complete: (msg) => {
@@ -1980,7 +2002,14 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1980
2002
  private isActiveAssistantTurn(token: symbol): boolean {
1981
2003
  const activeTurn = this.activeAssistantTurn;
1982
2004
  return (
1983
- activeTurn?.token === token && !activeTurn.finalized && !this.isClosed
2005
+ activeTurn?.token === token &&
2006
+ !activeTurn.finalized &&
2007
+ // Barge-in aborts synchronously but finalizes through an async
2008
+ // cancelAssistantTurn chain; the abort makes the turn dead at once so a
2009
+ // rejected startVoiceTurn or a trailing onError in that window does not
2010
+ // treat it as live (and emit a stray error frame or double-finalize).
2011
+ !activeTurn.abortController.signal.aborted &&
2012
+ !this.isClosed
1984
2013
  );
1985
2014
  }
1986
2015
 
@@ -1990,6 +2019,10 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1990
2019
  activeTurn?.token === token &&
1991
2020
  !activeTurn.assistantCompleted &&
1992
2021
  !activeTurn.finalized &&
2022
+ // Fence a late first assistant_text_delta once barge-in aborts a pre-TTS
2023
+ // turn, before its async teardown finalizes — mirrors isForwardingTts so
2024
+ // no cancelled-turn text leaks after turn_cancelled.
2025
+ !activeTurn.abortController.signal.aborted &&
1993
2026
  !this.isClosed
1994
2027
  );
1995
2028
  }
@@ -2281,10 +2314,10 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
2281
2314
  },
2282
2315
  () => this.isForwardingTts(token),
2283
2316
  );
2284
- // Arm the barge-in gate only once a tts_audio frame was actually
2285
- // written — a backed-up outbound queue must not let speech cancel a
2286
- // still-unspoken reply. Token match keeps a stale turn's late send
2287
- // from arming a newer turn.
2317
+ // Skip a frame that wasn't actually written — a backed-up outbound
2318
+ // queue hasn't reached the client, so it must not extend the
2319
+ // playback-tail estimate or latch first-audio state. Token match keeps
2320
+ // a stale turn's late send from latching a newer turn.
2288
2321
  if (!sent) {
2289
2322
  return;
2290
2323
  }
@@ -46,8 +46,10 @@ afterAll(() => {
46
46
  rmSync(ROOT, { recursive: true, force: true });
47
47
  });
48
48
 
49
- const { collectSourceVersions, createSourceWatchState, runSourceWatchPass } =
49
+ const { createSourceWatchState, runSourceWatchPass } =
50
50
  await import("../plugin-source-watch.js");
51
+ const { collectSourceVersions } =
52
+ await import("../../plugins/collect-source-versions.js");
51
53
  const { getSourceVersionsPath, readSourceVersions } =
52
54
  await import("../../plugins/source-versions.js");
53
55
 
@@ -25,14 +25,14 @@
25
25
  import {
26
26
  existsSync,
27
27
  mkdirSync,
28
+ readdirSync,
28
29
  renameSync,
29
30
  statSync,
30
31
  writeFileSync,
31
32
  } from "node:fs";
32
- import { readdirSync } from "node:fs";
33
33
  import { join } from "node:path";
34
34
 
35
- import { snapshotPluginSource } from "../plugins/source-fingerprint.js";
35
+ import { collectSourceVersions } from "../plugins/collect-source-versions.js";
36
36
  import type {
37
37
  PluginSourceVersion,
38
38
  SourceVersionsDocument,
@@ -43,69 +43,10 @@ import {
43
43
  SOURCE_VERSIONS_FORMAT,
44
44
  } from "../plugins/source-versions.js";
45
45
  import { getLogger } from "../util/logger.js";
46
- import {
47
- getMonitoringDataDir,
48
- getWorkspaceHooksDir,
49
- getWorkspacePluginsDir,
50
- } from "../util/platform.js";
46
+ import { getMonitoringDataDir } from "../util/platform.js";
51
47
 
52
48
  const log = getLogger("plugin-source-watch");
53
49
 
54
- /**
55
- * Collect the current source version of every watched directory: each
56
- * plugin directory under `<workspace>/plugins/` (same discovery rule as the
57
- * daemon's plugin scan — a directory with a `package.json`), plus the
58
- * standalone workspace hooks directory when it exists. Disabled plugins are
59
- * fingerprinted too: consumers need fresh state the moment a plugin is
60
- * re-enabled, and the `disabled` field is how they observe the toggle
61
- * itself (dotfiles are excluded from the fingerprint).
62
- */
63
- export function collectSourceVersions(): Record<string, PluginSourceVersion> {
64
- const out: Record<string, PluginSourceVersion> = {};
65
-
66
- const pluginsDir = getWorkspacePluginsDir();
67
- let entries: string[] = [];
68
- try {
69
- entries = readdirSync(pluginsDir);
70
- } catch {
71
- // No plugins directory yet — nothing to watch there.
72
- }
73
- for (const entry of entries) {
74
- if (entry.startsWith(".")) {
75
- continue;
76
- }
77
- const dir = join(pluginsDir, entry);
78
- try {
79
- if (!statSync(dir).isDirectory()) {
80
- continue;
81
- }
82
- } catch {
83
- continue;
84
- }
85
- if (!existsSync(join(dir, "package.json"))) {
86
- continue;
87
- }
88
- const snapshot = snapshotPluginSource(dir);
89
- out[dir] = {
90
- fingerprint: snapshot.fingerprint,
91
- evictionPaths: snapshot.evictionPaths,
92
- disabled: existsSync(join(dir, ".disabled")),
93
- };
94
- }
95
-
96
- const workspaceHooksDir = getWorkspaceHooksDir();
97
- if (existsSync(workspaceHooksDir)) {
98
- const snapshot = snapshotPluginSource(workspaceHooksDir);
99
- out[workspaceHooksDir] = {
100
- fingerprint: snapshot.fingerprint,
101
- evictionPaths: snapshot.evictionPaths,
102
- disabled: false,
103
- };
104
- }
105
-
106
- return out;
107
- }
108
-
109
50
  /**
110
51
  * Whether two version maps describe the same source state. Compares key
111
52
  * sets, fingerprints, and disabled flags; eviction paths are derived from
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Walk the workspace's plugin directories and snapshot each one's current
3
+ * source version.
4
+ *
5
+ * This is the single collector shared by the two producers of a source-versions
6
+ * map: the resource monitor's watcher (which fingerprints on a timer and writes
7
+ * the sentinel — see `../monitoring/plugin-source-watch.ts`) and the daemon's
8
+ * imperative reconcile (which applies the walk directly, without waiting on the
9
+ * watcher — see `reconcilePluginSourcesNow` in `./mtime-cache.ts`). Keeping the
10
+ * walk in one place guarantees both paths produce byte-identical maps, so an
11
+ * imperative reconcile never disagrees with the watcher's next publish and
12
+ * causes a spurious reload.
13
+ */
14
+
15
+ import { existsSync, readdirSync, statSync } from "node:fs";
16
+ import { join } from "node:path";
17
+
18
+ import {
19
+ getWorkspaceHooksDir,
20
+ getWorkspacePluginsDir,
21
+ } from "../util/platform.js";
22
+ import { snapshotPluginSource } from "./source-fingerprint.js";
23
+ import type { PluginSourceVersion } from "./source-versions.js";
24
+
25
+ /**
26
+ * Collect the current source version of every watched directory: each plugin
27
+ * directory under `<workspace>/plugins/` (a directory with a `package.json`),
28
+ * plus the standalone workspace hooks directory when it exists. Disabled
29
+ * plugins are fingerprinted too: consumers need fresh state the moment a plugin
30
+ * is re-enabled, and the `disabled` field is how they observe the toggle itself
31
+ * (dotfiles are excluded from the fingerprint).
32
+ */
33
+ export function collectSourceVersions(): Record<string, PluginSourceVersion> {
34
+ const out: Record<string, PluginSourceVersion> = {};
35
+
36
+ const pluginsDir = getWorkspacePluginsDir();
37
+ let entries: string[] = [];
38
+ try {
39
+ entries = readdirSync(pluginsDir);
40
+ } catch {
41
+ // No plugins directory yet — nothing to watch there.
42
+ }
43
+ for (const entry of entries) {
44
+ if (entry.startsWith(".")) {
45
+ continue;
46
+ }
47
+ const dir = join(pluginsDir, entry);
48
+ try {
49
+ if (!statSync(dir).isDirectory()) {
50
+ continue;
51
+ }
52
+ } catch {
53
+ continue;
54
+ }
55
+ if (!existsSync(join(dir, "package.json"))) {
56
+ continue;
57
+ }
58
+ const snapshot = snapshotPluginSource(dir);
59
+ out[dir] = {
60
+ fingerprint: snapshot.fingerprint,
61
+ evictionPaths: snapshot.evictionPaths,
62
+ disabled: existsSync(join(dir, ".disabled")),
63
+ };
64
+ }
65
+
66
+ const workspaceHooksDir = getWorkspaceHooksDir();
67
+ if (existsSync(workspaceHooksDir)) {
68
+ const snapshot = snapshotPluginSource(workspaceHooksDir);
69
+ out[workspaceHooksDir] = {
70
+ fingerprint: snapshot.fingerprint,
71
+ evictionPaths: snapshot.evictionPaths,
72
+ disabled: false,
73
+ };
74
+ }
75
+
76
+ return out;
77
+ }
@@ -58,6 +58,7 @@ import {
58
58
  getWorkspaceHooksDir,
59
59
  getWorkspacePluginsDir,
60
60
  } from "../util/platform.js";
61
+ import { collectSourceVersions } from "./collect-source-versions.js";
61
62
  import {
62
63
  deriveToolName,
63
64
  listSurfaceDir,
@@ -308,6 +309,52 @@ async function maybeReconcileFromSentinel(): Promise<void> {
308
309
  }
309
310
  }
310
311
 
312
+ /**
313
+ * Imperatively reconcile the plugin caches against the current on-disk state
314
+ * *now* — without waiting for the resource monitor to republish the
315
+ * source-versions sentinel or for the next hook dispatch to notice it.
316
+ *
317
+ * An install / uninstall / enable / disable materializes files on disk; the
318
+ * steady-state path picks that up eventually — the monitor republishes the
319
+ * sentinel and the dispatch-path gate applies the diff on the next turn. That
320
+ * is eventually-correct but not immediate: nothing runs a newly installed
321
+ * plugin's `init` until some later turn dispatches a hook. Callers that just
322
+ * changed the plugin set on disk (the install / uninstall routes, and the
323
+ * CLI's best-effort post-install poke) call this to bring the change up
324
+ * deterministically, so a freshly installed plugin's `init` fires as part of
325
+ * the install rather than at the next daemon boot.
326
+ *
327
+ * Reuses the same collector the monitor writes into the sentinel, so the map
328
+ * applied here is identical to the monitor's next publish — which then diffs to
329
+ * a no-op. Idempotent and safe to call redundantly: `applySourceVersions` only
330
+ * redeploys directories whose fingerprint moved, and activation is guarded so a
331
+ * plugin already up is never re-initialized. Never throws — a failure is
332
+ * contained inside `applySourceVersions` and logged there.
333
+ *
334
+ * Coordinates with the sentinel gate through the shared `reconcileInFlight`
335
+ * latch: it waits out any dispatch-driven reconcile already running, then
336
+ * claims the latch for its own apply, so the two paths never overlap.
337
+ */
338
+ export async function reconcilePluginSourcesNow(): Promise<void> {
339
+ while (reconcileInFlight !== null) {
340
+ await reconcileInFlight;
341
+ }
342
+ // `applySourceVersions` contains its own failures, but the `collectSourceVersions()`
343
+ // walk that feeds it runs outside that guard — wrap the whole thing so an
344
+ // imperative reconcile never rejects into its callers (the install route must
345
+ // still return success for an install whose files already landed on disk).
346
+ reconcileInFlight = (async () => {
347
+ try {
348
+ await applySourceVersions(collectSourceVersions());
349
+ } catch (err) {
350
+ log.error({ err }, "imperative plugin reconcile failed");
351
+ }
352
+ })().finally(() => {
353
+ reconcileInFlight = null;
354
+ });
355
+ await reconcileInFlight;
356
+ }
357
+
311
358
  /**
312
359
  * Validate that a directory path from the sentinel is an allowed plugin
313
360
  * source: either under the workspace plugins directory or the standalone
@@ -91,6 +91,7 @@ import {
91
91
  import { getPlatformBaseUrl } from "../../config/env.js";
92
92
  import { isPluginDisabled } from "../../plugins/disabled-state.js";
93
93
  import { ensurePluginApiShim } from "../../plugins/ensure-plugin-api-shim.js";
94
+ import { reconcilePluginSourcesNow } from "../../plugins/mtime-cache.js";
94
95
  import { getLocalCategorySlugs } from "../../skills/categories-cache.js";
95
96
  import { getLogger } from "../../util/logger.js";
96
97
  import { getWorkspacePluginsDir } from "../../util/platform.js";
@@ -1092,7 +1093,15 @@ async function handleUninstallPlugin({
1092
1093
  await ensurePluginApiShim().catch(() => {});
1093
1094
 
1094
1095
  try {
1096
+ // `uninstallPlugin` runs the plugin's `shutdown` hook (while its files are
1097
+ // still present) and then removes the directory — both in this daemon
1098
+ // process. Following it with a reconcile drops the plugin's now-absent
1099
+ // tools and hooks from the in-memory caches immediately (the `shutdown`
1100
+ // already ran, so the reconcile's deactivation does not run it again),
1101
+ // rather than leaving that to the background source watcher. Symmetric to
1102
+ // the install route, which reconciles to bring a new plugin up.
1095
1103
  const result = await uninstallPlugin({ name: rawName });
1104
+ await reconcilePluginSourcesNow();
1096
1105
  publishPluginsChanged(getOriginClientId(headers));
1097
1106
  return { name: result.name, target: result.target };
1098
1107
  } catch (err) {
@@ -1228,6 +1237,12 @@ async function handleInstallPlugin({ body = {}, headers }: RouteHandlerArgs) {
1228
1237
  { fetch: globalThis.fetch.bind(globalThis) },
1229
1238
  );
1230
1239
  }
1240
+ // Bring the freshly materialized plugin up in-process right now — register
1241
+ // its tools and run its `init` hook — instead of waiting for the resource
1242
+ // monitor to republish the sentinel and a later turn to apply it. This is
1243
+ // what makes `init` fire as part of the install rather than at the next
1244
+ // daemon boot. Never throws; a failure is contained and logged.
1245
+ await reconcilePluginSourcesNow();
1231
1246
  publishPluginsChanged(getOriginClientId(headers));
1232
1247
  return {
1233
1248
  ok: true as const,