@vellumai/assistant 0.10.11-dev.202607222325.35fc367 → 0.10.11-dev.202607230140.b414d01

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.
@@ -100,3 +100,93 @@ export interface RemoteWebPairingTokenApprovedResponse {
100
100
  export type RemoteWebPairingTokenResponse =
101
101
  | RemoteWebPairingTokenPendingResponse
102
102
  | RemoteWebPairingTokenApprovedResponse;
103
+
104
+ // ── Shared pairing URL helpers ──────────────────────────────────────────────
105
+ //
106
+ // Every surface that mints a pairing (the `vellum pair --qr` CLI, the web
107
+ // settings "Pair a device" card) must accept the same public URLs and build
108
+ // the same scannable links. The helpers are environment-neutral (WHATWG URL
109
+ // only) so both Node and browser callers share one implementation.
110
+
111
+ /** Why a public base URL can't be advertised in a pairing challenge. */
112
+ export type PublicBaseUrlRejection = "unparseable" | "loopback" | "non-https";
113
+
114
+ export type PublicBaseUrlResult =
115
+ | { ok: true; url: string }
116
+ | { ok: false; reason: PublicBaseUrlRejection };
117
+
118
+ /**
119
+ * A loopback URL — `localhost`, `[::1]`, or `127.x.x.x`. A pairing link that
120
+ * encodes a loopback address is unreachable from the scanning device.
121
+ */
122
+ export function isLoopbackPublicUrl(url: string): boolean {
123
+ try {
124
+ // WHATWG URL canonicalizes hostnames, so IPv6 loopback is always "[::1]".
125
+ const hostname = new URL(url).hostname;
126
+ return (
127
+ hostname === "localhost" ||
128
+ hostname === "[::1]" ||
129
+ /^127(?:\.\d{1,3}){3}$/.test(hostname)
130
+ );
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Normalize an address to the public base a scanning device opens:
138
+ * query/hash stripped, the `assistant` path segment (and everything after it)
139
+ * removed so a pasted pair-page URL collapses to its base, and trailing
140
+ * slashes trimmed. Throws if the value is not a parseable URL.
141
+ */
142
+ export function normalizePublicBaseUrl(value: string): string {
143
+ const url = new URL(value);
144
+ url.search = "";
145
+ url.hash = "";
146
+ const parts = url.pathname.split("/").filter(Boolean);
147
+ const assistantIndex = parts.indexOf("assistant");
148
+ if (assistantIndex >= 0) {
149
+ parts.splice(assistantIndex);
150
+ }
151
+ url.pathname = parts.length ? `/${parts.join("/")}` : "/";
152
+ return url.toString().replace(/\/+$/, "");
153
+ }
154
+
155
+ /**
156
+ * Resolve an address to the public https base URL to advertise in a pairing
157
+ * challenge, or report why it can't be used. Loopback and non-https links are
158
+ * refused with a specific reason callers turn into their own guidance.
159
+ */
160
+ export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
161
+ let normalized: string;
162
+ try {
163
+ normalized = normalizePublicBaseUrl(raw);
164
+ } catch {
165
+ return { ok: false, reason: "unparseable" };
166
+ }
167
+ if (isLoopbackPublicUrl(normalized)) {
168
+ return { ok: false, reason: "loopback" };
169
+ }
170
+ if (new URL(normalized).protocol !== "https:") {
171
+ return { ok: false, reason: "non-https" };
172
+ }
173
+ return { ok: true, url: normalized };
174
+ }
175
+
176
+ /**
177
+ * The scannable pair URL: the challenge's verification URI with the device
178
+ * code carried in the fragment (`#device_code=…`), matching what the pair
179
+ * page reads on load. Fragments never reach the wire.
180
+ */
181
+ export function buildRemoteWebPairingUrl(
182
+ challenge: Pick<
183
+ RemoteWebPairingChallengeResponse,
184
+ "verificationUri" | "deviceCode"
185
+ >,
186
+ ): string {
187
+ const url = new URL(challenge.verificationUri);
188
+ url.hash = new URLSearchParams({
189
+ device_code: challenge.deviceCode,
190
+ }).toString();
191
+ return url.toString();
192
+ }
@@ -100,3 +100,93 @@ export interface RemoteWebPairingTokenApprovedResponse {
100
100
  export type RemoteWebPairingTokenResponse =
101
101
  | RemoteWebPairingTokenPendingResponse
102
102
  | RemoteWebPairingTokenApprovedResponse;
103
+
104
+ // ── Shared pairing URL helpers ──────────────────────────────────────────────
105
+ //
106
+ // Every surface that mints a pairing (the `vellum pair --qr` CLI, the web
107
+ // settings "Pair a device" card) must accept the same public URLs and build
108
+ // the same scannable links. The helpers are environment-neutral (WHATWG URL
109
+ // only) so both Node and browser callers share one implementation.
110
+
111
+ /** Why a public base URL can't be advertised in a pairing challenge. */
112
+ export type PublicBaseUrlRejection = "unparseable" | "loopback" | "non-https";
113
+
114
+ export type PublicBaseUrlResult =
115
+ | { ok: true; url: string }
116
+ | { ok: false; reason: PublicBaseUrlRejection };
117
+
118
+ /**
119
+ * A loopback URL — `localhost`, `[::1]`, or `127.x.x.x`. A pairing link that
120
+ * encodes a loopback address is unreachable from the scanning device.
121
+ */
122
+ export function isLoopbackPublicUrl(url: string): boolean {
123
+ try {
124
+ // WHATWG URL canonicalizes hostnames, so IPv6 loopback is always "[::1]".
125
+ const hostname = new URL(url).hostname;
126
+ return (
127
+ hostname === "localhost" ||
128
+ hostname === "[::1]" ||
129
+ /^127(?:\.\d{1,3}){3}$/.test(hostname)
130
+ );
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Normalize an address to the public base a scanning device opens:
138
+ * query/hash stripped, the `assistant` path segment (and everything after it)
139
+ * removed so a pasted pair-page URL collapses to its base, and trailing
140
+ * slashes trimmed. Throws if the value is not a parseable URL.
141
+ */
142
+ export function normalizePublicBaseUrl(value: string): string {
143
+ const url = new URL(value);
144
+ url.search = "";
145
+ url.hash = "";
146
+ const parts = url.pathname.split("/").filter(Boolean);
147
+ const assistantIndex = parts.indexOf("assistant");
148
+ if (assistantIndex >= 0) {
149
+ parts.splice(assistantIndex);
150
+ }
151
+ url.pathname = parts.length ? `/${parts.join("/")}` : "/";
152
+ return url.toString().replace(/\/+$/, "");
153
+ }
154
+
155
+ /**
156
+ * Resolve an address to the public https base URL to advertise in a pairing
157
+ * challenge, or report why it can't be used. Loopback and non-https links are
158
+ * refused with a specific reason callers turn into their own guidance.
159
+ */
160
+ export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
161
+ let normalized: string;
162
+ try {
163
+ normalized = normalizePublicBaseUrl(raw);
164
+ } catch {
165
+ return { ok: false, reason: "unparseable" };
166
+ }
167
+ if (isLoopbackPublicUrl(normalized)) {
168
+ return { ok: false, reason: "loopback" };
169
+ }
170
+ if (new URL(normalized).protocol !== "https:") {
171
+ return { ok: false, reason: "non-https" };
172
+ }
173
+ return { ok: true, url: normalized };
174
+ }
175
+
176
+ /**
177
+ * The scannable pair URL: the challenge's verification URI with the device
178
+ * code carried in the fragment (`#device_code=…`), matching what the pair
179
+ * page reads on load. Fragments never reach the wire.
180
+ */
181
+ export function buildRemoteWebPairingUrl(
182
+ challenge: Pick<
183
+ RemoteWebPairingChallengeResponse,
184
+ "verificationUri" | "deviceCode"
185
+ >,
186
+ ): string {
187
+ const url = new URL(challenge.verificationUri);
188
+ url.hash = new URLSearchParams({
189
+ device_code: challenge.deviceCode,
190
+ }).toString();
191
+ return url.toString();
192
+ }
@@ -100,3 +100,93 @@ export interface RemoteWebPairingTokenApprovedResponse {
100
100
  export type RemoteWebPairingTokenResponse =
101
101
  | RemoteWebPairingTokenPendingResponse
102
102
  | RemoteWebPairingTokenApprovedResponse;
103
+
104
+ // ── Shared pairing URL helpers ──────────────────────────────────────────────
105
+ //
106
+ // Every surface that mints a pairing (the `vellum pair --qr` CLI, the web
107
+ // settings "Pair a device" card) must accept the same public URLs and build
108
+ // the same scannable links. The helpers are environment-neutral (WHATWG URL
109
+ // only) so both Node and browser callers share one implementation.
110
+
111
+ /** Why a public base URL can't be advertised in a pairing challenge. */
112
+ export type PublicBaseUrlRejection = "unparseable" | "loopback" | "non-https";
113
+
114
+ export type PublicBaseUrlResult =
115
+ | { ok: true; url: string }
116
+ | { ok: false; reason: PublicBaseUrlRejection };
117
+
118
+ /**
119
+ * A loopback URL — `localhost`, `[::1]`, or `127.x.x.x`. A pairing link that
120
+ * encodes a loopback address is unreachable from the scanning device.
121
+ */
122
+ export function isLoopbackPublicUrl(url: string): boolean {
123
+ try {
124
+ // WHATWG URL canonicalizes hostnames, so IPv6 loopback is always "[::1]".
125
+ const hostname = new URL(url).hostname;
126
+ return (
127
+ hostname === "localhost" ||
128
+ hostname === "[::1]" ||
129
+ /^127(?:\.\d{1,3}){3}$/.test(hostname)
130
+ );
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Normalize an address to the public base a scanning device opens:
138
+ * query/hash stripped, the `assistant` path segment (and everything after it)
139
+ * removed so a pasted pair-page URL collapses to its base, and trailing
140
+ * slashes trimmed. Throws if the value is not a parseable URL.
141
+ */
142
+ export function normalizePublicBaseUrl(value: string): string {
143
+ const url = new URL(value);
144
+ url.search = "";
145
+ url.hash = "";
146
+ const parts = url.pathname.split("/").filter(Boolean);
147
+ const assistantIndex = parts.indexOf("assistant");
148
+ if (assistantIndex >= 0) {
149
+ parts.splice(assistantIndex);
150
+ }
151
+ url.pathname = parts.length ? `/${parts.join("/")}` : "/";
152
+ return url.toString().replace(/\/+$/, "");
153
+ }
154
+
155
+ /**
156
+ * Resolve an address to the public https base URL to advertise in a pairing
157
+ * challenge, or report why it can't be used. Loopback and non-https links are
158
+ * refused with a specific reason callers turn into their own guidance.
159
+ */
160
+ export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
161
+ let normalized: string;
162
+ try {
163
+ normalized = normalizePublicBaseUrl(raw);
164
+ } catch {
165
+ return { ok: false, reason: "unparseable" };
166
+ }
167
+ if (isLoopbackPublicUrl(normalized)) {
168
+ return { ok: false, reason: "loopback" };
169
+ }
170
+ if (new URL(normalized).protocol !== "https:") {
171
+ return { ok: false, reason: "non-https" };
172
+ }
173
+ return { ok: true, url: normalized };
174
+ }
175
+
176
+ /**
177
+ * The scannable pair URL: the challenge's verification URI with the device
178
+ * code carried in the fragment (`#device_code=…`), matching what the pair
179
+ * page reads on load. Fragments never reach the wire.
180
+ */
181
+ export function buildRemoteWebPairingUrl(
182
+ challenge: Pick<
183
+ RemoteWebPairingChallengeResponse,
184
+ "verificationUri" | "deviceCode"
185
+ >,
186
+ ): string {
187
+ const url = new URL(challenge.verificationUri);
188
+ url.hash = new URLSearchParams({
189
+ device_code: challenge.deviceCode,
190
+ }).toString();
191
+ return url.toString();
192
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.11-dev.202607222325.35fc367",
3
+ "version": "0.10.11-dev.202607230140.b414d01",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -247,3 +247,107 @@ describe("cleanup on dismiss", () => {
247
247
  expect(ctx.accumulatedSurfaceState.get("surface-2")).toEqual({ y: 2 });
248
248
  });
249
249
  });
250
+
251
+ describe("ui_update preserves client-owned keys the daemon schema omits", () => {
252
+ test("a valid patch keeps unmodeled keys on the merged, sent, and stored data", async () => {
253
+ const sent: ServerMessage[] = [];
254
+ const ctx = makeContext({ sent });
255
+ // A document_preview whose stored data carries `surfaceId` — an unmodeled
256
+ // key read by the client renderer, not by the daemon schema.
257
+ ctx.surfaceState.set("doc-1", {
258
+ surfaceType: "document_preview",
259
+ data: {
260
+ title: "Notes",
261
+ surfaceId: "doc-real",
262
+ content: "# Heading",
263
+ mimeType: "text/markdown",
264
+ } as SurfaceData,
265
+ });
266
+
267
+ const result = await surfaceProxyResolver(ctx, "ui_update", {
268
+ surface_id: "doc-1",
269
+ data: { title: "Notes (edited)" },
270
+ });
271
+ expect(result.isError).toBe(false);
272
+
273
+ // Stored state keeps the unmodeled key and applies the patch.
274
+ expect(ctx.surfaceState.get("doc-1")?.data).toMatchObject({
275
+ title: "Notes (edited)",
276
+ surfaceId: "doc-real",
277
+ });
278
+
279
+ // The update sent to the client also carries it.
280
+ const update = sent.find((m) => m.type === "ui_surface_update");
281
+ expect(update).toBeDefined();
282
+ expect((update as { data: Record<string, unknown> }).data).toMatchObject({
283
+ title: "Notes (edited)",
284
+ surfaceId: "doc-real",
285
+ });
286
+ });
287
+ });
288
+
289
+ describe("ui_update on a restored unknown surface type", () => {
290
+ test("forwards the merge opaquely instead of storing garbage", async () => {
291
+ const sent: ServerMessage[] = [];
292
+ const ctx = makeContext({ sent });
293
+ // Restore preserves an unknown-but-non-empty surfaceType verbatim (a
294
+ // newer/custom client-rendered surface). safeParseSurfaceData has no schema
295
+ // for it — the update must forward the merge, not the type string.
296
+ ctx.surfaceState.set("future-1", {
297
+ surfaceType: "future_widget" as SurfaceType,
298
+ data: { title: "Widget", customField: 42 } as SurfaceData,
299
+ });
300
+
301
+ const result = await surfaceProxyResolver(ctx, "ui_update", {
302
+ surface_id: "future-1",
303
+ data: { title: "Widget (edited)" },
304
+ });
305
+ expect(result.isError).toBe(false);
306
+
307
+ const stored = ctx.surfaceState.get("future-1");
308
+ expect(stored?.surfaceType as string).toBe("future_widget");
309
+ expect(stored?.data as Record<string, unknown>).toEqual({
310
+ title: "Widget (edited)",
311
+ customField: 42,
312
+ });
313
+
314
+ const update = sent.find((m) => m.type === "ui_surface_update");
315
+ expect(update).toBeDefined();
316
+ expect((update as { data: Record<string, unknown> }).data).toEqual({
317
+ title: "Widget (edited)",
318
+ customField: 42,
319
+ });
320
+ });
321
+ });
322
+
323
+ describe("ui_update normalizes modeled fields for known surface types", () => {
324
+ test("a malformed dynamic_page html patch is stored as its schema-coerced string", async () => {
325
+ const sent: ServerMessage[] = [];
326
+ const ctx = makeContext({ sent });
327
+ ctx.surfaceState.set("page-1", {
328
+ surfaceType: "dynamic_page",
329
+ data: { html: "<p>original</p>" } as SurfaceData,
330
+ });
331
+
332
+ // A malformed patch: `html` as a non-string. The tolerant schema
333
+ // (`z.string().catch("")`) accepts it, so the update must not revert — but
334
+ // the stored/sent value must be the coerced string, never the raw object,
335
+ // or later `truncateHtml(...).slice()` on the stored html would crash.
336
+ const result = await surfaceProxyResolver(ctx, "ui_update", {
337
+ surface_id: "page-1",
338
+ data: { html: { unexpected: "object" } },
339
+ });
340
+ expect(result.isError).toBe(false);
341
+
342
+ const storedHtml = (
343
+ ctx.surfaceState.get("page-1")?.data as { html: unknown }
344
+ ).html;
345
+ expect(typeof storedHtml).toBe("string");
346
+
347
+ const update = sent.find((m) => m.type === "ui_surface_update");
348
+ expect(update).toBeDefined();
349
+ expect(typeof (update as { data: { html: unknown } }).data.html).toBe(
350
+ "string",
351
+ );
352
+ });
353
+ });
@@ -153,7 +153,6 @@ mock.module("../persistence/attachments-store.js", () => ({
153
153
  // ── Imports (after mocks) ──────────────────────────────────────────────────
154
154
 
155
155
  import type { AgentEvent } from "../agent/loop.js";
156
- import { clearThreadTs, setThreadTs } from "../channels/slack-thread-store.js";
157
156
  import type {
158
157
  EventHandlerDeps,
159
158
  EventHandlerState,
@@ -177,6 +176,7 @@ function makeDeps(
177
176
  requesterChatId?: string;
178
177
  requesterTimezoneLabel?: string;
179
178
  clientTimezone?: string;
179
+ sourceThreadId?: string;
180
180
  } = {},
181
181
  ): EventHandlerDeps {
182
182
  const assistantMessageChannel = overrides.assistantMessageChannel ?? "slack";
@@ -190,6 +190,7 @@ function makeDeps(
190
190
  trustClass: "guardian",
191
191
  requesterChatId: overrides.requesterChatId,
192
192
  requesterTimezoneLabel: overrides.requesterTimezoneLabel,
193
+ sourceThreadId: overrides.sourceThreadId,
193
194
  },
194
195
  clientTimezone: overrides.clientTimezone,
195
196
  } as unknown as EventHandlerDeps["ctx"],
@@ -257,16 +258,17 @@ describe("outbound assistant Slack metadata persistence", () => {
257
258
  nextDeliveryTs = null;
258
259
  });
259
260
 
260
- test("stamps slackMeta with threadTs when the conversation has a Slack thread mapping", async () => {
261
+ test("stamps slackMeta with threadTs from the turn's inbound thread id", async () => {
261
262
  const conversationId = "conv-slack-threaded";
262
263
  const channelId = "C123CHANNEL";
263
- // Seed an in-memory Slack thread mapping (mirrors the inbound path that
264
- // calls setThreadTs when a thread_ts arrives).
265
- setThreadTs(conversationId, channelId, "1234.5678");
266
264
 
265
+ // The turn arrived in a thread — its inbound thread ts is captured on the
266
+ // trust context (`sourceThreadId`) at ingress, and the reply is stamped
267
+ // from that turn-local value.
267
268
  const deps = makeDeps(conversationId, {
268
269
  assistantMessageChannel: "slack",
269
270
  requesterChatId: channelId,
271
+ sourceThreadId: "1234.5678",
270
272
  });
271
273
  await handleLlmCallStarted(state, deps);
272
274
  await handleMessageComplete(state, deps, makeMessageCompleteEvent("hi"));
@@ -398,8 +400,8 @@ describe("outbound assistant Slack metadata persistence", () => {
398
400
  test("stamps slackMeta WITHOUT threadTs for top-level Slack replies", async () => {
399
401
  const conversationId = "conv-slack-toplevel";
400
402
  const channelId = "C456NOTHREAD";
401
- // No setThreadTs() call — the conversation has no thread mapping, so
402
- // the assistant's reply targets the channel root, not a thread.
403
+ // The turn arrived at the channel root — no `sourceThreadId` on the trust
404
+ // context, so the reply targets the channel root, not a thread.
403
405
 
404
406
  const deps = makeDeps(conversationId, {
405
407
  assistantMessageChannel: "slack",
@@ -425,17 +427,14 @@ describe("outbound assistant Slack metadata persistence", () => {
425
427
  expect(slackMeta.channelTs).toBeUndefined();
426
428
  });
427
429
 
428
- test("does NOT stamp a stale threadTs after the mapping is cleared", async () => {
429
- const conversationId = "conv-slack-cleared";
430
- const channelId = "C789CLEARED";
431
- // Simulate an earlier threaded turn that seeded the mapping, followed
432
- // by a channel-root turn whose inbound path cleared it.
433
- setThreadTs(conversationId, channelId, "1111.2222");
434
- clearThreadTs(conversationId);
435
-
430
+ test("ignores a non-ts sourceThreadId", async () => {
431
+ const conversationId = "conv-slack-bad-thread";
432
+ const channelId = "C789BAD";
433
+ // A malformed thread id must not be stamped as a threadTs (isSlackTs guard).
436
434
  const deps = makeDeps(conversationId, {
437
435
  assistantMessageChannel: "slack",
438
436
  requesterChatId: channelId,
437
+ sourceThreadId: "not-a-ts",
439
438
  });
440
439
  await handleLlmCallStarted(state, deps);
441
440
  await handleMessageComplete(
@@ -509,6 +509,20 @@ export const MODEL_INVOKABLE_SURFACE_TYPES = SURFACE_TYPES.filter(
509
509
  (type) => !isDaemonInternalSurfaceType(type),
510
510
  );
511
511
 
512
+ const SURFACE_TYPE_SET = new Set<string>(SURFACE_TYPES);
513
+
514
+ /**
515
+ * Whether `type` is a surface type this daemon models (has a canonical schema
516
+ * for). Restore preserves an unknown-but-non-empty persisted `surfaceType`
517
+ * verbatim (a newer/custom client-rendered surface), so a runtime string can
518
+ * reach code that dispatches on the type; callers must gate on this before
519
+ * handing the type to `safeParseSurfaceData`, which has no schema for unknown
520
+ * types.
521
+ */
522
+ export function isKnownSurfaceType(type: string): type is SurfaceType {
523
+ return SURFACE_TYPE_SET.has(type);
524
+ }
525
+
512
526
  export type SurfaceData =
513
527
  | CardSurfaceData
514
528
  | ChoiceSurfaceData
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Slack reply-callback-URL helpers.
3
+ *
4
+ * The gateway encodes the Slack reply target (thread ts and, for non-threaded
5
+ * DMs, the originating message ts) as query parameters on the `/deliver/slack`
6
+ * callback URL it hands the daemon. These helpers parse those parameters back
7
+ * out at delivery time. (The assistant reply row's thread metadata is stamped
8
+ * separately, from the turn-local `trustContext.sourceThreadId`.)
9
+ */
10
+
11
+ /**
12
+ * Extract the threadTs from a Slack reply callback URL, if present.
13
+ * The gateway encodes threadTs as a query parameter on the callback URL.
14
+ */
15
+ export function extractThreadTsFromCallbackUrl(
16
+ callbackUrl: string | undefined,
17
+ ): string | null {
18
+ if (!callbackUrl) return null;
19
+ try {
20
+ const url = new URL(callbackUrl);
21
+ return url.searchParams.get("threadTs");
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Extract the messageTs from a Slack reply callback URL, if present.
29
+ * The gateway encodes messageTs for non-threaded DMs so the runtime
30
+ * can target the original message for emoji-based indicators.
31
+ */
32
+ export function extractMessageTsFromCallbackUrl(
33
+ callbackUrl: string | undefined,
34
+ ): string | null {
35
+ if (!callbackUrl) return null;
36
+ try {
37
+ const url = new URL(callbackUrl);
38
+ return url.searchParams.get("messageTs");
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Whether a reply callback URL targets the Slack delivery endpoint.
46
+ */
47
+ export function isSlackDeliveryCallbackUrl(callbackUrl?: string): boolean {
48
+ if (!callbackUrl) return false;
49
+ try {
50
+ return new URL(callbackUrl).pathname.endsWith("/deliver/slack");
51
+ } catch {
52
+ return callbackUrl.endsWith("/deliver/slack");
53
+ }
54
+ }
@@ -11,7 +11,6 @@ import type pino from "pino";
11
11
  import { v4 as uuid } from "uuid";
12
12
 
13
13
  import type { AgentEvent } from "../agent/loop.js";
14
- import { getThreadTs } from "../channels/slack-thread-store.js";
15
14
  import type {
16
15
  TurnChannelContext,
17
16
  TurnInterfaceContext,
@@ -23,6 +22,7 @@ import { stripInjectionsForCompaction } from "../context/strip-injections.js";
23
22
  import { getCalibrationProviderKey } from "../context/token-estimator.js";
24
23
  import {
25
24
  formatSlackTimezoneLabel,
25
+ isSlackTs,
26
26
  type SlackMessageMetadata,
27
27
  writeSlackMetadata,
28
28
  } from "../messaging/providers/slack/message-metadata.js";
@@ -1261,7 +1261,14 @@ function buildAssistantChannelMetadata(
1261
1261
  if (deps.turnChannelContext.assistantMessageChannel === "slack") {
1262
1262
  const channelId = deps.ctx.trustContext?.requesterChatId;
1263
1263
  if (channelId) {
1264
- const threadTs = getThreadTs(deps.ctx.conversationId);
1264
+ // Resolve the reply thread from this turn's own inbound thread id,
1265
+ // captured turn-locally on the trust context at ingress (the same field
1266
+ // guardian-approval cards read). This is deliberately not the shared
1267
+ // conversation binding: on a legacy flat→thread aliased Slack
1268
+ // conversation a concurrent inbound can rewrite the binding's
1269
+ // externalThreadId mid-turn, whereas the trust context is per-turn.
1270
+ const turnThreadTs = deps.ctx.trustContext?.sourceThreadId;
1271
+ const threadTs = isSlackTs(turnThreadTs) ? turnThreadTs : undefined;
1265
1272
  const timestampTimezone = resolveAssistantReplyTimestampTimezone(
1266
1273
  deps.ctx,
1267
1274
  );
@@ -8,6 +8,7 @@ import {
8
8
  coerceSurfaceDataRecord,
9
9
  DynamicPageSurfaceDataSchema,
10
10
  isDaemonInternalSurfaceType,
11
+ isKnownSurfaceType,
11
12
  MODEL_INVOKABLE_SURFACE_TYPES,
12
13
  normalizeCopyBlockShowData,
13
14
  OAuthConnectSurfaceDataSchema,
@@ -3250,19 +3251,38 @@ export async function surfaceProxyResolver(
3250
3251
  pushUndoState(ctx.surfaceUndoStacks, surfaceId, currentHtml);
3251
3252
  }
3252
3253
  const rawMerged = { ...stored.data, ...patch };
3253
- // Validate the merged data through the surface type's canonical schema
3254
- // so malformed patches (e.g. metadata as a string) are caught here
3255
- // instead of crashing the client's safeParse.
3256
- const parsed = safeParseSurfaceData(stored.surfaceType, rawMerged);
3257
- if (parsed !== undefined) {
3258
- mergedData = parsed;
3254
+ if (!isKnownSurfaceType(stored.surfaceType)) {
3255
+ // Restore preserves an unknown-but-non-empty persisted surfaceType
3256
+ // verbatim (a newer/custom client-rendered surface). safeParseSurfaceData
3257
+ // has no schema for it — it falls through to returning the type string
3258
+ // rather than a data object — so forward the merge opaquely rather than
3259
+ // storing that garbage, mirroring restore's verbatim handling.
3260
+ mergedData = rawMerged as SurfaceData;
3259
3261
  } else {
3260
- log.warn(
3261
- { surfaceId, surfaceType: stored.surfaceType },
3262
- "ui_update patch produced invalid merged data; reverting to stored data",
3263
- );
3264
- mergedData =
3265
- safeParseSurfaceData(stored.surfaceType, stored.data) ?? stored.data;
3262
+ // Validate the merged data through the surface type's canonical schema
3263
+ // so malformed patches (e.g. metadata as a string) are caught here
3264
+ // instead of crashing the client's safeParse. Keep unmodeled
3265
+ // client-owned keys from the raw merge, but take the schema-NORMALIZED
3266
+ // value for every modeled field: a tolerant field (dynamic_page `html`
3267
+ // is `z.string().catch("")`, file_upload `acceptedTypes` coerces to
3268
+ // `string[]`) accepts a malformed input and coerces it, and later daemon
3269
+ // code (active-workspace injection's `truncateHtml`, undo-stack pushes)
3270
+ // assumes the canonical shape — so storing the raw value would poison
3271
+ // surfaceState. The parsed object holds only modeled keys, so spreading
3272
+ // it over the raw merge normalizes those while preserving the
3273
+ // client-owned ones. Only a failed parse reverts to the stored data.
3274
+ const parsed = safeParseSurfaceData(stored.surfaceType, rawMerged);
3275
+ if (parsed !== undefined) {
3276
+ mergedData = { ...rawMerged, ...parsed } as SurfaceData;
3277
+ } else {
3278
+ log.warn(
3279
+ { surfaceId, surfaceType: stored.surfaceType },
3280
+ "ui_update patch produced invalid merged data; reverting to stored data",
3281
+ );
3282
+ mergedData =
3283
+ safeParseSurfaceData(stored.surfaceType, stored.data) ??
3284
+ stored.data;
3285
+ }
3266
3286
  }
3267
3287
  stored.data = mergedData;
3268
3288
  } else {
@@ -97,11 +97,6 @@ mock.module("../../channel-reply-delivery.js", () => ({
97
97
  },
98
98
  }));
99
99
 
100
- import {
101
- clearThreadTs,
102
- getThreadTs,
103
- setThreadTs,
104
- } from "../../../channels/slack-thread-store.js";
105
100
  import type { TrustContext } from "../../../daemon/trust-context-types.js";
106
101
  import type { MessageProcessor } from "../../http-types.js";
107
102
  import {
@@ -174,7 +169,7 @@ describe("isBoundGuardianActor", () => {
174
169
  });
175
170
  });
176
171
 
177
- describe("processChannelMessageInBackground — slack thread mapping", () => {
172
+ describe("processChannelMessageInBackground — reply delivery", () => {
178
173
  const trustCtx: TrustContext = {
179
174
  trustClass: "guardian",
180
175
  guardianExternalUserId: "guardian-1",
@@ -184,74 +179,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
184
179
  const flush = (): Promise<void> =>
185
180
  new Promise((resolve) => setTimeout(resolve, 10));
186
181
 
187
- test("restores prior thread mapping when processMessage is rejected as already-processing", async () => {
188
- const conversationId = "conv-restore-on-busy";
189
- const channelId = "C-RESTORE";
190
- const inFlightThreadTs = "1700000000.000001";
191
-
192
- // Simulate a prior threaded turn that installed the mapping and is
193
- // still in flight when a new channel-root event arrives.
194
- setThreadTs(conversationId, channelId, inFlightThreadTs);
195
-
196
- const processMessage: MessageProcessor = async () => {
197
- throw new Error("Conversation is already processing a message");
198
- };
199
-
200
- processChannelMessageInBackground({
201
- processMessage,
202
- conversationId,
203
- eventId: "evt-1",
204
- content: "root-level message",
205
- sourceChannel: "slack",
206
- sourceInterface: "slack",
207
- externalChatId: channelId,
208
- trustCtx,
209
- metadataHints: [],
210
- // Callback URL has no threadTs query param → channel-root event
211
- // that would otherwise call `clearThreadTs`.
212
- replyCallbackUrl: `https://example.test/deliver/slack?channel=${channelId}`,
213
- });
214
-
215
- await flush();
216
-
217
- // The in-flight threaded turn's mapping must survive the busy rejection.
218
- expect(getThreadTs(conversationId)).toBe(inFlightThreadTs);
219
-
220
- clearThreadTs(conversationId);
221
- });
222
-
223
- test("retains updated mapping when processMessage succeeds", async () => {
224
- const conversationId = "conv-retain-on-success";
225
- const channelId = "C-SUCCESS";
226
- const newThreadTs = "1700000000.000002";
227
-
228
- // No prior mapping; this turn arrives in a thread and should install one.
229
- clearThreadTs(conversationId);
230
-
231
- const processMessage: MessageProcessor = async () => ({
232
- messageId: "user-msg-1",
233
- });
234
-
235
- processChannelMessageInBackground({
236
- processMessage,
237
- conversationId,
238
- eventId: "evt-2",
239
- content: "thread reply",
240
- sourceChannel: "slack",
241
- sourceInterface: "slack",
242
- externalChatId: channelId,
243
- trustCtx,
244
- metadataHints: [],
245
- replyCallbackUrl: `https://example.test/deliver/slack?channel=${channelId}&threadTs=${newThreadTs}`,
246
- });
247
-
248
- await flush();
249
-
250
- expect(getThreadTs(conversationId)).toBe(newThreadTs);
251
-
252
- clearThreadTs(conversationId);
253
- });
254
-
255
182
  test("records callback delivery failures without failing processing", async () => {
256
183
  const conversationId = "conv-delivery-failure";
257
184
  const channelId = "C-DELIVERY-FAILURE";
@@ -300,8 +227,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
300
227
  ]);
301
228
  expect(deliveryFailureEvents).toEqual(["evt-delivery-failure"]);
302
229
  expect(deliveredEvents).toEqual([]);
303
-
304
- clearThreadTs(conversationId);
305
230
  });
306
231
 
307
232
  test("stores assistant reply ids returned by non-agent-loop fast paths", async () => {
@@ -339,8 +264,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
339
264
  { messageId: "assistant-msg-fast-path", startFromSegment: 0 },
340
265
  ]);
341
266
  expect(deliveredEvents).toEqual(["evt-fast-path"]);
342
-
343
- clearThreadTs(conversationId);
344
267
  });
345
268
 
346
269
  test("suppresses reply delivery when a deduplicated redelivery's prior attempt already delivered", async () => {
@@ -378,8 +301,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
378
301
  expect(replyDeliveryCalls).toEqual([]);
379
302
  expect(deliveredEvents).toEqual([]);
380
303
  expect(deliveredChannelReplies).toEqual([]);
381
-
382
- clearThreadTs(conversationId);
383
304
  });
384
305
 
385
306
  test("skips reply delivery when a deduplicated redelivery's prior attempt failed (sweep owns recovery)", async () => {
@@ -413,8 +334,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
413
334
  expect(replyDeliveryCalls).toEqual([]);
414
335
  expect(deliveredEvents).toEqual([]);
415
336
  expect(deliveredChannelReplies).toEqual([]);
416
-
417
- clearThreadTs(conversationId);
418
337
  });
419
338
 
420
339
  test("recovers the reply when a deduplicated redelivery's prior attempt is stuck pending (crash window)", async () => {
@@ -454,8 +373,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
454
373
  { messageId: undefined, startFromSegment: 0 },
455
374
  ]);
456
375
  expect(deliveredEvents).toEqual(["evt-dedup-pending"]);
457
-
458
- clearThreadTs(conversationId);
459
376
  });
460
377
 
461
378
  test("edits the sibling's streamed Slack reply in place when recovering a deduplicated redelivery in the crash window", async () => {
@@ -497,8 +414,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
497
414
  { messageId: undefined, startFromSegment: 0, messageTs: streamTs },
498
415
  ]);
499
416
  expect(deliveredEvents).toEqual(["evt-dedup-pending-streamed"]);
500
-
501
- clearThreadTs(conversationId);
502
417
  });
503
418
 
504
419
  test("falls back to durable delivery for a non-threaded Slack DM", async () => {
@@ -549,8 +464,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
549
464
  { messageId: "assistant-msg-no-thread", startFromSegment: 0 },
550
465
  ]);
551
466
  expect(deliveredEvents).toEqual(["evt-no-thread"]);
552
-
553
- clearThreadTs(conversationId);
554
467
  });
555
468
 
556
469
  test("streams a threaded Slack DM reply and reconciles durable delivery to the stream", async () => {
@@ -621,8 +534,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
621
534
  { eventId: "evt-streamed", messageTs: streamTs },
622
535
  ]);
623
536
  expect(deliveredEvents).toEqual(["evt-streamed"]);
624
-
625
- clearThreadTs(conversationId);
626
537
  });
627
538
 
628
539
  test("keeps Slack channel replies on the existing final delivery path", async () => {
@@ -686,8 +597,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
686
597
  { messageId: "assistant-msg-channel-final", startFromSegment: 0 },
687
598
  ]);
688
599
  expect(deliveredEvents).toEqual(["evt-channel-final-delivery"]);
689
-
690
- clearThreadTs(conversationId);
691
600
  });
692
601
 
693
602
  test("falls back to durable delivery when the Slack stream fails to start", async () => {
@@ -734,8 +643,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
734
643
  { messageId: "assistant-msg-stream-start-fails", startFromSegment: 0 },
735
644
  ]);
736
645
  expect(deliveredEvents).toEqual(["evt-stream-start-fails"]);
737
-
738
- clearThreadTs(conversationId);
739
646
  });
740
647
 
741
648
  test("finalizes the stream and records a processing failure when processing throws", async () => {
@@ -788,8 +695,6 @@ describe("processChannelMessageInBackground — slack thread mapping", () => {
788
695
  ]);
789
696
  expect(processingFailureEvents).toEqual(["evt-stream-processing-failure"]);
790
697
  expect(operationOrder).toEqual(["store-streamed-ts", "processing-failure"]);
791
-
792
- clearThreadTs(conversationId);
793
698
  });
794
699
  });
795
700
 
@@ -8,20 +8,15 @@
8
8
  * focused on orchestration.
9
9
  */
10
10
  import {
11
- clearThreadTs,
12
- extractChannelFromCallbackUrl,
13
11
  extractMessageTsFromCallbackUrl,
14
12
  extractThreadTsFromCallbackUrl,
15
13
  isSlackDeliveryCallbackUrl,
16
- peekThreadMapping,
17
- setThreadTs,
18
- } from "../../../channels/slack-thread-store.js";
14
+ } from "../../../channels/slack-callback-url.js";
19
15
  import type { ChannelId, InterfaceId } from "../../../channels/types.js";
20
16
  import {
21
17
  getGuardianDelivery,
22
18
  guardianForChannel,
23
19
  } from "../../../contacts/guardian-delivery-reader.js";
24
- import { CONVERSATION_BUSY_MESSAGE } from "../../../daemon/conversation-messaging.js";
25
20
  import type { ServerMessage } from "../../../daemon/message-protocol.js";
26
21
  import type { TrustContext } from "../../../daemon/trust-context-types.js";
27
22
  import {
@@ -196,37 +191,6 @@ export function processChannelMessageInBackground(
196
191
  })
197
192
  : undefined;
198
193
 
199
- // Align the Slack thread mapping with this turn's inbound state:
200
- // set it when the inbound arrived in a thread, clear it when the
201
- // inbound arrived at the channel root. `getThreadTs` is consulted
202
- // at outbound-persistence time, so the mapping must reflect the
203
- // current turn — a lingering mapping from a prior thread turn
204
- // would otherwise be stamped onto a channel-root reply.
205
- //
206
- // The update must happen BEFORE `processMessage` runs because outbound
207
- // persistence (inside the agent loop) reads the mapping. But if a prior
208
- // threaded turn is still in flight, our `processMessage` call will be
209
- // rejected as already-processing and our update would erase that
210
- // in-flight turn's mapping. Snapshot the prior state here and restore
211
- // it in the `already processing` rejection path below.
212
- let priorSlackMapping: {
213
- threadTs: string;
214
- channelId: string;
215
- } | null = null;
216
- let slackMappingMutated = false;
217
- if (sourceChannel === "slack" && replyCallbackUrl) {
218
- priorSlackMapping = peekThreadMapping(conversationId);
219
- const inboundThreadTs = extractThreadTsFromCallbackUrl(replyCallbackUrl);
220
- const inboundChannel = extractChannelFromCallbackUrl(replyCallbackUrl);
221
- if (inboundThreadTs && inboundChannel) {
222
- setThreadTs(conversationId, inboundChannel, inboundThreadTs);
223
- slackMappingMutated = true;
224
- } else {
225
- clearThreadTs(conversationId);
226
- slackMappingMutated = true;
227
- }
228
- }
229
-
230
194
  try {
231
195
  const cmdIntent =
232
196
  commandIntent && typeof commandIntent.type === "string"
@@ -297,27 +261,6 @@ export function processChannelMessageInBackground(
297
261
  storeReplyMessageId(eventId, replyMessageId);
298
262
  }
299
263
  } catch (err) {
300
- // When another turn is already processing this conversation,
301
- // `prepareConversationForMessage` throws before any of this turn's
302
- // work runs. Our pre-await mapping update would otherwise stomp the
303
- // in-flight turn's mapping, causing its outbound persistence to
304
- // record `slackMeta` with the wrong (or missing) `threadTs`. Restore
305
- // the snapshot so the in-flight turn sees the mapping it installed.
306
- if (
307
- slackMappingMutated &&
308
- err instanceof Error &&
309
- err.message.includes(CONVERSATION_BUSY_MESSAGE)
310
- ) {
311
- if (priorSlackMapping) {
312
- setThreadTs(
313
- conversationId,
314
- priorSlackMapping.channelId,
315
- priorSlackMapping.threadTs,
316
- );
317
- } else {
318
- clearThreadTs(conversationId);
319
- }
320
- }
321
264
  log.error(
322
265
  { err, conversationId },
323
266
  "Background channel message processing failed",
@@ -3,7 +3,7 @@ import type { SlackStreamTask } from "@vellumai/gateway-client";
3
3
  import {
4
4
  extractThreadTsFromCallbackUrl,
5
5
  isSlackDeliveryCallbackUrl,
6
- } from "../channels/slack-thread-store.js";
6
+ } from "../channels/slack-callback-url.js";
7
7
  import type { ChannelId } from "../channels/types.js";
8
8
  import {
9
9
  incompleteVellumLinkSuffixLength,
@@ -1,184 +0,0 @@
1
- /**
2
- * Slack conversation-to-thread mapping store.
3
- *
4
- * Tracks which Slack thread (identified by `threadTs`) is associated with
5
- * each conversation. When the assistant starts a new topic in a channel,
6
- * a new thread is created; when continuing a related conversation, replies
7
- * are sent to the existing thread.
8
- *
9
- * Uses an in-memory map with TTL eviction. Thread mappings are also
10
- * persisted as conversation metadata so they survive daemon restarts.
11
- */
12
-
13
- import { getLogger } from "../util/logger.js";
14
-
15
- const log = getLogger("slack-thread-store");
16
-
17
- // ── In-memory thread mapping ────────────────────────────────────────
18
-
19
- interface ThreadMapping {
20
- threadTs: string;
21
- channelId: string;
22
- createdAt: number;
23
- lastUsedAt: number;
24
- }
25
-
26
- /** Map from conversationId to thread mapping. */
27
- const threadMappings = new Map<string, ThreadMapping>();
28
-
29
- /** TTL for thread mappings — 24 hours. After this, a new thread is started. */
30
- const THREAD_TTL_MS = 24 * 60 * 60 * 1000;
31
-
32
- /** Hard cap on stored mappings to bound memory. */
33
- const MAX_MAPPINGS = 5_000;
34
-
35
- /**
36
- * Associate a conversation with a Slack thread. Called when:
37
- * - An inbound message arrives with a threadTs (from the gateway callback URL)
38
- * - The assistant creates a new thread for a channel conversation
39
- */
40
- export function setThreadTs(
41
- conversationId: string,
42
- channelId: string,
43
- threadTs: string,
44
- ): void {
45
- evictExpiredIfNeeded();
46
-
47
- const existing = threadMappings.get(conversationId);
48
- if (existing) {
49
- existing.threadTs = threadTs;
50
- existing.channelId = channelId;
51
- existing.lastUsedAt = Date.now();
52
- return;
53
- }
54
-
55
- threadMappings.set(conversationId, {
56
- threadTs,
57
- channelId,
58
- createdAt: Date.now(),
59
- lastUsedAt: Date.now(),
60
- });
61
-
62
- log.debug({ conversationId, channelId, threadTs }, "Thread mapping created");
63
- }
64
-
65
- /**
66
- * Read-side accessor for the in-memory thread mapping. Returns the
67
- * `threadTs` previously associated with this conversation via
68
- * {@link setThreadTs}, or `null` if no mapping exists. Does not bump
69
- * `lastUsedAt` or otherwise mutate the entry — pure lookup.
70
- */
71
- export function getThreadTs(conversationId: string): string | null {
72
- const mapping = threadMappings.get(conversationId);
73
- return mapping ? mapping.threadTs : null;
74
- }
75
-
76
- /**
77
- * Read both `threadTs` and `channelId` without mutating the entry. Used by
78
- * dispatch to snapshot pre-update state so a turn that ends up rejected
79
- * as already-processing can restore the in-flight turn's mapping.
80
- */
81
- export function peekThreadMapping(
82
- conversationId: string,
83
- ): { threadTs: string; channelId: string } | null {
84
- const mapping = threadMappings.get(conversationId);
85
- return mapping
86
- ? { threadTs: mapping.threadTs, channelId: mapping.channelId }
87
- : null;
88
- }
89
-
90
- /**
91
- * Drop any thread mapping associated with this conversation. Called on
92
- * inbound Slack turns that arrive at the channel root (no `threadTs` on
93
- * the callback URL) so that a stale mapping from a prior in-thread turn
94
- * cannot be copied onto the outbound reply's `slackMeta`. Without this,
95
- * a channel-root reply following an earlier thread turn would be
96
- * persisted as if it belonged to the old thread.
97
- */
98
- export function clearThreadTs(conversationId: string): void {
99
- threadMappings.delete(conversationId);
100
- }
101
-
102
- /**
103
- * Extract the threadTs from a Slack reply callback URL, if present.
104
- * The gateway encodes threadTs as a query parameter on the callback URL.
105
- */
106
- export function extractThreadTsFromCallbackUrl(
107
- callbackUrl: string | undefined,
108
- ): string | null {
109
- if (!callbackUrl) return null;
110
- try {
111
- const url = new URL(callbackUrl);
112
- return url.searchParams.get("threadTs");
113
- } catch {
114
- return null;
115
- }
116
- }
117
-
118
- /**
119
- * Extract the messageTs from a Slack reply callback URL, if present.
120
- * The gateway encodes messageTs for non-threaded DMs so the runtime
121
- * can target the original message for emoji-based indicators.
122
- */
123
- export function extractMessageTsFromCallbackUrl(
124
- callbackUrl: string | undefined,
125
- ): string | null {
126
- if (!callbackUrl) return null;
127
- try {
128
- const url = new URL(callbackUrl);
129
- return url.searchParams.get("messageTs");
130
- } catch {
131
- return null;
132
- }
133
- }
134
-
135
- /**
136
- * Whether a reply callback URL targets the Slack delivery endpoint.
137
- */
138
- export function isSlackDeliveryCallbackUrl(callbackUrl?: string): boolean {
139
- if (!callbackUrl) return false;
140
- try {
141
- return new URL(callbackUrl).pathname.endsWith("/deliver/slack");
142
- } catch {
143
- return callbackUrl.endsWith("/deliver/slack");
144
- }
145
- }
146
-
147
- /**
148
- * Extract the channel from a Slack reply callback URL, if present.
149
- */
150
- export function extractChannelFromCallbackUrl(
151
- callbackUrl: string | undefined,
152
- ): string | null {
153
- if (!callbackUrl) return null;
154
- try {
155
- const url = new URL(callbackUrl);
156
- return url.searchParams.get("channel");
157
- } catch {
158
- return null;
159
- }
160
- }
161
-
162
- // ── Internal helpers ────────────────────────────────────────────────
163
-
164
- function evictExpiredIfNeeded(): void {
165
- if (threadMappings.size < MAX_MAPPINGS) return;
166
-
167
- const now = Date.now();
168
- for (const [convId, mapping] of threadMappings) {
169
- if (now - mapping.lastUsedAt >= THREAD_TTL_MS) {
170
- threadMappings.delete(convId);
171
- }
172
- }
173
-
174
- // If still at capacity after TTL sweep, evict oldest entries (LRU)
175
- if (threadMappings.size >= MAX_MAPPINGS) {
176
- const entries = [...threadMappings.entries()].sort(
177
- (a, b) => a[1].lastUsedAt - b[1].lastUsedAt,
178
- );
179
- const toRemove = entries.slice(0, entries.length - MAX_MAPPINGS + 1);
180
- for (const [convId] of toRemove) {
181
- threadMappings.delete(convId);
182
- }
183
- }
184
- }