@dsh-ray/assistant-delivery 0.3.3 → 0.3.5

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 (42) hide show
  1. package/README.md +5 -4
  2. package/lib/agent-runtime.d.ts +11 -3
  3. package/lib/agent-runtime.d.ts.map +1 -1
  4. package/lib/agent-runtime.js +295 -37
  5. package/lib/agent-runtime.js.map +1 -1
  6. package/lib/command-catalog.d.ts +42 -0
  7. package/lib/command-catalog.d.ts.map +1 -0
  8. package/lib/command-catalog.js +248 -0
  9. package/lib/command-catalog.js.map +1 -0
  10. package/lib/config-control.d.ts +158 -0
  11. package/lib/config-control.d.ts.map +1 -0
  12. package/lib/config-control.js +1406 -0
  13. package/lib/config-control.js.map +1 -0
  14. package/lib/index.d.ts +4 -1
  15. package/lib/index.d.ts.map +1 -1
  16. package/lib/index.js +4 -1
  17. package/lib/index.js.map +1 -1
  18. package/lib/service.d.ts +10 -1
  19. package/lib/service.d.ts.map +1 -1
  20. package/lib/service.js +483 -3
  21. package/lib/service.js.map +1 -1
  22. package/lib/session-commands.d.ts +12 -0
  23. package/lib/session-commands.d.ts.map +1 -1
  24. package/lib/session-commands.js +57 -0
  25. package/lib/session-commands.js.map +1 -1
  26. package/lib/sqlite.d.ts.map +1 -1
  27. package/lib/sqlite.js +1 -0
  28. package/lib/sqlite.js.map +1 -1
  29. package/lib/stderr-logger.d.ts +24 -0
  30. package/lib/stderr-logger.d.ts.map +1 -0
  31. package/lib/stderr-logger.js +89 -0
  32. package/lib/stderr-logger.js.map +1 -0
  33. package/lib/store.d.ts +17 -1
  34. package/lib/store.d.ts.map +1 -1
  35. package/lib/store.js +333 -4
  36. package/lib/store.js.map +1 -1
  37. package/lib/types.d.ts +94 -1
  38. package/lib/types.d.ts.map +1 -1
  39. package/lib/types.js.map +1 -1
  40. package/lib/version.d.ts +1 -1
  41. package/lib/version.js +1 -1
  42. package/package.json +10 -10
package/lib/store.js CHANGED
@@ -1063,8 +1063,8 @@ function canonicalMetadata(input, kind) {
1063
1063
  }
