@steerable/agent-shell 0.12.7 → 0.13.1

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 (68) hide show
  1. package/dist/auth/credentials.d.ts +83 -0
  2. package/dist/auth/credentials.js +426 -0
  3. package/dist/auth/index.d.ts +33 -9
  4. package/dist/auth/index.js +85 -0
  5. package/dist/host/external-pack-loader.d.ts +40 -0
  6. package/dist/host/external-pack-loader.js +247 -0
  7. package/dist/host/http-routes.d.ts +6 -2
  8. package/dist/host/http-routes.js +5 -2
  9. package/dist/host/pack-assembly.d.ts +9 -1
  10. package/dist/host/runtime.js +54 -1
  11. package/dist/local-backend/coreloop-stream.d.ts +4 -0
  12. package/dist/local-backend/coreloop-stream.js +4 -0
  13. package/dist/local-backend/fact-chain.d.ts +38 -0
  14. package/dist/local-backend/fact-chain.js +145 -0
  15. package/dist/local-backend/router.d.ts +3 -1
  16. package/dist/local-backend/router.js +329 -35
  17. package/dist/local-backend/state-reconcile.d.ts +42 -0
  18. package/dist/local-backend/state-reconcile.js +81 -0
  19. package/dist/local-backend/title-refresh.d.ts +39 -0
  20. package/dist/local-backend/title-refresh.js +80 -0
  21. package/dist/local-backend/turn-security-context.d.ts +42 -0
  22. package/dist/local-backend/turn-security-context.js +62 -0
  23. package/dist/local-backend/ui-surface.d.ts +75 -0
  24. package/dist/local-backend/ui-surface.js +368 -0
  25. package/dist/local-executor.d.ts +3 -0
  26. package/dist/local-executor.js +40 -1
  27. package/dist/memory/authoring-candidates.d.ts +26 -0
  28. package/dist/memory/authoring-candidates.js +73 -0
  29. package/dist/memory/injector.d.ts +34 -0
  30. package/dist/memory/injector.js +111 -0
  31. package/dist/memory/routes.d.ts +16 -0
  32. package/dist/memory/routes.js +146 -0
  33. package/dist/memory/store.d.ts +176 -0
  34. package/dist/memory/store.js +623 -0
  35. package/dist/memory/tools.d.ts +83 -0
  36. package/dist/memory/tools.js +143 -0
  37. package/dist/present-files.d.ts +25 -1
  38. package/dist/present-files.js +170 -2
  39. package/dist/scenario/applications.d.ts +52 -0
  40. package/dist/scenario/applications.js +143 -0
  41. package/dist/scenario/pack.d.ts +1 -1
  42. package/dist/security/policy-digest.d.ts +28 -0
  43. package/dist/security/policy-digest.js +104 -0
  44. package/dist/server/http-server.js +23 -6
  45. package/dist/sidecar/boot.d.ts +1 -0
  46. package/dist/sidecar/boot.js +2 -0
  47. package/dist/sidecar/rejected-before-effect.d.ts +22 -0
  48. package/dist/sidecar/rejected-before-effect.js +63 -0
  49. package/dist/sidecar/reverse-approval.d.ts +2 -0
  50. package/dist/sidecar/reverse-approval.js +28 -5
  51. package/dist/sidecar/reverse-tools.d.ts +3 -0
  52. package/dist/sidecar/reverse-tools.js +129 -17
  53. package/dist/sidecar/types.d.ts +6 -0
  54. package/dist/storage/fde-fallback.d.ts +4 -0
  55. package/dist/storage/fde-fallback.js +354 -0
  56. package/dist/storage/fde-types.d.ts +215 -0
  57. package/dist/storage/fde-types.js +1 -0
  58. package/dist/storage/index.d.ts +113 -1
  59. package/dist/storage/index.js +797 -0
  60. package/dist/storage/insights-redact.d.ts +4 -1
  61. package/dist/storage/insights-redact.js +6 -1
  62. package/dist/storage/process-locks.d.ts +1 -1
  63. package/dist/storage/process-locks.js +1 -1
  64. package/dist/storage/scoped-store.d.ts +3 -1
  65. package/dist/tool-presentation.js +20 -0
  66. package/dist/tool-router.d.ts +20 -1
  67. package/dist/tool-router.js +76 -12
  68. package/package.json +5 -5
@@ -313,6 +313,150 @@ export class SqliteScopedStore {
313
313
  );
314
314
 
315
315
  CREATE INDEX IF NOT EXISTS idx_tasks_chat ON tasks(chat_id, datetime(updated_at) DESC);
