@vellumai/assistant 0.12.2-dev.202609212114.08dacde → 0.12.2-dev.202609212314.ad5e307

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
@@ -70,16 +70,16 @@ bun run src/index.ts # interactive CLI session
70
70
 
71
71
  ### CLI commands
72
72
 
73
- | Command | Description |
74
- | -------------------------------------------------- | ------------------------------------------------ |
75
- | `vellum wake` | Start assistant + gateway from current checkout |
76
- | `vellum sleep` | Stop assistant + gateway processes |
77
- | `vellum ps` | List assistants and per-assistant process status |
78
- | `assistant` | Launch interactive CLI session |
73
+ | Command | Description |
74
+ | ---------------------------------------------------------- | ------------------------------------------------ |
75
+ | `vellum wake` | Start assistant + gateway from current checkout |
76
+ | `vellum sleep` | Stop assistant + gateway processes |
77
+ | `vellum ps` | List assistants and per-assistant process status |
78
+ | `assistant` | Launch interactive CLI session |
79
79
  | `assistant conversations list\|search\|new\|export\|clear` | Manage conversations |
80
- | `assistant config set\|get\|list` | Manage configuration |
81
- | `assistant keys set\|list\|delete` | Manage API keys in secure storage |
82
- | `assistant trust list\|add\|update\|remove` | Manage trust rules |
80
+ | `assistant config set\|get\|list` | Manage configuration |
81
+ | `assistant keys set\|list\|delete` | Manage API keys in secure storage |
82
+ | `assistant trust list\|add\|update\|remove` | Manage trust rules |
83
83
 
84
84
  ## Project Structure
85
85
 
@@ -183,7 +183,7 @@ Internal forwarding routes (`/v1/internal/twilio/*`) are unaffected — these ac
183
183
  The `/channels/inbound` endpoint requires a JWT with the `svc_gateway` principal type and `ingress.write` scope to prove the request originated from the gateway. This ensures channel messages can only arrive via the gateway (which performs webhook-level verification) and not via direct HTTP calls that bypass signature checks.
184
184
 
185
185
  - **JWT-based enforcement:** The route policy in `route-policy.ts` restricts `/channels/inbound` to the `svc_gateway` principal type with `ingress.write` scope. Actor and local principals are rejected with 403.
186
- - **Auth bypass:** When `DISABLE_HTTP_AUTH=true` is set (platform-managed deployments), JWT verification is skipped and a synthetic context is used.
186
+ - **Auth bypass:** When `DISABLE_HTTP_AUTH=true` is set (platform-managed deployments), a request that supplies no `Authorization` header gets a synthetic context. A request that supplies one is verified normally, and a token that fails verification is rejected.
187
187
 
188
188
  ## Twilio Setup Primitive
189
189
 
@@ -244,8 +244,8 @@ The channel guardian service generates verification challenge instructions with
244
244
  ### Operator Notes
245
245
 
246
246
  - **Verification input format:** Channel verification accepts a bare code reply only (6-digit numeric for identity-bound sessions; 64-char hex for unbound inbound/bootstrap compatibility).
247
- - **Rebind requirement:** Creating a new guardian challenge when a binding already exists requires `rebind: true` in the HTTP request. Without it, the assistant returns `already_bound`. This prevents accidental guardian replacement.
248
- - **Takeover prevention:** Verification is rejected when an active binding exists for a different external user. Same-user re-verification is allowed.
247
+ - **Rebind requirement:** Creating a new guardian challenge when a binding already exists requires `rebind: true` in the HTTP request. Without it, the assistant returns `already_bound`. On text channels the resulting code can only be redeemed by the account already bound, which is how the same guardian verifies again; to move the guardian to a different account, revoke the binding first and verify again. An outbound phone verification is the exception: its code replaces the bound number.
248
+ - **Takeover prevention:** On text channels, verification is rejected when an active binding exists for a different external user: the code is spent, the reply is the generic "invalid or expired", and the sender is made neither guardian nor contact. Same-user re-verification is allowed, including for a guardian who revoked their binding and is verifying the same account again. Phone differs: an outbound verification with `rebind: true` replaces the bound number once its code is entered, and an inbound call from a different number is not bound.
249
249
 
250
250
  ### Vellum Guardian Identity (Actor Tokens)
