@vellumai/assistant 0.10.8-dev.202607151902.7dbe06e → 0.10.8-dev.202607152027.f053d5a

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.202607151902.7dbe06e",
3
+ "version": "0.10.8-dev.202607152027.f053d5a",
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",
@@ -505,6 +505,132 @@ describe("LiveVoiceSession server VAD", () => {
505
505
  expect(countType(frames, "utterance_end")).toBe(2);
506
506
  });
507
507
 
508
+ test("a thinking barge-in merges the interrupted request into the next turn's control prompt", async () => {
509
+ const startVoiceTurn = mock(async (_options: VoiceTurnOptions) => {
510
+ return { turnId: "bridge-turn", abort: mock() };
511
+ });
512
+ const streamTtsAudio = mock(async (options: LiveVoiceTtsOptions) => {
513
+ options.onAudioChunk(makeTtsChunk("assistant audio"));
514
+ return makeTtsResult("assistant audio");
515
+ });
516
+ const { frames, session } = createHarness({
517
+ finals: ["first question", "second question"],
518
+ startVoiceTurn,
519
+ streamTtsAudio,
520
+ });
521
+
522
+ await session.start();
523
+ await session.handleBinaryAudio(LOUD_CHUNK);
524
+ await waitFor(() => frames.some((frame) => frame.type === "thinking"));
525
+
526
+ // Barge in while the first turn is still thinking, then let the barge-in
527
+ // utterance start its own turn.
528
+ await session.handleBinaryAudio(SUSTAINED_LOUD_CHUNK);
529
+ await waitFor(() => startVoiceTurn.mock.calls.length === 2);
530
+
531
+ // The barged (first) turn ran on the plain control prompt.
532
+ const firstPrompt =
533
+ startVoiceTurn.mock.calls[0]?.[0]?.voiceControlPrompt ?? "";
534
+ expect(firstPrompt).not.toContain("interrupted");
535
+ expect(firstPrompt).not.toContain("first question");
536
+
537
+ // The follow-up turn's visible content is only what the user just said,
538
+ // but its control prompt carries the interrupted request so the model
539
+ // merges the two instead of treating it as a fresh follow-up.
540
+ const second = startVoiceTurn.mock.calls[1]?.[0];
541
+ expect(second).toMatchObject({ content: "second question" });
542
+ expect(second?.voiceControlPrompt).toContain("first question");
543
+ expect(second?.voiceControlPrompt).toContain("interrupted");
544
+ });
545
+
546
+ test("an ordinary turn carries no interruption merge context", async () => {
547
+ const { startVoiceTurn, calls } = makeAutoCompletingTurnStarter(["Hi."]);
548
+ const { frames, session } = createHarness({
549
+ finals: ["hello there"],
550
+ startVoiceTurn,
551
+ });
552
+
553
+ await session.start();
554
+ await session.handleBinaryAudio(LOUD_CHUNK);
555
+ await waitFor(() => countType(frames, "tts_done") === 1);
556
+
557
+ expect(calls).toHaveLength(1);
558
+ const prompt = calls[0]?.voiceControlPrompt ?? "";
559
+ expect(prompt).toContain("live voice session");
560
+ expect(prompt).not.toContain("interrupted");
561
+ });
562
+
563
+ test("a discarded barge-in utterance does not leak merge context into a later turn", async () => {
564
+ const startVoiceTurn = mock(async (_options: VoiceTurnOptions) => {
565
+ return { turnId: "bridge-turn", abort: mock() };
566
+ });
567
+ const streamTtsAudio = mock(async (options: LiveVoiceTtsOptions) => {
568
+ options.onAudioChunk(makeTtsChunk("assistant audio"));
569
+ return makeTtsResult("assistant audio");
570
+ });
571
+ // The barge-in utterance (second) transcribes to nothing and is discarded.
572
+ const { frames, session } = createHarness({
573
+ finals: ["first question", "", "third question"],
574
+ startVoiceTurn,
575
+ streamTtsAudio,
576
+ });
577
+
578
+ await session.start();
579
+ await session.handleBinaryAudio(LOUD_CHUNK);
580
+ await waitFor(() => frames.some((frame) => frame.type === "thinking"));
581
+
582
+ // Barge in during thinking (arms the pending merge context), but the
583
+ // barge-in utterance is discarded (empty transcript), which must drop it.
584
+ await session.handleBinaryAudio(SUSTAINED_LOUD_CHUNK);
585
+ await waitFor(() =>
586
+ frames.some((frame) => frame.type === "utterance_discarded"),
587
+ );
588
+
589
+ // A later, unrelated turn must not carry the discarded request.
590
+ await session.handleBinaryAudio(LOUD_CHUNK);
591
+ await waitFor(() => startVoiceTurn.mock.calls.length === 2);
592
+ const laterTurn = startVoiceTurn.mock.calls[1]?.[0];
593
+ expect(laterTurn).toMatchObject({ content: "third question" });
594
+ expect(laterTurn?.voiceControlPrompt).not.toContain("interrupted");
595
+ expect(laterTurn?.voiceControlPrompt).not.toContain("first question");
596
+ });
597
+
598
+ test("a client interrupt after a barge-in drops the pending merge context", async () => {
599
+ const startVoiceTurn = mock(async (_options: VoiceTurnOptions) => {
600
+ return { turnId: "bridge-turn", abort: mock() };
601
+ });
602
+ const streamTtsAudio = mock(async (options: LiveVoiceTtsOptions) => {
603
+ options.onAudioChunk(makeTtsChunk("assistant audio"));
604
+ return makeTtsResult("assistant audio");
605
+ });
606
+ const { frames, session } = createHarness({
607
+ finals: ["first question", "second question", "third question"],
608
+ startVoiceTurn,
609
+ streamTtsAudio,
610
+ });
611
+
612
+ await session.start();
613
+ await session.handleBinaryAudio(LOUD_CHUNK);
614
+ await waitFor(() => frames.some((frame) => frame.type === "thinking"));
615
+
616
+ // Barge in during thinking, then the client interrupts before the barge-in
617
+ // utterance launches a turn.
618
+ await session.handleBinaryAudio(SUSTAINED_LOUD_CHUNK);
619
+ await waitFor(() =>
620
+ frames.some((frame) => frame.type === "turn_cancelled"),
621
+ );
622
+ await session.handleClientFrame({ type: "interrupt" });
623
+ await flushAsyncCallbacks();
624
+ const callsAtInterrupt = startVoiceTurn.mock.calls.length;
625
+
626
+ // Any later turn must not carry the discarded request.
627
+ await session.handleBinaryAudio(LOUD_CHUNK);
628
+ await waitFor(() => startVoiceTurn.mock.calls.length > callsAtInterrupt);
629
+ const laterTurn = startVoiceTurn.mock.calls.at(-1)?.[0];
630
+ expect(laterTurn?.voiceControlPrompt).not.toContain("interrupted");
631
+ expect(laterTurn?.voiceControlPrompt).not.toContain("first question");
632
+ });
633
+
508
634
  test("a late assistant_text_delta after a thinking barge-in never reaches the client", async () => {
509
635
  let callbacks: VoiceTurnCallbacks | undefined;
510
636
  const abort = mock();
@@ -273,6 +273,11 @@ interface ActiveAssistantTurn {
273
273
  // forwarded chunk so the firstTtsAudio metric is marked exactly once per turn.
274
274
  ttsAudioStarted: boolean;
275
275
  finalized: boolean;
276
+ // When this turn started from a barge-in, the interrupted request's
277
+ // transcript. Appended to the turn's control prompt (both legs) so the model
278
+ // merges it with this turn's utterance instead of treating that utterance as
279
+ // a fresh follow-up. Null for an ordinary (non-barge-in) turn.
280
+ interruptedRequest: string | null;
276
281
  // Triage-and-escalate (Voice Mode): the front-door leg emitted [ESCALATE]
277
282
  // and the strong "escalated" leg has taken over this same turn. Guards the
278
283
  // front-door leg's trailing completion from finalizing the turn, and makes
@@ -294,6 +299,21 @@ interface ActiveAssistantTurn {
294
299
  assistantAudioSampleRate?: number;
295
300
  }
296
301
 
302
+ // Base control prompt for every live-voice turn. When a turn starts from a
303
+ // barge-in, the interruption merge note is appended to it (see
304
+ // buildInterruptionMergeNote) so the model reconciles the interrupted request
305
+ // with the new utterance.
306
+ const LIVE_VOICE_CONTROL_PROMPT =
307
+ "You are speaking in a local live voice session. Keep replies brief and conversational.";
308
+
309
+ // System-level guidance appended to a barge-in turn's control prompt so the
310
+ // model treats the new utterance as a continuation of the request it was cut
311
+ // off answering, rather than a fresh follow-up. Reaches the model only; it is
312
+ // not a user message and never renders as a transcript bubble.
313
+ function buildInterruptionMergeNote(interruptedRequest: string): string {
314
+ return `The user interrupted your previous, unfinished reply. Their earlier request was: "${interruptedRequest}". Treat their current message as a continuation of that request and address both together, or stay silent if they only want you to stop.`;
315
+ }
316
+
297
317
  export class LiveVoiceSession implements LiveVoiceSessionContract {
298
318
  private readonly context: LiveVoiceSessionFactoryContext;
299
319
  private readonly resolveTranscriber: LiveVoiceStreamingTranscriberResolver;
@@ -337,6 +357,11 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
337
357
  // the chunk's PCM duration; zeroed whenever the client flushes playback
338
358
  // (speech_started, turn_cancelled, interrupt, close).
339
359
  private assistantPlaybackTailUntilMs = 0;
360
+ // Set when barge-in cancels an in-flight turn: the interrupted request's
361
+ // transcript, carried into the next turn so the model merges the two.
362
+ // Consumed (and cleared) when that turn launches; cleared if the barge-in
363
+ // utterance is discarded, so it can never attach to a later, unrelated turn.
364
+ private pendingInterruptedRequest: string | null = null;
340
365
  private readonly maxPendingAudioBytes: number;
341
366
  // Set on VAD speech onset; consumed when the first speech chunk is routed
342
367
  // to an utterance so the metric lands on the right turn.
@@ -1001,6 +1026,13 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1001
1026
  // do not collide with it in the collector. turn_cancelled flushes
1002
1027
  // client playback, so the drain estimate resets with it.
1003
1028
  this.assistantPlaybackTailUntilMs = 0;
1029
+ // Carry the interrupted request into the next turn so it merges with the
1030
+ // barge-in utterance rather than being answered as a fresh follow-up.
1031
+ const interruptedRequest = turn.utterance.finalTranscriptSegments
1032
+ .join(" ")
1033
+ .trim();
1034
+ this.pendingInterruptedRequest =
1035
+ interruptedRequest.length > 0 ? interruptedRequest : null;
1004
1036
  turn.abortController.abort();
1005
1037
  this.metrics.markBargeIn(turn.turnId);
1006
1038
  void (async () => {
@@ -1447,6 +1479,10 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1447
1479
  this.assistantPlaybackTailUntilMs = 0;
1448
1480
  this.takeVadPreRoll();
1449
1481
  this.vadPendingTurnEnd = null;
1482
+ // A client interrupt is a hard reset: any barge-in merge context waiting for
1483
+ // the next turn is now stale (the interrupted utterance may be discarded
1484
+ // without ever reaching finalizePendingUtterance).
1485
+ this.pendingInterruptedRequest = null;
1450
1486
  const utterance = this.currentUtterance;
1451
1487
  this.stopSessionTranscriber();
1452
1488
  if (utterance) {
@@ -1519,7 +1555,11 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1519
1555
  return;
1520
1556
  }
1521
1557
 
1522
- await this.launchAssistantTurn(utterance, content);
1558
+ // Consume any pending barge-in merge context for this turn (one barge-in
1559
+ // feeds exactly the next launched turn).
1560
+ const interruptedRequest = this.pendingInterruptedRequest;
1561
+ this.pendingInterruptedRequest = null;
1562
+ await this.launchAssistantTurn(utterance, content, { interruptedRequest });
1523
1563
  }
1524
1564
 
1525
1565
  // Build the ActiveAssistantTurn for a released utterance and drive its model
@@ -1528,9 +1568,14 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1528
1568
  private async launchAssistantTurn(
1529
1569
  utterance: UtteranceCycle,
1530
1570
  content: string,
1531
- // Only set on the surface-resume path; the STT path leaves it undefined so
1532
- // no active-surface context is injected into an ordinary spoken turn.
1533
- activeSurfaceId?: string,
1571
+ opts?: {
1572
+ // Only set on the surface-resume path; the STT path leaves it undefined
1573
+ // so no active-surface context is injected into an ordinary spoken turn.
1574
+ activeSurfaceId?: string;
1575
+ // Set on a barge-in follow-up turn: the interrupted request's transcript,
1576
+ // appended to the turn's control prompt so the model merges the two.
1577
+ interruptedRequest?: string | null;
1578
+ },
1534
1579
  ): Promise<void> {
1535
1580
  utterance.assistantTurnStarted = true;
1536
1581
  const token = Symbol("live-voice-assistant-turn");
@@ -1547,6 +1592,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1547
1592
  ttsDone: false,
1548
1593
  ttsAudioStarted: false,
1549
1594
  finalized: false,
1595
+ interruptedRequest: opts?.interruptedRequest ?? null,
1550
1596
  escalationHandedOff: false,
1551
1597
  ttsBuffer: "",
1552
1598
  ttsSegmentEnqueued: false,
@@ -1583,11 +1629,15 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1583
1629
  overrideProfile: FRONT_DOOR_PROFILE,
1584
1630
  routingLeg: "front-door",
1585
1631
  frontDoor: true,
1586
- ...(activeSurfaceId !== undefined ? { activeSurfaceId } : {}),
1632
+ ...(opts?.activeSurfaceId !== undefined
1633
+ ? { activeSurfaceId: opts.activeSurfaceId }
1634
+ : {}),
1587
1635
  }
1588
1636
  : {
1589
1637
  content,
1590
- ...(activeSurfaceId !== undefined ? { activeSurfaceId } : {}),
1638
+ ...(opts?.activeSurfaceId !== undefined
1639
+ ? { activeSurfaceId: opts.activeSurfaceId }
1640
+ : {}),
1591
1641
  },
1592
1642
  );
1593
1643
  }
@@ -1662,7 +1712,9 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1662
1712
  finalTranscriptAtMs: null,
1663
1713
  },
1664
1714
  };
1665
- await this.launchAssistantTurn(utterance, content, opts?.activeSurfaceId);
1715
+ await this.launchAssistantTurn(utterance, content, {
1716
+ activeSurfaceId: opts?.activeSurfaceId,
1717
+ });
1666
1718
  }