316
+
317
+ CREATE TABLE IF NOT EXISTS pack_credentials (
318
+ tenant_id TEXT NOT NULL,
319
+ owner_user_id TEXT NOT NULL,
320
+ source_id TEXT NOT NULL,
321
+ auth_kind TEXT NOT NULL,
322
+ cipher_text TEXT NOT NULL,
323
+ iv TEXT NOT NULL,
324
+ auth_tag TEXT NOT NULL,
325
+ updated_by TEXT NOT NULL,
326
+ updated_at TEXT NOT NULL,
327
+ PRIMARY KEY (tenant_id, owner_user_id, source_id)
328
+ );
329
+
330
+ CREATE TABLE IF NOT EXISTS pending_reconciliations (
331
+ tenant_id TEXT NOT NULL,
332
+ user_id TEXT NOT NULL,
333
+ id TEXT NOT NULL,
334
+ chat_id TEXT NOT NULL,
335
+ tool_name TEXT NOT NULL,
336
+ args_digest TEXT NOT NULL,
337
+ args_preview TEXT NOT NULL,
338
+ error_detail TEXT NOT NULL,
339
+ status TEXT NOT NULL,
340
+ resolution_note TEXT,
341
+ resolved_by TEXT,
342
+ created_at TEXT NOT NULL,
343
+ resolved_at TEXT,
344
+ PRIMARY KEY (tenant_id, user_id, id)
345
+ );
346
+
347
+ CREATE INDEX IF NOT EXISTS idx_pending_reconciliations_chat
348
+ ON pending_reconciliations(tenant_id, user_id, chat_id, status);
349
+
350
+ CREATE TABLE IF NOT EXISTS chat_ui_surfaces (
351
+ tenant_id TEXT NOT NULL,
352
+ user_id TEXT NOT NULL,
353
+ chat_id TEXT NOT NULL,
354
+ surface_id TEXT NOT NULL,
355
+ revision INTEGER NOT NULL DEFAULT 1,
356
+ title_json TEXT NOT NULL,
357
+ spec_json TEXT NOT NULL,
358
+ state_json TEXT NOT NULL,
359
+ status TEXT NOT NULL,
360
+ updated_at TEXT NOT NULL,
361
+ PRIMARY KEY (tenant_id, user_id, chat_id, surface_id)
362
+ );
363
+
364
+ CREATE TABLE IF NOT EXISTS chat_ui_receipts (
365
+ tenant_id TEXT NOT NULL,
366
+ user_id TEXT NOT NULL,
367
+ id TEXT NOT NULL,
368
+ chat_id TEXT NOT NULL,
369
+ surface_id TEXT NOT NULL,
370
+ revision INTEGER NOT NULL,
371
+ action_id TEXT NOT NULL,
372
+ tool_name TEXT NOT NULL,
373
+ payload_json TEXT NOT NULL,
374
+ source_fingerprints_json TEXT NOT NULL,
375
+ result_json TEXT NOT NULL,
376
+ actor_id TEXT NOT NULL,
377
+ created_at TEXT NOT NULL,
378
+ PRIMARY KEY (tenant_id, user_id, id)
379
+ );
380
+
381
+ CREATE INDEX IF NOT EXISTS idx_chat_ui_receipts_chat
382
+ ON chat_ui_receipts(tenant_id, user_id, chat_id, created_at);
383
+
384
+ CREATE TABLE IF NOT EXISTS chat_deliverables (
385
+ tenant_id TEXT NOT NULL,
386
+ user_id TEXT NOT NULL,
387
+ id TEXT NOT NULL,
388
+ chat_id TEXT NOT NULL,
389
+ message_id TEXT,
390
+ file_path TEXT NOT NULL,
391
+ file_name TEXT NOT NULL,
392
+ mime_type TEXT NOT NULL,
393
+ size_bytes INTEGER NOT NULL DEFAULT 0,
394
+ sha256 TEXT NOT NULL,
395
+ verification_status TEXT NOT NULL,
396
+ verifier_id TEXT,
397
+ issues_json TEXT NOT NULL,
398
+ summary TEXT,
399
+ report_path TEXT,
400
+ source_refs_json TEXT NOT NULL,
401
+ tool_calls_json TEXT NOT NULL,
402
+ created_at TEXT NOT NULL,
403
+ PRIMARY KEY (tenant_id, user_id, id)
404
+ );
405
+
406
+ CREATE INDEX IF NOT EXISTS idx_chat_deliverables_chat
407
+ ON chat_deliverables(tenant_id, user_id, chat_id, created_at);
408
+
409
+ CREATE TABLE IF NOT EXISTS memory_documents (
410
+ tenant_id TEXT NOT NULL,
411
+ user_id TEXT NOT NULL,
412
+ scope_kind TEXT NOT NULL,
413
+ scope_id TEXT NOT NULL,
414
+ content_markdown TEXT NOT NULL,
415
+ content_sha256 TEXT NOT NULL,
416
+ updated_by TEXT NOT NULL,
417
+ source_chat_id TEXT,
418
+ updated_at TEXT NOT NULL,
419
+ PRIMARY KEY (tenant_id, user_id, scope_kind, scope_id)
420
+ );
421
+
422
+ CREATE TABLE IF NOT EXISTS memory_entries (
423
+ tenant_id TEXT NOT NULL,
424
+ user_id TEXT NOT NULL,
425
+ id TEXT NOT NULL,
426
+ scope_kind TEXT NOT NULL,
427
+ scope_id TEXT NOT NULL,
428
+ content TEXT NOT NULL,
429
+ content_sha256 TEXT NOT NULL,
430
+ source_chat_id TEXT,
431
+ status TEXT NOT NULL,
432
+ created_at TEXT NOT NULL,
433
+ updated_at TEXT NOT NULL,
434
+ PRIMARY KEY (tenant_id, user_id, id)
435
+ );
436
+
437
+ CREATE INDEX IF NOT EXISTS idx_memory_entries_scope
438
+ ON memory_entries(tenant_id, user_id, scope_kind, scope_id, status, updated_at);
439
+
440
+ CREATE TABLE IF NOT EXISTS memory_revoked_hashes (
441
+ tenant_id TEXT NOT NULL,
442
+ user_id TEXT NOT NULL,
443
+ scope_kind TEXT NOT NULL,
444
+ scope_id TEXT NOT NULL,
445
+ content_sha256 TEXT NOT NULL,
446
+ revoked_at TEXT NOT NULL,
447
+ PRIMARY KEY (tenant_id, user_id, scope_kind, scope_id, content_sha256)
448
+ );
449
+
450
+ CREATE TABLE IF NOT EXISTS memory_refinement_meta (
451
+ tenant_id TEXT NOT NULL,
452
+ user_id TEXT NOT NULL,
453
+ scope_kind TEXT NOT NULL,
454
+ scope_id TEXT NOT NULL,
455
+ refined_session_count INTEGER NOT NULL DEFAULT 0,
456
+ last_refined_at TEXT,
457
+ last_status TEXT,
458
+ PRIMARY KEY (tenant_id, user_id, scope_kind, scope_id)
459
+ );
316
460
  `);
317
461
  // 跨轮压缩已下沉框架 CoreLoop(token 压力触发 CompactionHooks,压缩边界
318
462
  // 持久化到 durable record)。桌面不再维护滚动摘要;历史库里的
@@ -759,6 +903,16 @@ export class SqliteScopedStore {
759
903
  const info = this.db.prepare(`DELETE FROM chat_sessions WHERE tenant_id = ? AND user_id = ? AND id = ?`).run(this.scope.tenantId, this.scope.userId, chatId);
760
904
  this.db.prepare(`DELETE FROM settings_kv WHERE tenant_id = ? AND user_id = ? AND key = ?`).run(this.scope.tenantId, this.scope.userId, `chat_record:${chatId}`);
761
905
  this.db.prepare(`DELETE FROM settings_kv WHERE tenant_id = ? AND user_id = ? AND key = ?`).run(this.scope.tenantId, this.scope.userId, `turn_active:${chatId}`);
906
+ for (const table of [
907
+ 'pending_reconciliations',
908
+ 'chat_ui_surfaces',
909
+ 'chat_ui_receipts',
910
+ 'chat_deliverables',
911
+ ]) {
912
+ this.db
913
+ .prepare(`DELETE FROM ${table} WHERE tenant_id = ? AND user_id = ? AND chat_id = ?`)
914
+ .run(this.scope.tenantId, this.scope.userId, chatId);
915
+ }
762
916
  return info.changes > 0;
763
917
  }
764
918
  async chatHasMessages(chatId) {
@@ -1508,6 +1662,649 @@ export class SqliteScopedStore {
1508
1662
  updatedAt: String(row.updated_at),
1509
1663
  };
1510
1664
  }
1665
+ async getCustomSetting(key) {
1666
+ return this.getSetting(`custom:${key}`);
1667
+ }
1668
+ async setCustomSetting(key, value) {
1669
+ const namespaced = `custom:${key}`;
1670
+ if (value === null) {
1671
+ this.db
1672
+ .prepare(`DELETE FROM settings_kv WHERE tenant_id = ? AND user_id = ? AND key = ?`)
1673
+ .run(this.scope.tenantId, this.scope.userId, namespaced);
1674
+ return;
1675
+ }
1676
+ this.setSetting(namespaced, value);
1677
+ }
1678
+ async upsertPackCredential(input) {
1679
+ const updatedAt = new Date().toISOString();
1680
+ this.db
1681
+ .prepare(`
1682
+ INSERT INTO pack_credentials (
1683
+ tenant_id, owner_user_id, source_id, auth_kind, cipher_text, iv, auth_tag, updated_by, updated_at
1684
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1685
+ ON CONFLICT(tenant_id, owner_user_id, source_id)
1686
+ DO UPDATE SET
1687
+ auth_kind = excluded.auth_kind,
1688
+ cipher_text = excluded.cipher_text,
1689
+ iv = excluded.iv,
1690
+ auth_tag = excluded.auth_tag,
1691
+ updated_by = excluded.updated_by,
1692
+ updated_at = excluded.updated_at
1693
+ `)
1694
+ .run(this.scope.tenantId, input.ownerUserId, input.sourceId, input.authKind, input.cipherText, input.iv, input.authTag, input.updatedBy, updatedAt);
1695
+ return {
1696
+ tenantId: this.scope.tenantId,
1697
+ ownerUserId: input.ownerUserId,
1698
+ sourceId: input.sourceId,
1699
+ authKind: input.authKind,
1700
+ cipherText: input.cipherText,
1701
+ iv: input.iv,
1702
+ authTag: input.authTag,
1703
+ updatedBy: input.updatedBy,
1704
+ updatedAt,
1705
+ };
1706
+ }
1707
+ async getPackCredential(ownerUserId, sourceId) {
1708
+ const row = this.db
1709
+ .prepare(`
1710
+ SELECT tenant_id, owner_user_id, source_id, auth_kind, cipher_text, iv, auth_tag, updated_by, updated_at
1711
+ FROM pack_credentials
1712
+ WHERE tenant_id = ? AND owner_user_id = ? AND source_id = ?
1713
+ `)
1714
+ .get(this.scope.tenantId, ownerUserId, sourceId);
1715
+ if (!row)
1716
+ return null;
1717
+ return this.mapPackCredential(row);
1718
+ }
1719
+ async listPackCredentials(ownerUserIds) {
1720
+ const ids = ownerUserIds && ownerUserIds.length > 0 ? [...ownerUserIds] : [this.scope.userId, '__tenant__'];
1721
+ const placeholders = ids.map(() => '?').join(', ');
1722
+ const rows = this.db
1723
+ .prepare(`
1724
+ SELECT tenant_id, owner_user_id, source_id, auth_kind, cipher_text, iv, auth_tag, updated_by, updated_at
1725
+ FROM pack_credentials
1726
+ WHERE tenant_id = ? AND owner_user_id IN (${placeholders})
1727
+ ORDER BY source_id ASC
1728
+ `)
1729
+ .all(this.scope.tenantId, ...ids);
1730
+ return rows.map((row) => this.mapPackCredential(row));
1731
+ }
1732
+ async deletePackCredential(ownerUserId, sourceId) {
1733
+ const res = this.db
1734
+ .prepare(`
1735
+ DELETE FROM pack_credentials
1736
+ WHERE tenant_id = ? AND owner_user_id = ? AND source_id = ?
1737
+ `)
1738
+ .run(this.scope.tenantId, ownerUserId, sourceId);
1739
+ return res.changes > 0;
1740
+ }
1741
+ mapPackCredential(row) {
1742
+ return {
1743
+ tenantId: String(row.tenant_id),
1744
+ ownerUserId: String(row.owner_user_id),
1745
+ sourceId: String(row.source_id),
1746
+ authKind: String(row.auth_kind),
1747
+ cipherText: String(row.cipher_text),
1748
+ iv: String(row.iv),
1749
+ authTag: String(row.auth_tag),
1750
+ updatedBy: String(row.updated_by),
1751
+ updatedAt: String(row.updated_at),
1752
+ };
1753
+ }
1754
+ async createPendingReconciliation(input) {
1755
+ const id = input.id ?? randomUUID();
1756
+ const createdAt = new Date().toISOString();
1757
+ this.db
1758
+ .prepare(`
1759
+ INSERT INTO pending_reconciliations (
1760
+ tenant_id, user_id, id, chat_id, tool_name, args_digest, args_preview,
1761
+ error_detail, status, resolution_note, resolved_by, created_at, resolved_at
1762
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NULL, NULL, ?, NULL)
1763
+ `)
1764
+ .run(this.scope.tenantId, this.scope.userId, id, input.chatId, input.toolName, input.argsDigest, input.argsPreview, input.errorDetail, createdAt);
1765
+ return {
1766
+ id,
1767
+ chatId: input.chatId,
1768
+ toolName: input.toolName,
1769
+ argsDigest: input.argsDigest,
1770
+ argsPreview: input.argsPreview,
1771
+ errorDetail: input.errorDetail,
1772
+ status: 'pending',
1773
+ resolutionNote: null,
1774
+ resolvedBy: null,
1775
+ createdAt,
1776
+ resolvedAt: null,
1777
+ };
1778
+ }
1779
+ async listPendingReconciliations(chatId, options) {
1780
+ const rows = options?.includeResolved
1781
+ ? this.db
1782
+ .prepare(`
1783
+ SELECT * FROM pending_reconciliations
1784
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ?
1785
+ ORDER BY created_at DESC
1786
+ `)
1787
+ .all(this.scope.tenantId, this.scope.userId, chatId)
1788
+ : this.db
1789
+ .prepare(`
1790
+ SELECT * FROM pending_reconciliations
1791
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ? AND status = 'pending'
1792
+ ORDER BY created_at DESC
1793
+ `)
1794
+ .all(this.scope.tenantId, this.scope.userId, chatId);
1795
+ return rows.map((row) => this.mapPendingReconciliation(row));
1796
+ }
1797
+ async resolvePendingReconciliation(input) {
1798
+ const resolvedAt = new Date().toISOString();
1799
+ const res = this.db
1800
+ .prepare(`
1801
+ UPDATE pending_reconciliations
1802
+ SET status = ?, resolution_note = ?, resolved_by = ?, resolved_at = ?
1803
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ? AND id = ?
1804
+ `)
1805
+ .run(input.status, input.resolutionNote ?? null, input.resolvedBy, resolvedAt, this.scope.tenantId, this.scope.userId, input.chatId, input.reconciliationId);
1806
+ if (res.changes === 0)
1807
+ return null;
1808
+ const row = this.db
1809
+ .prepare(`
1810
+ SELECT * FROM pending_reconciliations
1811
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ? AND id = ?
1812
+ `)
1813
+ .get(this.scope.tenantId, this.scope.userId, input.chatId, input.reconciliationId);
1814
+ return row ? this.mapPendingReconciliation(row) : null;
1815
+ }
1816
+ mapPendingReconciliation(row) {
1817
+ const rawStatus = String(row.status);
1818
+ const status = rawStatus === 'confirmed_executed' || rawStatus === 'confirmed_not_executed'
1819
+ ? rawStatus
1820
+ : 'pending';
1821
+ return {
1822
+ id: String(row.id),
1823
+ chatId: String(row.chat_id),
1824
+ toolName: String(row.tool_name),
1825
+ argsDigest: String(row.args_digest),
1826
+ argsPreview: String(row.args_preview),
1827
+ errorDetail: String(row.error_detail),
1828
+ status,
1829
+ resolutionNote: row.resolution_note != null ? String(row.resolution_note) : null,
1830
+ resolvedBy: row.resolved_by != null ? String(row.resolved_by) : null,
1831
+ createdAt: String(row.created_at),
1832
+ resolvedAt: row.resolved_at != null ? String(row.resolved_at) : null,
1833
+ };
1834
+ }
1835
+ async upsertChatUiSurface(input) {
1836
+ const existing = await this.getChatUiSurface(input.chatId, input.spec.surfaceId);
1837
+ const revision = existing ? existing.revision + 1 : 1;
1838
+ const updatedAt = new Date().toISOString();
1839
+ const state = input.state ?? existing?.state ?? {};
1840
+ const status = input.status ?? existing?.status ?? 'active';
1841
+ const title = { ...input.spec.title };
1842
+ this.db
1843
+ .prepare(`
1844
+ INSERT INTO chat_ui_surfaces (
1845
+ tenant_id, user_id, chat_id, surface_id, revision, title_json, spec_json, state_json, status, updated_at
1846
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1847
+ ON CONFLICT(tenant_id, user_id, chat_id, surface_id)
1848
+ DO UPDATE SET
1849
+ revision = excluded.revision,
1850
+ title_json = excluded.title_json,
1851
+ spec_json = excluded.spec_json,
1852
+ state_json = excluded.state_json,
1853
+ status = excluded.status,
1854
+ updated_at = excluded.updated_at
1855
+ `)
1856
+ .run(this.scope.tenantId, this.scope.userId, input.chatId, input.spec.surfaceId, revision, JSON.stringify(title), JSON.stringify(input.spec), JSON.stringify(state), status, updatedAt);
1857
+ return {
1858
+ chatId: input.chatId,
1859
+ surfaceId: input.spec.surfaceId,
1860
+ revision,
1861
+ title,
1862
+ spec: input.spec,
1863
+ state,
1864
+ status,
1865
+ updatedAt,
1866
+ };
1867
+ }
1868
+ async getChatUiSurface(chatId, surfaceId) {
1869
+ const row = this.db
1870
+ .prepare(`
1871
+ SELECT * FROM chat_ui_surfaces
1872
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ? AND surface_id = ?
1873
+ `)
1874
+ .get(this.scope.tenantId, this.scope.userId, chatId, surfaceId);
1875
+ return row ? this.mapChatUiSurface(row) : null;
1876
+ }
1877
+ async listChatUiSurfaces(chatId) {
1878
+ const rows = this.db
1879
+ .prepare(`
1880
+ SELECT * FROM chat_ui_surfaces
1881
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ?
1882
+ ORDER BY updated_at DESC
1883
+ `)
1884
+ .all(this.scope.tenantId, this.scope.userId, chatId);
1885
+ return rows.map((row) => this.mapChatUiSurface(row));
1886
+ }
1887
+ mapChatUiSurface(row) {
1888
+ const rawStatus = String(row.status);
1889
+ const status = rawStatus === 'submitted' || rawStatus === 'archived' ? rawStatus : 'active';
1890
+ return {
1891
+ chatId: String(row.chat_id),
1892
+ surfaceId: String(row.surface_id),
1893
+ revision: Number(row.revision ?? 1),
1894
+ title: this.safeJson(row.title_json, {}),
1895
+ spec: this.safeJson(row.spec_json, {
1896
+ surfaceId: String(row.surface_id),
1897
+ title: {},
1898
+ nodes: [],
1899
+ }),
1900
+ state: this.safeJson(row.state_json, {}),
1901
+ status,
1902
+ updatedAt: String(row.updated_at),
1903
+ };
1904
+ }
1905
+ async recordChatUiReceipt(input) {
1906
+ const id = randomUUID();
1907
+ const createdAt = new Date().toISOString();
1908
+ this.db
1909
+ .prepare(`
1910
+ INSERT INTO chat_ui_receipts (
1911
+ tenant_id, user_id, id, chat_id, surface_id, revision, action_id, tool_name,
1912
+ payload_json, source_fingerprints_json, result_json, actor_id, created_at
1913
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1914
+ `)
1915
+ .run(this.scope.tenantId, this.scope.userId, id, input.chatId, input.surfaceId, input.revision, input.actionId, input.toolName, JSON.stringify(input.payload), JSON.stringify(input.sourceFingerprints), JSON.stringify(input.result), input.actorId, createdAt);
1916
+ return {
1917
+ id,
1918
+ chatId: input.chatId,
1919
+ surfaceId: input.surfaceId,
1920
+ revision: input.revision,
1921
+ actionId: input.actionId,
1922
+ toolName: input.toolName,
1923
+ payload: input.payload,
1924
+ sourceFingerprints: input.sourceFingerprints,
1925
+ result: input.result,
1926
+ actorId: input.actorId,
1927
+ createdAt,
1928
+ };
1929
+ }
1930
+ async listChatUiReceipts(chatId, surfaceId) {
1931
+ const rows = surfaceId
1932
+ ? this.db
1933
+ .prepare(`
1934
+ SELECT * FROM chat_ui_receipts
1935
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ? AND surface_id = ?
1936
+ ORDER BY created_at DESC
1937
+ `)
1938
+ .all(this.scope.tenantId, this.scope.userId, chatId, surfaceId)
1939
+ : this.db
1940
+ .prepare(`
1941
+ SELECT * FROM chat_ui_receipts
1942
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ?
1943
+ ORDER BY created_at DESC
1944
+ `)
1945
+ .all(this.scope.tenantId, this.scope.userId, chatId);
1946
+ return rows.map((row) => ({
1947
+ id: String(row.id),
1948
+ chatId: String(row.chat_id),
1949
+ surfaceId: String(row.surface_id),
1950
+ revision: Number(row.revision ?? 1),
1951
+ actionId: String(row.action_id),
1952
+ toolName: String(row.tool_name),
1953
+ payload: this.safeJson(row.payload_json, {}),
1954
+ sourceFingerprints: this.safeJson(row.source_fingerprints_json, {}),
1955
+ result: this.safeJson(row.result_json, {}),
1956
+ actorId: String(row.actor_id),
1957
+ createdAt: String(row.created_at),
1958
+ }));
1959
+ }
1960
+ async saveChatDeliverable(input) {
1961
+ const id = input.id ?? randomUUID();
1962
+ const createdAt = new Date().toISOString();
1963
+ const issues = [...(input.issues ?? [])];
1964
+ const sourceRefs = [...(input.sourceRefs ?? [])];
1965
+ const toolCalls = [...(input.toolCalls ?? [])];
1966
+ this.db
1967
+ .prepare(`
1968
+ INSERT INTO chat_deliverables (
1969
+ tenant_id, user_id, id, chat_id, message_id, file_path, file_name, mime_type,
1970
+ size_bytes, sha256, verification_status, verifier_id, issues_json, summary,
1971
+ report_path, source_refs_json, tool_calls_json, created_at
1972
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1973
+ ON CONFLICT(tenant_id, user_id, id)
1974
+ DO UPDATE SET
1975
+ verification_status = excluded.verification_status,
1976
+ verifier_id = excluded.verifier_id,
1977
+ issues_json = excluded.issues_json,
1978
+ summary = excluded.summary,
1979
+ report_path = excluded.report_path,
1980
+ source_refs_json = excluded.source_refs_json,
1981
+ tool_calls_json = excluded.tool_calls_json
1982
+ `)
1983
+ .run(this.scope.tenantId, this.scope.userId, id, input.chatId, input.messageId ?? null, input.filePath, input.fileName, input.mimeType, input.sizeBytes, input.sha256, input.verificationStatus, input.verifierId ?? null, JSON.stringify(issues), input.summary ?? null, input.reportPath ?? null, JSON.stringify(sourceRefs), JSON.stringify(toolCalls), createdAt);
1984
+ return {
1985
+ id,
1986
+ chatId: input.chatId,
1987
+ messageId: input.messageId ?? null,
1988
+ filePath: input.filePath,
1989
+ fileName: input.fileName,
1990
+ mimeType: input.mimeType,
1991
+ sizeBytes: input.sizeBytes,
1992
+ sha256: input.sha256,
1993
+ verificationStatus: input.verificationStatus,
1994
+ verifierId: input.verifierId ?? null,
1995
+ issues,
1996
+ summary: input.summary ?? null,
1997
+ reportPath: input.reportPath ?? null,
1998
+ sourceRefs,
1999
+ toolCalls,
2000
+ createdAt,
2001
+ };
2002
+ }
2003
+ async listChatDeliverables(chatId) {
2004
+ const rows = this.db
2005
+ .prepare(`
2006
+ SELECT * FROM chat_deliverables
2007
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ?
2008
+ ORDER BY created_at DESC
2009
+ `)
2010
+ .all(this.scope.tenantId, this.scope.userId, chatId);
2011
+ return rows.map((row) => {
2012
+ const statusRaw = String(row.verification_status);
2013
+ const verificationStatus = statusRaw === 'verified' || statusRaw === 'warnings' || statusRaw === 'failed'
2014
+ ? statusRaw
2015
+ : 'unverified';
2016
+ return {
2017
+ id: String(row.id),
2018
+ chatId: String(row.chat_id),
2019
+ messageId: row.message_id != null ? String(row.message_id) : null,
2020
+ filePath: String(row.file_path),
2021
+ fileName: String(row.file_name),
2022
+ mimeType: String(row.mime_type),
2023
+ sizeBytes: Number(row.size_bytes ?? 0),
2024
+ sha256: String(row.sha256),
2025
+ verificationStatus,
2026
+ verifierId: row.verifier_id != null ? String(row.verifier_id) : null,
2027
+ issues: this.safeJson(row.issues_json, []),
2028
+ summary: row.summary != null ? String(row.summary) : null,
2029
+ reportPath: row.report_path != null ? String(row.report_path) : null,
2030
+ sourceRefs: this.safeJson(row.source_refs_json, []),
2031
+ toolCalls: this.safeJson(row.tool_calls_json, []),
2032
+ createdAt: String(row.created_at),
2033
+ };
2034
+ });
2035
+ }
2036
+ async getMemoryDocument(scopeKind, scopeId) {
2037
+ const row = this.db
2038
+ .prepare(`
2039
+ SELECT * FROM memory_documents
2040
+ WHERE tenant_id = ? AND user_id = ? AND scope_kind = ? AND scope_id = ?
2041
+ `)
2042
+ .get(this.scope.tenantId, this.scope.userId, scopeKind, scopeId);
2043
+ if (!row)
2044
+ return null;
2045
+ return {
2046
+ scopeKind,
2047
+ scopeId,
2048
+ contentMarkdown: String(row.content_markdown),
2049
+ contentSha256: String(row.content_sha256),
2050
+ updatedBy: String(row.updated_by),
2051
+ sourceChatId: row.source_chat_id != null ? String(row.source_chat_id) : null,
2052
+ updatedAt: String(row.updated_at),
2053
+ };
2054
+ }
2055
+ async putMemoryDocument(input) {
2056
+ const updatedAt = new Date().toISOString();
2057
+ this.db
2058
+ .prepare(`
2059
+ INSERT INTO memory_documents (
2060
+ tenant_id, user_id, scope_kind, scope_id, content_markdown, content_sha256, updated_by, source_chat_id, updated_at
2061
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
2062
+ ON CONFLICT(tenant_id, user_id, scope_kind, scope_id)
2063
+ DO UPDATE SET
2064
+ content_markdown = excluded.content_markdown,
2065
+ content_sha256 = excluded.content_sha256,
2066
+ updated_by = excluded.updated_by,
2067
+ source_chat_id = excluded.source_chat_id,
2068
+ updated_at = excluded.updated_at
2069
+ `)
2070
+ .run(this.scope.tenantId, this.scope.userId, input.scopeKind, input.scopeId, input.contentMarkdown, input.contentSha256, input.updatedBy, input.sourceChatId ?? null, updatedAt);
2071
+ return {
2072
+ scopeKind: input.scopeKind,
2073
+ scopeId: input.scopeId,
2074
+ contentMarkdown: input.contentMarkdown,
2075
+ contentSha256: input.contentSha256,
2076
+ updatedBy: input.updatedBy,
2077
+ sourceChatId: input.sourceChatId ?? null,
2078
+ updatedAt,
2079
+ };
2080
+ }
2081
+ async listMemoryEntries(scopeKind, scopeId, includeRevoked = false) {
2082
+ const clauses = ['tenant_id = ?', 'user_id = ?'];
2083
+ const params = [this.scope.tenantId, this.scope.userId];
2084
+ if (scopeKind) {
2085
+ clauses.push('scope_kind = ?');
2086
+ params.push(scopeKind);
2087
+ }
2088
+ if (scopeId !== undefined) {
2089
+ clauses.push('scope_id = ?');
2090
+ params.push(scopeId);
2091
+ }
2092
+ if (!includeRevoked) {
2093
+ clauses.push(`status = 'active'`);
2094
+ }
2095
+ const rows = this.db
2096
+ .prepare(`
2097
+ SELECT * FROM memory_entries
2098
+ WHERE ${clauses.join(' AND ')}
2099
+ ORDER BY updated_at DESC, created_at DESC
2100
+ `)
2101
+ .all(...params);
2102
+ return rows.map((row) => this.mapMemoryEntry(row));
2103
+ }
2104
+ async upsertMemoryEntry(input) {
2105
+ const revoked = await this.isMemoryHashRevoked(input.scopeKind, input.scopeId, input.contentSha256);
2106
+ if (revoked) {
2107
+ const now = new Date().toISOString();
2108
+ return {
2109
+ skippedRevoked: true,
2110
+ entry: {
2111
+ id: input.id ?? randomUUID(),
2112
+ scopeKind: input.scopeKind,
2113
+ scopeId: input.scopeId,
2114
+ content: input.content,
2115
+ contentSha256: input.contentSha256,
2116
+ sourceChatId: input.sourceChatId ?? null,
2117
+ status: 'revoked',
2118
+ createdAt: now,
2119
+ updatedAt: now,
2120
+ },
2121
+ };
2122
+ }
2123
+ const existing = this.db
2124
+ .prepare(`
2125
+ SELECT * FROM memory_entries
2126
+ WHERE tenant_id = ? AND user_id = ? AND scope_kind = ? AND scope_id = ? AND content_sha256 = ?
2127
+ `)
2128
+ .get(this.scope.tenantId, this.scope.userId, input.scopeKind, input.scopeId, input.contentSha256);
2129
+ const now = new Date().toISOString();
2130
+ if (existing) {
2131
+ this.db
2132
+ .prepare(`
2133
+ UPDATE memory_entries
2134
+ SET content = ?, status = 'active', source_chat_id = COALESCE(?, source_chat_id), updated_at = ?
2135
+ WHERE tenant_id = ? AND user_id = ? AND id = ?
2136
+ `)
2137
+ .run(input.content, input.sourceChatId ?? null, now, this.scope.tenantId, this.scope.userId, String(existing.id));
2138
+ return {
2139
+ skippedRevoked: false,
2140
+ entry: {
2141
+ ...this.mapMemoryEntry(existing),
2142
+ content: input.content,
2143
+ status: 'active',
2144
+ updatedAt: now,
2145
+ },
2146
+ };
2147
+ }
2148
+ const id = input.id ?? randomUUID();
2149
+ this.db
2150
+ .prepare(`
2151
+ INSERT INTO memory_entries (
2152
+ tenant_id, user_id, id, scope_kind, scope_id, content, content_sha256, source_chat_id, status, created_at, updated_at
2153
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
2154
+ `)
2155
+ .run(this.scope.tenantId, this.scope.userId, id, input.scopeKind, input.scopeId, input.content, input.contentSha256, input.sourceChatId ?? null, now, now);
2156
+ return {
2157
+ skippedRevoked: false,
2158
+ entry: {
2159
+ id,
2160
+ scopeKind: input.scopeKind,
2161
+ scopeId: input.scopeId,
2162
+ content: input.content,
2163
+ contentSha256: input.contentSha256,
2164
+ sourceChatId: input.sourceChatId ?? null,
2165
+ status: 'active',
2166
+ createdAt: now,
2167
+ updatedAt: now,
2168
+ },
2169
+ };
2170
+ }
2171
+ async revokeMemoryEntry(entryId) {
2172
+ const existing = this.db
2173
+ .prepare(`
2174
+ SELECT * FROM memory_entries
2175
+ WHERE tenant_id = ? AND user_id = ? AND id = ?
2176
+ `)
2177
+ .get(this.scope.tenantId, this.scope.userId, entryId);
2178
+ if (!existing)
2179
+ return null;
2180
+ const now = new Date().toISOString();
2181
+ this.db
2182
+ .prepare(`
2183
+ UPDATE memory_entries
2184
+ SET status = 'revoked', updated_at = ?
2185
+ WHERE tenant_id = ? AND user_id = ? AND id = ?
2186
+ `)
2187
+ .run(now, this.scope.tenantId, this.scope.userId, entryId);
2188
+ this.db
2189
+ .prepare(`
2190
+ INSERT INTO memory_revoked_hashes (
2191
+ tenant_id, user_id, scope_kind, scope_id, content_sha256, revoked_at
2192
+ ) VALUES (?, ?, ?, ?, ?, ?)
2193
+ ON CONFLICT(tenant_id, user_id, scope_kind, scope_id, content_sha256)
2194
+ DO UPDATE SET revoked_at = excluded.revoked_at
2195
+ `)
2196
+ .run(this.scope.tenantId, this.scope.userId, String(existing.scope_kind), String(existing.scope_id), String(existing.content_sha256), now);
2197
+ return {
2198
+ ...this.mapMemoryEntry(existing),
2199
+ status: 'revoked',
2200
+ updatedAt: now,
2201
+ };
2202
+ }
2203
+ async isMemoryHashRevoked(scopeKind, scopeId, contentSha256) {
2204
+ const row = this.db
2205
+ .prepare(`
2206
+ SELECT 1 FROM memory_revoked_hashes
2207
+ WHERE tenant_id = ? AND user_id = ? AND scope_kind = ? AND scope_id = ? AND content_sha256 = ?
2208
+ `)
2209
+ .get(this.scope.tenantId, this.scope.userId, scopeKind, scopeId, contentSha256);
2210
+ return Boolean(row);
2211
+ }
2212
+ async clearMemoryScope(scopeKind, scopeId) {
2213
+ const clauses = ['tenant_id = ?', 'user_id = ?'];
2214
+ const params = [this.scope.tenantId, this.scope.userId];
2215
+ if (scopeKind) {
2216
+ clauses.push('scope_kind = ?');
2217
+ params.push(scopeKind);
2218
+ }
2219
+ if (scopeId !== undefined) {
2220
+ clauses.push('scope_id = ?');
2221
+ params.push(scopeId);
2222
+ }
2223
+ const where = clauses.join(' AND ');
2224
+ const entries = this.db
2225
+ .prepare(`SELECT scope_kind, scope_id, content_sha256 FROM memory_entries WHERE ${where}`)
2226
+ .all(...params);
2227
+ const now = new Date().toISOString();
2228
+ for (const item of entries) {
2229
+ this.db
2230
+ .prepare(`
2231
+ INSERT INTO memory_revoked_hashes (
2232
+ tenant_id, user_id, scope_kind, scope_id, content_sha256, revoked_at
2233
+ ) VALUES (?, ?, ?, ?, ?, ?)
2234
+ ON CONFLICT(tenant_id, user_id, scope_kind, scope_id, content_sha256)
2235
+ DO UPDATE SET revoked_at = excluded.revoked_at
2236
+ `)
2237
+ .run(this.scope.tenantId, this.scope.userId, String(item.scope_kind), String(item.scope_id), String(item.content_sha256), now);
2238
+ }
2239
+ const delEntries = this.db.prepare(`DELETE FROM memory_entries WHERE ${where}`).run(...params);
2240
+ this.db.prepare(`DELETE FROM memory_documents WHERE ${where}`).run(...params);
2241
+ return delEntries.changes;
2242
+ }
2243
+ async getMemoryRefinementMeta(scopeKind, scopeId) {
2244
+ const row = this.db
2245
+ .prepare(`
2246
+ SELECT * FROM memory_refinement_meta
2247
+ WHERE tenant_id = ? AND user_id = ? AND scope_kind = ? AND scope_id = ?
2248
+ `)
2249
+ .get(this.scope.tenantId, this.scope.userId, scopeKind, scopeId);
2250
+ if (!row) {
2251
+ return {
2252
+ scopeKind,
2253
+ scopeId,
2254
+ refinedSessionCount: 0,
2255
+ lastRefinedAt: null,
2256
+ lastStatus: null,
2257
+ };
2258
+ }
2259
+ return {
2260
+ scopeKind,
2261
+ scopeId,
2262
+ refinedSessionCount: Number(row.refined_session_count ?? 0),
2263
+ lastRefinedAt: row.last_refined_at != null ? String(row.last_refined_at) : null,
2264
+ lastStatus: row.last_status != null ? String(row.last_status) : null,
2265
+ };
2266
+ }
2267
+ async setMemoryRefinementMeta(input) {
2268
+ this.db
2269
+ .prepare(`
2270
+ INSERT INTO memory_refinement_meta (
2271
+ tenant_id, user_id, scope_kind, scope_id, refined_session_count, last_refined_at, last_status
2272
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
2273
+ ON CONFLICT(tenant_id, user_id, scope_kind, scope_id)
2274
+ DO UPDATE SET
2275
+ refined_session_count = excluded.refined_session_count,
2276
+ last_refined_at = excluded.last_refined_at,
2277
+ last_status = excluded.last_status
2278
+ `)
2279
+ .run(this.scope.tenantId, this.scope.userId, input.scopeKind, input.scopeId, input.refinedSessionCount, input.lastRefinedAt ?? null, input.lastStatus ?? null);
2280
+ return {
2281
+ scopeKind: input.scopeKind,
2282
+ scopeId: input.scopeId,
2283
+ refinedSessionCount: input.refinedSessionCount,
2284
+ lastRefinedAt: input.lastRefinedAt ?? null,
2285
+ lastStatus: input.lastStatus ?? null,
2286
+ };
2287
+ }
2288
+ mapMemoryEntry(row) {
2289
+ const rawScope = String(row.scope_kind);
2290
+ const scopeKind = rawScope === 'workspace' ||
2291
+ rawScope === 'tenant' ||
2292
+ rawScope === 'project' ||
2293
+ rawScope === 'agent'
2294
+ ? rawScope
2295
+ : 'user';
2296
+ return {
2297
+ id: String(row.id),
2298
+ scopeKind,
2299
+ scopeId: String(row.scope_id),
2300
+ content: String(row.content),
2301
+ contentSha256: String(row.content_sha256),
2302
+ sourceChatId: row.source_chat_id != null ? String(row.source_chat_id) : null,
2303
+ status: String(row.status) === 'revoked' ? 'revoked' : 'active',
2304
+ createdAt: String(row.created_at),
2305
+ updatedAt: String(row.updated_at),
2306
+ };
2307
+ }
1511
2308
  getSetting(key) {
1512
2309
  const row = this.db.prepare(`SELECT value FROM settings_kv
1513
2310
  WHERE tenant_id = ? AND user_id = ? AND key = ?`).get(this.scope.tenantId, this.scope.userId, key);