@remnic/core 10.0.187 → 10.0.188

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.
Files changed (170) hide show
  1. package/dist/access-admin-ops-surface.js +38 -38
  2. package/dist/access-cli.js +38 -38
  3. package/dist/access-extraction-force-flush-preempt.js +38 -38
  4. package/dist/access-extraction-force-flush.js +38 -38
  5. package/dist/access-http-briefing.js +38 -38
  6. package/dist/access-http-query.js +38 -38
  7. package/dist/access-http.js +38 -38
  8. package/dist/access-identity-continuity-surface.js +38 -38
  9. package/dist/access-lcm-surface.js +38 -38
  10. package/dist/access-mcp.js +38 -38
  11. package/dist/access-observe-write-surface.js +38 -38
  12. package/dist/access-operations-batch.js +38 -38
  13. package/dist/access-operations.js +38 -38
  14. package/dist/access-recall-concurrency.js +38 -38
  15. package/dist/access-recall-response.js +38 -38
  16. package/dist/access-recall-surface.js +38 -38
  17. package/dist/access-service.js +38 -38
  18. package/dist/active-recall.js +1 -1
  19. package/dist/briefing.js +2 -2
  20. package/dist/buffer-add-turns-bounded.js +2 -2
  21. package/dist/buffer-admission-idempotency.d.ts.map +1 -1
  22. package/dist/buffer-admission-idempotency.js +1 -1
  23. package/dist/buffer-persistence.d.ts +14 -0
  24. package/dist/buffer-persistence.d.ts.map +1 -1
  25. package/dist/buffer-persistence.js +3 -1
  26. package/dist/buffer.js +4 -4
  27. package/dist/calibration.js +3 -3
  28. package/dist/causal-consolidation.js +3 -3
  29. package/dist/{chunk-2ZS7CB5H.js → chunk-2I3ETW3G.js} +2 -2
  30. package/dist/{chunk-PSUSA5SM.js → chunk-2VNMSEZR.js} +2 -2
  31. package/dist/{chunk-LANV6I63.js → chunk-56BNHKZM.js} +7 -7
  32. package/dist/{chunk-3FEQNKMB.js → chunk-5WDUY2ZZ.js} +2 -2
  33. package/dist/{chunk-BANMPRSC.js → chunk-65DWWJKI.js} +2 -2
  34. package/dist/{chunk-O5ZCDK32.js → chunk-6AMFGXG2.js} +39 -11
  35. package/dist/chunk-6AMFGXG2.js.map +1 -0
  36. package/dist/{chunk-VZBKCRU7.js → chunk-6MDHK6NO.js} +2 -2
  37. package/dist/{chunk-2RAVHJCD.js → chunk-6OHCNTKU.js} +2 -2
  38. package/dist/{chunk-K5RGHUX7.js → chunk-A32EBVCZ.js} +2 -2
  39. package/dist/{chunk-KVM3BS5K.js → chunk-ATPY63F5.js} +2 -2
  40. package/dist/chunk-B256MMS7.js +205 -0
  41. package/dist/chunk-B256MMS7.js.map +1 -0
  42. package/dist/{chunk-MOWLANEJ.js → chunk-C6Y2YHJL.js} +2 -2
  43. package/dist/{chunk-IMT7NTFV.js → chunk-CIAQK2OU.js} +6 -1
  44. package/dist/{chunk-IMT7NTFV.js.map → chunk-CIAQK2OU.js.map} +1 -1
  45. package/dist/{chunk-AJVCM2E3.js → chunk-CYX7JI4O.js} +2 -2
  46. package/dist/{chunk-76KL37ON.js → chunk-D3FP4JQI.js} +2 -2
  47. package/dist/{chunk-TQXKUQFX.js → chunk-FZU62GIV.js} +7 -6
  48. package/dist/chunk-FZU62GIV.js.map +1 -0
  49. package/dist/{chunk-YDGQYG4L.js → chunk-H442UKDV.js} +8 -8
  50. package/dist/{chunk-FXDQO7VX.js → chunk-HL53XYHC.js} +3 -3
  51. package/dist/{chunk-4VFEN3WT.js → chunk-IMSLPQJB.js} +2 -2
  52. package/dist/{chunk-FKLSIQBF.js → chunk-K3JGILZC.js} +3 -3
  53. package/dist/{chunk-JRHOL6B5.js → chunk-K6BS5RB4.js} +2 -2
  54. package/dist/{chunk-HHCLV572.js → chunk-KVTUUU7H.js} +2 -2
  55. package/dist/{chunk-TRFSTCQK.js → chunk-LL6WEMTC.js} +34 -6
  56. package/dist/chunk-LL6WEMTC.js.map +1 -0
  57. package/dist/{chunk-L2DYRQQH.js → chunk-MTKSH7HY.js} +30 -30
  58. package/dist/{chunk-2WITFW6F.js → chunk-NKHRIDYP.js} +2 -2
  59. package/dist/{chunk-KYZMCH4I.js → chunk-NN3LMWKA.js} +12 -4
  60. package/dist/chunk-NN3LMWKA.js.map +1 -0
  61. package/dist/{chunk-CTWWMEGR.js → chunk-PCGBESAN.js} +2 -2
  62. package/dist/{chunk-MDXZIU5X.js → chunk-QGT5KNQT.js} +2 -2
  63. package/dist/{chunk-YJZDRM33.js → chunk-QXHWOUS6.js} +3 -3
  64. package/dist/{chunk-OVJAQWHO.js → chunk-RPOG6HLI.js} +2 -2
  65. package/dist/{chunk-2QQCCUXF.js → chunk-RVODERA5.js} +2 -2
  66. package/dist/{chunk-P5FF44G3.js → chunk-T3XOP7TA.js} +4 -4
  67. package/dist/{chunk-FQE5QN5Q.js → chunk-TAPF7T26.js} +2 -2
  68. package/dist/{chunk-7UTCETGK.js → chunk-TQODBIMW.js} +2 -2
  69. package/dist/{chunk-KZJEKKK6.js → chunk-VQQZJ6KJ.js} +3 -3
  70. package/dist/{chunk-I233SAGS.js → chunk-X3ERYOLO.js} +2 -2
  71. package/dist/{chunk-UCCXPMTP.js → chunk-XQF2KLV5.js} +2 -2
  72. package/dist/{chunk-LPYGM6RE.js → chunk-XWPYK5T4.js} +2 -2
  73. package/dist/{chunk-7EPEZYX3.js → chunk-YVXR7CPS.js} +2 -2
  74. package/dist/cli.js +38 -38
  75. package/dist/coding/export-okf-codegraph.js +1 -1
  76. package/dist/compounding/engine.js +3 -3
  77. package/dist/config.js +1 -1
  78. package/dist/connectors/codex-materialize-runner.js +2 -2
  79. package/dist/connectors/index.js +2 -2
  80. package/dist/convergence-refresh.js +4 -4
  81. package/dist/corpus-watermark.js +4 -4
  82. package/dist/entity-retrieval.js +2 -2
  83. package/dist/explicit-capture.js +38 -38
  84. package/dist/extraction.js +6 -6
  85. package/dist/harmonic-retrieval.js +2 -2
  86. package/dist/index.js +38 -38
  87. package/dist/local-llm-helpers.d.ts.map +1 -1
  88. package/dist/local-llm-helpers.js +2 -2
  89. package/dist/local-llm-transport.d.ts +82 -9
  90. package/dist/local-llm-transport.d.ts.map +1 -1
  91. package/dist/local-llm-transport.js +11 -3
  92. package/dist/local-llm.d.ts.map +1 -1
  93. package/dist/local-llm.js +3 -3
  94. package/dist/location/index.js +3 -3
  95. package/dist/maintenance/memory-governance.js +2 -2
  96. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +2 -2
  97. package/dist/maintenance/rebuild-memory-projection-runner.js +4 -4
  98. package/dist/maintenance/rebuild-memory-projection.js +3 -3
  99. package/dist/namespaces/migrate.js +3 -3
  100. package/dist/namespaces/storage.js +2 -2
  101. package/dist/operator-doctor-corpus.js +5 -5
  102. package/dist/operator-toolkit.js +8 -8
  103. package/dist/orchestration/backlog-scheduler.js +39 -39
  104. package/dist/orchestration/buffer-drain-runner.js +39 -39
  105. package/dist/orchestration/maintenance.js +13 -13
  106. package/dist/orchestrator.js +38 -38
  107. package/dist/recall-navigation.js +38 -38
  108. package/dist/resume-bundles.js +1 -1
  109. package/dist/semantic-consolidation.js +3 -3
  110. package/dist/semantic-rule-promotion.js +2 -2
  111. package/dist/semantic-rule-verifier.js +2 -2
  112. package/dist/source-agent-qualifier.js +2 -2
  113. package/dist/standup/build.js +2 -2
  114. package/dist/storage/entity-canonical-id-migration-runner.d.ts.map +1 -1
  115. package/dist/storage.js +1 -1
  116. package/dist/summarizer.js +4 -4
  117. package/dist/support-passport/index.js +4 -4
  118. package/dist/transfer/export-okf.js +2 -2
  119. package/dist/verified-recall.js +2 -2
  120. package/dist/who-knows-cli.js +3 -3
  121. package/dist/who-knows.js +2 -2
  122. package/package.json +2 -2
  123. package/src/buffer-admission-idempotency.test.ts +115 -0
  124. package/src/buffer-admission-idempotency.ts +67 -11
  125. package/src/buffer-persistence.ts +46 -5
  126. package/src/local-llm-headers-timeout.test.ts +246 -16
  127. package/src/local-llm-helpers.ts +14 -4
  128. package/src/local-llm-transport.ts +253 -16
  129. package/src/local-llm.ts +7 -8
  130. package/src/storage/entity-canonical-id-migration-runner.test.ts +90 -0
  131. package/src/storage/entity-canonical-id-migration-runner.ts +10 -0
  132. package/dist/chunk-5YQXWVCP.js +0 -74
  133. package/dist/chunk-5YQXWVCP.js.map +0 -1
  134. package/dist/chunk-KYZMCH4I.js.map +0 -1
  135. package/dist/chunk-O5ZCDK32.js.map +0 -1
  136. package/dist/chunk-TQXKUQFX.js.map +0 -1
  137. package/dist/chunk-TRFSTCQK.js.map +0 -1
  138. /package/dist/{chunk-2ZS7CB5H.js.map → chunk-2I3ETW3G.js.map} +0 -0
  139. /package/dist/{chunk-PSUSA5SM.js.map → chunk-2VNMSEZR.js.map} +0 -0
  140. /package/dist/{chunk-LANV6I63.js.map → chunk-56BNHKZM.js.map} +0 -0
  141. /package/dist/{chunk-3FEQNKMB.js.map → chunk-5WDUY2ZZ.js.map} +0 -0
  142. /package/dist/{chunk-BANMPRSC.js.map → chunk-65DWWJKI.js.map} +0 -0
  143. /package/dist/{chunk-VZBKCRU7.js.map → chunk-6MDHK6NO.js.map} +0 -0
  144. /package/dist/{chunk-2RAVHJCD.js.map → chunk-6OHCNTKU.js.map} +0 -0
  145. /package/dist/{chunk-K5RGHUX7.js.map → chunk-A32EBVCZ.js.map} +0 -0
  146. /package/dist/{chunk-KVM3BS5K.js.map → chunk-ATPY63F5.js.map} +0 -0
  147. /package/dist/{chunk-MOWLANEJ.js.map → chunk-C6Y2YHJL.js.map} +0 -0
  148. /package/dist/{chunk-AJVCM2E3.js.map → chunk-CYX7JI4O.js.map} +0 -0
  149. /package/dist/{chunk-76KL37ON.js.map → chunk-D3FP4JQI.js.map} +0 -0
  150. /package/dist/{chunk-YDGQYG4L.js.map → chunk-H442UKDV.js.map} +0 -0
  151. /package/dist/{chunk-FXDQO7VX.js.map → chunk-HL53XYHC.js.map} +0 -0
  152. /package/dist/{chunk-4VFEN3WT.js.map → chunk-IMSLPQJB.js.map} +0 -0
  153. /package/dist/{chunk-FKLSIQBF.js.map → chunk-K3JGILZC.js.map} +0 -0
  154. /package/dist/{chunk-JRHOL6B5.js.map → chunk-K6BS5RB4.js.map} +0 -0
  155. /package/dist/{chunk-HHCLV572.js.map → chunk-KVTUUU7H.js.map} +0 -0
  156. /package/dist/{chunk-L2DYRQQH.js.map → chunk-MTKSH7HY.js.map} +0 -0
  157. /package/dist/{chunk-2WITFW6F.js.map → chunk-NKHRIDYP.js.map} +0 -0
  158. /package/dist/{chunk-CTWWMEGR.js.map → chunk-PCGBESAN.js.map} +0 -0
  159. /package/dist/{chunk-MDXZIU5X.js.map → chunk-QGT5KNQT.js.map} +0 -0
  160. /package/dist/{chunk-YJZDRM33.js.map → chunk-QXHWOUS6.js.map} +0 -0
  161. /package/dist/{chunk-OVJAQWHO.js.map → chunk-RPOG6HLI.js.map} +0 -0
  162. /package/dist/{chunk-2QQCCUXF.js.map → chunk-RVODERA5.js.map} +0 -0
  163. /package/dist/{chunk-P5FF44G3.js.map → chunk-T3XOP7TA.js.map} +0 -0
  164. /package/dist/{chunk-FQE5QN5Q.js.map → chunk-TAPF7T26.js.map} +0 -0
  165. /package/dist/{chunk-7UTCETGK.js.map → chunk-TQODBIMW.js.map} +0 -0
  166. /package/dist/{chunk-KZJEKKK6.js.map → chunk-VQQZJ6KJ.js.map} +0 -0
  167. /package/dist/{chunk-I233SAGS.js.map → chunk-X3ERYOLO.js.map} +0 -0
  168. /package/dist/{chunk-UCCXPMTP.js.map → chunk-XQF2KLV5.js.map} +0 -0
  169. /package/dist/{chunk-LPYGM6RE.js.map → chunk-XWPYK5T4.js.map} +0 -0
  170. /package/dist/{chunk-7EPEZYX3.js.map → chunk-YVXR7CPS.js.map} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remnic/core",