251
251
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.12.2-dev.202609212114.08dacde",
3
+ "version": "0.12.2-dev.202609212314.ad5e307",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -241,8 +241,10 @@ function makeConfirmationEmittingSession(opts?: {
241
241
  // Tests
242
242
  // ---------------------------------------------------------------------------
243
243
 
244
- const TEST_TOKEN = "test-bearer-token-approvals";
245
- const AUTH_HEADERS = { Authorization: `Bearer ${TEST_TOKEN}` };
244
+ // This suite mocks isHttpAuthDisabled() to true, so a request carrying no
245
+ // bearer authenticates through the dev bypass. A bearer that is present is
246
+ // verified against the signing key, which these tests do not set up.
247
+ const AUTH_HEADERS: Record<string, string> = {};
246
248
 
247
249
  describe("standalone approval endpoints — HTTP layer", () => {
248
250
  let server: RuntimeHttpServer;
@@ -82,8 +82,10 @@ await initializeDb();
82
82
  // Helpers
83
83
  // ---------------------------------------------------------------------------
84
84
 
85
- const TEST_TOKEN = "test-bearer-token-calls";
86
- const AUTH_HEADERS = { Authorization: `Bearer ${TEST_TOKEN}` };
85
+ // This suite mocks isHttpAuthDisabled() to true, so a request carrying no
86
+ // bearer authenticates through the dev bypass. A bearer that is present is
87
+ // verified against the signing key, which these tests do not set up.
88
+ const AUTH_HEADERS: Record<string, string> = {};
87
89
 
88
90
  let ensuredConvIds = new Set<string>();
89
91
 
@@ -55,8 +55,10 @@ afterAll(() => {
55
55
  resetDbForTesting();
56
56
  });
57
57
 
58
- const TEST_TOKEN = "test-bearer-token-attach";
59
- const AUTH_HEADERS = { Authorization: `Bearer ${TEST_TOKEN}` };
58
+ // This suite mocks isHttpAuthDisabled() to true, so a request carrying no
59
+ // bearer authenticates through the dev bypass. A bearer that is present is
60
+ // verified against the signing key, which these tests do not set up.
61
+ const AUTH_HEADERS: Record<string, string> = {};
60
62
 
61
63
  describe("Runtime attachment metadata", () => {
62
64
  let server: RuntimeHttpServer;
@@ -302,8 +302,10 @@ function makePendingApprovalConversation(
302
302
  // Tests
303
303
  // ---------------------------------------------------------------------------
304
304
 
305
- const TEST_TOKEN = "test-bearer-token-send";
306
- const AUTH_HEADERS = { Authorization: `Bearer ${TEST_TOKEN}` };
305
+ // This suite mocks isHttpAuthDisabled() to true, so a request carrying no
306
+ // bearer authenticates through the dev bypass. A bearer that is present is
307
+ // verified against the signing key, which these tests do not set up.
308
+ const AUTH_HEADERS: Record<string, string> = {};
307
309
 
308
310
  describe("POST /v1/messages — queue-if-busy and hub publishing", () => {
309
311
  let server: RuntimeHttpServer;
@@ -44,7 +44,11 @@ Examples:
44
44
  description:
45
45
  "Destination address for outbound verification (handle, phone number, user ID, or email address)",
46
46
  },
47
- { flags: "--rebind", description: "Replace existing guardian binding" },
47
+ {
48
+ flags: "--rebind",
49
+ description:
50
+ "Create a code although the channel already has a guardian (see below)",
51
+ },
48
52
  {
49
53
  flags: "--conversation-id <conversationId>",
50
54
  description: "Conversation ID for inbound challenges",
@@ -74,7 +78,13 @@ Routes between three creation modes based on the provided options:
74
78
  2. Outbound: --channel <ch> --destination <dest>
75
79
  Sends a verification code to the given destination. Supports telegram
76
80
  (handle or chat ID), phone (E.164 number), slack and discord (user ID),
77
- and email. Use --rebind to replace an existing guardian binding.
81
+ and email.
82
+
83
+ --rebind creates a code although the channel already has a guardian. On
84
+ telegram, slack, discord and email, only the account already bound can redeem
85
+ that code, which is how the same guardian verifies again. A code never moves
86
+ the guardian to a different account there: run "revoke" first, then create
87
+ without --rebind. On phone, an outbound code replaces the bound number.
78
88
 
79
89
  3. Inbound: --channel <ch> (no --destination)
80
90
  Generates a challenge secret for the guardian to send back on the
@@ -176,16 +176,16 @@
176
176
  "icon": "\ud83d\udcbb"
177
177
  },
178
178
  {
179
- "name": "ecommerce-wismo-supporter",
179
+ "name": "ecommerce-order-supporter",
180
180
  "description": "Resolves ecommerce Where-Is-My-Order (WISMO) support inquiries, cross-checks real-time carrier tracking milestones, flags delivery exceptions, and stages customer update drafts without helpdesk seat taxes.",
181
181
  "category": "commerce",
182
182
  "icon": "📦",
183
183
  "license": "MIT",
184
- "homepage": "https://github.com/ZeebBoyBlue/ecommerce-wismo-supporter",
184
+ "homepage": "https://github.com/ZeebBoyBlue/ecommerce-order-supporter",
185
185
  "source": {
186
186
  "source": "github",
187
- "repo": "ZeebBoyBlue/ecommerce-wismo-supporter",
188
- "ref": "9218c23d325c749500d59b6ae651f38264a43cd1"
187
+ "repo": "ZeebBoyBlue/ecommerce-order-supporter",
188
+ "ref": "35e2165a14447a897aee750a198c3f166458226b"
189
189
  }
190
190
  },
191
191
  {
@@ -156,7 +156,9 @@ export async function createInboundChallenge(
156
156
  success: false,
157
157
  error: "already_bound",
158
158
  message:
159
- "A guardian is already bound for this channel. Revoke the existing binding first, or set rebind: true to replace.",
159
+ resolvedChannel === "phone"
160
+ ? "A guardian is already bound for this channel. On phone, verify through an outbound call with rebind: true. To a new number, it replaces the bound number once the code is entered. To the bound number, it confirms that number again and leaves the binding as it is. An inbound challenge cannot be completed by phone: a call collects a six-digit code, which an inbound challenge does not issue."
161
+ : "A guardian is already bound for this channel. To verify a different account, revoke the existing binding first. Set rebind: true only to verify the same account again.",
160
162
  channel: resolvedChannel,
161
163
  };
162
164
  }
@@ -27,9 +27,14 @@ import { LocalEmbeddingBackend } from "../embedding-local.js";
27
27
  type Internals = any;
28
28
 
29
29
  /**
30
- * A stand-in for a Bun subprocess whose stdin pipe is broken. `write` throws
31
- * EPIPE the way a real worker's pipe does once the child is gone.
30
+ * A backend of its own for one test. Production gets the per-model instance
31
+ * from `forModel`; constructing directly keeps tests from sharing state.
32
32
  */
33
+ function newBackend(): Internals {
34
+ return new (LocalEmbeddingBackend as Internals)("test-model");
35
+ }
36
+
37
+ /** A stand-in for a Bun subprocess whose stdin `write` fails synchronously. */
33
38
  function brokenPipeProc(pid = 4242) {
34
39
  return {
35
40
  pid,
@@ -196,7 +201,7 @@ describe("PID file ownership", () => {
196
201
  */
197
202
  test("releasePidFile leaves an entry that names someone else's worker", () => {
198
203
  writeFileSync(pidPath, "777");
199
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
204
+ const backend = newBackend();
200
205
 
201
206
  backend.releasePidFile(888);
202
207
 
@@ -206,7 +211,7 @@ describe("PID file ownership", () => {
206
211
 
207
212
  test("releasePidFile drops the entry when it names our worker", () => {
208
213
  writeFileSync(pidPath, "777");
209
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
214
+ const backend = newBackend();
210
215
 
211
216
  backend.releasePidFile(777);
212
217
 
@@ -219,7 +224,7 @@ describe("PID file ownership", () => {
219
224
  */
220
225
  test("disposing an instance with no worker keeps another's PID entry", () => {
221
226
  writeFileSync(pidPath, "777");
222
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
227
+ const backend = newBackend();
223
228
  backend.disposeRequested = true;
224
229
  backend.workerProc = null;
225
230
 
@@ -232,12 +237,12 @@ describe("PID file ownership", () => {
232
237
 
233
238
  describe("broken worker pipe", () => {
234
239
  /**
235
- * A write to a dead worker raises EPIPE. Escaping, it reached the daemon's
236
- * `unhandledRejection` handler and terminated the process; it must instead
237
- * come back as an ordinary failed embed the backend chain can fall back from.
240
+ * A broken pipe comes back as an ordinary failed embed the backend chain can
241
+ * fall back from. An escaping rejection reaches the daemon's
242
+ * `unhandledRejection` handler, which shuts the process down.
238
243
  */
239
244
  test("EPIPE on write resolves the request as an error", async () => {
240
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
245
+ const backend = newBackend();
241
246
  backend.workerProc = brokenPipeProc();
242
247
 
243
248
  const response = await backend.sendRequest(["hello"]);
@@ -247,7 +252,7 @@ describe("broken worker pipe", () => {
247
252
  });
248
253
 
249
254
  test("EPIPE surfaces to embed() as a rejection, not a process crash", async () => {
250
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
255
+ const backend = newBackend();
251
256
  backend.workerProc = brokenPipeProc();
252
257
  // Skip initialization: the worker is already (notionally) running.
253
258
  backend.ensureInitialized = async () => {};
@@ -257,8 +262,34 @@ describe("broken worker pipe", () => {
257
262
  );
258
263
  });
259
264
 
265
+ /**
266
+ * A real pipe, because the failure lives in Bun's behaviour rather than in
267
+ * ours: a batch larger than the pipe buffer, sent to a worker too busy to
268
+ * drain stdin, leaves the write pending, and the pending write rejects when
269
+ * the worker dies. A synchronous guard never sees that rejection.
270
+ */
271
+ test("a write still pending when the worker dies resolves the request as an error", async () => {
272
+ const backend = newBackend();
273
+ const proc = Bun.spawn({
274
+ cmd: [process.execPath, "-e", "setTimeout(() => {}, 60_000)"],
275
+ windowsHide: true,
276
+ stdin: "pipe",
277
+ stdout: "ignore",
278
+ stderr: "ignore",
279
+ });
280
+ spawned.push(proc);
281
+ backend.workerProc = proc;
282
+
283
+ const request = backend.sendRequest(["x".repeat(4 * 1024 * 1024)]);
284
+ proc.kill("SIGKILL");
285
+ const response = await request;
286
+
287
+ expect(response.error).toContain("worker pipe write failed");
288
+ expect(backend.pendingRequests.size).toBe(0);
289
+ });
290
+
260
291
  test("a failed write does not leak the pending request", async () => {
261
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
292
+ const backend = newBackend();
262
293
  backend.workerProc = brokenPipeProc();
263
294
 
264
295
  await backend.sendRequest(["hello"]);
@@ -274,7 +305,7 @@ describe("releasing ownership of a worker", () => {
274
305
  * strands it: no handle, no PID entry, invisible to every later reclaim.
275
306
  */
276
307
  test("stdout ending kills the child before clearing workerProc", async () => {
277
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
308
+ const backend = newBackend();
278
309
  const proc = liveProc();
279
310
  backend.workerProc = proc;
280
311
 
@@ -285,7 +316,7 @@ describe("releasing ownership of a worker", () => {
285
316
  });
286
317
 
287
318
  test("shutdown reaps the worker and resolves only once it exits", async () => {
288
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
319
+ const backend = newBackend();
289
320
  const proc = liveProc(555);
290
321
  backend.workerProc = proc;
291
322
  writeFileSync(getEmbedWorkerPidPath(), "555");
@@ -298,7 +329,7 @@ describe("releasing ownership of a worker", () => {
298
329
  });
299
330
 
300
331
  test("shutdown settles in-flight requests instead of hanging them", async () => {
301
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
332
+ const backend = newBackend();
302
333
  backend.workerProc = liveProc(556);
303
334
 
304
335
  const inFlight = backend.sendRequest(["hello"]);
@@ -315,7 +346,7 @@ describe("releasing ownership of a worker", () => {
315
346
  * pending requests are only settled after the wait.
316
347
  */
317
348
  test("a worker that ignores SIGTERM is escalated to SIGKILL, not waited on forever", async () => {
318
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
349
+ const backend = newBackend();
319
350
  backend.terminateGraceMs = 50;
320
351
  const signals: (string | undefined)[] = [];
321
352
  const wedged = {
@@ -354,7 +385,7 @@ describe("termination that cannot be confirmed", () => {
354
385
  }
355
386
 
356
387
  test("keeps the PID publication instead of unpublishing a possibly-live child", async () => {
357
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
388
+ const backend = newBackend();
358
389
  backend.terminateGraceMs = 20;
359
390
  const proc = wedgedProc();
360
391
  backend.workerProc = proc;
@@ -370,7 +401,7 @@ describe("termination that cannot be confirmed", () => {
370
401
  });
371
402
 
372
403
  test("refuses to start a replacement while the child may still be alive", async () => {
373
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
404
+ const backend = newBackend();
374
405
  // No workerPath recorded, so liveness falls back to a PID probe. Our own
375
406
  // PID is certainly alive, standing in for a child that will not die.
376
407
  backend.unconfirmedWorker = process.pid;
@@ -381,7 +412,7 @@ describe("termination that cannot be confirmed", () => {
381
412
  });
382
413
 
383
414
  test("surfaces the incomplete teardown through embed() rather than failing silently", async () => {
384
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
415
+ const backend = newBackend();
385
416
  backend.unconfirmedWorker = process.pid;
386
417
 
387
418
  await expect(backend.embed(["hello"])).rejects.toThrow(
@@ -401,7 +432,7 @@ describe("termination that cannot be confirmed", () => {
401
432
  });
402
433
  await Bun.sleep(400);
403
434
 
404
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
435
+ const backend = newBackend();
405
436
  backend.workerPath = scriptPath;
406
437
  backend.unconfirmedWorker = proc.pid;
407
438
  writeFileSync(getEmbedWorkerPidPath(), String(proc.pid));
@@ -440,7 +471,7 @@ describe("reclaiming before spawning a replacement", () => {
440
471
  await Bun.sleep(400);
441
472
  writeFileSync(getEmbedWorkerPidPath(), String(proc.pid));
442
473
 
443
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
474
+ const backend = newBackend();
444
475
  await backend.reclaimOwnedWorkers(scriptPath);
445
476
 
446
477
  // Confirmed gone by the time reclaim returns, not merely signalled.
@@ -464,7 +495,7 @@ describe("reclaiming before spawning a replacement", () => {
464
495
  spawned.push(proc);
465
496
  await Bun.sleep(400);
466
497
 
467
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
498
+ const backend = newBackend();
468
499
  backend.terminateGraceMs = 300;
469
500
  await backend.reclaimOwnedWorkers(scriptPath);
470
501
 
@@ -497,7 +528,7 @@ setTimeout(() => {}, 60_000);\n`,
497
528
  expect(workers.length).toBe(1);
498
529
  expect(workers[0].ppid).toBe(parent.pid);
499
530
 
500
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
531
+ const backend = newBackend();
501
532
  backend.terminateGraceMs = 300;
502
533
  await backend.reclaimOwnedWorkers(scriptPath);
503
534
 
@@ -521,7 +552,7 @@ describe("shutdown versus in-flight initialization", () => {
521
552
  * lets the initializer spawn a worker afterwards, with nobody left to reap it.
522
553
  */
523
554
  test("shutdown waits for an in-flight init and reaps the worker it creates", async () => {
524
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
555
+ const backend = newBackend();
525
556
  const proc = liveProc(600);
526
557
 
527
558
  let finishInit: () => void = () => {};
@@ -564,7 +595,7 @@ describe("parent exit orderings", () => {
564
595
  * process's and left it alone. So it kills its own child on the way out.
565
596
  */
566
597
  test("terminateNow kills the worker and releases the entry without waiting", () => {
567
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
598
+ const backend = newBackend();
568
599
  const signals: string[] = [];
569
600
  const proc = {
570
601
  pid: 909,
@@ -590,7 +621,7 @@ describe("parent exit orderings", () => {
590
621
  * process while the child was still being adopted.
591
622
  */
592
623
  test("shutdown does not inherit the model-load wait when init never settles", async () => {
593
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
624
+ const backend = newBackend();
594
625
  backend.terminateGraceMs = 50;
595
626
  // An initialization that never resolves, as during a cold model load.
596
627
  backend.initInFlight = new Promise<void>(() => {});
@@ -602,7 +633,7 @@ describe("parent exit orderings", () => {
602
633
  });
603
634
 
604
635
  test("a backend already shutting down refuses to spawn a replacement", async () => {
605
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
636
+ const backend = newBackend();
606
637
  backend.disposeRequested = true;
607
638
 
608
639
  await expect(backend.embed(["hello"])).rejects.toThrow(/shutting down/);
@@ -621,7 +652,7 @@ describe("transient failures stay transient", () => {
621
652
  const PERMANENT_FAILURE_SENTINEL = "Local embedding backend unavailable";
622
653
 
623
654
  test("an unconfirmed termination does not claim permanent unavailability", async () => {
624
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
655
+ const backend = newBackend();
625
656
  backend.unconfirmedWorker = process.pid;
626
657
 
627
658
  const err = await backend.ensureInitialized().catch((e: Error) => e);
@@ -631,7 +662,7 @@ describe("transient failures stay transient", () => {
631
662
  });
632
663
 
633
664
  test("shutting down does not claim permanent unavailability", async () => {
634
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
665
+ const backend = newBackend();
635
666
  backend.disposeRequested = true;
636
667
 
637
668
  const err = await backend.embed(["hello"]).catch((e: Error) => e);
@@ -652,7 +683,7 @@ describe("audit regressions", () => {
652
683
  * embed queued behind it.
653
684
  */
654
685
  test("a startup failure against a wedged worker does not hang", async () => {
655
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
686
+ const backend = newBackend();
656
687
  backend.terminateGraceMs = 30;
657
688
  const signals: (string | undefined)[] = [];
658
689
  backend.workerProc = {
@@ -680,7 +711,7 @@ describe("audit regressions", () => {
680
711
  * startup for the full two-minute timeout.
681
712
  */
682
713
  test("terminateNow clears the stdout buffer so a retry can parse ready", () => {
683
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
714
+ const backend = newBackend();
684
715
  backend.stdoutBuffer = '{"id":5,"vect';
685
716
  backend.workerProc = null;
686
717
 
@@ -707,7 +738,7 @@ describe("audit regressions", () => {
707
738
  spawned.push(proc);
708
739
  await Bun.sleep(400);
709
740
 
710
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
741
+ const backend = newBackend();
711
742
  backend.workerPath = scriptPath;
712
743
  backend.workerProc = null; // spawned, never adopted
713
744
 
@@ -722,7 +753,7 @@ describe("audit regressions", () => {
722
753
  * contract, so it must leave the instance able to start a replacement.
723
754
  */
724
755
  test("terminateNow leaves the instance reusable", () => {
725
- const backend = new LocalEmbeddingBackend("test-model") as Internals;
756
+ const backend = newBackend();
726
757
  backend.workerProc = null;
727
758
  backend.stdoutReaderActive = true;
728
759
 
@@ -766,3 +797,97 @@ test("orphan reclaim outlasts the embedding reap it must not truncate", () => {
766
797
  EMBEDDING_SHUTDOWN_BUDGET_MS + 1_000,
767
798
  );
768
799
  });
800
+
801
+ describe("one backend per model", () => {
802
+ test("forModel hands out one instance per model", () => {
803
+ const first = LocalEmbeddingBackend.forModel("per-model-a");
804
+
805
+ expect(LocalEmbeddingBackend.forModel("per-model-a")).toBe(first);
806
+ expect(LocalEmbeddingBackend.forModel("per-model-b")).not.toBe(first);
807
+ });
808
+
809
+ /**
810
+ * A backend-cache reset disposes the backend it evicts, and that disposal
811
+ * waits for in-flight embeds. The next embed needs the model again inside
812
+ * that window, and the embeds in flight keep their worker.
813
+ */
814
+ test("needing the model again while a disposal is pending keeps the busy worker", () => {
815
+ const backend = LocalEmbeddingBackend.forModel(
816
+ "per-model-reopen",
817
+ ) as Internals;
818
+ const proc = liveProc(7101);
819
+ backend.workerProc = proc;
820
+ backend.activeEmbeds = 1;
821
+ backend.dispose();
822
+
823
+ const again = LocalEmbeddingBackend.forModel(
824
+ "per-model-reopen",
825
+ ) as Internals;
826
+ backend.activeEmbeds = 0;
827
+ backend.disposeIfIdle();
828
+
829
+ expect(again).toBe(backend);
830
+ expect(again.workerProc).toBe(proc);
831
+ expect(proc.killed).toBe(false);
832
+ });
833
+
834
+ test("a pending disposal nobody withdraws still releases the worker once idle", () => {
835
+ const backend = LocalEmbeddingBackend.forModel(
836
+ "per-model-dispose",
837
+ ) as Internals;
838
+ const proc = liveProc(7102);
839
+ backend.workerProc = proc;
840
+ backend.activeEmbeds = 1;
841
+ backend.dispose();
842
+
843
+ backend.activeEmbeds = 0;
844
+ backend.disposeIfIdle();
845
+
846
+ expect(backend.workerProc).toBeNull();
847
+ expect(proc.killed).toBe(true);
848
+ });
849
+
850
+ /** The process is exiting, so nothing may spawn a worker behind the reap. */
851
+ test("a shut-down backend stays shut down", async () => {
852
+ const backend = LocalEmbeddingBackend.forModel("per-model-shutdown");
853
+ await backend.shutdown();
854
+
855
+ const again = LocalEmbeddingBackend.forModel("per-model-shutdown");
856
+
857
+ expect(again).toBe(backend);
858
+ await expect(again.embed(["hello"])).rejects.toThrow(/shutting down/);
859
+ });
860
+
861
+ /**
862
+ * The backend cache forgets a backend whose disposal is pending, so process
863
+ * teardown reaches it through the class's own list.
864
+ */
865
+ test("shutdownAll reaps a busy backend no cache still holds", async () => {
866
+ const backend = LocalEmbeddingBackend.forModel(
867
+ "per-model-evicted",
868
+ ) as Internals;
869
+ const proc = liveProc(7103);
870
+ backend.workerProc = proc;
871
+ backend.activeEmbeds = 1;
872
+ backend.dispose();
873
+
874
+ await LocalEmbeddingBackend.shutdownAll();
875
+
876
+ expect(proc.killed).toBe(true);
877
+ expect(backend.workerProc).toBeNull();
878
+ });
879
+
880
+ test("terminateAllNow kills a busy backend no cache still holds", () => {
881
+ const backend = LocalEmbeddingBackend.forModel(
882
+ "per-model-evicted-now",
883
+ ) as Internals;
884
+ const proc = liveProc(7104);
885
+ backend.workerProc = proc;
886
+ backend.activeEmbeds = 1;
887
+ backend.dispose();
888
+
889
+ LocalEmbeddingBackend.terminateAllNow();
890
+
891
+ expect(proc.killed).toBe(true);
892
+ });
893
+ });
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Process teardown reaches every local embedding worker the process owns.
3
+ *
4
+ * Kept in its own file: `shutdownEmbeddingBackends` latches the module into its
5
+ * shut-down state for the rest of the process.
6
+ */
7
+ import { expect, test } from "bun:test";
8
+
9
+ import { AssistantConfigSchema } from "../../config/schema.js";
10
+ import {
11
+ clearEmbeddingBackendCache,
12
+ selectEmbeddingBackend,
13
+ shutdownEmbeddingBackends,
14
+ } from "./embedding-backend.js";
15
+
16
+ /** Reach past `private`, which is compile-time only, so tests drive real state. */
17
+ type Internals = any;
18
+
19
+ /**
20
+ * A backend-cache reset forgets a backend whose disposal is waiting on
21
+ * in-flight embeds, while that backend still holds a live worker.
22
+ */
23
+ test("shutdown reaps a busy local worker the cache has already forgotten", async () => {
24
+ const config = AssistantConfigSchema.parse({
25
+ memory: { embeddings: { provider: "local" } },
26
+ });
27
+ const { backend } = await selectEmbeddingBackend(config);
28
+ const delegate = await (backend as Internals).getDelegate();
29
+ let killed = false;
30
+ delegate.workerProc = {
31
+ pid: 7201,
32
+ exited: new Promise<number>(() => {}),
33
+ kill() {
34
+ killed = true;
35
+ },
36
+ stdin: { write: () => 0, flush: () => 0 },
37
+ };
38
+ delegate.terminateGraceMs = 10;
39
+ delegate.activeEmbeds = 1;
40
+
41
+ clearEmbeddingBackendCache();
42
+ expect(killed).toBe(false);
43
+
44
+ await shutdownEmbeddingBackends();
45
+
46
+ expect(killed).toBe(true);
47
+ });