@vellumai/assistant 0.3.16 → 0.3.19

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 (114) hide show
  1. package/ARCHITECTURE.md +74 -13
  2. package/README.md +6 -0
  3. package/docs/architecture/http-token-refresh.md +23 -1
  4. package/docs/architecture/security.md +80 -0
  5. package/package.json +1 -1
  6. package/src/__tests__/__snapshots__/ipc-snapshot.test.ts.snap +4 -0
  7. package/src/__tests__/access-request-decision.test.ts +4 -7
  8. package/src/__tests__/call-controller.test.ts +170 -0
  9. package/src/__tests__/channel-guardian.test.ts +3 -1
  10. package/src/__tests__/checker.test.ts +139 -48
  11. package/src/__tests__/config-watcher.test.ts +11 -13
  12. package/src/__tests__/conversation-pairing.test.ts +103 -3
  13. package/src/__tests__/guardian-action-conversation-turn.test.ts +1 -1
  14. package/src/__tests__/guardian-action-followup-executor.test.ts +1 -1
  15. package/src/__tests__/guardian-action-grant-mint-consume.test.ts +511 -0
  16. package/src/__tests__/guardian-action-late-reply.test.ts +131 -0
  17. package/src/__tests__/guardian-action-store.test.ts +182 -0
  18. package/src/__tests__/guardian-dispatch.test.ts +180 -0
  19. package/src/__tests__/guardian-grant-minting.test.ts +543 -0
  20. package/src/__tests__/ipc-snapshot.test.ts +22 -0
  21. package/src/__tests__/non-member-access-request.test.ts +1 -2
  22. package/src/__tests__/notification-broadcaster.test.ts +115 -4
  23. package/src/__tests__/notification-decision-strategy.test.ts +2 -1
  24. package/src/__tests__/notification-deep-link.test.ts +44 -1
  25. package/src/__tests__/notification-guardian-path.test.ts +157 -0
  26. package/src/__tests__/notification-thread-candidate-validation.test.ts +215 -0
  27. package/src/__tests__/remote-skill-policy.test.ts +215 -0
  28. package/src/__tests__/scoped-approval-grants.test.ts +521 -0
  29. package/src/__tests__/scoped-grant-security-matrix.test.ts +443 -0
  30. package/src/__tests__/slack-channel-config.test.ts +3 -3
  31. package/src/__tests__/trust-store.test.ts +23 -21
  32. package/src/__tests__/trusted-contact-lifecycle-notifications.test.ts +5 -7
  33. package/src/__tests__/trusted-contact-multichannel.test.ts +2 -6
  34. package/src/__tests__/trusted-contact-verification.test.ts +9 -9
  35. package/src/__tests__/update-bulletin-state.test.ts +1 -1
  36. package/src/__tests__/update-bulletin.test.ts +66 -3
  37. package/src/__tests__/update-template-contract.test.ts +6 -11
  38. package/src/__tests__/voice-scoped-grant-consumer.test.ts +571 -0
  39. package/src/__tests__/voice-session-bridge.test.ts +109 -9
  40. package/src/calls/call-controller.ts +150 -8
  41. package/src/calls/call-domain.ts +12 -0
  42. package/src/calls/guardian-action-sweep.ts +1 -1
  43. package/src/calls/guardian-dispatch.ts +16 -0
  44. package/src/calls/relay-server.ts +13 -0
  45. package/src/calls/voice-session-bridge.ts +46 -5
  46. package/src/cli/core-commands.ts +41 -1
  47. package/src/config/bundled-skills/notifications/SKILL.md +18 -0
  48. package/src/config/schema.ts +6 -0
  49. package/src/config/skills-schema.ts +27 -0
  50. package/src/config/templates/UPDATES.md +5 -6
  51. package/src/config/update-bulletin-format.ts +2 -0
  52. package/src/config/update-bulletin-state.ts +1 -1
  53. package/src/config/update-bulletin-template-path.ts +6 -0
  54. package/src/config/update-bulletin.ts +21 -6
  55. package/src/daemon/config-watcher.ts +3 -2
  56. package/src/daemon/daemon-control.ts +64 -10
  57. package/src/daemon/handlers/config-channels.ts +18 -0
  58. package/src/daemon/handlers/config-slack-channel.ts +1 -1
  59. package/src/daemon/handlers/identity.ts +45 -25
  60. package/src/daemon/handlers/sessions.ts +1 -1
  61. package/src/daemon/handlers/skills.ts +45 -2
  62. package/src/daemon/ipc-contract/sessions.ts +1 -1
  63. package/src/daemon/ipc-contract/skills.ts +1 -0
  64. package/src/daemon/ipc-contract/workspace.ts +12 -1
  65. package/src/daemon/ipc-contract-inventory.json +1 -0
  66. package/src/daemon/lifecycle.ts +8 -0
  67. package/src/daemon/server.ts +25 -3
  68. package/src/daemon/session-process.ts +450 -184
  69. package/src/daemon/tls-certs.ts +17 -12
  70. package/src/daemon/tool-side-effects.ts +1 -1
  71. package/src/memory/channel-delivery-store.ts +18 -20
  72. package/src/memory/channel-guardian-store.ts +39 -42
  73. package/src/memory/conversation-crud.ts +2 -2
  74. package/src/memory/conversation-queries.ts +2 -2
  75. package/src/memory/conversation-store.ts +24 -25
  76. package/src/memory/db-init.ts +17 -1
  77. package/src/memory/embedding-local.ts +16 -7
  78. package/src/memory/fts-reconciler.ts +41 -26
  79. package/src/memory/guardian-action-store.ts +65 -7
  80. package/src/memory/guardian-verification.ts +1 -0
  81. package/src/memory/jobs-worker.ts +2 -2
  82. package/src/memory/migrations/032-guardian-delivery-conversation-index.ts +15 -0
  83. package/src/memory/migrations/032-notification-delivery-thread-decision.ts +20 -0
  84. package/src/memory/migrations/033-scoped-approval-grants.ts +51 -0
  85. package/src/memory/migrations/034-guardian-action-tool-metadata.ts +12 -0
  86. package/src/memory/migrations/index.ts +6 -2
  87. package/src/memory/schema-migration.ts +1 -0
  88. package/src/memory/schema.ts +36 -1
  89. package/src/memory/scoped-approval-grants.ts +509 -0
  90. package/src/memory/search/semantic.ts +3 -3
  91. package/src/notifications/README.md +158 -17
  92. package/src/notifications/broadcaster.ts +68 -50
  93. package/src/notifications/conversation-pairing.ts +96 -18
  94. package/src/notifications/decision-engine.ts +6 -3
  95. package/src/notifications/deliveries-store.ts +12 -0
  96. package/src/notifications/emit-signal.ts +1 -0
  97. package/src/notifications/thread-candidates.ts +60 -25
  98. package/src/notifications/types.ts +2 -1
  99. package/src/permissions/checker.ts +28 -16
  100. package/src/permissions/defaults.ts +14 -4
  101. package/src/runtime/guardian-action-followup-executor.ts +1 -1
  102. package/src/runtime/guardian-action-grant-minter.ts +97 -0
  103. package/src/runtime/http-server.ts +11 -11
  104. package/src/runtime/routes/access-request-decision.ts +1 -1
  105. package/src/runtime/routes/debug-routes.ts +4 -4
  106. package/src/runtime/routes/guardian-approval-interception.ts +120 -4
  107. package/src/runtime/routes/inbound-message-handler.ts +100 -33
  108. package/src/runtime/routes/integration-routes.ts +2 -2
  109. package/src/security/tool-approval-digest.ts +67 -0
  110. package/src/skills/remote-skill-policy.ts +131 -0
  111. package/src/tools/permission-checker.ts +1 -2
  112. package/src/tools/secret-detection-handler.ts +1 -1
  113. package/src/tools/system/voice-config.ts +1 -1
  114. package/src/version.ts +29 -2