1064
1064
  function canonicalIntent(input, binding, maxTextBytes) {
1065
1065
  const allowed = [
1066
- 'idempotencyKey', 'bindingId', 'target', 'text', 'format', 'approval', 'modelPicker', 'permissionPicker',
1067
- 'replyToEventId', 'metadata', 'attachment',
1066
+ 'idempotencyKey', 'bindingId', 'target', 'text', 'format', 'approval', 'configPicker',
1067
+ 'modelPicker', 'permissionPicker', 'replyToEventId', 'metadata', 'attachment',
1068
1068
  ];
1069
1069
  if (input === null || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !allowed.includes(key))) {
1070
1070
  throw new DeliveryStoreError('invalid-intent', 'outbound intent shape is invalid');
@@ -1088,8 +1088,8 @@ function canonicalIntent(input, binding, maxTextBytes) {
1088
1088
  throw new DeliveryStoreError('invalid-intent', 'outbound text exceeds its byte budget');
1089
1089
  }
1090
1090
  const format = input.format ?? 'plain';
1091
- if (format !== 'plain' && format !== 'markdown' && format !== 'approval' && format !== 'model-picker'
1092
- && format !== 'permission-picker') {
1091
+ if (format !== 'plain' && format !== 'markdown' && format !== 'approval' && format !== 'config-picker'
1092
+ && format !== 'model-picker' && format !== 'permission-picker') {
1093
1093
  throw new DeliveryStoreError('invalid-intent', 'outbound format is invalid');
1094
1094
  }
1095
1095
  let approval;
@@ -1123,6 +1123,13 @@ function canonicalIntent(input, binding, maxTextBytes) {
1123
1123
  else if (input.approval !== undefined) {
1124
1124
  throw new DeliveryStoreError('invalid-intent', 'approval payload requires approval format');
1125
1125
  }
1126
+ let configPicker;
1127
+ if (format === 'config-picker') {
1128
+ configPicker = canonicalConfigPicker(input.configPicker, binding);
1129
+ }
1130
+ else if (input.configPicker !== undefined) {
1131
+ throw new DeliveryStoreError('invalid-intent', 'config picker payload requires config-picker format');
1132
+ }
1126
1133
  let modelPicker;
1127
1134
  if (format === 'model-picker') {
1128
1135
  modelPicker = canonicalModelPicker(input.modelPicker);
@@ -1150,6 +1157,7 @@ function canonicalIntent(input, binding, maxTextBytes) {
1150
1157
  const attachment = canonicalTextAttachment(input.attachment, format, maxTextBytes);
1151
1158
  return { idempotencyKey, bindingId, target, text: input.text, format,
1152
1159
  ...(approval === undefined ? {} : { approval }),
1160
+ ...(configPicker === undefined ? {} : { configPicker }),
1153
1161
  ...(modelPicker === undefined ? {} : { modelPicker }),
1154
1162
  ...(permissionPicker === undefined ? {} : { permissionPicker }),
1155
1163
  ...(replyToEventId === undefined ? {} : { replyToEventId }),
@@ -1203,6 +1211,7 @@ function parseOwnerRouteReceipt(record) {
1203
1211
  || metadata['dsh.route.receiptVersion'] !== '2'
1204
1212
  || !['plain', 'markdown'].includes(record.intent.format ?? 'plain')
1205
1213
  || record.intent.approval !== undefined
1214
+ || record.intent.configPicker !== undefined
1206
1215
  || record.intent.modelPicker !== undefined
1207
1216
  || record.intent.permissionPicker !== undefined
1208
1217
  || record.intent.replyToEventId !== undefined)
@@ -1265,6 +1274,240 @@ function ownerRouteReceiptMetadata(input) {
1265
1274
  'dsh.route.sourceId': input.sourceId,
1266
1275
  };
1267
1276
  }
1277
+ const CONFIG_PICKER_CATEGORY_IDS = new Set([
1278
+ 'conversation',
1279
+ 'lark',
1280
+ 'routing',
1281
+ 'providers',
1282
+ ]);
1283
+ function canonicalConfigPickerField(input) {
1284
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
1285
+ throw new DeliveryStoreError('invalid-intent', 'config picker field is invalid');
1286
+ }
1287
+ const key = validateBindingText(input.key, 'configPicker.field.key', 120);
1288
+ const label = validateBindingText(input.label, 'configPicker.field.label', 120);
1289
+ const description = input.description === undefined
1290
+ ? undefined
1291
+ : validateBindingText(input.description, 'configPicker.field.description', 400);
1292
+ const unavailableReason = input.unavailableReason === undefined
1293
+ ? undefined
1294
+ : validateBindingText(input.unavailableReason, 'configPicker.field.unavailableReason', 240);
1295
+ if (input.kind === 'select') {
1296
+ const allowed = ['kind', 'key', 'label', 'description', 'options', 'currentValue', 'unavailableReason'];
1297
+ if (Object.keys(input).some(field => !allowed.includes(field))
1298
+ || !Array.isArray(input.options) || input.options.length > 80) {
1299
+ throw new DeliveryStoreError('invalid-intent', 'config picker select field is invalid');
1300
+ }
1301
+ const options = input.options.map(option => {
1302
+ if (option === null || typeof option !== 'object' || Array.isArray(option)
1303
+ || Object.keys(option).length !== 2 || Object.keys(option).some(f => f !== 'value' && f !== 'label')) {
1304
+ throw new DeliveryStoreError('invalid-intent', 'config picker select option is invalid');
1305
+ }
1306
+ return {
1307
+ value: typeof option.value === 'string' && option.value.length <= 256 ? option.value : (() => {
1308
+ throw new DeliveryStoreError('invalid-intent', 'config picker select option value is invalid');
1309
+ })(),
1310
+ label: validateBindingText(option.label, 'configPicker.option.label', 160),
1311
+ };
1312
+ });
1313
+ if (typeof input.currentValue !== 'string' || input.currentValue.length > 256) {
1314
+ throw new DeliveryStoreError('invalid-intent', 'config picker select currentValue is invalid');
1315
+ }
1316
+ return {
1317
+ kind: 'select',
1318
+ key,
1319
+ label,
1320
+ ...(description === undefined ? {} : { description }),
1321
+ options,
1322
+ currentValue: input.currentValue,
1323
+ ...(unavailableReason === undefined ? {} : { unavailableReason }),
1324
+ };
1325
+ }
1326
+ if (input.kind === 'input') {
1327
+ const allowed = [
1328
+ 'kind', 'key', 'label', 'description', 'inputType', 'currentValue',
1329
+ 'placeholder', 'required', 'maxLength', 'statusBadge', 'unavailableReason',
1330
+ ];
1331
+ if (Object.keys(input).some(field => !allowed.includes(field))
1332
+ || (input.inputType !== 'text' && input.inputType !== 'number' && input.inputType !== 'password')) {
1333
+ throw new DeliveryStoreError('invalid-intent', 'config picker input field is invalid');
1334
+ }
1335
+ if (input.inputType === 'password' && input.currentValue !== undefined) {
1336
+ throw new DeliveryStoreError('invalid-intent', 'config picker password field must never carry currentValue');
1337
+ }
1338
+ const currentValue = input.currentValue === undefined
1339
+ ? undefined
1340
+ : typeof input.currentValue === 'string' && input.currentValue.length <= 1_024
1341
+ ? input.currentValue
1342
+ : (() => { throw new DeliveryStoreError('invalid-intent', 'config picker input currentValue is invalid'); })();
1343
+ const placeholder = input.placeholder === undefined
1344
+ ? undefined
1345
+ : validateBindingText(input.placeholder, 'configPicker.field.placeholder', 200);
1346
+ const statusBadge = input.statusBadge === undefined
1347
+ ? undefined
1348
+ : validateBindingText(input.statusBadge, 'configPicker.field.statusBadge', 160);
1349
+ if (input.required !== undefined && typeof input.required !== 'boolean') {
1350
+ throw new DeliveryStoreError('invalid-intent', 'config picker input required flag is invalid');
1351
+ }
1352
+ if (input.maxLength !== undefined && (!Number.isSafeInteger(input.maxLength) || input.maxLength < 1 || input.maxLength > 2_048)) {
1353
+ throw new DeliveryStoreError('invalid-intent', 'config picker input maxLength is invalid');
1354
+ }
1355
+ return {
1356
+ kind: 'input',
1357
+ key,
1358
+ label,
1359
+ ...(description === undefined ? {} : { description }),
1360
+ inputType: input.inputType,
1361
+ ...(currentValue === undefined ? {} : { currentValue }),
1362
+ ...(placeholder === undefined ? {} : { placeholder }),
1363
+ ...(input.required === undefined ? {} : { required: input.required }),
1364
+ ...(input.maxLength === undefined ? {} : { maxLength: input.maxLength }),
1365
+ ...(statusBadge === undefined ? {} : { statusBadge }),
1366
+ ...(unavailableReason === undefined ? {} : { unavailableReason }),
1367
+ };
1368
+ }
1369
+ throw new DeliveryStoreError('invalid-intent', 'config picker field kind is invalid');
1370
+ }
1371
+ function canonicalConfigPickerProviderItem(input) {
1372
+ const allowed = [
1373
+ 'id', 'label', 'isNew', 'credentialRef', 'credentialConfigured',
1374
+ 'credentialMasked', 'credentialWritable', 'fields',
1375
+ ];
1376
+ if (input === null || typeof input !== 'object' || Array.isArray(input)
1377
+ || Object.keys(input).some(field => !allowed.includes(field))
1378
+ || !Array.isArray(input.fields) || input.fields.length > 20) {
1379
+ throw new DeliveryStoreError('invalid-intent', 'config picker provider item is invalid');
1380
+ }
1381
+ const id = validateBindingText(input.id, 'configPicker.provider.id', 120);
1382
+ const label = validateBindingText(input.label, 'configPicker.provider.label', 160);
1383
+ const credentialRef = input.credentialRef === undefined
1384
+ ? undefined
1385
+ : validateBindingText(input.credentialRef, 'configPicker.provider.credentialRef', 128);
1386
+ const credentialMasked = input.credentialMasked === undefined
1387
+ ? undefined
1388
+ : validateBindingText(input.credentialMasked, 'configPicker.provider.credentialMasked', 128);
1389
+ if ((input.isNew !== undefined && typeof input.isNew !== 'boolean')
1390
+ || (input.credentialConfigured !== undefined && typeof input.credentialConfigured !== 'boolean')
1391
+ || (input.credentialWritable !== undefined && typeof input.credentialWritable !== 'boolean')) {
1392
+ throw new DeliveryStoreError('invalid-intent', 'config picker provider metadata is invalid');
1393
+ }
1394
+ return {
1395
+ id,
1396
+ label,
1397
+ ...(input.isNew === undefined ? {} : { isNew: input.isNew }),
1398
+ ...(credentialRef === undefined ? {} : { credentialRef }),
1399
+ ...(input.credentialConfigured === undefined ? {} : { credentialConfigured: input.credentialConfigured }),
1400
+ ...(credentialMasked === undefined ? {} : { credentialMasked }),
1401
+ ...(input.credentialWritable === undefined ? {} : { credentialWritable: input.credentialWritable }),
1402
+ fields: input.fields.map(canonicalConfigPickerField),
1403
+ };
1404
+ }
1405
+ function canonicalConfigPickerCategory(input, conversationKind) {
1406
+ const allowed = [
1407
+ 'id', 'label', 'subtitle', 'available', 'unavailableReason', 'dmOnly',
1408
+ 'namespace', 'revision', 'notice', 'fields', 'providers', 'activeProviderId',
1409
+ ];
1410
+ if (input === null || typeof input !== 'object' || Array.isArray(input)
1411
+ || Object.keys(input).some(field => !allowed.includes(field))
1412
+ || !CONFIG_PICKER_CATEGORY_IDS.has(input.id)
1413
+ || typeof input.available !== 'boolean'
1414
+ || !Array.isArray(input.fields) || input.fields.length > 24) {
1415
+ throw new DeliveryStoreError('invalid-intent', 'config picker category is invalid');
1416
+ }
1417
+ const label = validateBindingText(input.label, 'configPicker.category.label', 120);
1418
+ const subtitle = validateBindingText(input.subtitle, 'configPicker.category.subtitle', 240);
1419
+ const unavailableReason = input.unavailableReason === undefined
1420
+ ? undefined
1421
+ : validateBindingText(input.unavailableReason, 'configPicker.category.unavailableReason', 240);
1422
+ const namespace = input.namespace === undefined
1423
+ ? undefined
1424
+ : validateBindingText(input.namespace, 'configPicker.category.namespace', 128);
1425
+ const notice = input.notice === undefined
1426
+ ? undefined
1427
+ : validateBindingText(input.notice, 'configPicker.category.notice', 400);
1428
+ const activeProviderId = input.activeProviderId === undefined
1429
+ ? undefined
1430
+ : validateBindingText(input.activeProviderId, 'configPicker.category.activeProviderId', 120);
1431
+ if ((input.dmOnly !== undefined && typeof input.dmOnly !== 'boolean')
1432
+ || (input.revision !== undefined && (!Number.isSafeInteger(input.revision) || input.revision < 0))) {
1433
+ throw new DeliveryStoreError('invalid-intent', 'config picker category revision is invalid');
1434
+ }
1435
+ if (input.id === 'providers' && conversationKind !== 'dm') {
1436
+ if (input.dmOnly !== true || input.fields.length !== 0 || input.providers !== undefined
1437
+ || activeProviderId !== undefined) {
1438
+ throw new DeliveryStoreError('invalid-intent', 'config picker providers require dm conversation');
1439
+ }
1440
+ }
1441
+ if (input.providers !== undefined && (!Array.isArray(input.providers) || input.providers.length > 30)) {
1442
+ throw new DeliveryStoreError('invalid-intent', 'config picker providers list is invalid');
1443
+ }
1444
+ return {
1445
+ id: input.id,
1446
+ label,
1447
+ subtitle,
1448
+ available: input.available,
1449
+ ...(unavailableReason === undefined ? {} : { unavailableReason }),
1450
+ ...(input.dmOnly === undefined ? {} : { dmOnly: input.dmOnly }),
1451
+ ...(namespace === undefined ? {} : { namespace }),
1452
+ ...(input.revision === undefined ? {} : { revision: input.revision }),
1453
+ ...(notice === undefined ? {} : { notice }),
1454
+ fields: input.fields.map(canonicalConfigPickerField),
1455
+ ...(input.providers === undefined ? {} : { providers: input.providers.map(canonicalConfigPickerProviderItem) }),
1456
+ ...(activeProviderId === undefined ? {} : { activeProviderId }),
1457
+ };
1458
+ }
1459
+ function canonicalConfigPicker(input, binding) {
1460
+ const allowed = [
1461
+ 'operationId', 'issuedAt', 'expiresAt', 'bindingVersion', 'sessionId',
1462
+ 'conversationKind', 'activeCategory', 'activeProviderId', 'stateHash', 'categories',
1463
+ ];
1464
+ if (input === undefined || input === null || typeof input !== 'object' || Array.isArray(input)
1465
+ || Object.keys(input).some(field => !allowed.includes(field))) {
1466
+ throw new DeliveryStoreError('invalid-intent', 'config picker intent shape is invalid');
1467
+ }
1468
+ const operationId = validateBindingText(input.operationId, 'operationId', 256);
1469
+ const sessionId = validateBindingText(input.sessionId, 'sessionId', 512);
1470
+ if (!Number.isSafeInteger(input.issuedAt) || input.issuedAt < 1
1471
+ || !Number.isSafeInteger(input.expiresAt) || input.expiresAt <= input.issuedAt) {
1472
+ throw new DeliveryStoreError('invalid-intent', 'config picker lifetime is invalid');
1473
+ }
1474
+ if (!Number.isSafeInteger(input.bindingVersion) || input.bindingVersion < 1
1475
+ || input.bindingVersion !== binding.version || sessionId !== binding.sessionId
1476
+ || input.conversationKind !== binding.conversation.kind) {
1477
+ throw new DeliveryStoreError('invalid-intent', 'config picker binding snapshot is invalid');
1478
+ }
1479
+ if (!CONFIG_PICKER_CATEGORY_IDS.has(input.activeCategory)) {
1480
+ throw new DeliveryStoreError('invalid-intent', 'config picker active category is invalid');
1481
+ }
1482
+ if (typeof input.stateHash !== 'string' || !/^[a-f0-9]{64}$/u.test(input.stateHash)) {
1483
+ throw new DeliveryStoreError('invalid-intent', 'config picker state hash is invalid');
1484
+ }
1485
+ const activeProviderId = input.activeProviderId === undefined
1486
+ ? undefined
1487
+ : validateBindingText(input.activeProviderId, 'configPicker.activeProviderId', 120);
1488
+ if (input.conversationKind !== 'dm' && activeProviderId !== undefined) {
1489
+ throw new DeliveryStoreError('invalid-intent', 'config picker provider requires dm conversation');
1490
+ }
1491
+ if (!Array.isArray(input.categories) || input.categories.length < 1 || input.categories.length > 4) {
1492
+ throw new DeliveryStoreError('invalid-intent', 'config picker categories list is invalid');
1493
+ }
1494
+ const categories = input.categories.map(entry => canonicalConfigPickerCategory(entry, binding.conversation.kind));
1495
+ if (new Set(categories.map(entry => entry.id)).size !== categories.length) {
1496
+ throw new DeliveryStoreError('invalid-intent', 'config picker categories contain duplicates');
1497
+ }
1498
+ return {
1499
+ operationId,
1500
+ issuedAt: input.issuedAt,
1501
+ expiresAt: input.expiresAt,
1502
+ bindingVersion: input.bindingVersion,
1503
+ sessionId,
1504
+ conversationKind: input.conversationKind,
1505
+ activeCategory: input.activeCategory,
1506
+ ...(activeProviderId === undefined ? {} : { activeProviderId }),
1507
+ stateHash: input.stateHash,
1508
+ categories,
1509
+ };
1510
+ }
1268
1511
  function canonicalPermissionPicker(input, binding) {
1269
1512
  if (input === undefined || input === null || typeof input !== 'object' || Array.isArray(input)
1270
1513
  || Object.keys(input).some(field => ![
@@ -5322,6 +5565,92 @@ export class DeliveryStore {
5322
5565
  }
5323
5566
  return { ...record, intent };
5324
5567
  }
5568
+ getConfigPicker(operationId, bindingId) {
5569
+ return this.getConfigPickerRecord(operationId, bindingId)?.intent.configPicker;
5570
+ }
5571
+ getConfigPickerRecord(operationId, bindingId) {
5572
+ this.assertOpen();
5573
+ const operation = validateBindingText(operationId, 'operationId', 256);
5574
+ const bindingKey = validateBindingText(bindingId, 'bindingId', 256);
5575
+ const row = this.database.prepare(`${outboxSelect}
5576
+ WHERE binding_id = ? AND json_valid(intent_json)
5577
+ AND json_extract(intent_json, '$.configPicker.operationId') = ?
5578
+ ORDER BY created_at DESC, id DESC LIMIT 1`).get(bindingKey, operation);
5579
+ if (row === undefined)
5580
+ return undefined;
5581
+ const binding = this.getBinding(bindingKey);
5582
+ if (binding === undefined)
5583
+ throw new DeliveryStoreError('invalid-intent', 'config picker binding does not exist');
5584
+ const record = outboxFromRow(row);
5585
+ const intent = canonicalIntent(record.intent, binding, this.maxTextBytes);
5586
+ if (intent.format !== 'config-picker' || intent.configPicker?.operationId !== operation
5587
+ || digest(JSON.stringify(intent)) !== record.intentHash) {
5588
+ throw new DeliveryStoreError('invalid-intent', 'persisted config picker intent is invalid');
5589
+ }
5590
+ return { ...record, intent };
5591
+ }
5592
+ latestAdmissionCursor() {
5593
+ this.assertOpen();
5594
+ const row = this.database.prepare(`
5595
+ SELECT epoch, admission_sequence
5596
+ FROM delivery_inbox_admissions
5597
+ ORDER BY admission_sequence DESC LIMIT 1
5598
+ `).get();
5599
+ return row === undefined ? undefined : Object.freeze({ epoch: row.epoch, sequence: row.admission_sequence });
5600
+ }
5601
+ claimConfigCallbackInbox(input) {
5602
+ this.assertOpen();
5603
+ const bindingId = validateBindingText(input.bindingId, 'bindingId', 256);
5604
+ const ownerId = validateBindingText(input.ownerId, 'ownerId', 256);
5605
+ if (!Number.isSafeInteger(input.leaseMs) || input.leaseMs < 1) {
5606
+ throw new DeliveryStoreError('conflict', 'invalid inbox lease');
5607
+ }
5608
+ const accepted = this.acceptInbound(input.envelope);
5609
+ const existing = accepted.record;
5610
+ if (accepted.duplicate) {
5611
+ if (existing.status === 'processed' && existing.bindingId === bindingId) {
5612
+ return { duplicate: true, record: existing, fencingToken: 0 };
5613
+ }
5614
+ if (existing.status === 'dead_letter') {
5615
+ throw new DeliveryStoreError('conflict', 'config callback selection previously failed');
5616
+ }
5617
+ if (existing.status === 'claimed') {
5618
+ throw new DeliveryStoreError('conflict', 'config callback selection is already in progress');
5619
+ }
5620
+ }
5621
+ const binding = this.getBinding(bindingId);
5622
+ if (binding?.status !== 'active'
5623
+ || conversationHash(existing.envelope.conversation) !== conversationHash(binding.conversation)
5624
+ || principalHash(existing.envelope.principal) !== principalHash(binding.principal)) {
5625
+ throw new DeliveryStoreError('invalid-binding', 'config callback binding is not active');
5626
+ }
5627
+ const now = this.now();
5628
+ return this.transaction(() => {
5629
+ const current = this.getInbox(existing.id);
5630
+ if (current.status === 'processed' && current.bindingId === bindingId) {
5631
+ return { duplicate: true, record: current, fencingToken: 0 };
5632
+ }
5633
+ if (!['received', 'authorized'].includes(current.status)) {
5634
+ throw new DeliveryStoreError('conflict', `cannot claim config callback inbox in ${current.status}`);
5635
+ }
5636
+ const previousFence = this.database.prepare('SELECT COALESCE(MAX(fencing_token), 0) AS maximum FROM inbox_attempts WHERE inbox_id = ?').get(current.id);
5637
+ const fencingToken = previousFence.maximum + 1;
5638
+ const changed = this.database.prepare(`
5639
+ UPDATE inbox_messages SET status = 'claimed', binding_id = ?, claimed_by = ?,
5640
+ fencing_token = ?, lease_until = ?, attempt_count = attempt_count + 1,
5641
+ failure_code = NULL, updated_at = ?
5642
+ WHERE id = ? AND status IN ('received', 'authorized')
5643
+ `).run(bindingId, ownerId, fencingToken, now + input.leaseMs, now, current.id);
5644
+ if (changed.changes !== 1) {
5645
+ throw new DeliveryStoreError('conflict', 'config callback inbox claim lost a race');
5646
+ }
5647
+ this.database.prepare(`
5648
+ INSERT INTO inbox_attempts (id, inbox_id, attempt_number, owner_id, fencing_token, status, created_at)
5649
+ VALUES (?, ?, ?, ?, ?, 'claimed', ?)
5650
+ `).run(`inbox_attempt_${randomUUID()}`, current.id, fencingToken, ownerId, fencingToken, now);
5651
+ return { duplicate: false, record: this.getInbox(current.id), fencingToken };
5652
+ });
5653
+ }
5325
5654
  getPermissionPicker(operationId, bindingId) {
5326
5655
  return this.getPermissionPickerRecord(operationId, bindingId)?.intent.permissionPicker;
5327
5656
  }