3
- "version": "10.0.187",
3
+ "version": "10.0.188",
4
4
  "description": "Framework-agnostic Remnic memory engine — orchestrator, storage, extraction, search, trust zones",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -3416,7 +3416,7 @@
3416
3416
  "core"
3417
3417
  ],
3418
3418
  "peerDependencies": {
3419
- "@remnic/coding-graph": "^10.0.187"
3419
+ "@remnic/coding-graph": "^10.0.188"
3420
3420
  },
3421
3421
  "peerDependenciesMeta": {
3422
3422
  "@remnic/coding-graph": {
@@ -311,3 +311,118 @@ test("observe idempotency ring retains keys past the old 512-entry bound", () =>
311
311
  assert.ok(hasBufferedAdmissionIdempotencyKey(state, "k0"), "oldest of 600 keys still deduped");
312
312
  assert.equal(state.admissionIdempotencyOrder!.length, 600);
313
313
  });
314
+
315
+ test("COS-825 full ring keeps FIFO eviction and dedup at the 4096 cap", () => {
316
+ const state: BufferState = {
317
+ turns: [],
318
+ lastExtractionAt: null,
319
+ extractionCount: 0,
320
+ };
321
+ for (let i = 0; i < BUFFER_ADMISSION_IDEMPOTENCY_CAP; i++) {
322
+ recordBufferedAdmissionIdempotencyKey(state, `k${i}`, 1);
323
+ }
324
+ const order = state.admissionIdempotencyOrder!;
325
+ assert.equal(order.length, BUFFER_ADMISSION_IDEMPOTENCY_CAP);
326
+ assert.equal(order[0], "k0");
327
+
328
+ // Same key again: dedup (no re-push, no eviction), turn count refreshed.
329
+ recordBufferedAdmissionIdempotencyKey(state, "k4095", 2);
330
+ assert.equal(order.length, BUFFER_ADMISSION_IDEMPOTENCY_CAP);
331
+ assert.equal(order[order.length - 1], "k4095");
332
+ assert.equal(state.admissionIdempotency!["k4095"], 2);
333
+
334
+ // One new key evicts exactly the oldest entry.
335
+ recordBufferedAdmissionIdempotencyKey(state, "k4096", 1);
336
+ assert.equal(order.length, BUFFER_ADMISSION_IDEMPOTENCY_CAP);
337
+ assert.equal(order[0], "k1");
338
+ assert.equal(hasBufferedAdmissionIdempotencyKey(state, "k0"), false);
339
+ assert.equal(hasBufferedAdmissionIdempotencyKey(state, "k4096"), true);
340
+ assert.equal(hasBufferedAdmissionIdempotencyKey(state, "k1"), true);
341
+ });
342
+
343
+ test("COS-825 perf: 10k record calls on a full ring stay well under 1s", () => {
344
+ const state: BufferState = {
345
+ turns: [],
346
+ lastExtractionAt: null,
347
+ extractionCount: 0,
348
+ };
349
+ for (let i = 0; i < BUFFER_ADMISSION_IDEMPOTENCY_CAP; i++) {
350
+ recordBufferedAdmissionIdempotencyKey(state, `seed${i}`, 1);
351
+ }
352
+ const t0 = performance.now();
353
+ for (let i = 0; i < 10_000; i++) {
354
+ recordBufferedAdmissionIdempotencyKey(state, `new${i}`, 1);
355
+ }
356
+ const ms = performance.now() - t0;
357
+ assert.ok(
358
+ ms < 500,
359
+ `10k record calls on a full ring took ${ms.toFixed(0)}ms — ring reconciliation is not O(n) amortized`,
360
+ );
361
+ assert.equal(state.admissionIdempotencyOrder!.length, BUFFER_ADMISSION_IDEMPOTENCY_CAP);
362
+ assert.equal(hasBufferedAdmissionIdempotencyKey(state, "seed0"), false, "oldest seed evicted");
363
+ assert.equal(hasBufferedAdmissionIdempotencyKey(state, "new9999"), true, "newest key retained");
364
+ });
365
+
366
+ test("COS-825 admission idempotency persists at most once per second under steady load", async () => {
367
+ class AdmissionRateStorage {
368
+ admissionPersistSaves = 0;
369
+ private initial: BufferState = { turns: [], lastExtractionAt: null, extractionCount: 0 };
370
+ async loadBuffer(): Promise<BufferState> {
371
+ return structuredClone(this.initial);
372
+ }
373
+ async saveBuffer(state: BufferState): Promise<void> {
374
+ this.initial = structuredClone(state);
375
+ }
376
+ async saveBufferSession(): Promise<void> {}
377
+ async saveBufferAdmissionIdempotency(): Promise<void> {
378
+ this.admissionPersistSaves++;
379
+ }
380
+ async deleteBufferSession(): Promise<void> {}
381
+ isBufferSessionClaimed(): boolean {
382
+ return false;
383
+ }
384
+ }
385
+
386
+ const storage = new AdmissionRateStorage();
387
+ const entries = new Map<string, BufferEntryState>();
388
+ const peek = (key: string) => entries.get(key);
389
+ const persistence = new BufferSessionPersistence();
390
+ let now = 1_000;
391
+ const clock = () => now;
392
+ const state: BufferState = {
393
+ turns: [],
394
+ lastExtractionAt: null,
395
+ extractionCount: 0,
396
+ admissionIdempotency: { "obs-key": 1 },
397
+ };
398
+
399
+ // First persist under steady load writes (never defers a first write).
400
+ persistence.markAdmissionIdempotencyDirty();
401
+ const first = await persistence.persist(storage, state, peek, undefined, { now: clock, allowDeferral: true });
402
+ assert.equal(storage.admissionPersistSaves, 1, "first admission write is immediate");
403
+ assert.equal(persistence.hasPending(), false);
404
+
405
+ // A write less than a second later is rate-limited: dirty stays, retry armed.
406
+ persistence.markAdmissionIdempotencyDirty();
407
+ now += 100;
408
+ const second = await persistence.persist(storage, state, peek, undefined, { now: clock, allowDeferral: true });
409
+ assert.equal(storage.admissionPersistSaves, 1, "second write within 1s is coalesced");
410
+ assert.equal(persistence.hasPending(), true, "coalesced write stays pending");
411
+ assert.ok(
412
+ second.deferredRetryDelayMs !== undefined && second.deferredRetryDelayMs <= 900,
413
+ `retry armed for the tail write, got ${second.deferredRetryDelayMs}`,
414
+ );
415
+
416
+ // Past the interval the pending write lands.
417
+ now += 1_000;
418
+ await persistence.persist(storage, state, peek, undefined, { now: clock, allowDeferral: true });
419
+ assert.equal(storage.admissionPersistSaves, 2, "interval elapse lands the pending write");
420
+ assert.equal(persistence.hasPending(), false);
421
+
422
+ // Durability barrier (no allowDeferral) writes immediately despite the rate limit.
423
+ persistence.markAdmissionIdempotencyDirty();
424
+ now += 100;
425
+ await persistence.persist(storage, state, peek, undefined, { now: clock });
426
+ assert.equal(storage.admissionPersistSaves, 3, "barrier writes bypass the rate limit");
427
+ assert.equal(persistence.hasPending(), false);
428
+ });
@@ -3,7 +3,6 @@ export interface BufferAdmissionIdempotencyState {
3
3
  admissionIdempotency?: Record<string, number>;
4
4
  admissionIdempotencyOrder?: string[];
5
5
  }
6
-
7
6
  /**
8
7
  * FIFO bound on recorded observe-buffer admission keys per session buffer.
9
8
  * 4096 retains the most recent keys per session — roughly two
@@ -41,18 +40,64 @@ export function ensureAdmissionIdempotencyMap(state: BufferAdmissionIdempotencyS
41
40
  return map;
42
41
  }
43
42
 
44
- export function ensureAdmissionIdempotencyOrder(state: BufferAdmissionIdempotencyState): string[] {
45
- if (!state.admissionIdempotencyOrder) {
46
- state.admissionIdempotencyOrder = [];
47
- }
48
- const order = state.admissionIdempotencyOrder;
49
- const map = state.admissionIdempotency;
43
+ /**
44
+ * Derived membership index for {@link ensureAdmissionIdempotencyOrder}'s array,
45
+ * keyed on the state object (never persisted — the on-disk format stays
46
+ * {keys, order}). Mirrors the order array and the map's key count, so the
47
+ * healthy path is O(1): the old code ran an `order.includes` scan over every
48
+ * map key on EVERY observe — O(n²) once the ring widened to 4096 keys
49
+ * (COS-825 CPU profile: 6.1% self time in this reconcile alone).
50
+ *
51
+ * The map and order can legitimately diverge only on restore (an order array
52
+ * that predates some map keys), so reconciliation runs when the cached map
53
+ * size and the order length disagree — the prescribed heuristic. A
54
+ * same-length but different-membership order (hand corruption) is tolerated
55
+ * until the next membership change, matching the prescription; the map, not
56
+ * the order, stays authoritative for dedup questions.
57
+ */
58
+ const admissionIdempotencyOrderIndex = new WeakMap<
59
+ BufferAdmissionIdempotencyState,
60
+ { set: Set<string>; mapSize: number }
61
+ >();
62
+
63
+ function reconcileAdmissionIdempotencyIndex(
64
+ state: BufferAdmissionIdempotencyState,
65
+ order: string[],
66
+ map: Record<string, number> | undefined,
67
+ ) {
68
+ const set = new Set(order);
69
+ let mapSize = 0;
50
70
  if (map) {
51
71
  for (const key of Object.keys(map)) {
52
- if (Object.hasOwn(map, key) && !order.includes(key)) order.push(key);
72
+ if (!Object.hasOwn(map, key)) continue;
73
+ mapSize++;
74
+ if (!set.has(key)) {
75
+ order.push(key);
76
+ set.add(key);
77
+ }
53
78
  }
54
79
  }
55
- return order;
80
+ const entry = { set, mapSize };
81
+ admissionIdempotencyOrderIndex.set(state, entry);
82
+ return entry;
83
+ }
84
+
85
+ function admissionIdempotencyIndexFor(
86
+ state: BufferAdmissionIdempotencyState,
87
+ order: string[],
88
+ map: Record<string, number> | undefined,
89
+ ) {
90
+ const entry = admissionIdempotencyOrderIndex.get(state);
91
+ if (entry && entry.mapSize === order.length) return entry;
92
+ return reconcileAdmissionIdempotencyIndex(state, order, map);
93
+ }
94
+
95
+ export function ensureAdmissionIdempotencyOrder(state: BufferAdmissionIdempotencyState): string[] {
96
+ if (!state.admissionIdempotencyOrder) {
97
+ state.admissionIdempotencyOrder = [];
98
+ }
99
+ admissionIdempotencyIndexFor(state, state.admissionIdempotencyOrder, state.admissionIdempotency);
100
+ return state.admissionIdempotencyOrder;
56
101
  }
57
102
 
58
103
  export function hasBufferedAdmissionIdempotencyKey(state: BufferAdmissionIdempotencyState, key: string): boolean {
@@ -67,10 +112,21 @@ export function recordBufferedAdmissionIdempotencyKey(state: BufferAdmissionIdem
67
112
  if (!trimmed || turnCount <= 0) return;
68
113
  const map = ensureAdmissionIdempotencyMap(state);
69
114
  const order = ensureAdmissionIdempotencyOrder(state);
115
+ const { set, mapSize } = admissionIdempotencyIndexFor(state, order, map);
116
+ const wasMapKey = Object.hasOwn(map, trimmed);
70
117
  map[trimmed] = turnCount;
71
- if (!order.includes(trimmed)) order.push(trimmed);
118
+ if (!set.has(trimmed)) {
119
+ order.push(trimmed);
120
+ set.add(trimmed);
121
+ }
122
+ const index = admissionIdempotencyOrderIndex.get(state)!;
123
+ index.mapSize = mapSize + (wasMapKey ? 0 : 1);
72
124
  while (order.length > BUFFER_ADMISSION_IDEMPOTENCY_CAP) {
73
125
  const evicted = order.shift();
74
- if (evicted !== undefined) delete map[evicted];
126
+ if (evicted !== undefined) {
127
+ set.delete(evicted);
128
+ delete map[evicted];
129
+ index.mapSize--;
130
+ }
75
131
  }
76
132
  }
@@ -52,6 +52,16 @@ export const BUFFER_SESSION_DEFER_MIN_BYTES = 8 * 1024 * 1024;
52
52
  /** A session past the size floor is rewritten at most once per this interval. */
53
53
  export const BUFFER_SESSION_DEFER_INTERVAL_MS = 60_000;
54
54
 
55
+ /**
56
+ * The admission-idempotency metadata file is rewritten at most once per this
57
+ * interval on steady-state passes (COS-825: it is ~1.16 MB and every observe
58
+ * marks it dirty, so under fleet load it was re-serialized ~4x/s). The keys
59
+ * stay in memory until the coalesced write lands; the pass arms
60
+ * deferredRetryDelayMs so the tail write happens even if observes stop, and
61
+ * durability barriers (allowDeferral omitted/false) always write immediately.
62
+ */
63
+ export const ADMISSION_IDEMPOTENCY_PERSIST_INTERVAL_MS = 1_000;
64
+
55
65
  export interface BufferPersistOptions {
56
66
  /** Injectable clock (monotonic ms) for tests. */
57
67
  now?: () => number;
@@ -92,20 +102,26 @@ export interface BufferSessionPersistenceOptions {
92
102
  now?: () => number;
93
103
  /** Test seam: override BUFFER_SESSION_DEFER_INTERVAL_MS. */
94
104
  deferIntervalMs?: number;
105
+ /** Test seam: override ADMISSION_IDEMPOTENCY_PERSIST_INTERVAL_MS. */
106
+ admissionPersistIntervalMs?: number;
95
107
  }
96
108
 
97
109
  export class BufferSessionPersistence {
98
110
  private readonly dirty = new Set<string>();
99
111
  private readonly deleted = new Set<string>();
100
112
  private admissionIdempotencyDirty = false;
113
+ /** Last successful admission-idempotency write (rate-limit bookkeeping, COS-825). */
114
+ private lastAdmissionPersistAt?: number;
101
115
  /** Last successful session-file write per key (deferral bookkeeping, #3389). */
102
116
  private readonly lastPersistedAt = new Map<string, number>();
103
117
  private readonly clock: () => number;
104
118
  private readonly deferIntervalMs: number;
119
+ private readonly admissionPersistIntervalMs: number;
105
120
 
106
121
  constructor(options: BufferSessionPersistenceOptions = {}) {
107
122
  this.clock = options.now ?? (() => performance.now());
108
123
  this.deferIntervalMs = options.deferIntervalMs ?? BUFFER_SESSION_DEFER_INTERVAL_MS;
124
+ this.admissionPersistIntervalMs = options.admissionPersistIntervalMs ?? ADMISSION_IDEMPOTENCY_PERSIST_INTERVAL_MS;
109
125
  }
110
126
 
111
127
  markDirty(key: string): void {
@@ -156,13 +172,22 @@ export class BufferSessionPersistence {
156
172
  const deleteSession = storage.deleteBufferSession?.bind(storage);
157
173
  if (!saveSession || !deleteSession) {
158
174
  await storage.saveBuffer(state);
175
+ let admissionDeferredMs: number | undefined;
159
176
  if (this.admissionIdempotencyDirty && storage.saveBufferAdmissionIdempotency) {
160
- await storage.saveBufferAdmissionIdempotency(state);
177
+ const nowMs = (opts?.now ?? this.clock)();
178
+ const since = this.lastAdmissionPersistAt === undefined ? Infinity : nowMs - this.lastAdmissionPersistAt;
179
+ if (opts?.allowDeferral === true && since < this.admissionPersistIntervalMs) {
180
+ admissionDeferredMs = this.admissionPersistIntervalMs - since;
181
+ } else {
182
+ await storage.saveBufferAdmissionIdempotency(state);
183
+ this.admissionIdempotencyDirty = false;
184
+ this.lastAdmissionPersistAt = nowMs;
185
+ }
161
186
  }
162
187
  this.dirty.clear();
163
188
  this.deleted.clear();
164
- this.admissionIdempotencyDirty = false;
165
- return { handedOver: [], drainedTurns, deferred: [] };
189
+ if (admissionDeferredMs === undefined) this.admissionIdempotencyDirty = false;
190
+ return { handedOver: [], drainedTurns, deferred: [], deferredRetryDelayMs: admissionDeferredMs };
166
191
  }
167
192
  const now = opts?.now ?? this.clock;
168
193
  const handedOver: string[] = [];
@@ -218,14 +243,30 @@ export class BufferSessionPersistence {
218
243
  // #3368: never persist admission keys while session bodies are still deferred —
219
244
  // a crash after the key lands but before the deferred rewrite would make a
220
245
  // same-key retry swallow the unwritten turns.
246
+ let admissionDeferredMs: number | undefined;
221
247
  if (this.admissionIdempotencyDirty && deferred.length === 0 && storage.saveBufferAdmissionIdempotency) {
222
- await storage.saveBufferAdmissionIdempotency(state);
223
- this.admissionIdempotencyDirty = false;
248
+ // COS-825: steady-state passes coalesce this ~1.16 MB rewrite to at most
249
+ // one per interval; the tail write arms deferredRetryDelayMs so it lands
250
+ // even if observes stop. Barriers (allowDeferral omitted) always write.
251
+ const since = this.lastAdmissionPersistAt === undefined ? Infinity : now() - this.lastAdmissionPersistAt;
252
+ if (opts?.allowDeferral === true && since < this.admissionPersistIntervalMs) {
253
+ admissionDeferredMs = this.admissionPersistIntervalMs - since;
254
+ } else {
255
+ await storage.saveBufferAdmissionIdempotency(state);
256
+ this.admissionIdempotencyDirty = false;
257
+ this.lastAdmissionPersistAt = now();
258
+ }
224
259
  }
225
260
  const outcome: BufferPersistOutcome = { handedOver, drainedTurns, deferred };
226
261
  if (deferred.length > 0 && nextEligibleAt !== undefined) {
227
262
  outcome.deferredRetryDelayMs = Math.max(0, nextEligibleAt - now());
228
263
  }
264
+ if (admissionDeferredMs !== undefined) {
265
+ const retry = Math.max(0, admissionDeferredMs);
266
+ if (outcome.deferredRetryDelayMs === undefined || retry < outcome.deferredRetryDelayMs) {
267
+ outcome.deferredRetryDelayMs = retry;
268
+ }
269
+ }
229
270
  return outcome;
230
271
  }
231
272
  }
@@ -5,6 +5,7 @@ import test from "node:test";
5
5
 
6
6
  import {
7
7
  Agent,
8
+ EnvHttpProxyAgent,
8
9
  ProxyAgent,
9
10
  fetch as undiciFetch,
10
11
  getGlobalDispatcher,
@@ -14,7 +15,7 @@ import {
14
15
  import { LocalLlmClient } from "./local-llm.js";
15
16
  import { probeFetch, type LocalLlmChatCompletionOptions } from "./local-llm-helpers.js";
16
17
  import { classifyAnalysisProviderError } from "./activity/timeline/analysis-provider.js";
17
- import { ChatTransport } from "./local-llm-transport.js";
18
+ import { ChatTransport, EXTRACTION_MIN_TRANSPORT_BUDGET_MS, isInvalidDispatcherArg, resolveProxyEnv, routeBudgets } from "./local-llm-transport.js";
18
19
  import { initLogger, resetLogger } from "./logger.js";
19
20
  import type { PluginConfig } from "./types.js";
20
21
 
@@ -82,9 +83,11 @@ function dispatcherOf(client: LocalLlmClient): Agent {
82
83
  chatTransport: ChatTransport;
83
84
  config: PluginConfig;
84
85
  };
85
- const agent = seam.chatTransport.dispatcherFor(seam.config.localLlmTimeoutMs);
86
- assert.ok(agent, "expected a widened pool under the default global dispatcher");
87
- return agent;
86
+ const dispatcher = seam.chatTransport.dispatcherFor(seam.config.localLlmTimeoutMs);
87
+ // The direct/plain path returns the widened Agent; the proxyline chain
88
+ // returns a ProxyAgent, which its own test covers.
89
+ assert.ok(dispatcher instanceof Agent, "expected a widened pool under the default global dispatcher");
90
+ return dispatcher;
88
91
  }
89
92
 
90
93
  function undiciErrorCode(err: unknown): string | undefined {
@@ -467,27 +470,41 @@ test("a truncated 503 body retains the configured retry", async () => {
467
470
  test("a process-wide custom dispatcher is left in place", async () => {
468
471
  // A deployment may reach the local endpoint only through a ProxyAgent (or
469
472
  // another custom connect/TLS/DNS transport) installed with
470
- // setGlobalDispatcher. Swapping in our own pool would bypass it and break
471
- // the request outright, so the widened pool must stand down.
473
+ // setGlobalDispatcher. When no standard proxy environment variable names
474
+ // that route, the transport cannot mirror it: swapping in our own pool
475
+ // would bypass it and break the request outright, so the global
476
+ // dispatcher must stand down untouched.
472
477
  const original = getGlobalDispatcher();
473
478
  const proxy = new ProxyAgent("http://127.0.0.1:9");
479
+ const prior = {
480
+ HTTPS_PROXY: process.env.HTTPS_PROXY,
481
+ https_proxy: process.env.https_proxy,
482
+ HTTP_PROXY: process.env.HTTP_PROXY,
483
+ http_proxy: process.env.http_proxy,
484
+ REMNIC_LOCAL_LLM_DIRECT: process.env.REMNIC_LOCAL_LLM_DIRECT,
485
+ };
474
486
  try {
487
+ for (const key of Object.keys(prior)) delete process.env[key];
475
488
  setGlobalDispatcher(proxy);
476
489
  const transport = new ChatTransport();
477
490
  assert.equal(
478
491
  transport.dispatcherFor(900_000),
479
492
  undefined,
480
- "must not displace a non-Agent global dispatcher",
493
+ "no named proxy environment: the transport cannot mirror the custom dispatcher",
494
+ );
495
+ assert.equal(
496
+ getGlobalDispatcher(),
497
+ proxy,
498
+ "must not displace a non-Agent global dispatcher it cannot mirror",
481
499
  );
482
500
  } finally {
501
+ for (const [key, value] of Object.entries(prior)) {
502
+ if (value !== undefined) process.env[key] = value;
503
+ else delete process.env[key];
504
+ }
483
505
  setGlobalDispatcher(original);
484
506
  await proxy.close();
485
507
  }
486
-
487
- // ...and the widened pool returns once the default transport is back.
488
- const restored = new ChatTransport().dispatcherFor(900_000);
489
- assert.ok(restored);
490
- await restored.close();
491
508
  });
492
509
 
493
510
  test("an explicit opt-in widens the pool even when a custom global dispatcher is installed", async () => {
@@ -499,10 +516,16 @@ test("an explicit opt-in widens the pool even when a custom global dispatcher is
499
516
  // previous behavior (leave the custom dispatcher alone) is unchanged.
500
517
  const original = getGlobalDispatcher();
501
518
  const proxy = new ProxyAgent("http://127.0.0.1:9");
502
- const priorFlag = process.env.REMNIC_LOCAL_LLM_DIRECT;
519
+ const prior = {
520
+ HTTPS_PROXY: process.env.HTTPS_PROXY,
521
+ https_proxy: process.env.https_proxy,
522
+ HTTP_PROXY: process.env.HTTP_PROXY,
523
+ http_proxy: process.env.http_proxy,
524
+ REMNIC_LOCAL_LLM_DIRECT: process.env.REMNIC_LOCAL_LLM_DIRECT,
525
+ };
503
526
  try {
527
+ for (const key of Object.keys(prior)) delete process.env[key];
504
528
  setGlobalDispatcher(proxy);
505
- delete process.env.REMNIC_LOCAL_LLM_DIRECT;
506
529
  assert.equal(new ChatTransport().dispatcherFor(900_000), undefined, "no flag: custom dispatcher stays");
507
530
 
508
531
  process.env.REMNIC_LOCAL_LLM_DIRECT = "1";
@@ -515,13 +538,60 @@ test("an explicit opt-in widens the pool even when a custom global dispatcher is
515
538
  process.env.REMNIC_LOCAL_LLM_DIRECT = "0";
516
539
  assert.equal(new ChatTransport().dispatcherFor(900_000), undefined, "flag 0: custom dispatcher stays");
517
540
  } finally {
518
- if (priorFlag === undefined) delete process.env.REMNIC_LOCAL_LLM_DIRECT;
519
- else process.env.REMNIC_LOCAL_LLM_DIRECT = priorFlag;
541
+ for (const [key, value] of Object.entries(prior)) {
542
+ if (value !== undefined) process.env[key] = value;
543
+ else delete process.env[key];
544
+ }
520
545
  setGlobalDispatcher(original);
521
546
  await proxy.close();
522
547
  }
523
548
  });
524
549
 
550
+ test("a request the runtime rejects with UND_ERR_INVALID_ARG falls back to the bundled undici fetch", async () => {
551
+ // Node 26 rejects a per-request dispatcher in global fetch's init with
552
+ // UND_ERR_INVALID_ARG, wrapped in TypeError("fetch failed"). The transport
553
+ // must retry through the bundled undici's fetch — which accepts the same
554
+ // init — rather than dying on the widened-budget path.
555
+ const server = http.createServer((_req, res) => {
556
+ res.setHeader("content-type", "application/json");
557
+ res.end('{"choices":[{"message":{"content":"the answer"}}]}');
558
+ });
559
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
560
+ // SAFETY: listen(0, "127.0.0.1") above binds a TCP port, so address() is an AddressInfo, never a pipe string or null.
561
+ const { port } = server.address() as AddressInfo;
562
+ const original = globalThis.fetch;
563
+ const globalCalls: string[] = [];
564
+ try {
565
+ const fakeFetch: typeof fetch = async (url) => {
566
+ globalCalls.push(String(url));
567
+ throw Object.assign(new TypeError("fetch failed"), { code: "UND_ERR_INVALID_ARG" });
568
+ };
569
+ globalThis.fetch = fakeFetch;
570
+ const transport = new ChatTransport();
571
+ const response = await transport.post({
572
+ url: `http://127.0.0.1:${port}/v1/chat/completions`,
573
+ budgetMs: 60_000,
574
+ headers: { "content-type": "application/json" },
575
+ body: "{}",
576
+ signal: AbortSignal.timeout(30_000),
577
+ });
578
+ assert.equal(response.status, 200, "the undici fallback must serve the request");
579
+ assert.ok(globalCalls.length >= 1, "the global fetch was attempted first");
580
+ } finally {
581
+ globalThis.fetch = original;
582
+ await new Promise<void>((resolve) => server.close(() => resolve()));
583
+ }
584
+ });
585
+
586
+ test("isInvalidDispatcherArg finds the code on the error and down its cause chain", () => {
587
+ const direct = Object.assign(new TypeError("fetch failed"), { code: "UND_ERR_INVALID_ARG" });
588
+ assert.equal(isInvalidDispatcherArg(direct), true);
589
+ const wrapped = new TypeError("fetch failed", { cause: direct });
590
+ assert.equal(isInvalidDispatcherArg(wrapped), true);
591
+ const plain = Object.assign(new TypeError("fetch failed"), { code: "ECONNREFUSED" });
592
+ assert.equal(isInvalidDispatcherArg(plain), false);
593
+ });
594
+
525
595
  test("REMNIC_LOCAL_LLM_DIRECT=1 also sends availability probes around a global proxy dispatcher", async () => {
526
596
  // A host whose global dispatcher cannot reach the LAN model server would fail
527
597
  // checkAvailability() before any chat request runs, so direct mode must cover
@@ -670,3 +740,163 @@ test("failureDiag preserves a 429 rate-limit failure cause (issue #2891)", { con
670
740
  await dispatcherOf(client).close();
671
741
  }
672
742
  });
743
+
744
+ test("the proxyline dispatcher is chained with the widened budgets when the proxy environment names it", async () => {
745
+ // Issue #2148 root cause: an agent runtime's managed proxy dispatcher
746
+ // ("proxyline") kept undici's 300s headersTimeout, so extraction
747
+ // calls over five minutes died. When the standard egress-proxy variables
748
+ // name the route, dispatcherFor chains a ProxyAgent over the SAME proxy
749
+ // with the route's budgets instead of leaving the cap in place.
750
+ const original = getGlobalDispatcher();
751
+ const proxy = new ProxyAgent("http://127.0.0.1:9");
752
+ const prior = {
753
+ HTTPS_PROXY: process.env.HTTPS_PROXY,
754
+ https_proxy: process.env.https_proxy,
755
+ HTTP_PROXY: process.env.HTTP_PROXY,
756
+ http_proxy: process.env.http_proxy,
757
+ REMNIC_LOCAL_LLM_DIRECT: process.env.REMNIC_LOCAL_LLM_DIRECT,
758
+ };
759
+ try {
760
+ setGlobalDispatcher(proxy);
761
+ delete process.env.https_proxy;
762
+ delete process.env.HTTP_PROXY;
763
+ delete process.env.http_proxy;
764
+ delete process.env.REMNIC_LOCAL_LLM_DIRECT;
765
+ process.env.HTTPS_PROXY = "http://127.0.0.1:9";
766
+ const transport = new ChatTransport();
767
+ const chained = transport.dispatcherFor(900_000);
768
+ assert.ok(
769
+ chained instanceof EnvHttpProxyAgent,
770
+ "a named proxy environment must produce a chained EnvHttpProxyAgent, not undefined",
771
+ );
772
+ const again = transport.dispatcherFor(900_000);
773
+ assert.equal(again, chained, "the chained proxy pool is cached per proxy+budget");
774
+ await chained.close();
775
+ } finally {
776
+ for (const [key, value] of Object.entries(prior)) {
777
+ if (value !== undefined) process.env[key] = value;
778
+ else delete process.env[key];
779
+ }
780
+ setGlobalDispatcher(original);
781
+ await proxy.close();
782
+ }
783
+ });
784
+
785
+ test("NO_PROXY on the request URL keeps the installed custom dispatcher instead of replacing it", async () => {
786
+ // A host may install a global dispatcher whose custom DNS or connect logic
787
+ // the local endpoint needs (for example model.internal resolves only
788
+ // through it). With NO_PROXY covering that host, the environment routes
789
+ // the request direct — but a fresh direct pool cannot reproduce the
790
+ // custom transport, so dispatcherFor must leave the installed dispatcher
791
+ // in place rather than swapping in the chained EnvHttpProxyAgent either.
792
+ const original = getGlobalDispatcher();
793
+ const proxy = new ProxyAgent("http://127.0.0.1:9");
794
+ const prior = {
795
+ HTTPS_PROXY: process.env.HTTPS_PROXY,
796
+ https_proxy: process.env.https_proxy,
797
+ HTTP_PROXY: process.env.HTTP_PROXY,
798
+ http_proxy: process.env.http_proxy,
799
+ NO_PROXY: process.env.NO_PROXY,
800
+ no_proxy: process.env.no_proxy,
801
+ REMNIC_LOCAL_LLM_DIRECT: process.env.REMNIC_LOCAL_LLM_DIRECT,
802
+ };
803
+ try {
804
+ setGlobalDispatcher(proxy);
805
+ delete process.env.https_proxy;
806
+ delete process.env.HTTP_PROXY;
807
+ delete process.env.http_proxy;
808
+ delete process.env.no_proxy;
809
+ delete process.env.REMNIC_LOCAL_LLM_DIRECT;
810
+ process.env.HTTPS_PROXY = "http://127.0.0.1:9";
811
+ process.env.NO_PROXY = "model.internal:80,.lan.example";
812
+
813
+ const transport = new ChatTransport();
814
+ const exempt = transport.dispatcherFor(900_000, "http://model.internal/v1/chat/completions");
815
+ assert.equal(exempt, undefined, "host:80 match: no substitute dispatcher");
816
+ assert.equal(getGlobalDispatcher(), proxy, "the installed custom dispatcher stands");
817
+
818
+ const suffix = transport.dispatcherFor(900_000, "https://chat.lan.example/v1/chat/completions");
819
+ assert.equal(suffix, undefined, "leading-dot suffix match exempts the URL too");
820
+
821
+ const portMiss = transport.dispatcherFor(900_000, "https://model.internal/v1/chat/completions");
822
+ assert.ok(portMiss instanceof EnvHttpProxyAgent, "a non-matching port is not exempt");
823
+ await portMiss.close();
824
+
825
+ process.env.NO_PROXY = "other.example";
826
+ const covered = transport.dispatcherFor(900_000, "http://model.internal/v1/chat/completions");
827
+ assert.ok(covered instanceof EnvHttpProxyAgent, "a URL outside NO_PROXY still chains the proxy agent");
828
+ await covered.close();
829
+ } finally {
830
+ for (const [key, value] of Object.entries(prior)) {
831
+ if (value !== undefined) process.env[key] = value;
832
+ else delete process.env[key];
833
+ }
834
+ setGlobalDispatcher(original);
835
+ await proxy.close();
836
+ }
837
+ });
838
+
839
+ test("an empty lowercase proxy variable cannot hide a set uppercase one", async () => {
840
+ // undici's raw env read is `process.env.https_proxy ?? process.env.HTTPS_PROXY`
841
+ // — an empty lowercase string is not undefined, so it would shadow the URI.
842
+ // The resolved environment skips empty values; the gate and the
843
+ // EnvHttpProxyAgent overrides must agree on the uppercase URI.
844
+ const prior = {
845
+ HTTPS_PROXY: process.env.HTTPS_PROXY,
846
+ https_proxy: process.env.https_proxy,
847
+ HTTP_PROXY: process.env.HTTP_PROXY,
848
+ http_proxy: process.env.http_proxy,
849
+ NO_PROXY: process.env.NO_PROXY,
850
+ no_proxy: process.env.no_proxy,
851
+ };
852
+ try {
853
+ for (const key of Object.keys(prior)) delete process.env[key];
854
+ process.env.HTTPS_PROXY = "http://upper.example:3128";
855
+ process.env.https_proxy = "";
856
+ assert.equal(resolveProxyEnv().httpsProxy, "http://upper.example:3128");
857
+
858
+ const original = getGlobalDispatcher();
859
+ const proxy = new ProxyAgent("http://127.0.0.1:9");
860
+ try {
861
+ setGlobalDispatcher(proxy);
862
+ const transport = new ChatTransport();
863
+ const chained = transport.dispatcherFor(900_000);
864
+ assert.ok(
865
+ chained instanceof EnvHttpProxyAgent,
866
+ "the empty lowercase value must not suppress the chained agent",
867
+ );
868
+ await chained.close();
869
+ } finally {
870
+ setGlobalDispatcher(original);
871
+ await proxy.close();
872
+ }
873
+ } finally {
874
+ for (const [key, value] of Object.entries(prior)) {
875
+ if (value !== undefined) process.env[key] = value;
876
+ else delete process.env[key];
877
+ }
878
+ }
879
+ });
880
+
881
+ test("the extraction route floors the dispatcher budget at fifteen minutes and leaves the abort budget to the operator", () => {
882
+ // The floor widens ONLY the transport's inactivity
883
+ // budgets (a proxyline host's 300s dispatcher cap must not dead-letter a
884
+ // longer configured budget); the operator's localLlmTimeoutMs still bounds
885
+ // the call through the abort signal (the drain engine's contract).
886
+ const floored = routeBudgets("extraction", 300, undefined);
887
+ assert.equal(floored.effectiveTimeoutMs, 300, "the abort budget stays the operator's");
888
+ assert.equal(floored.transportBudgetMs, EXTRACTION_MIN_TRANSPORT_BUDGET_MS, "the dispatcher budget carries the floor");
889
+ const explicit = routeBudgets("extraction", 600_000, 30_000);
890
+ assert.equal(explicit.effectiveTimeoutMs, 30_000, "an explicit operator timeout stays clamped by the ceiling");
891
+ assert.equal(explicit.transportBudgetMs, EXTRACTION_MIN_TRANSPORT_BUDGET_MS);
892
+ const other = routeBudgets("chat", 300, undefined);
893
+ assert.equal(other.effectiveTimeoutMs, 300);
894
+ assert.equal(other.transportBudgetMs, 300, "other routes keep the generic ceiling");
895
+ });
896
+
897
+ test("the extraction transport floor is fifteen minutes, well past undici's 300s default", () => {
898
+ // The issue-#2148 failure died at undici's 300s default and at the 300s-class
899
+ // generic budgets; the floor must clear 301s with room to spare.
900
+ assert.equal(EXTRACTION_MIN_TRANSPORT_BUDGET_MS, 900_000);
901
+ assert.ok(EXTRACTION_MIN_TRANSPORT_BUDGET_MS >= 301_000);
902
+ });