@@ -0,0 +1,509 @@
1
+ /**
2
+ * CRUD and atomic consume for scoped approval grants.
3
+ *
4
+ * Grants authorise exactly one tool execution. Two scope modes exist:
5
+ * - `request_id` — grant is bound to a specific pending request
6
+ * - `tool_signature` — grant is bound to a tool name + input digest
7
+ *
8
+ * Invariants:
9
+ * - At most one successful consume per grant (CAS: active -> consumed).
10
+ * - Matching requires all non-null scope fields to match exactly.
11
+ * - Expired and revoked grants cannot be consumed.
12
+ */
13
+
14
+ import { and, eq, lt, sql } from 'drizzle-orm';
15
+ import { v4 as uuid } from 'uuid';
16
+
17
+ import { getDb, rawChanges } from './db.js';
18
+ import { scopedApprovalGrants } from './schema.js';
19
+ import { getLogger } from '../util/logger.js';
20
+
21
+ const log = getLogger('scoped-approval-grants');
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Types
25
+ // ---------------------------------------------------------------------------
26
+
27
+ export type ScopeMode = 'request_id' | 'tool_signature';
28
+ export type GrantStatus = 'active' | 'consumed' | 'expired' | 'revoked';
29
+
30
+ export interface ScopedApprovalGrant {
31
+ id: string;
32
+ assistantId: string;
33
+ scopeMode: ScopeMode;
34
+ requestId: string | null;
35
+ toolName: string | null;
36
+ inputDigest: string | null;
37
+ requestChannel: string;
38
+ decisionChannel: string;
39
+ executionChannel: string | null;
40
+ conversationId: string | null;
41
+ callSessionId: string | null;
42
+ requesterExternalUserId: string | null;
43
+ guardianExternalUserId: string | null;
44
+ status: GrantStatus;
45
+ expiresAt: string;
46
+ consumedAt: string | null;
47
+ consumedByRequestId: string | null;
48
+ createdAt: string;
49
+ updatedAt: string;
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Constants
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /** Max CAS retry attempts when a concurrent consumer steals the selected candidate. */
57
+ const MAX_CAS_RETRIES = 3;
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Helpers
61
+ // ---------------------------------------------------------------------------
62
+
63
+ function rowToGrant(row: typeof scopedApprovalGrants.$inferSelect): ScopedApprovalGrant {
64
+ return {
65
+ id: row.id,
66
+ assistantId: row.assistantId,
67
+ scopeMode: row.scopeMode as ScopeMode,
68
+ requestId: row.requestId,
69
+ toolName: row.toolName,
70
+ inputDigest: row.inputDigest,
71
+ requestChannel: row.requestChannel,
72
+ decisionChannel: row.decisionChannel,
73
+ executionChannel: row.executionChannel,
74
+ conversationId: row.conversationId,
75
+ callSessionId: row.callSessionId,
76
+ requesterExternalUserId: row.requesterExternalUserId,
77
+ guardianExternalUserId: row.guardianExternalUserId,
78
+ status: row.status as GrantStatus,
79
+ expiresAt: row.expiresAt,
80
+ consumedAt: row.consumedAt,
81
+ consumedByRequestId: row.consumedByRequestId,
82
+ createdAt: row.createdAt,
83
+ updatedAt: row.updatedAt,
84
+ };
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // Create
89
+ // ---------------------------------------------------------------------------
90
+
91
+ export interface CreateScopedApprovalGrantParams {
92
+ assistantId: string;
93
+ scopeMode: ScopeMode;
94
+ requestId?: string | null;
95
+ toolName?: string | null;
96
+ inputDigest?: string | null;
97
+ requestChannel: string;
98
+ decisionChannel: string;
99
+ executionChannel?: string | null;
100
+ conversationId?: string | null;
101
+ callSessionId?: string | null;
102
+ requesterExternalUserId?: string | null;
103
+ guardianExternalUserId?: string | null;
104
+ expiresAt: string;
105
+ }
106
+
107
+ export function createScopedApprovalGrant(params: CreateScopedApprovalGrantParams): ScopedApprovalGrant {
108
+ const db = getDb();
109
+ const now = new Date().toISOString();
110
+ const id = uuid();
111
+
112
+ const row = {
113
+ id,
114
+ assistantId: params.assistantId,
115
+ scopeMode: params.scopeMode,
116
+ requestId: params.requestId ?? null,
117
+ toolName: params.toolName ?? null,
118
+ inputDigest: params.inputDigest ?? null,
119
+ requestChannel: params.requestChannel,
120
+ decisionChannel: params.decisionChannel,
121
+ executionChannel: params.executionChannel ?? null,
122
+ conversationId: params.conversationId ?? null,
123
+ callSessionId: params.callSessionId ?? null,
124
+ requesterExternalUserId: params.requesterExternalUserId ?? null,
125
+ guardianExternalUserId: params.guardianExternalUserId ?? null,
126
+ status: 'active' as const,
127
+ expiresAt: params.expiresAt,
128
+ consumedAt: null,
129
+ consumedByRequestId: null,
130
+ createdAt: now,
131
+ updatedAt: now,
132
+ };
133
+
134
+ db.insert(scopedApprovalGrants).values(row).run();
135
+
136
+ log.info(
137
+ {
138
+ event: 'scoped_grant_created',
139
+ grantId: id,
140
+ scopeMode: params.scopeMode,
141
+ toolName: params.toolName ?? null,
142
+ assistantId: params.assistantId,
143
+ requestChannel: params.requestChannel,
144
+ decisionChannel: params.decisionChannel,
145
+ executionChannel: params.executionChannel ?? null,
146
+ expiresAt: params.expiresAt,
147
+ },
148
+ 'Scoped approval grant created',
149
+ );
150
+
151
+ return rowToGrant(row);
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // Consume by request ID (CAS: active -> consumed)
156
+ // ---------------------------------------------------------------------------
157
+
158
+ export interface ConsumeByRequestIdResult {
159
+ ok: boolean;
160
+ grant: ScopedApprovalGrant | null;
161
+ }
162
+
163
+ /**
164
+ * Atomically consume a grant by request ID.
165
+ *
166
+ * Only succeeds when exactly one active, non-expired grant matches the
167
+ * given `requestId` and `assistantId`. Uses compare-and-swap on the
168
+ * `status` column so concurrent consumers race safely — at most one wins.
169
+ */
170
+ export function consumeScopedApprovalGrantByRequestId(
171
+ requestId: string,
172
+ consumingRequestId: string,
173
+ assistantId: string,
174
+ now?: string,
175
+ ): ConsumeByRequestIdResult {
176
+ const db = getDb();
177
+ const currentTime = now ?? new Date().toISOString();
178
+
179
+ // Two-step select-then-update with LIMIT 1 to consume exactly one grant
180
+ // even if duplicate rows exist (the index on request_id is non-unique).
181
+ for (let attempt = 0; attempt <= MAX_CAS_RETRIES; attempt++) {
182
+ const candidate = db
183
+ .select({ id: scopedApprovalGrants.id })
184
+ .from(scopedApprovalGrants)
185
+ .where(
186
+ and(
187
+ eq(scopedApprovalGrants.requestId, requestId),
188
+ eq(scopedApprovalGrants.assistantId, assistantId),
189
+ eq(scopedApprovalGrants.scopeMode, 'request_id'),
190
+ eq(scopedApprovalGrants.status, 'active'),
191
+ sql`${scopedApprovalGrants.expiresAt} > ${currentTime}`,
192
+ ),
193
+ )
194
+ .limit(1)
195
+ .get();
196
+
197
+ if (!candidate) {
198
+ log.info(
199
+ { event: 'scoped_grant_consume_miss', requestId, consumingRequestId, assistantId, scopeMode: 'request_id', attempt },
200
+ 'No matching active grant found for request ID',
201
+ );
202
+ return { ok: false, grant: null };
203
+ }
204
+
205
+ db.update(scopedApprovalGrants)
206
+ .set({
207
+ status: 'consumed',
208
+ consumedAt: currentTime,
209
+ consumedByRequestId: consumingRequestId,
210
+ updatedAt: currentTime,
211
+ })
212
+ .where(
213
+ and(
214
+ eq(scopedApprovalGrants.id, candidate.id),
215
+ eq(scopedApprovalGrants.status, 'active'),
216
+ ),
217
+ )
218
+ .run();
219
+
220
+ if (rawChanges() === 0) {
221
+ // CAS failed — another consumer raced and won this candidate; retry with next match
222
+ continue;
223
+ }
224
+
225
+ // Fetch the consumed grant to return to the caller
226
+ const row = db
227
+ .select()
228
+ .from(scopedApprovalGrants)
229
+ .where(eq(scopedApprovalGrants.id, candidate.id))
230
+ .get();
231
+
232
+ const grant = row ? rowToGrant(row) : null;
233
+ log.info(
234
+ { event: 'scoped_grant_consume_success', grantId: grant?.id, requestId, consumingRequestId, assistantId, scopeMode: 'request_id' },
235
+ 'Scoped approval grant consumed by request ID',
236
+ );
237
+
238
+ return { ok: true, grant };
239
+ }
240
+
241
+ // All retry attempts exhausted — every candidate was stolen by concurrent consumers
242
+ log.info(
243
+ { event: 'scoped_grant_consume_miss', requestId, consumingRequestId, assistantId, scopeMode: 'request_id', reason: 'cas_exhausted' },
244
+ 'All CAS retry attempts exhausted for request ID consume',
245
+ );
246
+ return { ok: false, grant: null };
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Consume by tool signature (CAS: active -> consumed)
251
+ // ---------------------------------------------------------------------------
252
+
253
+ export interface ConsumeByToolSignatureParams {
254
+ toolName: string;
255
+ inputDigest: string;
256
+ consumingRequestId: string;
257
+ /** Optional context constraints — only matched when the grant has a non-null value */
258
+ assistantId?: string;
259
+ executionChannel?: string;
260
+ conversationId?: string;
261
+ callSessionId?: string;
262
+ requesterExternalUserId?: string;
263
+ now?: string;
264
+ }
265
+
266
+ export interface ConsumeByToolSignatureResult {
267
+ ok: boolean;
268
+ grant: ScopedApprovalGrant | null;
269
+ }
270
+
271
+ /**
272
+ * Atomically consume a grant by tool name + input digest.
273
+ *
274
+ * All non-null scope fields on the grant must match the provided context.
275
+ * This is enforced via SQL conditions that check: either the grant field is
276
+ * NULL (wildcard), or it equals the provided value.
277
+ *
278
+ * If a CAS contention miss occurs (another consumer races and wins the
279
+ * selected candidate), re-selects and retries up to {@link MAX_CAS_RETRIES}
280
+ * times before giving up. This prevents false denials when multiple matching
281
+ * grants exist but a concurrent consumer steals the first pick.
282
+ */
283
+ export function consumeScopedApprovalGrantByToolSignature(
284
+ params: ConsumeByToolSignatureParams,
285
+ ): ConsumeByToolSignatureResult {
286
+ const db = getDb();
287
+ const currentTime = params.now ?? new Date().toISOString();
288
+
289
+ const conditions = [
290
+ eq(scopedApprovalGrants.toolName, params.toolName),
291
+ eq(scopedApprovalGrants.inputDigest, params.inputDigest),
292
+ eq(scopedApprovalGrants.scopeMode, 'tool_signature'),
293
+ eq(scopedApprovalGrants.status, 'active'),
294
+ sql`${scopedApprovalGrants.expiresAt} > ${currentTime}`,
295
+ ];
296
+
297
+ // assistantId is always set on grants — scope consumption to the current
298
+ // assistant so grants minted for one assistant cannot be consumed by another.
299
+ if (params.assistantId !== undefined) {
300
+ conditions.push(eq(scopedApprovalGrants.assistantId, params.assistantId));
301
+ }
302
+
303
+ // Context constraints: grant field must be NULL (any) or match exactly
304
+ if (params.executionChannel !== undefined) {
305
+ conditions.push(
306
+ sql`(${scopedApprovalGrants.executionChannel} IS NULL OR ${scopedApprovalGrants.executionChannel} = ${params.executionChannel})`,
307
+ );
308
+ } else {
309
+ // If caller provides no execution channel, only match grants with NULL (any)
310
+ conditions.push(sql`${scopedApprovalGrants.executionChannel} IS NULL`);
311
+ }
312
+
313
+ if (params.conversationId !== undefined) {
314
+ conditions.push(
315
+ sql`(${scopedApprovalGrants.conversationId} IS NULL OR ${scopedApprovalGrants.conversationId} = ${params.conversationId})`,
316
+ );
317
+ } else {
318
+ conditions.push(sql`${scopedApprovalGrants.conversationId} IS NULL`);
319
+ }
320
+
321
+ if (params.callSessionId !== undefined) {
322
+ conditions.push(
323
+ sql`(${scopedApprovalGrants.callSessionId} IS NULL OR ${scopedApprovalGrants.callSessionId} = ${params.callSessionId})`,
324
+ );
325
+ } else {
326
+ conditions.push(sql`${scopedApprovalGrants.callSessionId} IS NULL`);
327
+ }
328
+
329
+ if (params.requesterExternalUserId !== undefined) {
330
+ conditions.push(
331
+ sql`(${scopedApprovalGrants.requesterExternalUserId} IS NULL OR ${scopedApprovalGrants.requesterExternalUserId} = ${params.requesterExternalUserId})`,
332
+ );
333
+ } else {
334
+ conditions.push(sql`${scopedApprovalGrants.requesterExternalUserId} IS NULL`);
335
+ }
336
+
337
+ const specificityOrder = sql`(CASE WHEN ${scopedApprovalGrants.executionChannel} IS NOT NULL THEN 1 ELSE 0 END
338
+ + CASE WHEN ${scopedApprovalGrants.conversationId} IS NOT NULL THEN 1 ELSE 0 END
339
+ + CASE WHEN ${scopedApprovalGrants.callSessionId} IS NOT NULL THEN 1 ELSE 0 END
340
+ + CASE WHEN ${scopedApprovalGrants.requesterExternalUserId} IS NOT NULL THEN 1 ELSE 0 END) DESC`;
341
+
342
+ // Retry loop: if CAS fails because another consumer stole our candidate,
343
+ // re-select and try again — another matching active grant may still exist.
344
+ for (let attempt = 0; attempt <= MAX_CAS_RETRIES; attempt++) {
345
+ // Select a single matching grant to consume (prefer most specific: fewest NULL scope fields).
346
+ // This avoids burning multiple grants when a wildcard grant and a specific grant both match.
347
+ const candidate = db
348
+ .select({ id: scopedApprovalGrants.id })
349
+ .from(scopedApprovalGrants)
350
+ .where(and(...conditions))
351
+ .orderBy(specificityOrder)
352
+ .limit(1)
353
+ .get();
354
+
355
+ if (!candidate) {
356
+ log.info(
357
+ { event: 'scoped_grant_consume_miss', toolName: params.toolName, scopeMode: 'tool_signature', attempt },
358
+ 'No matching active grant found for tool signature',
359
+ );
360
+ return { ok: false, grant: null };
361
+ }
362
+
363
+ db.update(scopedApprovalGrants)
364
+ .set({
365
+ status: 'consumed',
366
+ consumedAt: currentTime,
367
+ consumedByRequestId: params.consumingRequestId,
368
+ updatedAt: currentTime,
369
+ })
370
+ .where(
371
+ and(
372
+ eq(scopedApprovalGrants.id, candidate.id),
373
+ eq(scopedApprovalGrants.status, 'active'),
374
+ ),
375
+ )
376
+ .run();
377
+
378
+ if (rawChanges() === 0) {
379
+ // CAS failed — another consumer raced and won this candidate; retry with next match
380
+ continue;
381
+ }
382
+
383
+ // Fetch the consumed grant
384
+ const row = db
385
+ .select()
386
+ .from(scopedApprovalGrants)
387
+ .where(eq(scopedApprovalGrants.id, candidate.id))
388
+ .get();
389
+
390
+ const grant = row ? rowToGrant(row) : null;
391
+ log.info(
392
+ { event: 'scoped_grant_consume_success', grantId: grant?.id, toolName: params.toolName, consumingRequestId: params.consumingRequestId, scopeMode: 'tool_signature' },
393
+ 'Scoped approval grant consumed by tool signature',
394
+ );
395
+
396
+ return { ok: true, grant };
397
+ }
398
+
399
+ // All retry attempts exhausted — every candidate was stolen by concurrent consumers
400
+ log.info(
401
+ { event: 'scoped_grant_consume_miss', toolName: params.toolName, scopeMode: 'tool_signature', reason: 'cas_exhausted' },
402
+ 'All CAS retry attempts exhausted for tool signature consume',
403
+ );
404
+ return { ok: false, grant: null };
405
+ }
406
+
407
+ // ---------------------------------------------------------------------------
408
+ // Expire grants past their TTL
409
+ // ---------------------------------------------------------------------------
410
+
411
+ /**
412
+ * Bulk-expire all active grants whose `expiresAt` is at or before `now`.
413
+ * Returns the number of grants expired.
414
+ */
415
+ export function expireScopedApprovalGrants(now?: string): number {
416
+ const db = getDb();
417
+ const currentTime = now ?? new Date().toISOString();
418
+
419
+ db.update(scopedApprovalGrants)
420
+ .set({
421
+ status: 'expired',
422
+ updatedAt: currentTime,
423
+ })
424
+ .where(
425
+ and(
426
+ eq(scopedApprovalGrants.status, 'active'),
427
+ sql`${scopedApprovalGrants.expiresAt} <= ${currentTime}`,
428
+ ),
429
+ )
430
+ .run();
431
+
432
+ const count = rawChanges();
433
+ if (count > 0) {
434
+ log.info(
435
+ { event: 'scoped_grant_expired', count },
436
+ `Expired ${count} scoped approval grant(s)`,
437
+ );
438
+ }
439
+
440
+ return count;
441
+ }
442
+
443
+ // ---------------------------------------------------------------------------
444
+ // Revoke active grants for a context
445
+ // ---------------------------------------------------------------------------
446
+
447
+ export interface RevokeContextParams {
448
+ assistantId?: string;
449
+ conversationId?: string;
450
+ callSessionId?: string;
451
+ requestChannel?: string;
452
+ }
453
+
454
+ /**
455
+ * Revoke all active grants matching the given context filters.
456
+ * At least one filter must be provided. Returns the number of
457
+ * grants revoked.
458
+ *
459
+ * Typical use: revoke all grants for a call session when the call ends.
460
+ */
461
+ export function revokeScopedApprovalGrantsForContext(params: RevokeContextParams, now?: string): number {
462
+ const db = getDb();
463
+ const currentTime = now ?? new Date().toISOString();
464
+
465
+ const conditions = [eq(scopedApprovalGrants.status, 'active')];
466
+
467
+ if (params.assistantId !== undefined) {
468
+ conditions.push(eq(scopedApprovalGrants.assistantId, params.assistantId));
469
+ }
470
+ if (params.conversationId !== undefined) {
471
+ conditions.push(eq(scopedApprovalGrants.conversationId, params.conversationId));
472
+ }
473
+ if (params.callSessionId !== undefined) {
474
+ conditions.push(eq(scopedApprovalGrants.callSessionId, params.callSessionId));
475
+ }
476
+ if (params.requestChannel !== undefined) {
477
+ conditions.push(eq(scopedApprovalGrants.requestChannel, params.requestChannel));
478
+ }
479
+
480
+ // Guard: at least one context filter must be provided to avoid revoking ALL active grants
481
+ if (conditions.length === 1) {
482
+ throw new Error('revokeScopedApprovalGrantsForContext requires at least one context filter');
483
+ }
484
+
485
+ db.update(scopedApprovalGrants)
486
+ .set({
487
+ status: 'revoked',
488
+ updatedAt: currentTime,
489
+ })
490
+ .where(and(...conditions))
491
+ .run();
492
+
493
+ const count = rawChanges();
494
+ if (count > 0) {
495
+ log.info(
496
+ {
497
+ event: 'scoped_grant_revoked',
498
+ count,
499
+ assistantId: params.assistantId,
500
+ conversationId: params.conversationId,
501
+ callSessionId: params.callSessionId,
502
+ requestChannel: params.requestChannel,
503
+ },
504
+ `Revoked ${count} scoped approval grant(s) for context`,
505
+ );
506
+ }
507
+
508
+ return count;
509
+ }
@@ -2,7 +2,7 @@ import { inArray } from 'drizzle-orm';
2
2
 
3
3
  import { getLogger } from '../../util/logger.js';
4
4
  import { getDb } from '../db.js';
5
- import { withQdrantBreaker, _resetQdrantBreaker, _getQdrantBreakerState } from '../qdrant-circuit-breaker.js';
5
+ import { _getQdrantBreakerState,_resetQdrantBreaker, withQdrantBreaker } from '../qdrant-circuit-breaker.js';
6
6
  import type { QdrantSearchResult } from '../qdrant-client.js';
7
7
  import { getQdrantClient } from '../qdrant-client.js';
8
8
  import {
@@ -14,10 +14,10 @@ import {
14
14
  import { computeRecencyScore } from './ranking.js';
15
15
  import type { Candidate } from './types.js';
16
16
 
17
- const log = getLogger('semantic-search');
17
+ const _log = getLogger('semantic-search');
18
18
 
19
19
  // Re-export for tests that depend on these from this module
20
- export { _resetQdrantBreaker, _getQdrantBreakerState };
20
+ export { _getQdrantBreakerState,_resetQdrantBreaker };
21
21
 
22
22
  export async function semanticSearch(
23
23
  queryVector: number[],