1667
1719
 
1668
1720
  // Dispatch a resume deferred behind an in-flight turn, once that turn has
@@ -1786,8 +1838,11 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1786
1838
  assistantMessageChannel: "vellum",
1787
1839
  userMessageInterface: "macos",
1788
1840
  assistantMessageInterface: "macos",
1789
- voiceControlPrompt:
1790
- "You are speaking in a local live voice session. Keep replies brief and conversational.",
1841
+ voiceControlPrompt: activeTurn.interruptedRequest
1842
+ ? `${LIVE_VOICE_CONTROL_PROMPT}\n\n${buildInterruptionMergeNote(
1843
+ activeTurn.interruptedRequest,
1844
+ )}`
1845
+ : LIVE_VOICE_CONTROL_PROMPT,
1791
1846
  approvalMode: "local-live-voice",
1792
1847
  content: leg.content,
1793
1848
  isInbound: true,
@@ -2461,6 +2516,13 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
2461
2516
  utterance: UtteranceCycle,
2462
2517
  reason: string,
2463
2518
  ): Promise<void> {
2519
+ // An utterance that finalizes here never became a turn (empty transcript,
2520
+ // client interrupt, transcriber close, error), so it ends the window a
2521
+ // barge-in's merge context was waiting to attach to. Drop that context so
2522
+ // it can't leak into a later, unrelated turn. The barged turn itself
2523
+ // finalizes through finalizeAssistantTurn, not here, so this never clears a
2524
+ // request that the barge-in follow-up turn is still about to consume.
2525
+ this.pendingInterruptedRequest = null;
2464
2526
  utterance.completed = true;
2465
2527
  const turnId = utterance.turnId;
2466
2528
  if (!turnId) {
@@ -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,