@lobu/runtime-server 24.10.0 → 24.11.0

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 (172) hide show
  1. package/dist/catalogs/connectors.json +1 -1
  2. package/dist/component.json +1 -1
  3. package/dist/connectors/linkedin-inbox-adapter.js +13 -3
  4. package/dist/connectors/whatsapp-web-adapter.js +14 -13
  5. package/dist/connectors/whatsapp-web-helpers.ts +37 -1
  6. package/dist/connectors/whatsapp_web.ts +5 -5
  7. package/dist/connectors/x-dm-adapter.js +17 -3
  8. package/dist/db/migrations/20261113170000_member_sql_rls.sql +254 -0
  9. package/dist/db/migrations/20261113180000_member_sql_rls_parallel_plans.sql +192 -0
  10. package/dist/db/migrations/20261113190000_member_sql_schema_usage.sql +24 -0
  11. package/dist/db/migrations/20261114120000_events_owner_only_visibility.sql +39 -0
  12. package/dist/dependencies.bun.lock +10 -10
  13. package/dist/embeddings-server.mjs +1 -1
  14. package/dist/guest.bundle.js +1 -1
  15. package/dist/owletto/dist/assets/_-BDMUN9XZ.js +2 -0
  16. package/dist/owletto/dist/assets/_-CF5X4ANe.js +3 -0
  17. package/dist/owletto/dist/assets/{_agentId-DN0EwMAC.js → _agentId-CGScf8z_.js} +2 -2
  18. package/dist/owletto/dist/assets/_agentId-EQU2aUP0.js +2 -0
  19. package/dist/owletto/dist/assets/_automationId-PXZ33jsF.js +2 -0
  20. package/dist/owletto/dist/assets/{_connectorKey._connectionId-CVKfL9AG.js → _connectorKey._connectionId-DcI29kGy.js} +2 -2
  21. package/dist/owletto/dist/assets/_connectorKey.index-Cr2NDJWX.js +2 -0
  22. package/dist/owletto/dist/assets/{_conversationId-CPpNySjO.js → _conversationId-CnmLYlVS.js} +2 -2
  23. package/dist/owletto/dist/assets/_eventId-w5sDz5oa.js +2 -0
  24. package/dist/owletto/dist/assets/_owner-CkOZR4n0.js +3 -0
  25. package/dist/owletto/dist/assets/_shape-C_FmSf9G.js +2 -0
  26. package/dist/owletto/dist/assets/{_slug-DJx_8fsV.js → _slug-COPpRXLt.js} +2 -2
  27. package/dist/owletto/dist/assets/_viewKey-BVdJiilV.js +2 -0
  28. package/dist/owletto/dist/assets/_viewKey-mxxpqjtC.js +2 -0
  29. package/dist/owletto/dist/assets/{accept-invitation-Dwq1GAnG.js → accept-invitation-BKeIzZXE.js} +2 -2
  30. package/dist/owletto/dist/assets/{activity-route-location-C1jcXC7v.js → activity-route-location-sLvKaSCa.js} +2 -2
  31. package/dist/owletto/dist/assets/activity-route-view-msesKUwn.js +2 -0
  32. package/dist/owletto/dist/assets/{agent-connect-pages-DoI9UR0a.js → agent-connect-pages-DVq9nAR7.js} +3 -3
  33. package/dist/owletto/dist/assets/{agent-editor-form-DlavYg2q.js → agent-editor-form-DVFyyMyd.js} +2 -2
  34. package/dist/owletto/dist/assets/{agent-loading-shells-DYqQphN7.js → agent-loading-shells-BLNHIy-r.js} +2 -2
  35. package/dist/owletto/dist/assets/{agent-permissions-matrix-C1L8IcYR.js → agent-permissions-matrix-UBKRR5vs.js} +2 -2
  36. package/dist/owletto/dist/assets/{agent-skill-context-D1nMrVod.js → agent-skill-context-fqedKd0D.js} +2 -2
  37. package/dist/owletto/dist/assets/{agent-subpage-shell-2w7vTeXw.js → agent-subpage-shell-BUCoY2Nf.js} +2 -2
  38. package/dist/owletto/dist/assets/{agent-thread-BopD-2k1.js → agent-thread-Cqf9ITrT.js} +2 -2
  39. package/dist/owletto/dist/assets/app-bridge-B-L0rGz9.js +121 -0
  40. package/dist/owletto/dist/assets/{app._appId-BXeFXW1w.js → app._appId-ByIypCL9.js} +2 -2
  41. package/dist/owletto/dist/assets/{assist-composer-CL5x8pNt.js → assist-composer-kG_heHXo.js} +2 -2
  42. package/dist/owletto/dist/assets/{automation-run-now-MtxUTfzd.js → automation-run-now-C5XTS00o.js} +2 -2
  43. package/dist/owletto/dist/assets/{callback-BgfwP1Eo.js → callback-Pz5uS-k7.js} +2 -2
  44. package/dist/owletto/dist/assets/{card-DtLIFq7D.js → card-CAPpY9P5.js} +2 -2
  45. package/dist/owletto/dist/assets/{claim-CT3hYVMF.js → claim-DgWWK0KI.js} +2 -2
  46. package/dist/owletto/dist/assets/{client-activity-scopes-BPbRX-Pe.js → client-activity-scopes-Aqdo6Pdr.js} +2 -2
  47. package/dist/owletto/dist/assets/{client-rows-vrNA6FLs.js → client-rows-Dd5YV8vn.js} +2 -2
  48. package/dist/owletto/dist/assets/{clients-xnzZeEdZ.js → clients-Bf7ZgGro.js} +2 -2
  49. package/dist/owletto/dist/assets/{code-editor-mrKkAfcE.js → code-editor-z1Sy_hiX.js} +2 -2
  50. package/dist/owletto/dist/assets/connect-BFNp1y_s.js +2 -0
  51. package/dist/owletto/dist/assets/{connect-menu-C6iVtuSo.js → connect-menu-BWrAhMqO.js} +2 -2
  52. package/dist/owletto/dist/assets/connect._clientId-CSPfwYIN.js +2 -0
  53. package/dist/owletto/dist/assets/{connected._clientId-ROfVgp9h.js → connected._clientId-CuOeHafK.js} +2 -2
  54. package/dist/owletto/dist/assets/{connection-BMz740Wi.js → connection-CVeHmDLs.js} +2 -2
  55. package/dist/owletto/dist/assets/{connection-feed-detail-0VAJiZTP.js → connection-feed-detail-BYo7zdVD.js} +2 -2
  56. package/dist/owletto/dist/assets/{connector-page-shell-BFv21yuv.js → connector-page-shell-an3SYLim.js} +2 -2
  57. package/dist/owletto/dist/assets/{connector-provenance-b59RfBtk.js → connector-provenance-mSZCOud-.js} +2 -2
  58. package/dist/owletto/dist/assets/{connectors-nYS31lO2.js → connectors-DBEM9QQz.js} +2 -2
  59. package/dist/owletto/dist/assets/{consent-cPRF9JQv.js → consent-1ulwyJ3k.js} +2 -2
  60. package/dist/owletto/dist/assets/{copy-button-C3wMMv63.js → copy-button-Xhh7ZnjO.js} +2 -2
  61. package/dist/owletto/dist/assets/{core.esm-C9QlSrgK.js → core.esm-Ctg_pXLe.js} +2 -2
  62. package/dist/owletto/dist/assets/{create-CGOWfMk4.js → create-CGuoqPh8.js} +2 -2
  63. package/dist/owletto/dist/assets/create-Ccb5R-S4.js +2 -0
  64. package/dist/owletto/dist/assets/{create-ASRN3Obq.js → create-DmhbacIa.js} +2 -2
  65. package/dist/owletto/dist/assets/{create-automation-form-CLicoPH5.js → create-automation-form-CD6jSlWL.js} +2 -2
  66. package/dist/owletto/dist/assets/create._connectorKey-CZsAqj1p.js +2 -0
  67. package/dist/owletto/dist/assets/{custom-guardrail-edits-BUL7nmuO.js → custom-guardrail-edits-Ce_BwiwD.js} +2 -2
  68. package/dist/owletto/dist/assets/{definition-comparison-4UYMI6BK.js → definition-comparison-D_qP25jR.js} +2 -2
  69. package/dist/owletto/dist/assets/{detail-page-skeleton-C8v3rJXK.js → detail-page-skeleton-CPAfZLG0.js} +2 -2
  70. package/dist/owletto/dist/assets/{device-BBwsOi7q.js → device-DDl5XKvt.js} +2 -2
  71. package/dist/owletto/dist/assets/{device-pin-tombstone-Bcpe7nAA.js → device-pin-tombstone-Dkj7hrBE.js} +2 -2
  72. package/dist/owletto/dist/assets/{device._deviceId-DLT4jh0Z.js → device._deviceId-bNhTcops.js} +2 -2
  73. package/dist/owletto/dist/assets/{dynamic-schema-form-BDT8x0Vg.js → dynamic-schema-form-CRyUchXo.js} +2 -2
  74. package/dist/owletto/dist/assets/{entity-options-B9hm9V87.js → entity-options-D4t-NAcg.js} +2 -2
  75. package/dist/owletto/dist/assets/entity-page-BOOL_vy3.js +2 -0
  76. package/dist/owletto/dist/assets/{entity-pages-BWBpttz3.js → entity-pages-_nuesgnp.js} +2 -2
  77. package/dist/owletto/dist/assets/{entity-schema-graph-lMMx3HhR.js → entity-schema-graph-Cq96SJ3c.js} +2 -2
  78. package/dist/owletto/dist/assets/{entity-type-page-CkQm0yEu.js → entity-type-page-CkCSbkBx.js} +2 -2
  79. package/dist/owletto/dist/assets/event-detail-DUvlqn9b.js +2 -0
  80. package/dist/owletto/dist/assets/{events-feed-DmRzikZW.js → events-feed-DcKTkJVe.js} +2 -2
  81. package/dist/owletto/dist/assets/{filter-editors-CQoSj-20.js → filter-editors-DGVl9U4D.js} +3 -3
  82. package/dist/owletto/dist/assets/{full-page-spinner-CYyCnKve.js → full-page-spinner-CtVlF8GQ.js} +2 -2
  83. package/dist/owletto/dist/assets/index-BUlkNJzX.js +2 -0
  84. package/dist/owletto/dist/assets/{index-BS5Ty3tf.js → index-BifR-LE9.js} +2 -2
  85. package/dist/owletto/dist/assets/{index-DByaMzsG.js → index-BoqrvLHQ.js} +1383 -1383
  86. package/dist/owletto/dist/assets/index-CA9mW_ZM.js +2 -0
  87. package/dist/owletto/dist/assets/index-CH0GzG4i.js +2 -0
  88. package/dist/owletto/dist/assets/index-CK5GDX4B.js +2 -0
  89. package/dist/owletto/dist/assets/index-CtI5Eomq.js +2 -0
  90. package/dist/owletto/dist/assets/{index-CUndAH6o.js → index-DbjbHlDe.js} +2 -2
  91. package/dist/owletto/dist/assets/index-DmtQ0bds.js +2 -0
  92. package/dist/owletto/dist/assets/{index-CDyFQ32o.js → index-Du_J8hnx.js} +2 -2
  93. package/dist/owletto/dist/assets/{index-ittfA0k8.js → index-DvuJ_S_o.js} +2 -2
  94. package/dist/owletto/dist/assets/index-Pae_f9LM.css +1 -0
  95. package/dist/owletto/dist/assets/{index-C3hz9tzx.js → index-XETZnN7L.js} +2 -2
  96. package/dist/owletto/dist/assets/{json-diff-mcDgyct_.js → json-diff-OjtREegr.js} +2 -2
  97. package/dist/owletto/dist/assets/{list-skeleton-DsYGUHxi.js → list-skeleton-CH0qQBYk.js} +2 -2
  98. package/dist/owletto/dist/assets/{login-EoLq136v.js → login-DG0b9uSC.js} +2 -2
  99. package/dist/owletto/dist/assets/{logout-gLgEQOiX.js → logout-DfdgOLoM.js} +2 -2
  100. package/dist/owletto/dist/assets/{member-scope-gate-vvkgSAb2.js → member-scope-gate-Cxg2zGQT.js} +2 -2
  101. package/dist/owletto/dist/assets/memory-browse-page-qEDQ9Z18.js +74 -0
  102. package/dist/owletto/dist/assets/missing-view-xT0B-f5z.js +2 -0
  103. package/dist/owletto/dist/assets/{model-selector-D3vSMLO2.js → model-selector-D2OpDkwH.js} +2 -2
  104. package/dist/owletto/dist/assets/{needs-you-list-B5Bgd05M.js → needs-you-list-3uMsWcDv.js} +2 -2
  105. package/dist/owletto/dist/assets/{new-dLXsCHBd.js → new-AdGV6a8R.js} +2 -2
  106. package/dist/owletto/dist/assets/new-BdtIhBpo.js +2 -0
  107. package/dist/owletto/dist/assets/{new-Bk_flKQO.js → new-BjGwX6s6.js} +2 -2
  108. package/dist/owletto/dist/assets/{new-BPW3V0Y1.js → new-D-iMjV74.js} +2 -2
  109. package/dist/owletto/dist/assets/{organization-DBfgBkzq.js → organization-qaIpEiQg.js} +2 -2
  110. package/dist/owletto/dist/assets/peek-pane-content-CEsDVScl.js +2 -0
  111. package/dist/owletto/dist/assets/{pending-seed-CBhx2Ql-.js → pending-seed-BBACroge.js} +2 -2
  112. package/dist/owletto/dist/assets/{proposal-review-shell-B-jYcKfB.js → proposal-review-shell-C8ZfIAYn.js} +2 -2
  113. package/dist/owletto/dist/assets/public-shell-ready-K2R8iXSI.js +2 -0
  114. package/dist/owletto/dist/assets/{record-session-CAmGHMyM.js → record-session-BrM9cdXu.js} +2 -2
  115. package/dist/owletto/dist/assets/{renderer-olRv_HMI.js → renderer-CTKNMcXP.js} +4 -4
  116. package/dist/owletto/dist/assets/{reset-password-B9_xi8Pq.js → reset-password-DKBEneyR.js} +2 -2
  117. package/dist/owletto/dist/assets/{run-initiator-DhE5v4z0.js → run-initiator-BKSgI1o0.js} +2 -2
  118. package/dist/owletto/dist/assets/{runs-C8sZQr4o.js → runs-k2NpbZm8.js} +2 -2
  119. package/dist/owletto/dist/assets/runs-list-DUXRMkWN.js +2 -0
  120. package/dist/owletto/dist/assets/{schema-value-zTJGE4eh.js → schema-value-wjqGxXhv.js} +3 -3
  121. package/dist/owletto/dist/assets/{scoped-feed-bar-BKyJSa3_.js → scoped-feed-bar-DNFL0sYX.js} +2 -2
  122. package/dist/owletto/dist/assets/{settings-z02cvVS3.js → settings-V0m5Om5j.js} +2 -2
  123. package/dist/owletto/dist/assets/{source-record-panels-CGmKIJdN.js → source-record-panels-BMut9YIA.js} +2 -2
  124. package/dist/owletto/dist/assets/{status-variants-DyRCXBzM.js → status-variants-SzXYYedJ.js} +2 -2
  125. package/dist/owletto/dist/assets/subDays-9s9OEl5t.js +2 -0
  126. package/dist/owletto/dist/assets/{table-C637cQxG.js → table-ZuYMOjVR.js} +2 -2
  127. package/dist/owletto/dist/assets/{use-automations-CgWNoYio.js → use-automations-DfBtVzGa.js} +2 -2
  128. package/dist/owletto/dist/assets/{use-login-redirect-tDdhXTpt.js → use-login-redirect-BDiS3eyl.js} +2 -2
  129. package/dist/owletto/dist/assets/{use-mention-search-D-kIKchD.js → use-mention-search-khySpz_V.js} +2 -2
  130. package/dist/owletto/dist/assets/view-card-DiHWlypr.js +2 -0
  131. package/dist/owletto/dist/assets/view-param-filters-DGKxSr7r.js +2 -0
  132. package/dist/owletto/dist/assets/{views-access-required-C35Dyt91.js → views-access-required-HA-PiOwA.js} +2 -2
  133. package/dist/owletto/dist/index.html +2 -2
  134. package/dist/server-main.bundle.mjs +1052 -538
  135. package/npm-shrinkwrap.json +38 -38
  136. package/package.json +1 -1
  137. package/vendor/connector-sdk/package.json +1 -1
  138. package/vendor/core/package.json +1 -1
  139. package/vendor/views/package.json +1 -1
  140. package/dist/owletto/dist/assets/_-CYvj1y65.js +0 -3
  141. package/dist/owletto/dist/assets/_-CeLTSYYY.js +0 -2
  142. package/dist/owletto/dist/assets/_agentId-BB5E-L6T.js +0 -2
  143. package/dist/owletto/dist/assets/_automationId-DvUl9CSd.js +0 -2
  144. package/dist/owletto/dist/assets/_connectorKey.index-Cv6FzK1v.js +0 -2
  145. package/dist/owletto/dist/assets/_eventId-DZKicuq6.js +0 -2
  146. package/dist/owletto/dist/assets/_owner-Dauk3YuD.js +0 -3
  147. package/dist/owletto/dist/assets/_shape-cKrEID3T.js +0 -2
  148. package/dist/owletto/dist/assets/_viewKey-CPVzVKEf.js +0 -2
  149. package/dist/owletto/dist/assets/_viewKey-CW8gexOQ.js +0 -2
  150. package/dist/owletto/dist/assets/activity-route-view-D78Wj0RH.js +0 -2
  151. package/dist/owletto/dist/assets/app-bridge-C4nPtae3.js +0 -121
  152. package/dist/owletto/dist/assets/connect-NUCSay8X.js +0 -2
  153. package/dist/owletto/dist/assets/connect._clientId-Cp-d9Q5b.js +0 -2
  154. package/dist/owletto/dist/assets/create-CBcodaSO.js +0 -2
  155. package/dist/owletto/dist/assets/create._connectorKey-s4xkktTC.js +0 -2
  156. package/dist/owletto/dist/assets/entity-page-DZjzQ2V4.js +0 -2
  157. package/dist/owletto/dist/assets/event-detail-CkzfakTK.js +0 -2
  158. package/dist/owletto/dist/assets/index-BE7eb2kE.js +0 -2
  159. package/dist/owletto/dist/assets/index-BFR0uiKY.js +0 -2
  160. package/dist/owletto/dist/assets/index-C38OzBpB.js +0 -2
  161. package/dist/owletto/dist/assets/index-CiKysEhV.js +0 -2
  162. package/dist/owletto/dist/assets/index-DfdinB7B.js +0 -2
  163. package/dist/owletto/dist/assets/index-DgMM4Zt5.css +0 -1
  164. package/dist/owletto/dist/assets/index-Xk711gVC.js +0 -2
  165. package/dist/owletto/dist/assets/memory-browse-page-DvDtwrEI.js +0 -74
  166. package/dist/owletto/dist/assets/new-C5HtQdM_.js +0 -2
  167. package/dist/owletto/dist/assets/peek-pane-content-c2PG3TEX.js +0 -2
  168. package/dist/owletto/dist/assets/public-shell-ready-D8TijlRY.js +0 -2
  169. package/dist/owletto/dist/assets/record-activity-DnRVOrG2.js +0 -2
  170. package/dist/owletto/dist/assets/runs-list-CwtH-wmk.js +0 -2
  171. package/dist/owletto/dist/assets/subDays-D8nHthaS.js +0 -2
  172. package/dist/owletto/dist/assets/view-param-filters-CUCj9Df-.js +0 -2
@@ -3211,7 +3211,7 @@ var init_package = __esm({
3211
3211
  "package.json"() {
3212
3212
  package_default = {
3213
3213
  name: "@lobu/server",
3214
- version: "24.10.0",
3214
+ version: "24.11.0",
3215
3215
  private: true,
3216
3216
  license: "BUSL-1.1",
3217
3217
  type: "module",
@@ -5224,14 +5224,10 @@ async function notifyEventContentChanged(sql2, eventId) {
5224
5224
  await sql2`
5225
5225
  SELECT pg_notify(
5226
5226
  ${CHANNEL},
5227
- json_build_object('org', o.org, 'keys', json_build_array(${CONTENT_INVALIDATION_KEY}::text))::text
5227
+ json_build_object('org', e.organization_id, 'keys', json_build_array(${CONTENT_INVALIDATION_KEY}::text))::text
5228
5228
  )
5229
- FROM (
5230
- SELECT e.organization_id AS org FROM events e WHERE e.id = ${eventId}
5231
- UNION
5232
- SELECT unnest(e.linked_org_ids) FROM events e WHERE e.id = ${eventId}
5233
- ) o
5234
- WHERE o.org IS NOT NULL
5229
+ FROM events e
5230
+ WHERE e.id = ${eventId} AND e.organization_id IS NOT NULL
5235
5231
  `;
5236
5232
  }
5237
5233
  var logger12, CONTENT_INVALIDATION_KEY, CHANNEL, COALESCE_MS, listeners, origin, pending, flushTimer, listening;
@@ -10441,6 +10437,8 @@ async function lockEventDedupIdentities(sql2, connectionId, originIds) {
10441
10437
  }
10442
10438
  function stableJson(value) {
10443
10439
  if (value === null || typeof value !== "object") return JSON.stringify(value);
10440
+ const toJSON = value.toJSON;
10441
+ if (typeof toJSON === "function") return stableJson(toJSON.call(value));
10444
10442
  if (Array.isArray(value)) return `[${value.map((item) => stableJson(item)).join(",")}]`;
10445
10443
  const entries = Object.entries(value).sort(
10446
10444
  ([a], [b]) => a.localeCompare(b)
@@ -10751,8 +10749,7 @@ async function insertEvent(params, options) {
10751
10749
  semantic_type, client_id, created_by,
10752
10750
  interaction_type, interaction_status, interaction_input_schema, interaction_input,
10753
10751
  interaction_output, interaction_error, supersedes_event_id,
10754
- identity_ns, identity_key,
10755
- linked_org_ids
10752
+ identity_ns, identity_key
10756
10753
  ) VALUES (
10757
10754
  ${entityIdsValue}::bigint[],
10758
10755
  ${params.organizationId},
@@ -10788,21 +10785,7 @@ async function insertEvent(params, options) {
10788
10785
  ${params.interactionError ?? null},
10789
10786
  ${supersedesEventId},
10790
10787
  ${lineage.identity_ns},
10791
- ${lineage.identity_key},
10792
- (
10793
- SELECT COALESCE(array_agg(DISTINCT x.o), '{}'::text[])
10794
- FROM (
10795
- SELECT ent.organization_id AS o
10796
- FROM public.entities ent
10797
- WHERE ent.id = ANY(${entityIdsValue}::bigint[])
10798
- UNION ALL
10799
- SELECT c.organization_id AS o
10800
- FROM public.connections c
10801
- WHERE c.id = ${lineage.connection_id}
10802
- ) x
10803
- WHERE x.o IS NOT NULL
10804
- AND (x.o <> ${params.organizationId}::text OR ${params.organizationId}::text IS NULL)
10805
- )
10788
+ ${lineage.identity_key}
10806
10789
  )
10807
10790
  RETURNING id, entity_ids, origin_id, title, semantic_type, created_at
10808
10791
  `;
@@ -11427,6 +11410,7 @@ var init_insert_event = __esm({
11427
11410
  search_tsv: "version",
11428
11411
  identity_ns: "chain",
11429
11412
  identity_key: "chain",
11413
+ // Retired: no longer written or read. The entry goes with the column drop.
11430
11414
  linked_org_ids: "version"
11431
11415
  };
11432
11416
  INHERITED_COLUMNS = Object.keys(EVENT_SUPERSEDE_RULES).filter((column) => EVENT_SUPERSEDE_RULES[column] !== "version");
@@ -31030,6 +31014,14 @@ function boundedRead(sql2, options, run) {
31030
31014
  const transaction = sql2.begin("read only", async (tx) => {
31031
31015
  options.signal?.throwIfAborted();
31032
31016
  await tx.unsafe(`SET LOCAL statement_timeout = ${timeoutMs}`);
31017
+ if (options.fence) {
31018
+ await tx.unsafe(
31019
+ `SELECT set_config('lobu.member_sql_org', $1, true),
31020
+ set_config('lobu.member_sql_principal', $2, true),
31021
+ set_config('role', 'lobu_member_sql', true)`,
31022
+ [options.fence.organizationId, options.fence.principal ?? ""]
31023
+ );
31024
+ }
31033
31025
  return run(tx);
31034
31026
  });
31035
31027
  return raceAbort(transaction, options.signal);
@@ -31059,6 +31051,12 @@ function classifyReadQueryFailure(error) {
31059
31051
  if (pgCode === "25006") {
31060
31052
  return { code: "VALIDATION", message: "Only read-only queries are allowed." };
31061
31053
  }
31054
+ if (pgCode === "42501") {
31055
+ return {
31056
+ code: "VALIDATION",
31057
+ message: "Only read-only queries over the workspace tables are allowed; the query used a relation or function outside them."
31058
+ };
31059
+ }
31062
31060
  const rawCode = error?.code;
31063
31061
  return {
31064
31062
  code: classifyToolError({
@@ -31087,13 +31085,120 @@ var init_bounded_read = __esm({
31087
31085
  }
31088
31086
  });
31089
31087
 
31090
- // src/utils/linked-org-ids.ts
31091
- function useLinkedOrgScope() {
31092
- return process.env.LOBU_LINKED_ORG_SCOPE === "1";
31088
+ // src/utils/content-read-bounds.ts
31089
+ function sqlRef(value) {
31090
+ if (!SAFE_SQL_REF.test(value)) throw new Error(`Unsafe SQL reference: ${value}`);
31091
+ return value;
31092
+ }
31093
+ function boundedPayloadTextSql(alias) {
31094
+ const a = sqlRef(alias);
31095
+ return `CASE WHEN ${a}.content_length > ${CONTENT_TEXT_HEAD_CHARS} THEN left(${a}.payload_text, ${CONTENT_TEXT_HEAD_CHARS}) || '${TRUNCATION_SUFFIX}' ELSE ${a}.payload_text END AS payload_text, ${a}.content_length, (${a}.content_length > ${CONTENT_TEXT_HEAD_CHARS}) AS payload_truncated`;
31096
+ }
31097
+ function boundedJsonSql(alias, column) {
31098
+ const a = sqlRef(alias);
31099
+ const c = sqlRef(column);
31100
+ const ref = `${a}.${c}`;
31101
+ return `CASE WHEN octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES} THEN jsonb_build_object('_truncated', true, 'bytes', octet_length(${ref}::text)) ELSE ${ref} END AS ${c}`;
31102
+ }
31103
+ function boundedAttachmentsSql(alias) {
31104
+ const a = sqlRef(alias);
31105
+ const ref = `${a}.attachments`;
31106
+ return `CASE WHEN octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES} THEN NULL ELSE ${ref} END AS attachments, (octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES}) AS attachments_truncated, CASE WHEN octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES} THEN octet_length(${ref}::text) ELSE NULL END AS attachments_bytes`;
31107
+ }
31108
+ function truncateByCodePoint(value) {
31109
+ if (value.length <= CONTENT_TEXT_HEAD_CHARS) return { truncated: false };
31110
+ let length = 0;
31111
+ let head = "";
31112
+ for (const character of value) {
31113
+ if (length < CONTENT_TEXT_HEAD_CHARS) head += character;
31114
+ length += 1;
31115
+ }
31116
+ if (length <= CONTENT_TEXT_HEAD_CHARS) return { truncated: false };
31117
+ return { value: `${head}${TRUNCATION_SUFFIX}`, length, truncated: true };
31118
+ }
31119
+ function jsonBytes2(value) {
31120
+ try {
31121
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
31122
+ } catch {
31123
+ return Number.POSITIVE_INFINITY;
31124
+ }
31125
+ }
31126
+ function assignGeneratedSidecar(input, row, key2, value, collisions) {
31127
+ if (Object.prototype.hasOwnProperty.call(input, key2) && input[key2] !== value || Object.prototype.hasOwnProperty.call(row, key2) && row[key2] !== value) {
31128
+ collisions.add(key2);
31129
+ return;
31130
+ }
31131
+ row[key2] = value;
31132
+ }
31133
+ function finalizeDynamicQueryRows(inputRows, maxSerializedBytes = QUERY_SQL_RESULT_MAX_BYTES) {
31134
+ const boundedRows = [];
31135
+ const sidecarCollisions = /* @__PURE__ */ new Set();
31136
+ const truncatedColumns = /* @__PURE__ */ new Set();
31137
+ let serializedBytes = 2;
31138
+ for (const input of inputRows) {
31139
+ const row = { ...input };
31140
+ const rowTruncated = [];
31141
+ for (const key2 of Object.keys(row)) {
31142
+ const value = row[key2];
31143
+ if (typeof value === "string") {
31144
+ const bounded2 = truncateByCodePoint(value);
31145
+ if (!bounded2.truncated) continue;
31146
+ row[key2] = bounded2.value;
31147
+ rowTruncated.push(key2);
31148
+ if (key2 === "payload_text" || key2 === "text_content") {
31149
+ assignGeneratedSidecar(input, row, "content_length", bounded2.length, sidecarCollisions);
31150
+ assignGeneratedSidecar(input, row, "payload_truncated", true, sidecarCollisions);
31151
+ }
31152
+ continue;
31153
+ }
31154
+ if (value === null || typeof value !== "object") continue;
31155
+ const bytes = jsonBytes2(value);
31156
+ if (bytes <= CONTENT_JSON_MAX_BYTES) continue;
31157
+ rowTruncated.push(key2);
31158
+ if (key2 === "attachments") {
31159
+ row.attachments = null;
31160
+ assignGeneratedSidecar(input, row, "attachments_truncated", true, sidecarCollisions);
31161
+ assignGeneratedSidecar(
31162
+ input,
31163
+ row,
31164
+ "attachments_bytes",
31165
+ Number.isFinite(bytes) ? bytes : null,
31166
+ sidecarCollisions
31167
+ );
31168
+ } else {
31169
+ row[key2] = {
31170
+ _truncated: true,
31171
+ bytes: Number.isFinite(bytes) ? bytes : null
31172
+ };
31173
+ }
31174
+ }
31175
+ const encoded = JSON.stringify(row);
31176
+ const rowBytes = Buffer.byteLength(encoded, "utf8");
31177
+ const separatorBytes = boundedRows.length > 0 ? 1 : 0;
31178
+ if (serializedBytes + separatorBytes + rowBytes > maxSerializedBytes) break;
31179
+ boundedRows.push(row);
31180
+ serializedBytes += separatorBytes + rowBytes;
31181
+ for (const key2 of rowTruncated) truncatedColumns.add(key2);
31182
+ }
31183
+ return {
31184
+ rows: boundedRows,
31185
+ omittedRows: inputRows.length - boundedRows.length,
31186
+ sidecarCollisions: [...sidecarCollisions].sort(),
31187
+ truncatedColumns: [...truncatedColumns].sort()
31188
+ };
31093
31189
  }
31094
- var init_linked_org_ids = __esm({
31095
- "src/utils/linked-org-ids.ts"() {
31190
+ var CONTENT_TEXT_HEAD_CHARS, CONTENT_JSON_MAX_BYTES, QUERY_SQL_RESULT_MAX_BYTES, AUTOMATION_READ_MAX_BYTES, CONTENT_READ_STATEMENT_TIMEOUT_MS, QUERY_SQL_STATEMENT_TIMEOUT_MS, TRUNCATION_SUFFIX, SAFE_SQL_REF;
31191
+ var init_content_read_bounds = __esm({
31192
+ "src/utils/content-read-bounds.ts"() {
31096
31193
  "use strict";
31194
+ CONTENT_TEXT_HEAD_CHARS = 4e3;
31195
+ CONTENT_JSON_MAX_BYTES = 16 * 1024;
31196
+ QUERY_SQL_RESULT_MAX_BYTES = 1048576;
31197
+ AUTOMATION_READ_MAX_BYTES = 1048576;
31198
+ CONTENT_READ_STATEMENT_TIMEOUT_MS = 15e3;
31199
+ QUERY_SQL_STATEMENT_TIMEOUT_MS = 5e3;
31200
+ TRUNCATION_SUFFIX = "\u2026 [truncated]";
31201
+ SAFE_SQL_REF = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
31097
31202
  }
31098
31203
  });
31099
31204
 
@@ -32135,6 +32240,10 @@ function validateAndScopeQuery(rawSql, organizationId, options) {
32135
32240
  function buildScopedQuery(userQuery, tableRefs, context5, options) {
32136
32241
  const params = [];
32137
32242
  let idx = 0;
32243
+ const scope = {
32244
+ organizationId: context5.organizationId,
32245
+ principal: context5.userId ?? null
32246
+ };
32138
32247
  let organizationP;
32139
32248
  const bindOrganization = () => {
32140
32249
  if (!organizationP) {
@@ -32182,12 +32291,8 @@ function buildScopedQuery(userQuery, tableRefs, context5, options) {
32182
32291
  if (/\$\d+/.test(userQuery)) {
32183
32292
  throw new ToolUserError("Positional parameters ($1, $2, ...) are not allowed in data source queries", 400, "VALIDATION");
32184
32293
  }
32185
- if (tableRefs.length === 0) return { sql: processedQuery, params };
32294
+ if (tableRefs.length === 0) return { sql: processedQuery, params, scope };
32186
32295
  const orgP = bindOrganization();
32187
- const scope = {
32188
- organizationId: context5.organizationId,
32189
- principal: context5.userId ?? null
32190
- };
32191
32296
  const eventConnVisibility = (alias) => {
32192
32297
  const vis = compileConnectionFkVisibility(scope, idx + 1, alias);
32193
32298
  params.push(...vis.params);
@@ -32200,12 +32305,7 @@ function buildScopedQuery(userQuery, tableRefs, context5, options) {
32200
32305
  idx += vis.params.length;
32201
32306
  return ` ${vis.sql}`;
32202
32307
  };
32203
- const eventOrgScope = (alias) => useLinkedOrgScope() ? `(${alias}.organization_id = ${orgP}
32204
- OR ${alias}.linked_org_ids @> ARRAY[${orgP}]::text[])` : `(${alias}.organization_id = ${orgP}
32205
- OR EXISTS (SELECT 1 FROM public.entities ent
32206
- WHERE ent.id = ANY(${alias}.entity_ids) AND ent.organization_id = ${orgP})
32207
- OR EXISTS (SELECT 1 FROM public.connections con
32208
- WHERE con.id = ${alias}.connection_id AND con.organization_id = ${orgP}))`;
32308
+ const eventOrgScope = (alias) => `${alias}.organization_id = ${orgP}`;
32209
32309
  const channelMessagesVisibility = (alias) => {
32210
32310
  const vis = compileChannelMessagesVisibility(scope, idx + 1, alias);
32211
32311
  params.push(...vis.params);
@@ -32356,13 +32456,13 @@ function buildScopedQuery(userQuery, tableRefs, context5, options) {
32356
32456
  );
32357
32457
  }
32358
32458
  }
32359
- if (ctes.length === 0) return { sql: processedQuery, params };
32459
+ if (ctes.length === 0) return { sql: processedQuery, params, scope };
32360
32460
  const cteStr = `WITH ${ctes.join(",\n")}`;
32361
32461
  const body2 = stripLeadingComments(processedQuery).trim();
32362
32462
  const finalSql = /^WITH\b/i.test(body2) ? `${cteStr},
32363
32463
  ${body2.replace(/^WITH\s+/i, "")}` : `${cteStr}
32364
32464
  ${body2}`;
32365
- return { sql: finalSql, params };
32465
+ return { sql: finalSql, params, scope };
32366
32466
  }
32367
32467
  function queryProjectsIdColumn(query) {
32368
32468
  try {
@@ -32458,11 +32558,12 @@ async function executeDataSources(dataSources, context5, sql2, options) {
32458
32558
  }
32459
32559
  }
32460
32560
  }
32461
- let { sql: scopedQuery, params } = buildScopedQuery(query, tableRefs, context5, {
32561
+ const scoped = buildScopedQuery(query, tableRefs, context5, {
32462
32562
  safeColumns: SAFE_COLUMN_DEFS,
32463
32563
  excludeWorkspaceAudit: options?.excludeWorkspaceAudit,
32464
32564
  excludeMemberEntities: options?.excludeMemberEntities
32465
32565
  });
32566
+ let { sql: scopedQuery, params } = scoped;
32466
32567
  const placeholderMatches = scopedQuery.match(/\$(\d+)/g);
32467
32568
  if (placeholderMatches) {
32468
32569
  const maxPlaceholder = Math.max(
@@ -32483,10 +32584,9 @@ async function executeDataSources(dataSources, context5, sql2, options) {
32483
32584
  params = wrapped.params;
32484
32585
  }
32485
32586
  }
32486
- const rows = await sql2.begin(async (tx) => {
32487
- await tx.unsafe("SET TRANSACTION READ ONLY");
32488
- await tx.unsafe(`SET LOCAL statement_timeout = '${QUERY_TIMEOUT_MS}'`);
32489
- return tx.unsafe(scopedQuery, params);
32587
+ const rows = await boundedQuery(sql2, scopedQuery, params, {
32588
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
32589
+ fence: scoped.scope
32490
32590
  });
32491
32591
  const rowLimit = MAX_DATA_SOURCE_ROWS + (options?.includeOverflowRow ? 1 : 0);
32492
32592
  results[name] = Array.isArray(rows) ? rows.slice(0, rowLimit) : [];
@@ -32504,15 +32604,15 @@ async function executeDataSources(dataSources, context5, sql2, options) {
32504
32604
  );
32505
32605
  return results;
32506
32606
  }
32507
- var FORBIDDEN_OPS, FORBIDDEN_QUERY_FUNCTIONS, FORBIDDEN_QUERY_FUNCTION_PREFIXES, FORBIDDEN_QUERY_FUNCTION_INFIX, MAX_DATA_SOURCE_ROWS, QUERY_TIMEOUT_MS;
32607
+ var FORBIDDEN_OPS, FORBIDDEN_QUERY_FUNCTIONS, FORBIDDEN_QUERY_FUNCTION_PREFIXES, FORBIDDEN_QUERY_FUNCTION_INFIX, MAX_DATA_SOURCE_ROWS;
32508
32608
  var init_execute_data_sources = __esm({
32509
32609
  "src/utils/execute-data-sources.ts"() {
32510
32610
  "use strict";
32511
32611
  init_client();
32512
32612
  init_bounded_read();
32613
+ init_content_read_bounds();
32513
32614
  init_errors2();
32514
32615
  init_logger2();
32515
- init_linked_org_ids();
32516
32616
  init_connection_visibility();
32517
32617
  init_channel_messages_visibility();
32518
32618
  init_resource_visibility();
@@ -32538,124 +32638,6 @@ var init_execute_data_sources = __esm({
32538
32638
  FORBIDDEN_QUERY_FUNCTION_PREFIXES = ["pg_", "dblink", "lo_"];
32539
32639
  FORBIDDEN_QUERY_FUNCTION_INFIX = "_to_xml";
32540
32640
  MAX_DATA_SOURCE_ROWS = 1e3;
32541
- QUERY_TIMEOUT_MS = 5e3;
32542
- }
32543
- });
32544
-
32545
- // src/utils/content-read-bounds.ts
32546
- function sqlRef(value) {
32547
- if (!SAFE_SQL_REF.test(value)) throw new Error(`Unsafe SQL reference: ${value}`);
32548
- return value;
32549
- }
32550
- function boundedPayloadTextSql(alias) {
32551
- const a = sqlRef(alias);
32552
- return `CASE WHEN ${a}.content_length > ${CONTENT_TEXT_HEAD_CHARS} THEN left(${a}.payload_text, ${CONTENT_TEXT_HEAD_CHARS}) || '${TRUNCATION_SUFFIX}' ELSE ${a}.payload_text END AS payload_text, ${a}.content_length, (${a}.content_length > ${CONTENT_TEXT_HEAD_CHARS}) AS payload_truncated`;
32553
- }
32554
- function boundedJsonSql(alias, column) {
32555
- const a = sqlRef(alias);
32556
- const c = sqlRef(column);
32557
- const ref = `${a}.${c}`;
32558
- return `CASE WHEN octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES} THEN jsonb_build_object('_truncated', true, 'bytes', octet_length(${ref}::text)) ELSE ${ref} END AS ${c}`;
32559
- }
32560
- function boundedAttachmentsSql(alias) {
32561
- const a = sqlRef(alias);
32562
- const ref = `${a}.attachments`;
32563
- return `CASE WHEN octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES} THEN NULL ELSE ${ref} END AS attachments, (octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES}) AS attachments_truncated, CASE WHEN octet_length(${ref}::text) > ${CONTENT_JSON_MAX_BYTES} THEN octet_length(${ref}::text) ELSE NULL END AS attachments_bytes`;
32564
- }
32565
- function truncateByCodePoint(value) {
32566
- if (value.length <= CONTENT_TEXT_HEAD_CHARS) return { truncated: false };
32567
- let length = 0;
32568
- let head = "";
32569
- for (const character of value) {
32570
- if (length < CONTENT_TEXT_HEAD_CHARS) head += character;
32571
- length += 1;
32572
- }
32573
- if (length <= CONTENT_TEXT_HEAD_CHARS) return { truncated: false };
32574
- return { value: `${head}${TRUNCATION_SUFFIX}`, length, truncated: true };
32575
- }
32576
- function jsonBytes2(value) {
32577
- try {
32578
- return Buffer.byteLength(JSON.stringify(value), "utf8");
32579
- } catch {
32580
- return Number.POSITIVE_INFINITY;
32581
- }
32582
- }
32583
- function assignGeneratedSidecar(input, row, key2, value, collisions) {
32584
- if (Object.prototype.hasOwnProperty.call(input, key2) && input[key2] !== value || Object.prototype.hasOwnProperty.call(row, key2) && row[key2] !== value) {
32585
- collisions.add(key2);
32586
- return;
32587
- }
32588
- row[key2] = value;
32589
- }
32590
- function finalizeDynamicQueryRows(inputRows, maxSerializedBytes = QUERY_SQL_RESULT_MAX_BYTES) {
32591
- const boundedRows = [];
32592
- const sidecarCollisions = /* @__PURE__ */ new Set();
32593
- const truncatedColumns = /* @__PURE__ */ new Set();
32594
- let serializedBytes = 2;
32595
- for (const input of inputRows) {
32596
- const row = { ...input };
32597
- const rowTruncated = [];
32598
- for (const key2 of Object.keys(row)) {
32599
- const value = row[key2];
32600
- if (typeof value === "string") {
32601
- const bounded2 = truncateByCodePoint(value);
32602
- if (!bounded2.truncated) continue;
32603
- row[key2] = bounded2.value;
32604
- rowTruncated.push(key2);
32605
- if (key2 === "payload_text" || key2 === "text_content") {
32606
- assignGeneratedSidecar(input, row, "content_length", bounded2.length, sidecarCollisions);
32607
- assignGeneratedSidecar(input, row, "payload_truncated", true, sidecarCollisions);
32608
- }
32609
- continue;
32610
- }
32611
- if (value === null || typeof value !== "object") continue;
32612
- const bytes = jsonBytes2(value);
32613
- if (bytes <= CONTENT_JSON_MAX_BYTES) continue;
32614
- rowTruncated.push(key2);
32615
- if (key2 === "attachments") {
32616
- row.attachments = null;
32617
- assignGeneratedSidecar(input, row, "attachments_truncated", true, sidecarCollisions);
32618
- assignGeneratedSidecar(
32619
- input,
32620
- row,
32621
- "attachments_bytes",
32622
- Number.isFinite(bytes) ? bytes : null,
32623
- sidecarCollisions
32624
- );
32625
- } else {
32626
- row[key2] = {
32627
- _truncated: true,
32628
- bytes: Number.isFinite(bytes) ? bytes : null
32629
- };
32630
- }
32631
- }
32632
- const encoded = JSON.stringify(row);
32633
- const rowBytes = Buffer.byteLength(encoded, "utf8");
32634
- const separatorBytes = boundedRows.length > 0 ? 1 : 0;
32635
- if (serializedBytes + separatorBytes + rowBytes > maxSerializedBytes) break;
32636
- boundedRows.push(row);
32637
- serializedBytes += separatorBytes + rowBytes;
32638
- for (const key2 of rowTruncated) truncatedColumns.add(key2);
32639
- }
32640
- return {
32641
- rows: boundedRows,
32642
- omittedRows: inputRows.length - boundedRows.length,
32643
- sidecarCollisions: [...sidecarCollisions].sort(),
32644
- truncatedColumns: [...truncatedColumns].sort()
32645
- };
32646
- }
32647
- var CONTENT_TEXT_HEAD_CHARS, CONTENT_JSON_MAX_BYTES, QUERY_SQL_RESULT_MAX_BYTES, AUTOMATION_READ_MAX_BYTES, CONTENT_READ_STATEMENT_TIMEOUT_MS, QUERY_SQL_STATEMENT_TIMEOUT_MS, TRUNCATION_SUFFIX, SAFE_SQL_REF;
32648
- var init_content_read_bounds = __esm({
32649
- "src/utils/content-read-bounds.ts"() {
32650
- "use strict";
32651
- CONTENT_TEXT_HEAD_CHARS = 4e3;
32652
- CONTENT_JSON_MAX_BYTES = 16 * 1024;
32653
- QUERY_SQL_RESULT_MAX_BYTES = 1048576;
32654
- AUTOMATION_READ_MAX_BYTES = 1048576;
32655
- CONTENT_READ_STATEMENT_TIMEOUT_MS = 15e3;
32656
- QUERY_SQL_STATEMENT_TIMEOUT_MS = 5e3;
32657
- TRUNCATION_SUFFIX = "\u2026 [truncated]";
32658
- SAFE_SQL_REF = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
32659
32641
  }
32660
32642
  });
32661
32643
 
@@ -34377,12 +34359,16 @@ var init_manage_automations = __esm({
34377
34359
  });
34378
34360
 
34379
34361
  // src/utils/content-search/entity-link.ts
34380
- function visibleToOrgSql(orgSql) {
34381
- return `(e2.organization_id = ${orgSql} OR e2.linked_org_ids @> ARRAY[${orgSql}]::text[])`;
34362
+ function ownedByOrgSql(orgSql) {
34363
+ return `e2.organization_id = ${orgSql}`;
34382
34364
  }
34383
34365
  function entityLinkMatchSql(paramRef, alias = "f", eventSource = "events") {
34384
- const directBranch = `SELECT e2.id FROM ${eventSource} e2
34385
- WHERE e2.entity_ids && ARRAY(SELECT id FROM identity_members)`;
34366
+ const entityOrgSql = "(SELECT organization_id FROM identity_members LIMIT 1)";
34367
+ const directBranch = directEntityLinkBranch(
34368
+ "ARRAY(SELECT id FROM identity_members)",
34369
+ entityOrgSql,
34370
+ eventSource
34371
+ );
34386
34372
  const standardBranches = STANDARD_IDENTITY_NAMESPACES.map(
34387
34373
  (ns) => `SELECT e2.id FROM ${eventSource} e2
34388
34374
  JOIN entity_identities ei
@@ -34391,7 +34377,7 @@ function entityLinkMatchSql(paramRef, alias = "f", eventSource = "events") {
34391
34377
  AND ei.deleted_at IS NULL
34392
34378
  WHERE e2.metadata ? '${ns}'
34393
34379
  AND e2.metadata->>'${ns}' = ei.identifier
34394
- AND ${visibleToOrgSql("(SELECT organization_id FROM identity_members LIMIT 1)")}
34380
+ AND ${ownedByOrgSql(entityOrgSql)}
34395
34381
  AND COALESCE((e2.metadata->'${IDENTITY_SCOPE_BY_NAMESPACE_METADATA_KEY}')->>'${ns}', '${ORGANIZATION_SCOPE_PROJECTION}') = COALESCE(ei.scope_key, '${ORGANIZATION_SCOPE_PROJECTION}')`
34396
34382
  );
34397
34383
  const branches = [directBranch, ...standardBranches].join("\n UNION\n ");
@@ -34401,11 +34387,10 @@ function entityLinkMatchSql(paramRef, alias = "f", eventSource = "events") {
34401
34387
  ${branches}
34402
34388
  ) SELECT id FROM entity_link_ids)`;
34403
34389
  }
34404
- function directEntityLinkBranch(entityRef) {
34405
- return `SELECT e2.id FROM events e2
34406
- WHERE e2.entity_ids && ARRAY(
34407
- ${identityMemberIdsSql(entityRef)}
34408
- )`;
34390
+ function directEntityLinkBranch(membersSql, orgSql, eventSource = "events") {
34391
+ return `SELECT e2.id FROM ${eventSource} e2
34392
+ WHERE e2.entity_ids && ${membersSql}
34393
+ AND e2.organization_id || '' = ${orgSql}`;
34409
34394
  }
34410
34395
  async function fetchEntityIdentityScopes(sql2, entityId) {
34411
34396
  const rows = await sql2.unsafe(`
@@ -34428,7 +34413,8 @@ function buildEntityLinkUnion(opts) {
34428
34413
  const { branches, params } = buildEntityLinkBranches({
34429
34414
  entityIdLiteral: opts.entityIdLiteral,
34430
34415
  scopes: opts.scopes,
34431
- baseParamIndex: opts.baseParamIndex
34416
+ baseParamIndex: opts.baseParamIndex,
34417
+ ownerOrganizationId: opts.ownerOrganizationId
34432
34418
  });
34433
34419
  return {
34434
34420
  sql: `${alias}.id IN (WITH entity_link_ids AS MATERIALIZED (
@@ -34438,17 +34424,28 @@ function buildEntityLinkUnion(opts) {
34438
34424
  };
34439
34425
  }
34440
34426
  function buildEntityLinkBranches(opts) {
34441
- const direct = opts.directMembersSql ? `SELECT e2.id FROM events e2 WHERE e2.entity_ids && ${opts.directMembersSql}` : directEntityLinkBranch(`${opts.entityIdLiteral}::bigint`);
34442
34427
  const params = [];
34443
34428
  let paramIndex = opts.baseParamIndex;
34444
- const indexed = new Set(STANDARD_IDENTITY_NAMESPACES);
34445
34429
  const entityOrgSql = `(SELECT organization_id FROM entities WHERE id = ${opts.entityIdLiteral}::bigint)`;
34430
+ let ownerOrgSql = entityOrgSql;
34431
+ if (opts.ownerOrganizationId) {
34432
+ params.push(opts.ownerOrganizationId);
34433
+ ownerOrgSql = `$${paramIndex}::text`;
34434
+ paramIndex += 1;
34435
+ }
34436
+ const direct = directEntityLinkBranch(
34437
+ opts.directMembersSql ?? `ARRAY(
34438
+ ${identityMemberIdsSql(`${opts.entityIdLiteral}::bigint`)}
34439
+ )`,
34440
+ ownerOrgSql
34441
+ );
34442
+ const indexed = new Set(STANDARD_IDENTITY_NAMESPACES);
34446
34443
  const scopeBranches = [];
34447
34444
  for (const scope of opts.scopes) {
34448
34445
  if (!indexed.has(scope.namespace)) continue;
34449
34446
  params.push(scope.identifier, scope.scopeKey ?? ORGANIZATION_SCOPE_PROJECTION);
34450
34447
  scopeBranches.push(
34451
- `SELECT e2.id FROM events e2 WHERE e2.metadata ? '${scope.namespace}' AND e2.metadata->>'${scope.namespace}' = $${paramIndex} AND ${visibleToOrgSql(entityOrgSql)} AND COALESCE((e2.metadata->'${IDENTITY_SCOPE_BY_NAMESPACE_METADATA_KEY}')->>'${scope.namespace}', '${ORGANIZATION_SCOPE_PROJECTION}') = $${paramIndex + 1}`
34448
+ `SELECT e2.id FROM events e2 WHERE e2.metadata ? '${scope.namespace}' AND e2.metadata->>'${scope.namespace}' = $${paramIndex} AND ${ownedByOrgSql(entityOrgSql)} AND COALESCE((e2.metadata->'${IDENTITY_SCOPE_BY_NAMESPACE_METADATA_KEY}')->>'${scope.namespace}', '${ORGANIZATION_SCOPE_PROJECTION}') = $${paramIndex + 1}`
34452
34449
  );
34453
34450
  paramIndex += 2;
34454
34451
  }
@@ -34526,32 +34523,12 @@ function buildProducedByAutomationClause(producedByAutomationId, baseParamIndex)
34526
34523
  };
34527
34524
  }
34528
34525
  function buildOrgScopeWhere(options) {
34529
- if (!options.organization_id || options.entity_id && !options.strict_organization_scope) {
34530
- return { sql: "", params: [], branches: null };
34526
+ if (!options.organization_id) {
34527
+ return { sql: "", params: [] };
34531
34528
  }
34532
- const p = `$${options.baseParamIndex}::text`;
34533
- if (useLinkedOrgScope()) {
34534
- const direct = `f.organization_id = ${p}`;
34535
- return {
34536
- sql: `AND (${direct} OR f.linked_org_ids @> ARRAY[${p}]::text[])`,
34537
- params: [options.organization_id],
34538
- // The same predicate as two DISJOINT arms. Their union is exactly `sql`;
34539
- // `IS DISTINCT FROM` keeps a row that matches both arms in one of them.
34540
- // Splitting the OR lets the direct arm use the ordered organization
34541
- // index; linked matches use their own scan before the top-N merge.
34542
- branches: {
34543
- direct,
34544
- linked: `f.linked_org_ids @> ARRAY[${p}]::text[] AND f.organization_id IS DISTINCT FROM ${p}`
34545
- }
34546
- };
34547
- }
34548
- const directCond = `f.organization_id = ${p}`;
34549
- const entityCond = `EXISTS (SELECT 1 FROM entities ent_org WHERE ent_org.id = ANY(f.entity_ids) AND ent_org.organization_id = ${p})`;
34550
- const connCond = `c.organization_id = ${p}`;
34551
34529
  return {
34552
- sql: `AND (${directCond} OR ${entityCond} OR ${connCond})`,
34553
- params: [options.organization_id],
34554
- branches: null
34530
+ sql: `AND f.organization_id = $${options.baseParamIndex}::text`,
34531
+ params: [options.organization_id]
34555
34532
  };
34556
34533
  }
34557
34534
  function buildConnectionVisibilityClause(options, tableAlias = "f") {
@@ -34576,7 +34553,6 @@ var init_visibility = __esm({
34576
34553
  "use strict";
34577
34554
  init_connection_visibility();
34578
34555
  init_resource_visibility();
34579
- init_linked_org_ids();
34580
34556
  init_sql_validation();
34581
34557
  }
34582
34558
  });
@@ -35188,7 +35164,7 @@ var init_sql_fragments = __esm({
35188
35164
 
35189
35165
  // src/utils/content-search/entity-types-filter.ts
35190
35166
  function buildEntityTypesFilterClause(options) {
35191
- if (!options.entity_types?.length || !options.organization_id) {
35167
+ if (!options.entity_types?.length || !options.organization_id || options.entity_id != null) {
35192
35168
  return { sql: "", predicate: "", params: [] };
35193
35169
  }
35194
35170
  const orgParam = `$${options.baseParamIndex}::text`;
@@ -35373,14 +35349,12 @@ async function executeListQuery(args) {
35373
35349
  statementTimeoutMs: CONTENT_READ_STATEMENT_TIMEOUT_MS
35374
35350
  });
35375
35351
  const whereExpr = `${args.whereExpr} ${args.orgScope.sql}`;
35376
- const countFrom = (scopeSql) => `FROM current_event_records f
35352
+ const orgWide = args.entityId == null && args.orgScope.sql !== "";
35353
+ const orgWideRangeSql = orgWide ? args.orgWideRangeSql : "";
35354
+ const countSql = `SELECT COUNT(*) as total FROM current_event_records f
35377
35355
  LEFT JOIN connections c ON c.id = f.connection_id
35378
35356
  ${joinSql}
35379
- WHERE ${args.whereExpr} ${scopeSql}`;
35380
- const countBranches = args.entityId == null ? args.orgScope.branches : null;
35381
- const countSql = countBranches ? `SELECT
35382
- (SELECT COUNT(*) ${countFrom(`AND ${countBranches.direct} ${args.directArmRangeSql}`)})
35383
- + (SELECT COUNT(*) ${countFrom(`AND ${countBranches.linked}`)}) AS total` : `SELECT COUNT(*) as total ${countFrom(args.orgScope.sql)}`;
35357
+ WHERE ${whereExpr} ${orgWideRangeSql}`;
35384
35358
  const cursorClause = buildDateCursorClause(
35385
35359
  args.cursor,
35386
35360
  "COALESCE(f.occurred_at, f.created_at)",
@@ -35405,19 +35379,9 @@ async function executeListQuery(args) {
35405
35379
  if (args.useDateFeed) {
35406
35380
  const candidateSetSql = buildDateCandidateSetSql({
35407
35381
  joinSql,
35408
- whereExpr: args.whereExpr,
35409
- // Entity-scoped feeds are already narrowed by the entity link; keep their
35410
- // scope (normally empty) as one predicate.
35411
- orgScope: args.entityId == null ? args.orgScope : { ...args.orgScope, branches: null },
35382
+ whereExpr,
35412
35383
  cursorSql: cursorClause.sql,
35413
- // Same params, keyed on the fenced linked arm's output alias.
35414
- linkedCursorSql: buildDateCursorClause(
35415
- args.cursor,
35416
- "COALESCE(l.occurred_at, l.created_at)",
35417
- "l.id",
35418
- countParams.length + 1
35419
- ).sql,
35420
- directArmRangeSql: `${cursorClause.rangeSql} ${args.directArmRangeSql}`,
35384
+ rangeSql: orgWide ? `${cursorClause.rangeSql} ${orgWideRangeSql}` : "",
35421
35385
  cursor: args.cursor,
35422
35386
  limitParam: `$${limitIdx}`
35423
35387
  });
@@ -35521,42 +35485,17 @@ async function executeListQuery(args) {
35521
35485
  };
35522
35486
  }
35523
35487
  function buildDateCandidateSetSql(args) {
35524
- const arm = (scopeSql) => `SELECT
35488
+ return `SELECT
35525
35489
  f.id,
35526
35490
  f.occurred_at,
35527
35491
  f.created_at
35528
35492
  FROM current_event_records f
35529
35493
  LEFT JOIN connections c ON c.id = f.connection_id
35530
35494
  ${args.joinSql}
35531
- WHERE ${args.whereExpr} ${scopeSql}
35495
+ WHERE ${args.whereExpr} ${args.rangeSql}
35532
35496
  ${args.cursorSql}
35533
35497
  ORDER BY ${buildDateCandidateOrderBy(args.cursor, "f")}
35534
35498
  LIMIT ${args.limitParam}`;
35535
- const branches = args.orgScope?.branches;
35536
- if (!branches) return arm(args.orgScope?.sql ?? "");
35537
- const linkedArm = `SELECT l.id, l.occurred_at, l.created_at
35538
- FROM (
35539
- SELECT
35540
- f.id,
35541
- f.occurred_at,
35542
- f.created_at
35543
- FROM current_event_records f
35544
- LEFT JOIN connections c ON c.id = f.connection_id
35545
- ${args.joinSql}
35546
- WHERE ${args.whereExpr} AND ${branches.linked}
35547
- OFFSET 0
35548
- ) l
35549
- WHERE TRUE ${args.linkedCursorSql}
35550
- ORDER BY ${buildDateCandidateOrderBy(args.cursor, "l")}
35551
- LIMIT ${args.limitParam}`;
35552
- return `SELECT u.id, u.occurred_at, u.created_at
35553
- FROM (
35554
- (${arm(`AND ${branches.direct} ${args.directArmRangeSql}`)})
35555
- UNION ALL
35556
- (${linkedArm})
35557
- ) u
35558
- ORDER BY ${buildDateCandidateOrderBy(args.cursor, "u")}
35559
- LIMIT ${args.limitParam}`;
35560
35499
  }
35561
35500
  async function listContentInternal(sql2, options, limit, offset) {
35562
35501
  const entityId = options.entity_id;
@@ -35612,7 +35551,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35612
35551
  const runFilterClause = buildRunFilter(runIdsArray);
35613
35552
  const baseConditions = [];
35614
35553
  const baseParams = [];
35615
- let orgScope3 = { sql: "", params: [], branches: null };
35554
+ let orgScope3 = { sql: "", params: [] };
35616
35555
  let threadEntityLinkSql;
35617
35556
  if (entityId != null) {
35618
35557
  const validatedId = validateNumericId(entityId, "entity_id");
@@ -35620,7 +35559,8 @@ async function listContentInternal(sql2, options, limit, offset) {
35620
35559
  entityIdLiteral: validatedId,
35621
35560
  scopes: entityScopes,
35622
35561
  alias: "f",
35623
- baseParamIndex: baseParams.length + 1
35562
+ baseParamIndex: baseParams.length + 1,
35563
+ ownerOrganizationId: organizationId
35624
35564
  });
35625
35565
  baseConditions.push(link.sql);
35626
35566
  baseParams.push(...link.params);
@@ -35631,16 +35571,17 @@ async function listContentInternal(sql2, options, limit, offset) {
35631
35571
  // params don't need fresh slots — they're the same identifier values
35632
35572
  // emitted by the outer `link` already in baseParams. We re-bind them
35633
35573
  // by reusing the same $N slots.
35634
- baseParamIndex: baseParams.length - link.params.length + 1
35574
+ baseParamIndex: baseParams.length - link.params.length + 1,
35575
+ ownerOrganizationId: organizationId
35635
35576
  }).sql;
35636
- } else if (organizationId) {
35637
- orgScope3 = buildOrgScopeWhere({
35638
- organization_id: organizationId,
35639
- baseParamIndex: baseParams.length + 1
35640
- });
35641
- baseParams.push(...orgScope3.params);
35577
+ } else {
35642
35578
  threadEntityLinkSql = "TRUE";
35643
35579
  }
35580
+ orgScope3 = buildOrgScopeWhere({
35581
+ organization_id: organizationId,
35582
+ baseParamIndex: baseParams.length + 1
35583
+ });
35584
+ baseParams.push(...orgScope3.params);
35644
35585
  baseConditions.push(connectionFilterClause);
35645
35586
  baseConditions.push(feedFilterClause);
35646
35587
  baseConditions.push(runFilterClause);
@@ -35706,6 +35647,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35706
35647
  ];
35707
35648
  const entityTypesClause2 = buildEntityTypesFilterClause({
35708
35649
  entity_types: options.entity_types,
35650
+ entity_id: entityId,
35709
35651
  organization_id: organizationId,
35710
35652
  baseParamIndex: filterParamsBeforeEntityTypes.length + 1
35711
35653
  });
@@ -35715,7 +35657,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35715
35657
  joinSql: "",
35716
35658
  whereExpr: `${whereSql} ${excludeClause2.sql}${producedClause.sql}${analyzedClause.sql} ${visibilityClause2.sql}${entityTypesClause2.sql} ${futureClause.sql}`,
35717
35659
  orgScope: orgScope3,
35718
- directArmRangeSql: buildEffectiveAtRangeSql(sinceParam, untilParam),
35660
+ orgWideRangeSql: buildEffectiveAtRangeSql(sinceParam, untilParam),
35719
35661
  countParams: allFilterParams,
35720
35662
  entityId: entityId ?? null,
35721
35663
  threadEntityLinkSqlForP: threadEntityLinkSql,
@@ -35746,7 +35688,8 @@ async function listContentInternal(sql2, options, limit, offset) {
35746
35688
  entityIdLiteral: validatedId,
35747
35689
  scopes: entityScopes,
35748
35690
  alias: "f",
35749
- baseParamIndex: standardParams.length + 1
35691
+ baseParamIndex: standardParams.length + 1,
35692
+ ownerOrganizationId: organizationId
35750
35693
  });
35751
35694
  standardEntityLinkSql = link.sql;
35752
35695
  standardEntityLinkParams = link.params;
@@ -35754,7 +35697,8 @@ async function listContentInternal(sql2, options, limit, offset) {
35754
35697
  entityIdLiteral: validatedId,
35755
35698
  scopes: entityScopes,
35756
35699
  alias: "p",
35757
- baseParamIndex: standardParams.length + 1
35700
+ baseParamIndex: standardParams.length + 1,
35701
+ ownerOrganizationId: organizationId
35758
35702
  }).sql;
35759
35703
  } else {
35760
35704
  standardEntityLinkSql = entityLinkMatchSql("$1::bigint");
@@ -35764,7 +35708,6 @@ async function listContentInternal(sql2, options, limit, offset) {
35764
35708
  });
35765
35709
  const paramsAfterEntityLink = [...standardParams, ...standardEntityLinkParams];
35766
35710
  const orgScope2 = buildOrgScopeWhere({
35767
- entity_id: entityId,
35768
35711
  organization_id: organizationId,
35769
35712
  baseParamIndex: paramsAfterEntityLink.length + 1
35770
35713
  });
@@ -35795,6 +35738,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35795
35738
  const paramsBeforeEntityTypes = [...paramsBeforeVisibility, ...visibilityClause.params];
35796
35739
  const entityTypesClause = buildEntityTypesFilterClause({
35797
35740
  entity_types: options.entity_types,
35741
+ entity_id: entityId,
35798
35742
  organization_id: organizationId,
35799
35743
  baseParamIndex: paramsBeforeEntityTypes.length + 1
35800
35744
  });
@@ -35827,7 +35771,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35827
35771
  ${entityTypesClause.sql} ${resourceClause.sql} ${futureClause.sql}`,
35828
35772
  orgScope: orgScope2,
35829
35773
  // $3/$4 are buildStandardParams' since/until slots.
35830
- directArmRangeSql: buildEffectiveAtRangeSql("$3::timestamptz", "$4::timestamptz"),
35774
+ orgWideRangeSql: buildEffectiveAtRangeSql("$3::timestamptz", "$4::timestamptz"),
35831
35775
  countParams,
35832
35776
  threadEntityLinkSqlForP: standardEntityLinkSqlForP,
35833
35777
  needClassifications,
@@ -35984,14 +35928,39 @@ var init_embeddings = __esm({
35984
35928
  });
35985
35929
 
35986
35930
  // src/utils/content-search/fts.ts
35987
- function buildTsqueryString(queryText) {
35988
- const tokens = queryText.toLowerCase().replace(/[^a-z0-9\s]+/g, " ").split(/\s+/).filter((t) => t.length > 0 && !STOPWORDS_SET.has(t));
35989
- return tokens.length > 0 ? tokens.join(" | ") : null;
35931
+ function tsqueryTokens(queryText) {
35932
+ return queryText.toLowerCase().replace(/[^a-z0-9\s]+/g, " ").split(/\s+/).filter((t) => t.length > 0 && !STOPWORDS_SET.has(t));
35933
+ }
35934
+ function selectCandidateWords(tokens, frequencies, budget = CANDIDATE_TEXT_MATCH_BUDGET) {
35935
+ const stats = frequencies[0];
35936
+ if (!stats || stats.floor_frequency == null || !(stats.total_rows > 0)) return tokens;
35937
+ const unlistedFrequency = stats.floor_frequency / 2;
35938
+ const seen = /* @__PURE__ */ new Set();
35939
+ const estimated = [];
35940
+ for (const word of frequencies) {
35941
+ const key2 = [...word.lexemes].sort().join(" ");
35942
+ if (word.lexemes.length === 0 || seen.has(key2)) continue;
35943
+ seen.add(key2);
35944
+ estimated.push({
35945
+ token: word.token,
35946
+ rows: (word.frequency ?? unlistedFrequency) * stats.total_rows,
35947
+ position: estimated.length
35948
+ });
35949
+ }
35950
+ estimated.sort((a, b) => a.rows - b.rows || a.position - b.position);
35951
+ const kept = /* @__PURE__ */ new Set();
35952
+ let rows = 0;
35953
+ for (const word of estimated) {
35954
+ if (rows + word.rows > budget) break;
35955
+ rows += word.rows;
35956
+ kept.add(word.token);
35957
+ }
35958
+ return tokens.filter((token) => kept.has(token));
35990
35959
  }
35991
35960
  function buildSearchDocumentExpr(alias) {
35992
35961
  return `${alias}.search_tsv`;
35993
35962
  }
35994
- var STOPWORDS, STOPWORDS_SET, NORMALIZED_QUERY_SQL, TSQUERY_SQL, CANDIDATE_VECTOR_LIMIT, COLLAPSE_POOL_FACTOR, COLLAPSE_POOL_MAX, CANDIDATE_QUERY_TIMEOUT_MS, CANDIDATE_IVFFLAT_PROBES;
35963
+ var STOPWORDS, STOPWORDS_SET, CANDIDATE_TEXT_MATCH_BUDGET, NORMALIZED_QUERY_SQL, TSQUERY_SQL, CANDIDATE_VECTOR_LIMIT, COLLAPSE_POOL_FACTOR, COLLAPSE_POOL_MAX, CANDIDATE_QUERY_TIMEOUT_MS, CANDIDATE_IVFFLAT_PROBES;
35995
35964
  var init_fts = __esm({
35996
35965
  "src/utils/content-search/fts.ts"() {
35997
35966
  "use strict";
@@ -36027,6 +35996,7 @@ var init_fts = __esm({
36027
35996
  "made"
36028
35997
  ];
36029
35998
  STOPWORDS_SET = new Set(STOPWORDS);
35999
+ CANDIDATE_TEXT_MATCH_BUDGET = 1e5;
36030
36000
  NORMALIZED_QUERY_SQL = `trim(regexp_replace(regexp_replace(regexp_replace(lower($1), '\\m(${STOPWORDS.join("|")})\\M', ' ', 'g'), '[^a-z0-9\\s]+', ' ', 'g'), '\\s+', ' ', 'g'))`;
36031
36001
  TSQUERY_SQL = `CASE WHEN NULLIF(${NORMALIZED_QUERY_SQL}, '') IS NOT NULL THEN to_tsquery('english', regexp_replace(${NORMALIZED_QUERY_SQL}, '\\s+', ' | ', 'g')) ELSE NULL END`;
36032
36002
  CANDIDATE_VECTOR_LIMIT = 200;
@@ -36058,6 +36028,18 @@ async function runBoundedRecallQuery(sql2, querySQL, queryParams, signal) {
36058
36028
  throw error;
36059
36029
  }
36060
36030
  }
36031
+ async function selectFulltextCandidateTsquery(sql2, queryText, signal, budget) {
36032
+ const tokens = tsqueryTokens(queryText);
36033
+ if (tokens.length === 0) return null;
36034
+ const frequencies = await runBoundedRecallQuery(
36035
+ sql2,
36036
+ QUERY_WORD_FREQUENCY_SQL,
36037
+ [pgTextArray(tokens)],
36038
+ signal
36039
+ );
36040
+ const words = selectCandidateWords(tokens, frequencies, budget);
36041
+ return words.length > 0 ? words.join(" | ") : null;
36042
+ }
36061
36043
  async function searchContentBySingleQuery(sql2, queryText, options, env) {
36062
36044
  const entityId = options.entity_id;
36063
36045
  const limit = Math.min(options.limit ?? 50, 500);
@@ -36089,9 +36071,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36089
36071
  const runCondition = buildRunFilter(runIdsArray);
36090
36072
  const searchEntityScopes = entityId != null ? await fetchEntityIdentityScopes(sql2, entityId) : [];
36091
36073
  const orgScope2 = buildOrgScopeWhere({
36092
- entity_id: entityId,
36093
36074
  organization_id: options.organization_id,
36094
- strict_organization_scope: options.strict_organization_scope,
36095
36075
  baseParamIndex: 14
36096
36076
  });
36097
36077
  const excludeParamIdx = 14 + orgScope2.params.length;
@@ -36118,6 +36098,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36118
36098
  const entityTypesParamIdx = visibilityParamIdx + visibilityClause.params.length;
36119
36099
  const entityTypesClause = buildEntityTypesFilterClause({
36120
36100
  entity_types: options.entity_types,
36101
+ entity_id: entityId,
36121
36102
  organization_id: options.organization_id,
36122
36103
  baseParamIndex: entityTypesParamIdx
36123
36104
  });
@@ -36131,7 +36112,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36131
36112
  entityIdLiteral: validatedId,
36132
36113
  scopes: searchEntityScopes,
36133
36114
  alias: "f",
36134
- baseParamIndex: entityLinkParamIdx
36115
+ baseParamIndex: entityLinkParamIdx,
36116
+ ownerOrganizationId: options.organization_id
36135
36117
  });
36136
36118
  searchEntityLinkSql = link.sql;
36137
36119
  searchEntityLinkParams = link.params;
@@ -36139,7 +36121,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36139
36121
  entityIdLiteral: validatedId,
36140
36122
  scopes: searchEntityScopes,
36141
36123
  alias: "p",
36142
- baseParamIndex: entityLinkParamIdx
36124
+ baseParamIndex: entityLinkParamIdx,
36125
+ ownerOrganizationId: options.organization_id
36143
36126
  }).sql;
36144
36127
  } else {
36145
36128
  searchEntityLinkSql = entityLinkMatchSql("$2::bigint");
@@ -36178,7 +36161,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36178
36161
  const vectorParamIdx = hasEmbedding ? baseParamIdx : null;
36179
36162
  const minSimilarityParamIdx = baseParamIdx + (hasEmbedding ? 1 : 0);
36180
36163
  const entityFilterSQL = entityId != null ? `${searchEntityLinkSql} AND ($2::bigint IS NOT NULL)` : `($2::bigint IS NULL OR ${searchEntityLinkSql})`;
36181
- const standardFiltersFor = (orgScopeSql) => `${entityFilterSQL}
36164
+ const standardFiltersSQL = `${entityFilterSQL}
36182
36165
  AND ${connectionCondition}
36183
36166
  AND ${feedCondition}
36184
36167
  AND ${runCondition}
@@ -36208,8 +36191,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36208
36191
  options.exclude_recall_bookkeeping && !options.semantic_type ? `AND ${RECALL_BOOKKEEPING_EXCLUSION_SQL}` : ""}
36209
36192
  ${classificationClause.sql}
36210
36193
  ${resourceClause.sql}
36211
- ${orgScopeSql}${entityTypesClause.sql}`;
36212
- const standardFiltersSQL = standardFiltersFor(orgScope2.sql);
36194
+ ${orgScope2.sql}${entityTypesClause.sql}`;
36213
36195
  const textDocumentExpr = buildSearchDocumentExpr("f");
36214
36196
  const resultDocumentExpr = buildSearchDocumentExpr("fi");
36215
36197
  const substringMatchExpr = hasEmbedding ? "text_match.substring_match" : `f.payload_text ILIKE '%' || $1 || '%'`;
@@ -36231,8 +36213,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36231
36213
  const bestSimSelect = hasEmbedding ? "chunk_score.best_sim" : "NULL";
36232
36214
  const substringMatchSelect = hasEmbedding ? "text_match.substring_match" : "NULL";
36233
36215
  const matchCondition = hasEmbedding ? `(${textMatchExpr} OR ${bestSimSelect} >= ${minSimilarityParam})` : textMatchExpr;
36234
- const searchWhereFor = (orgScopeSql) => `${matchCondition}
36235
- AND ${standardFiltersFor(orgScopeSql)}`;
36216
+ const searchWhereSQL = `${matchCondition}
36217
+ AND ${standardFiltersSQL}`;
36236
36218
  const rankedSubstringMatch = hasEmbedding ? "fi.substring_match" : `fi.payload_text ILIKE '%' || $1 || '%'`;
36237
36219
  const textRankExpr = `
36238
36220
  (CASE WHEN LENGTH($1) > 0 AND ${rankedSubstringMatch} THEN 0.5 ELSE 0.0 END)
@@ -36292,6 +36274,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36292
36274
  const validatedLimit = validateNumericId(limit, "limit");
36293
36275
  const useCandidatePath = options.approximate_candidate_search === true && options.agent_id == null && entityId == null && options.organization_id != null && !useDateFeed && effectiveOffset === 0 && hasEmbedding;
36294
36276
  const hasTextCandidates = useCandidatePath && trimmedQuery.length >= 3;
36277
+ const fulltextTsquery = hasTextCandidates ? await selectFulltextCandidateTsquery(sql2, trimmedQuery, options.signal) : null;
36295
36278
  let searchCandidatesCteSql = "";
36296
36279
  if (useCandidatePath) {
36297
36280
  const tsqueryParamIdx = offsetParamIdx + 1;
@@ -36316,23 +36299,20 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36316
36299
  ORDER BY MIN(dist)
36317
36300
  LIMIT ${CANDIDATE_VECTOR_LIMIT}`);
36318
36301
  if (hasTextCandidates) {
36319
- const textScopeFilters = orgScope2.branches ? [orgScope2.branches.direct, orgScope2.branches.linked].map((scope) => standardFiltersFor(`AND ${scope}`)) : [standardFiltersSQL];
36320
- const textCandidates = (matchSql, rankSql) => `SELECT id FROM (
36321
- ${textScopeFilters.map((filters) => `(SELECT ce.id AS id, ${rankSql} AS rank
36302
+ const textCandidates = (matchSql, rankSql) => `SELECT ce.id AS id
36322
36303
  FROM events ce
36323
36304
  JOIN current_event_records f ON f.id = ce.id
36324
36305
  ${candidateFilterJoins}
36325
36306
  WHERE ${matchSql}
36326
- AND ${filters}
36307
+ AND ${standardFiltersSQL}
36327
36308
  ORDER BY ${rankSql} DESC, ce.id + 0 DESC
36328
- LIMIT ${CANDIDATE_VECTOR_LIMIT})`).join("\n UNION ALL\n ")}
36329
- ) text_candidates
36330
- ORDER BY rank DESC, id DESC
36331
- LIMIT ${CANDIDATE_VECTOR_LIMIT}`;
36332
- branches.push(textCandidates(
36333
- `ce.search_tsv @@ to_tsquery('english', $${tsqueryParamIdx})`,
36334
- `ts_rank_cd(ce.search_tsv, to_tsquery('english', $${tsqueryParamIdx}))`
36335
- ));
36309
+ LIMIT ${CANDIDATE_VECTOR_LIMIT}`;
36310
+ if (fulltextTsquery !== null) {
36311
+ branches.push(textCandidates(
36312
+ `ce.search_tsv @@ to_tsquery('english', $${tsqueryParamIdx})`,
36313
+ `ts_rank_cd(ce.search_tsv, to_tsquery('english', $${tsqueryParamIdx}))`
36314
+ ));
36315
+ }
36336
36316
  branches.push(textCandidates(`ce.payload_text ILIKE '%' || $1 || '%'`, "ce.id + 0"));
36337
36317
  }
36338
36318
  searchCandidatesCteSql = `search_candidates AS (
@@ -36350,10 +36330,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36350
36330
  AND ($6::int IS NOT NULL)
36351
36331
  AND iwf.run_id = $6::int
36352
36332
  WHERE ${whereSql}`;
36353
- const exactBranches = entityId == null ? orgScope2.branches : null;
36354
- const exactFilteredIdsBody = exactBranches ? `(${filteredIdsSelect(searchWhereFor(`AND ${exactBranches.direct}`))})
36355
- UNION ALL
36356
- (${filteredIdsSelect(searchWhereFor(`AND ${exactBranches.linked}`))})` : filteredIdsSelect(searchWhereFor(orgScope2.sql));
36333
+ const exactFilteredIdsBody = filteredIdsSelect(searchWhereSQL);
36357
36334
  const nonDateFilteredIdsCteSql = `filtered_ids AS (
36358
36335
  ${useCandidatePath ? filteredIdsSelect(standardFiltersSQL, "JOIN search_candidates sc ON sc.id = f.id") : exactFilteredIdsBody}
36359
36336
  )`;
@@ -36496,8 +36473,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36496
36473
  ...cursorClause.params,
36497
36474
  ...useDateFeed ? [fetchLimit] : [includeTotal ? limit : limit + 1, effectiveOffset]
36498
36475
  ];
36499
- if (hasTextCandidates) {
36500
- queryParams.push(buildTsqueryString(trimmedQuery));
36476
+ if (fulltextTsquery !== null) {
36477
+ queryParams.push(fulltextTsquery);
36501
36478
  }
36502
36479
  let rawRows;
36503
36480
  const exactRead = { signal: options.signal, statementTimeoutMs: CONTENT_READ_STATEMENT_TIMEOUT_MS };
@@ -36532,6 +36509,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36532
36509
  ...queryEmbeddingUnavailable && { query_embedding_unavailable: true }
36533
36510
  };
36534
36511
  }
36512
+ var QUERY_WORD_FREQUENCY_SQL;
36535
36513
  var init_search_path = __esm({
36536
36514
  "src/utils/content-search/search-path.ts"() {
36537
36515
  "use strict";
@@ -36555,6 +36533,25 @@ var init_search_path = __esm({
36555
36533
  init_types4();
36556
36534
  init_entity_types_filter();
36557
36535
  init_visibility();
36536
+ QUERY_WORD_FREQUENCY_SQL = `
36537
+ WITH stats AS MATERIALIZED (
36538
+ SELECT s.most_common_elems::text::text[] AS elems, s.most_common_elem_freqs AS freqs
36539
+ FROM pg_stats s
36540
+ JOIN pg_class c ON c.oid = 'events'::regclass
36541
+ JOIN pg_namespace n ON n.oid = c.relnamespace
36542
+ WHERE s.schemaname = n.nspname AND s.tablename = c.relname AND s.attname = 'search_tsv'
36543
+ ),
36544
+ words AS (
36545
+ SELECT t.token, tsvector_to_array(to_tsvector('english', t.token)) AS lexemes
36546
+ FROM unnest($1::text[]) AS t(token)
36547
+ )
36548
+ SELECT w.token, to_json(w.lexemes) AS lexemes,
36549
+ (SELECT max(e.freq) FROM stats, unnest(stats.elems, stats.freqs) AS e(elem, freq)
36550
+ WHERE e.elem = ANY(w.lexemes)) AS frequency,
36551
+ -- tsvector element frequencies are followed by their minimum and maximum.
36552
+ (SELECT stats.freqs[cardinality(stats.elems) + 1] FROM stats) AS floor_frequency,
36553
+ (SELECT c.reltuples FROM pg_class c WHERE c.oid = 'events'::regclass) AS total_rows
36554
+ FROM words w`;
36558
36555
  }
36559
36556
  });
36560
36557
 
@@ -51520,6 +51517,291 @@ var init_source_read_bridge = __esm({
51520
51517
  }
51521
51518
  });
51522
51519
 
51520
+ // src/lib/source-admission.ts
51521
+ function sourceCallerClassOfAccess(access) {
51522
+ return access === "public_visitor" ? "anonymous" : "member";
51523
+ }
51524
+ function sourceCallerClass(ctx) {
51525
+ return sourceCallerClassOfAccess(chatAccessOfToolContext(ctx));
51526
+ }
51527
+ var SOURCE_RUNS_PER_CONNECTION, SOURCE_WAITERS_PER_CONNECTION, MIN_RUN_BUDGET_MS, RATE_LIMIT_STEP_MS, REFUSAL_LOG_INTERVAL_MS, DEFAULT_RUN_LATENCY_MS, MAX_RETRY_AFTER_SECONDS, SourceAdmissionRefusedError, SourceAdmission, sourceAdmission;
51528
+ var init_source_admission = __esm({
51529
+ "src/lib/source-admission.ts"() {
51530
+ "use strict";
51531
+ init_src();
51532
+ init_device_access();
51533
+ init_race_abort();
51534
+ init_logger2();
51535
+ SOURCE_RUNS_PER_CONNECTION = 4;
51536
+ SOURCE_WAITERS_PER_CONNECTION = 32;
51537
+ MIN_RUN_BUDGET_MS = 2e3;
51538
+ RATE_LIMIT_STEP_MS = 3e4;
51539
+ REFUSAL_LOG_INTERVAL_MS = 1e4;
51540
+ DEFAULT_RUN_LATENCY_MS = 1e3;
51541
+ MAX_RETRY_AFTER_SECONDS = 30;
51542
+ SourceAdmissionRefusedError = class extends ToolError {
51543
+ constructor(message, retryAfterSeconds, outcome) {
51544
+ super("UPSTREAM_UNAVAILABLE", message);
51545
+ this.retryAfterSeconds = retryAfterSeconds;
51546
+ this.outcome = outcome;
51547
+ }
51548
+ retryAfterSeconds;
51549
+ outcome;
51550
+ };
51551
+ SourceAdmission = class {
51552
+ constructor(capacity = SOURCE_RUNS_PER_CONNECTION, maxWaiters = SOURCE_WAITERS_PER_CONNECTION) {
51553
+ this.capacity = capacity;
51554
+ this.maxWaiters = maxWaiters;
51555
+ }
51556
+ capacity;
51557
+ maxWaiters;
51558
+ connections = /* @__PURE__ */ new Map();
51559
+ reads = /* @__PURE__ */ new Map();
51560
+ lastRefusalLogAt = Number.NEGATIVE_INFINITY;
51561
+ unloggedRefusals = 0;
51562
+ /**
51563
+ * Run `start` once for every concurrent caller with the same `key`. A caller
51564
+ * that finds the read already running joins it and takes no slot. Each
51565
+ * participant waits under its own deadline and abort signal and receives its
51566
+ * own copy of the result; the shared run is aborted when every participant
51567
+ * has left or its original deadline expires. The entry is dropped when the
51568
+ * run settles.
51569
+ */
51570
+ async coalesce(key2, connectionId, participant, start) {
51571
+ participant.signal?.throwIfAborted();
51572
+ let shared = this.reads.get(key2);
51573
+ if (shared) {
51574
+ this.endSpan(this.startSpan(connectionId, participant.callerClass), "joined", 0, this.connections.get(connectionId));
51575
+ } else {
51576
+ const controller = new AbortController();
51577
+ const read2 = {
51578
+ participants: 0,
51579
+ controller,
51580
+ promise: Promise.resolve(),
51581
+ deadlineAt: participant.deadlineAt
51582
+ };
51583
+ const timer = setTimeout(() => controller.abort(Object.assign(
51584
+ new Error("source read timed out at the caller deadline"),
51585
+ { exitReason: "timeout" }
51586
+ )), Math.max(0, read2.deadlineAt - Date.now()));
51587
+ read2.promise = raceAbort((async () => start(controller.signal))(), controller.signal).finally(() => {
51588
+ clearTimeout(timer);
51589
+ if (this.reads.get(key2) === read2) this.reads.delete(key2);
51590
+ });
51591
+ this.reads.set(key2, read2);
51592
+ shared = read2;
51593
+ }
51594
+ const read = shared;
51595
+ read.participants += 1;
51596
+ return new Promise((resolve14, reject) => {
51597
+ let done = false;
51598
+ const settle = (finish) => {
51599
+ if (done) return;
51600
+ done = true;
51601
+ clearTimeout(timer);
51602
+ participant.signal?.removeEventListener("abort", onAbort);
51603
+ read.participants -= 1;
51604
+ finish();
51605
+ };
51606
+ const leave = (reason) => settle(() => {
51607
+ if (read.participants === 0) {
51608
+ if (this.reads.get(key2) === read) this.reads.delete(key2);
51609
+ read.controller.abort(reason);
51610
+ }
51611
+ reject(reason);
51612
+ });
51613
+ const onAbort = () => leave(participant.signal?.reason);
51614
+ const timer = participant.deadlineAt < read.deadlineAt ? setTimeout(
51615
+ () => leave(Object.assign(new Error("source read timed out at the caller deadline"), { exitReason: "timeout" })),
51616
+ Math.max(0, participant.deadlineAt - Date.now())
51617
+ ) : void 0;
51618
+ participant.signal?.addEventListener("abort", onAbort, { once: true });
51619
+ read.promise.then(
51620
+ (value) => settle(() => resolve14(structuredClone(value))),
51621
+ (error) => settle(() => reject(error))
51622
+ );
51623
+ });
51624
+ }
51625
+ /** Take a run slot on `connectionId`, waiting for one when the connection is full. */
51626
+ async acquire(connectionId, request2) {
51627
+ const startedAt = Date.now();
51628
+ const span = this.startSpan(connectionId, request2.callerClass);
51629
+ const state = this.state(connectionId);
51630
+ try {
51631
+ request2.signal?.throwIfAborted();
51632
+ this.pump(state);
51633
+ if (this.canRun(state, request2.callerClass)) {
51634
+ this.take(state, request2.callerClass);
51635
+ } else {
51636
+ if (state.waiters.length >= this.maxWaiters) throw this.refuse(connectionId, state, "refused_queue_full");
51637
+ const waitMs = request2.deadlineAt - MIN_RUN_BUDGET_MS - Date.now();
51638
+ if (waitMs <= 0) throw this.refuse(connectionId, state, "refused_deadline");
51639
+ await this.wait(connectionId, state, request2, waitMs);
51640
+ }
51641
+ } catch (error) {
51642
+ this.endSpan(
51643
+ span,
51644
+ error instanceof SourceAdmissionRefusedError ? error.outcome : "aborted",
51645
+ Date.now() - startedAt,
51646
+ state
51647
+ );
51648
+ this.forgetIdle(connectionId, state);
51649
+ throw error;
51650
+ }
51651
+ this.endSpan(span, "admitted", Date.now() - startedAt, state);
51652
+ return this.slot(connectionId, state, request2.callerClass);
51653
+ }
51654
+ state(connectionId) {
51655
+ let state = this.connections.get(connectionId);
51656
+ if (!state) {
51657
+ state = {
51658
+ running: 0,
51659
+ runningAnonymous: 0,
51660
+ waiters: [],
51661
+ limit: this.capacity,
51662
+ generation: 0,
51663
+ nextRestoreAt: 0,
51664
+ avgLatencyMs: null
51665
+ };
51666
+ this.connections.set(connectionId, state);
51667
+ }
51668
+ return state;
51669
+ }
51670
+ /** Drop a connection's state once nothing runs, waits, or is throttled on it. */
51671
+ forgetIdle(connectionId, state) {
51672
+ if (state.running === 0 && state.waiters.length === 0 && state.limit === this.capacity) {
51673
+ if (this.connections.get(connectionId) === state) this.connections.delete(connectionId);
51674
+ }
51675
+ }
51676
+ anonymousLimit(state) {
51677
+ return Math.max(1, state.limit - 1);
51678
+ }
51679
+ canRun(state, callerClass) {
51680
+ return state.running < state.limit && (callerClass === "member" || state.runningAnonymous < this.anonymousLimit(state));
51681
+ }
51682
+ take(state, callerClass) {
51683
+ state.running += 1;
51684
+ if (callerClass === "anonymous") state.runningAnonymous += 1;
51685
+ }
51686
+ /** Restore one slot per clean interval since the last 429, then admit whoever can run. */
51687
+ pump(state) {
51688
+ const now = Date.now();
51689
+ while (state.limit < this.capacity && now >= state.nextRestoreAt) {
51690
+ state.limit += 1;
51691
+ state.nextRestoreAt += RATE_LIMIT_STEP_MS;
51692
+ }
51693
+ for (; ; ) {
51694
+ if (state.running >= state.limit) return;
51695
+ let index = state.waiters.findIndex((waiter2) => waiter2.callerClass === "member");
51696
+ if (index < 0 && state.runningAnonymous < this.anonymousLimit(state)) index = 0;
51697
+ const waiter = index < 0 ? void 0 : state.waiters[index];
51698
+ if (!waiter) return;
51699
+ state.waiters.splice(index, 1);
51700
+ this.take(state, waiter.callerClass);
51701
+ waiter.admit();
51702
+ }
51703
+ }
51704
+ wait(connectionId, state, request2, waitMs) {
51705
+ return new Promise((resolve14, reject) => {
51706
+ const cleanup = () => {
51707
+ clearTimeout(timer);
51708
+ request2.signal?.removeEventListener("abort", onAbort);
51709
+ };
51710
+ const waiter = {
51711
+ callerClass: request2.callerClass,
51712
+ admit: () => {
51713
+ cleanup();
51714
+ resolve14();
51715
+ }
51716
+ };
51717
+ const leave = (error) => {
51718
+ const index = state.waiters.indexOf(waiter);
51719
+ if (index < 0) return;
51720
+ state.waiters.splice(index, 1);
51721
+ cleanup();
51722
+ reject(error);
51723
+ };
51724
+ const onAbort = () => leave(request2.signal?.reason);
51725
+ const timer = setTimeout(() => leave(this.refuse(connectionId, state, "refused_deadline")), waitMs);
51726
+ request2.signal?.addEventListener("abort", onAbort, { once: true });
51727
+ state.waiters.push(waiter);
51728
+ });
51729
+ }
51730
+ slot(connectionId, state, callerClass) {
51731
+ const generation = state.generation;
51732
+ const startedAt = Date.now();
51733
+ let released = false;
51734
+ return {
51735
+ release: ({ rateLimited }) => {
51736
+ if (released) return;
51737
+ released = true;
51738
+ state.running -= 1;
51739
+ if (callerClass === "anonymous") state.runningAnonymous -= 1;
51740
+ const latencyMs = Date.now() - startedAt;
51741
+ state.avgLatencyMs = state.avgLatencyMs === null ? latencyMs : state.avgLatencyMs * 0.8 + latencyMs * 0.2;
51742
+ if (rateLimited) {
51743
+ state.nextRestoreAt = Date.now() + RATE_LIMIT_STEP_MS;
51744
+ if (generation === state.generation) {
51745
+ state.limit = Math.max(1, Math.floor(state.limit / 2));
51746
+ state.generation += 1;
51747
+ }
51748
+ }
51749
+ this.pump(state);
51750
+ this.forgetIdle(connectionId, state);
51751
+ }
51752
+ };
51753
+ }
51754
+ /** Seconds until the queue ahead has likely drained at the current limit. */
51755
+ retryAfterSeconds(state) {
51756
+ const latencySeconds = (state.avgLatencyMs ?? DEFAULT_RUN_LATENCY_MS) / 1e3;
51757
+ const estimate = Math.ceil(state.waiters.length * latencySeconds / state.limit);
51758
+ return Math.min(MAX_RETRY_AFTER_SECONDS, Math.max(1, estimate));
51759
+ }
51760
+ refuse(connectionId, state, outcome) {
51761
+ const retryAfterSeconds = this.retryAfterSeconds(state);
51762
+ const now = Date.now();
51763
+ if (now - this.lastRefusalLogAt >= REFUSAL_LOG_INTERVAL_MS) {
51764
+ logger_default.warn({
51765
+ connectionId,
51766
+ outcome,
51767
+ running: state.running,
51768
+ waiting: state.waiters.length,
51769
+ limit: state.limit,
51770
+ refusedSinceLastLog: this.unloggedRefusals
51771
+ }, "[source-admission] refusing live source reads at the connection limit");
51772
+ this.lastRefusalLogAt = now;
51773
+ this.unloggedRefusals = 0;
51774
+ } else {
51775
+ this.unloggedRefusals += 1;
51776
+ }
51777
+ return new SourceAdmissionRefusedError(
51778
+ outcome === "refused_queue_full" ? `the source is busy (${state.running} reads running, ${state.waiters.length} waiting); retry in ${retryAfterSeconds}s` : `the source is busy and too little of the read deadline remains to wait; retry in ${retryAfterSeconds}s`,
51779
+ retryAfterSeconds,
51780
+ outcome
51781
+ );
51782
+ }
51783
+ startSpan(connectionId, callerClass) {
51784
+ return createSpan("source.admission", {
51785
+ "lobu.source.connection_id": connectionId,
51786
+ "lobu.source.admission.class": callerClass
51787
+ });
51788
+ }
51789
+ /** Close the admission span with what the caller got and what it found. */
51790
+ endSpan(span, outcome, waitMs, state) {
51791
+ span?.setAttributes({
51792
+ "lobu.source.admission.outcome": outcome,
51793
+ "lobu.source.admission.wait_ms": waitMs,
51794
+ "lobu.source.admission.inflight": state?.running ?? 0,
51795
+ "lobu.source.admission.queue_depth": state?.waiters.length ?? 0,
51796
+ "lobu.source.admission.limit": state?.limit ?? this.capacity
51797
+ });
51798
+ span?.end();
51799
+ }
51800
+ };
51801
+ sourceAdmission = new SourceAdmission();
51802
+ }
51803
+ });
51804
+
51523
51805
  // src/lib/connector-pushdown.ts
51524
51806
  import { createHash as createHash19 } from "node:crypto";
51525
51807
  function isTransientUpstreamFailure(error) {
@@ -51557,10 +51839,37 @@ async function runConnectorQuery(p) {
51557
51839
  );
51558
51840
  }
51559
51841
  const conn = connRows[0];
51560
- const compiledCode = await resolveConnectorCodeForKey(
51842
+ const readKey = createHash19("sha256").update(stableJson({
51843
+ connectionId: Number(conn.id),
51844
+ connectorKey: conn.connector_key,
51845
+ callerClass: p.callerClass,
51846
+ query: p.query,
51847
+ exactMatch: p.exactMatch ?? null,
51848
+ selection: p.selection ?? null,
51849
+ limit: p.limit ?? null,
51850
+ offset: p.offset ?? null,
51851
+ sort: p.sort ?? null,
51852
+ config: p.config ?? null
51853
+ })).digest("hex");
51854
+ const participant = { callerClass: p.callerClass, deadlineAt, signal: p.signal };
51855
+ return sourceAdmission.coalesce(readKey, Number(conn.id), participant, async (signal) => {
51856
+ const slot = await sourceAdmission.acquire(Number(conn.id), { ...participant, signal });
51857
+ let rateLimited = false;
51858
+ try {
51859
+ return await raceAbort(runAdmittedQuery(p, conn, deadlineAt, signal, () => {
51860
+ rateLimited = true;
51861
+ }), signal);
51862
+ } finally {
51863
+ slot.release({ rateLimited });
51864
+ }
51865
+ });
51866
+ }
51867
+ async function runAdmittedQuery(p, conn, deadlineAt, signal, onRateLimited) {
51868
+ signal.throwIfAborted();
51869
+ const compiledCode = await raceAbort(resolveConnectorCodeForKey(
51561
51870
  conn.connector_key,
51562
51871
  p.scope.organizationId
51563
- );
51872
+ ), signal);
51564
51873
  const authParams = {
51565
51874
  organizationId: p.scope.organizationId,
51566
51875
  connectionId: conn.id,
@@ -51570,8 +51879,9 @@ async function runConnectorQuery(p) {
51570
51879
  logContext: { connection: p.connectionSlug },
51571
51880
  logMessage: "Failed to resolve connector query credentials"
51572
51881
  };
51573
- let auth = await resolveExecutionAuth(authParams);
51882
+ let auth = await raceAbort(resolveExecutionAuth(authParams), signal);
51574
51883
  const execute = async (resolved) => {
51884
+ signal.throwIfAborted();
51575
51885
  const { credentials, connectionCredentials, sessionState, httpAuth, onHttpFetch } = resolved;
51576
51886
  return executeCompiledConnector({
51577
51887
  compiledCode,
@@ -51602,7 +51912,7 @@ async function runConnectorQuery(p) {
51602
51912
  offset: p.offset,
51603
51913
  sort: p.sort
51604
51914
  },
51605
- hooks: { onHttpFetch },
51915
+ hooks: { onHttpFetch, signal },
51606
51916
  timeoutMs: resolvePushdownTimeoutMs(deadlineAt)
51607
51917
  });
51608
51918
  };
@@ -51610,18 +51920,25 @@ async function runConnectorQuery(p) {
51610
51920
  try {
51611
51921
  result = await execute(auth);
51612
51922
  } catch (error) {
51923
+ signal.throwIfAborted();
51613
51924
  const status = error?.httpStatus;
51925
+ if (status === 429) onRateLimited();
51614
51926
  if (status === 401 && auth.credentials?.accessToken) {
51615
51927
  const rejectedAccessToken = auth.credentials.accessToken;
51616
- auth = await resolveExecutionAuth({ ...authParams, rejectedAccessToken });
51928
+ auth = await raceAbort(resolveExecutionAuth({ ...authParams, rejectedAccessToken }), signal);
51617
51929
  if (!auth.credentials?.accessToken || auth.credentials.accessToken === rejectedAccessToken) throw error;
51618
51930
  } else {
51619
51931
  if (!isTransientUpstreamFailure(error)) throw error;
51620
51932
  if (deadlineAt - Date.now() <= PUSHDOWN_RETRY_BACKOFF_MS) throw error;
51621
- await new Promise((resolve14) => setTimeout(resolve14, PUSHDOWN_RETRY_BACKOFF_MS));
51933
+ await raceAbort(new Promise((resolve14) => setTimeout(resolve14, PUSHDOWN_RETRY_BACKOFF_MS)), signal);
51622
51934
  }
51623
51935
  if (deadlineAt <= Date.now()) throw error;
51624
- result = await execute(auth);
51936
+ try {
51937
+ result = await execute(auth);
51938
+ } catch (retryError) {
51939
+ if (retryError?.httpStatus === 429) onRateLimited();
51940
+ throw retryError;
51941
+ }
51625
51942
  }
51626
51943
  if (result.mode !== "query") {
51627
51944
  throw new Error(`Expected query result, got mode=${result.mode}`);
@@ -51639,11 +51956,14 @@ function isCompletePushdownResult(result) {
51639
51956
  }
51640
51957
  function pushdownFailureError(err, connectionSlug, subject) {
51641
51958
  const code = classifyPushdownFailure(err);
51642
- return new ToolUserError(
51959
+ const failure = new ToolUserError(
51643
51960
  `connection pushdown failed (connection=${connectionSlug}): ${getErrorMessage(err)}. The ${subject} did not run against the source \u2014 this is not an empty result.`,
51644
51961
  toolErrorHttpStatus(code),
51645
51962
  code
51646
51963
  );
51964
+ const retryAfterSeconds = err?.retryAfterSeconds;
51965
+ if (typeof retryAfterSeconds === "number") failure.retryAfterSeconds = retryAfterSeconds;
51966
+ return failure;
51647
51967
  }
51648
51968
  function classifyPushdownFailure(err) {
51649
51969
  if (err instanceof ToolError) return err.code;
@@ -51664,8 +51984,9 @@ async function readSourceFeed(p) {
51664
51984
  let timer;
51665
51985
  const deadline = new Promise((_resolve, reject) => {
51666
51986
  timer = setTimeout(() => {
51667
- controller.abort();
51668
- reject(browserLeased ? new BrowserInterruptionError("timeout", `Browser source read ${p.feedId} timed out; no recovery handoff was issued.`) : sourceReadDeadlineError(p.feedId));
51987
+ const error = browserLeased ? new BrowserInterruptionError("timeout", `Browser source read ${p.feedId} timed out; no recovery handoff was issued.`) : sourceReadDeadlineError(p.feedId);
51988
+ controller.abort(error);
51989
+ reject(error);
51669
51990
  }, timeoutMs);
51670
51991
  });
51671
51992
  try {
@@ -51910,7 +52231,27 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51910
52231
  signal: p.signal
51911
52232
  });
51912
52233
  }
51913
- const adapterResult = p.recoveryId ? null : await readSourceFeedFromAdapter({
52234
+ if (feed.device_worker_id !== null) {
52235
+ return readLiveSourceFeed(p, feed, feedConfig, sourceRevision, sourceSubscription, finish, onBrowserLease);
52236
+ }
52237
+ const slot = await sourceAdmission.acquire(Number(feed.connection_id), {
52238
+ callerClass: sourceCallerClassOfAccess(p.scope.chatAccess),
52239
+ deadlineAt: p.deadlineAt,
52240
+ signal: p.signal
52241
+ });
52242
+ let rateLimited = false;
52243
+ try {
52244
+ return await raceAbort(readLiveSourceFeed(p, feed, feedConfig, sourceRevision, sourceSubscription, finish, onBrowserLease), p.signal);
52245
+ } catch (error) {
52246
+ rateLimited = error?.httpStatus === 429;
52247
+ throw error;
52248
+ } finally {
52249
+ slot.release({ rateLimited });
52250
+ }
52251
+ }
52252
+ async function readLiveSourceFeed(p, feed, feedConfig, sourceRevision, sourceSubscription, finish, onBrowserLease) {
52253
+ remainingReadMs(p);
52254
+ const adapterResult = p.recoveryId ? null : await raceAbort(readSourceFeedFromAdapter({
51914
52255
  organizationId: p.scope.organizationId,
51915
52256
  connectionId: Number(feed.connection_id),
51916
52257
  connectorKey: feed.connector_key,
@@ -51926,16 +52267,16 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51926
52267
  sort: p.sort,
51927
52268
  signal: p.signal,
51928
52269
  deadlineAt: p.deadlineAt
51929
- });
52270
+ }), p.signal);
51930
52271
  if (adapterResult) {
51931
52272
  return finish({ ...adapterResult, columns: adapterResult.columns ?? [] });
51932
52273
  }
51933
- const compiledCode = await resolveConnectorCodeForKey(
52274
+ const compiledCode = await raceAbort(resolveConnectorCodeForKey(
51934
52275
  feed.connector_key,
51935
52276
  p.scope.organizationId,
51936
52277
  feed.pinned_version ?? feed.definition_version
51937
- );
51938
- const { credentials, connectionCredentials, sessionState, httpAuth, onHttpFetch } = await resolveExecutionAuth({
52278
+ ), p.signal);
52279
+ const { credentials, connectionCredentials, sessionState, httpAuth, onHttpFetch } = await raceAbort(resolveExecutionAuth({
51939
52280
  organizationId: p.scope.organizationId,
51940
52281
  connectionId: feed.connection_id,
51941
52282
  authProfileId: Number(feed.auth_profile_id) || null,
@@ -51943,12 +52284,12 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51943
52284
  credentialDb: getDb(),
51944
52285
  logContext: { feedId: String(p.feedId) },
51945
52286
  logMessage: "Failed to resolve feed source-read credentials"
51946
- });
52287
+ }), p.signal);
51947
52288
  const config = {
51948
52289
  ...mergeExecutionConfig(feed.connection_config, connectionCredentials, feedConfig),
51949
52290
  ...dbEgressConfig()
51950
52291
  };
51951
- const timeoutMs = remainingReadMs(p);
52292
+ remainingReadMs(p);
51952
52293
  const artifactHash = computeCodeHash(compiledCode);
51953
52294
  const browser = createSourceReadBridge({ ...feed, selected_artifact_hash: artifactHash }, {
51954
52295
  scope: p.scope,
@@ -51985,7 +52326,7 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51985
52326
  config,
51986
52327
  env: { ...dbEgressConfig(), ...httpEgressAllowHostsEnv() },
51987
52328
  sessionState,
51988
- browser: await connectionBrowserGrant(p.scope.organizationId, feed.connection_id, feed.pinned_version ?? feed.definition_version),
52329
+ browser: await raceAbort(connectionBrowserGrant(p.scope.organizationId, feed.connection_id, feed.pinned_version ?? feed.definition_version), p.signal),
51989
52330
  credentials,
51990
52331
  httpAuth,
51991
52332
  limit: p.limit,
@@ -51998,7 +52339,7 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51998
52339
  signal: p.signal,
51999
52340
  onChromeDispatch: browser.onChromeDispatch
52000
52341
  },
52001
- timeoutMs
52342
+ timeoutMs: remainingReadMs(p)
52002
52343
  });
52003
52344
  if (result.mode !== "read") {
52004
52345
  throw new Error(`Expected read result, got mode=${result.mode}`);
@@ -52035,6 +52376,7 @@ var init_connector_pushdown = __esm({
52035
52376
  init_connector_catalog();
52036
52377
  init_ensure_connector_installed();
52037
52378
  init_execution_context();
52379
+ init_race_abort();
52038
52380
  init_device_feed_read();
52039
52381
  init_source_feed_adapters();
52040
52382
  init_source_read_bridge();
@@ -52042,6 +52384,7 @@ var init_connector_pushdown = __esm({
52042
52384
  init_connector_execution_placement();
52043
52385
  init_compiler_core();
52044
52386
  init_source_feed_subscriptions();
52387
+ init_source_admission();
52045
52388
  PUSHDOWN_QUERY_TIMEOUT_MS = 3e4;
52046
52389
  PUSHDOWN_RETRY_BACKOFF_MS = 250;
52047
52390
  }
@@ -59822,20 +60165,6 @@ function stripChatLinkTriggers(triggers) {
59822
60165
  return true;
59823
60166
  });
59824
60167
  }
59825
- function canonicalizeJson(value) {
59826
- if (Array.isArray(value)) return value.map(canonicalizeJson);
59827
- if (value !== null && typeof value === "object") {
59828
- const out = {};
59829
- for (const key2 of Object.keys(value).sort()) {
59830
- out[key2] = canonicalizeJson(value[key2]);
59831
- }
59832
- return out;
59833
- }
59834
- return value;
59835
- }
59836
- function stableJson2(value) {
59837
- return JSON.stringify(canonicalizeJson(value ?? null));
59838
- }
59839
60168
  async function handleCreate(args, _env, ctx) {
59840
60169
  const sql2 = getDb();
59841
60170
  if (!args.slug) {
@@ -60322,17 +60651,17 @@ async function handleUpdate(args, _env, ctx, base) {
60322
60651
  const lockedCadenceChanged = lockedTouchesCadence && (lockedEffectiveSchedule !== locked.schedule || lockedEffectiveTimezone !== locked.timezone);
60323
60652
  const lockedNextRunAtVal = lockedTouchesCadence && lockedEffectiveSchedule ? nextRunAt(lockedEffectiveSchedule, /* @__PURE__ */ new Date(), lockedEffectiveTimezone) : null;
60324
60653
  const valueChangedFields = [];
60325
- if (has("execution_config") && stableJson2(patch.execution_config ?? null) !== stableJson2(locked.execution_config ?? null)) valueChangedFields.push("execution_config");
60654
+ if (has("execution_config") && stableJson(patch.execution_config ?? null) !== stableJson(locked.execution_config ?? null)) valueChangedFields.push("execution_config");
60326
60655
  if (has("triggers") && !lockedTriggersValueEqual) valueChangedFields.push("triggers");
60327
60656
  if (has("managed_agent_id") && (patch.managed_agent_id ?? null) !== (locked.managed_agent_id ?? null)) valueChangedFields.push("managed_agent_id");
60328
60657
  if (has("tags")) {
60329
60658
  const lockedTags = parsePgTextArray(locked.tags);
60330
60659
  const nextTags = patch.tags ?? [];
60331
- if (stableJson2([...lockedTags].sort()) !== stableJson2([...nextTags].sort())) valueChangedFields.push("tags");
60660
+ if (stableJson([...lockedTags].sort()) !== stableJson([...nextTags].sort())) valueChangedFields.push("tags");
60332
60661
  }
60333
60662
  if (has("device_worker_id") && (patch.device_worker_id ?? null) !== (locked.device_worker_id ?? null)) valueChangedFields.push("device_worker_id");
60334
60663
  if (has("agent_kind") && (patch.agent_kind ?? null) !== (locked.agent_kind ?? null)) valueChangedFields.push("agent_kind");
60335
- if (has("delivery_target") && stableJson2(patch.delivery_target ?? null) !== stableJson2(locked.delivery_target ?? null)) valueChangedFields.push("delivery_target");
60664
+ if (has("delivery_target") && stableJson(patch.delivery_target ?? null) !== stableJson(locked.delivery_target ?? null)) valueChangedFields.push("delivery_target");
60336
60665
  if (has("min_cooldown_seconds") && Number(patch.min_cooldown_seconds ?? 0) !== Number(locked.min_cooldown_seconds ?? 0)) valueChangedFields.push("min_cooldown_seconds");
60337
60666
  if (lockedTouchesCadence) {
60338
60667
  if (lockedEffectiveSchedule !== locked.schedule) valueChangedFields.push("schedule");
@@ -64510,11 +64839,13 @@ async function runMetric(input) {
64510
64839
  });
64511
64840
  let rows;
64512
64841
  try {
64513
- rows = await sql2.begin(async (tx) => {
64514
- await tx`SET TRANSACTION READ ONLY`;
64515
- return tx.unsafe(scoped.sql, scoped.params);
64842
+ rows = await boundedQuery(sql2, scoped.sql, scoped.params, {
64843
+ signal: input.signal,
64844
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
64845
+ fence: scoped.scope
64516
64846
  });
64517
64847
  } catch (err) {
64848
+ if (input.signal?.aborted) throw err;
64518
64849
  const failure = classifyReadQueryFailure(err);
64519
64850
  throw new ToolUserError(failure.message, toolErrorHttpStatus(failure.code), failure.code);
64520
64851
  }
@@ -64543,7 +64874,9 @@ async function runPushdownMetric(input, metrics2, backingSql, backingSource) {
64543
64874
  isAdmin: input.isAdmin ?? false,
64544
64875
  connectionSlug: backingSource,
64545
64876
  query,
64546
- limit: METRIC_PUSHDOWN_MAX_ROWS
64877
+ limit: METRIC_PUSHDOWN_MAX_ROWS,
64878
+ signal: input.signal,
64879
+ callerClass: input.callerClass ?? "member"
64547
64880
  });
64548
64881
  } catch (err) {
64549
64882
  throw pushdownFailureError(err, backingSource, "metric");
@@ -64564,6 +64897,7 @@ var init_run_metric = __esm({
64564
64897
  init_client();
64565
64898
  init_connector_pushdown();
64566
64899
  init_bounded_read();
64900
+ init_content_read_bounds();
64567
64901
  init_errors2();
64568
64902
  init_execute_data_sources();
64569
64903
  init_table_schema();
@@ -74380,6 +74714,9 @@ function connectionOperationsExecutor(connection) {
74380
74714
  function connectorChatPlatform(defaultUserName, create2) {
74381
74715
  return {
74382
74716
  connectorTransport: true,
74717
+ // Replies are plain text sent through the connector; a card's buttons
74718
+ // would arrive as an untappable list.
74719
+ rendersActionButtons: false,
74383
74720
  parseSourceMessage: (adapter, row) => adapter.parseSourceRow(row),
74384
74721
  createAdapter: async (_config, context5) => {
74385
74722
  const connection = context5?.connection;
@@ -78823,12 +79160,28 @@ var init_tokens = __esm({
78823
79160
  });
78824
79161
 
78825
79162
  // src/diagnostics.ts
79163
+ import { HTTPException as HTTPException2 } from "hono/http-exception";
78826
79164
  function markErrorReported(c) {
78827
79165
  c.set(ERROR_REPORTED_FLAG, true);
78828
79166
  }
78829
79167
  function isErrorReported(c) {
78830
79168
  return Boolean(c.get(ERROR_REPORTED_FLAG));
78831
79169
  }
79170
+ function routeFailure(response, cause) {
79171
+ return new HTTPException2(response.status, { res: response, cause });
79172
+ }
79173
+ function redactedFailure(error) {
79174
+ const shape = error && typeof error === "object" ? error : {};
79175
+ const cause = shape.cause && typeof shape.cause === "object" ? shape.cause : {};
79176
+ const code = typeof shape.code === "string" ? shape.code : typeof cause.code === "string" ? cause.code : void 0;
79177
+ const frames = typeof shape.stack === "string" ? shape.stack.split("\n").filter((line) => line.trimStart().startsWith("at ")).join("\n") : "";
79178
+ return {
79179
+ name: typeof shape.name === "string" && shape.name ? shape.name : "Error",
79180
+ message: "details withheld at a credential boundary",
79181
+ ...code ? { code } : {},
79182
+ ...frames ? { stack: frames } : {}
79183
+ };
79184
+ }
78832
79185
  function captureServerError(c, error, source, httpStatus) {
78833
79186
  if (error instanceof ToolUserError || isErrorReported(c)) return;
78834
79187
  logger_default.error({
@@ -79155,6 +79508,7 @@ var init_agent_ownership = __esm({
79155
79508
  });
79156
79509
 
79157
79510
  // src/gateway/routes/shared/helpers.ts
79511
+ import { HTTPException as HTTPException3 } from "hono/http-exception";
79158
79512
  function errorResponse(c, message, status) {
79159
79513
  return c.json({ error: message }, status);
79160
79514
  }
@@ -79202,8 +79556,9 @@ async function withOwnedAgent(c, options, handler) {
79202
79556
  }
79203
79557
  return await handler({ session, agentId, access });
79204
79558
  } catch (error) {
79559
+ if (error instanceof HTTPException3) throw error;
79205
79560
  options.logger.error(options.errorLabel, { error, agentId });
79206
- return errorResponse(c, "Internal server error", 500);
79561
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
79207
79562
  }
79208
79563
  }
79209
79564
  var init_helpers = __esm({
@@ -79211,6 +79566,7 @@ var init_helpers = __esm({
79211
79566
  "use strict";
79212
79567
  init_settings_auth();
79213
79568
  init_agent_ownership();
79569
+ init_diagnostics();
79214
79570
  }
79215
79571
  });
79216
79572
 
@@ -79324,7 +79680,7 @@ async function listDeviceWorkers(c) {
79324
79680
  } catch (err) {
79325
79681
  logger_default.error({ error: errorMessage(err) }, "[listDeviceWorkers] Error");
79326
79682
  captureServerError(c, err, "listDeviceWorkers", 500);
79327
- return c.json({ error: errorMessage(err) }, 500);
79683
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79328
79684
  }
79329
79685
  }
79330
79686
  async function mintDeviceChildToken(c) {
@@ -79566,7 +79922,7 @@ async function mintDeviceChildToken(c) {
79566
79922
  } catch (err) {
79567
79923
  logger_default.error({ err: errorMessage(err) }, "[mintDeviceChildToken] failed");
79568
79924
  captureServerError(c, err, "mintDeviceChildToken", 500);
79569
- return c.json({ error: errorMessage(err) }, 500);
79925
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79570
79926
  }
79571
79927
  }
79572
79928
  async function updateDeviceWorkerOrg(c) {
@@ -79690,7 +80046,7 @@ async function updateDeviceWorkerOrg(c) {
79690
80046
  return c.json({ ok: true, ...hasLabel ? { label: nextLabel ?? null } : {} });
79691
80047
  } catch (err) {
79692
80048
  logger_default.error({ error: errorMessage(err) }, "[updateDeviceWorkerOrg] Error");
79693
- return c.json({ error: errorMessage(err) }, 500);
80049
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79694
80050
  }
79695
80051
  }
79696
80052
  async function deleteDeviceWorker(c) {
@@ -79793,7 +80149,7 @@ async function deleteDeviceWorker(c) {
79793
80149
  return c.json({ ok: true });
79794
80150
  } catch (err) {
79795
80151
  logger_default.error({ error: errorMessage(err) }, "[deleteDeviceWorker] Error");
79796
- return c.json({ error: errorMessage(err) }, 500);
80152
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79797
80153
  }
79798
80154
  }
79799
80155
  var DEVICE_WORKER_ID_PATTERN, CHILD_PAT_EXPIRES_IN_DAYS, CHILD_SELF_MINT_ONLY, DEVICE_LABEL_MAX_LEN;
@@ -80098,7 +80454,8 @@ function publicVisitorContext(organizationId, request2) {
80098
80454
  directSearchFederation: false,
80099
80455
  requestUrl: request2.requestUrl,
80100
80456
  baseUrl: request2.baseUrl,
80101
- ...request2.abortSignal ? { abortSignal: request2.abortSignal } : {}
80457
+ ...request2.abortSignal ? { abortSignal: request2.abortSignal } : {},
80458
+ ...request2.deadlineAt !== void 0 ? { deadlineAt: request2.deadlineAt } : {}
80102
80459
  };
80103
80460
  }
80104
80461
  var init_public_browse_context = __esm({
@@ -89012,7 +89369,6 @@ async function buildExactIdScopeWhere(sql2, opts) {
89012
89369
  const params = [];
89013
89370
  const orgScope2 = buildOrgScopeWhere({
89014
89371
  organization_id: opts.organizationId,
89015
- strict_organization_scope: true,
89016
89372
  baseParamIndex: opts.baseParamIndex + params.length
89017
89373
  });
89018
89374
  params.push(...orgScope2.params);
@@ -89024,7 +89380,8 @@ async function buildExactIdScopeWhere(sql2, opts) {
89024
89380
  entityIdLiteral: validatedId,
89025
89381
  scopes,
89026
89382
  alias: "f",
89027
- baseParamIndex: opts.baseParamIndex + params.length
89383
+ baseParamIndex: opts.baseParamIndex + params.length,
89384
+ ownerOrganizationId: opts.organizationId
89028
89385
  });
89029
89386
  entityFilter = ` AND ${link.sql}`;
89030
89387
  params.push(...link.params);
@@ -90019,20 +90376,7 @@ async function getContentImpl(args, env, ctx) {
90019
90376
  ON et.id = e.entity_type_id
90020
90377
  AND et.deleted_at IS NULL
90021
90378
  WHERE ev.id = ANY(${pgBigintArray(args.content_ids)}::bigint[])
90022
- AND (
90023
- ev.organization_id = ${ctx.organizationId}
90024
- OR ev.linked_org_ids @> ARRAY[${ctx.organizationId}]::text[]
90025
- OR EXISTS (
90026
- SELECT 1 FROM entities scoped_entity
90027
- WHERE scoped_entity.id = ANY(ev.entity_ids)
90028
- AND scoped_entity.organization_id = ${ctx.organizationId}
90029
- )
90030
- OR EXISTS (
90031
- SELECT 1 FROM connections scoped_connection
90032
- WHERE scoped_connection.id = ev.connection_id
90033
- AND scoped_connection.organization_id = ${ctx.organizationId}
90034
- )
90035
- )
90379
+ AND ev.organization_id = ${ctx.organizationId}
90036
90380
  `;
90037
90381
  requestedRecords.push(...eventTypeRows.flatMap((row) => row.id === null ? [] : [{ id: row.id }]));
90038
90382
  for (const row of eventTypeRows) {
@@ -90305,7 +90649,7 @@ async function getContentImpl(args, env, ctx) {
90305
90649
  logger_default.info(`[get_content] ${args.query ? "Search query provided" : "Listing content"}`);
90306
90650
  const searchOptions = {
90307
90651
  entity_id: args.entity_id,
90308
- organization_id: !args.entity_id ? ctx.organizationId : void 0,
90652
+ organization_id: ctx.organizationId,
90309
90653
  connection_ids: effectiveConnectionIds,
90310
90654
  feed_ids: args.feed_ids,
90311
90655
  run_ids: args.run_ids,
@@ -92019,6 +92363,54 @@ function verifyClientSecret(secret, storedHash) {
92019
92363
  return false;
92020
92364
  }
92021
92365
  }
92366
+ async function releaseClientHomedInOrganization(tx, organizationId) {
92367
+ const [homed] = await tx`
92368
+ SELECT id FROM oauth_clients
92369
+ WHERE organization_id = ${organizationId}
92370
+ LIMIT 1
92371
+ FOR UPDATE
92372
+ `;
92373
+ if (!homed) return null;
92374
+ const clientId = homed.id;
92375
+ await new OAuthClientsStore(tx).revokeClientForOrganization(clientId, organizationId, null, tx);
92376
+ const [credentials] = await tx`
92377
+ SELECT (
92378
+ EXISTS (
92379
+ SELECT 1 FROM oauth_tokens
92380
+ WHERE client_id = ${clientId} AND revoked_at IS NULL AND expires_at > NOW()
92381
+ )
92382
+ OR EXISTS (
92383
+ SELECT 1 FROM oauth_authorization_codes
92384
+ WHERE client_id = ${clientId} AND expires_at > NOW()
92385
+ )
92386
+ OR EXISTS (
92387
+ SELECT 1 FROM oauth_device_codes
92388
+ WHERE client_id = ${clientId} AND expires_at > NOW()
92389
+ )
92390
+ OR EXISTS (
92391
+ SELECT 1 FROM mcp_sessions
92392
+ WHERE client_id = ${clientId} AND expires_at > NOW()
92393
+ )
92394
+ ) AS live
92395
+ `;
92396
+ if (credentials.live || await anyEventNamesClient(tx, clientId)) {
92397
+ await tx`
92398
+ UPDATE oauth_clients SET organization_id = NULL, updated_at = NOW()
92399
+ WHERE id = ${clientId}
92400
+ `;
92401
+ return "detached";
92402
+ }
92403
+ await tx`DELETE FROM oauth_clients WHERE id = ${clientId}`;
92404
+ return "deleted";
92405
+ }
92406
+ async function anyEventNamesClient(tx, clientId) {
92407
+ await tx`SET LOCAL enable_seqscan = off`;
92408
+ const [probe] = await tx`
92409
+ SELECT EXISTS (SELECT 1 FROM events WHERE client_id = ${clientId}) AS named
92410
+ `;
92411
+ await tx`SET LOCAL enable_seqscan TO DEFAULT`;
92412
+ return probe.named;
92413
+ }
92022
92414
  var OAuthClientsStore;
92023
92415
  var init_clients = __esm({
92024
92416
  "src/auth/oauth/clients.ts"() {
@@ -92197,9 +92589,12 @@ var init_clients = __esm({
92197
92589
  * the operation to the owner displayed in the connected-apps inventory.
92198
92590
  * Omitting `userId` retains the org-wide operation used by administrative
92199
92591
  * cleanup paths. The registration remains intact for other organizations.
92592
+ *
92593
+ * A caller that must commit the revoke together with its own writes passes
92594
+ * its open `transaction`; otherwise the revoke runs in one of its own.
92200
92595
  */
92201
- async revokeClientForOrganization(clientId, organizationId, userId) {
92202
- return this.sql.begin(async (tx) => {
92596
+ async revokeClientForOrganization(clientId, organizationId, userId, transaction) {
92597
+ const revoke = async (tx) => {
92203
92598
  const clientLock = await tx`
92204
92599
  SELECT id FROM oauth_clients WHERE id = ${clientId} FOR UPDATE
92205
92600
  `;
@@ -92319,7 +92714,8 @@ var init_clients = __esm({
92319
92714
  RETURNING session_id
92320
92715
  `;
92321
92716
  return revokedTokens.length > 0 || narrowedAuthorizationCodes.length > 0 || deletedAuthorizationCodes.length > 0 || narrowedDeviceCodes.length > 0 || deletedDeviceCodes.length > 0 || deletedSessions.length > 0;
92322
- });
92717
+ };
92718
+ return transaction ? revoke(transaction) : this.sql.begin(revoke);
92323
92719
  }
92324
92720
  /**
92325
92721
  * List clients for a user
@@ -94915,10 +95311,7 @@ async function fetchContentSnippets(gate, workspaceSlug, query, contentLimit, en
94915
95311
  {
94916
95312
  organization_id: gate.organizationId,
94917
95313
  signal,
94918
- ...entityId != null && {
94919
- entity_id: entityId,
94920
- strict_organization_scope: true
94921
- },
95314
+ ...entityId != null && { entity_id: entityId },
94922
95315
  ...excludeWorkspaceAudit && { exclude_workspace_audit: true },
94923
95316
  ...excludeOperationalTrail && { exclude_operational_trail: true },
94924
95317
  // Recall is a memory surface, not an ops console: internal tool-invocation
@@ -95175,6 +95568,17 @@ async function coverageForLocalSources(gate, workspaceSlug, local_sources) {
95175
95568
  const [discovered] = await Promise.allSettled([discoverSourceFeeds(gate, workspaceSlug)]);
95176
95569
  return buildCoverage(workspaceSlug, local_sources, discovered);
95177
95570
  }
95571
+ function reportLocalRecallFailure(gate, store, reason) {
95572
+ const { name, code } = reason ?? {};
95573
+ const report = describeError(
95574
+ { name, code, message: `Local ${store} recall failed` },
95575
+ { scope: `search_memory ${store} recall` }
95576
+ );
95577
+ logger_default.error(
95578
+ { organization_id: gate.organizationId, ...errorReportLogFields(report) },
95579
+ `[search] local ${store} recall failed (pg_code=${report.code ?? "none"}): ${getErrorMessage(reason)}`
95580
+ );
95581
+ }
95178
95582
  async function gatherLocalRecall(gate, ctx) {
95179
95583
  const shouldSearchConversation = Boolean(ctx.query && gate.agentId && ctx.entityId == null);
95180
95584
  const contentPromise = fetchContentSnippets(
@@ -95211,10 +95615,7 @@ async function gatherLocalRecall(gate, ctx) {
95211
95615
  local_sources.push("events");
95212
95616
  } else {
95213
95617
  localRecallFailed = true;
95214
- const pgCode = contentResult.reason?.code;
95215
- logger_default.warn(
95216
- `[search] local events recall failed (pg_code=${typeof pgCode === "string" ? pgCode : "none"}): ${getErrorMessage(contentResult.reason)}`
95217
- );
95618
+ reportLocalRecallFailure(gate, "events", contentResult.reason);
95218
95619
  }
95219
95620
  if (shouldSearchConversation && conversationResult.status === "fulfilled") {
95220
95621
  local_sources.push("channel_messages");
@@ -95223,9 +95624,7 @@ async function gatherLocalRecall(gate, ctx) {
95223
95624
  }
95224
95625
  } else if (conversationResult.status === "rejected") {
95225
95626
  localRecallFailed = true;
95226
- logger_default.warn(
95227
- `[search] local conversation recall failed: ${getErrorMessage(conversationResult.reason)}`
95228
- );
95627
+ reportLocalRecallFailure(gate, "conversation", conversationResult.reason);
95229
95628
  }
95230
95629
  result.coverage = buildCoverage(
95231
95630
  ctx.workspaceSlug,
@@ -96402,7 +96801,7 @@ async function metricSeriesImpl(args, _env, ctx) {
96402
96801
  if (rangeEndMs <= rangeStartMs) {
96403
96802
  throw new ToolUserError("metric_series: end must be after start");
96404
96803
  }
96405
- const { sql: scopedSql, params } = validateAndScopeQuery(args.sql, orgId, {
96804
+ const { sql: scopedSql, params, scope } = validateAndScopeQuery(args.sql, orgId, {
96406
96805
  // Emit the safe column allowlist (not SELECT *) so a member charting e.g.
96407
96806
  // `connections` can't pull credential columns the allowlist withholds.
96408
96807
  safeColumns: SAFE_COLUMN_DEFS,
@@ -96420,12 +96819,13 @@ async function metricSeriesImpl(args, _env, ctx) {
96420
96819
  const db = getDb();
96421
96820
  let rows;
96422
96821
  try {
96423
- rows = await db.begin(async (tx) => {
96424
- await tx.unsafe("SET TRANSACTION READ ONLY");
96425
- await tx.unsafe(`SET LOCAL statement_timeout = ${STATEMENT_TIMEOUT_MS}`);
96426
- return tx.unsafe(scopedSql, params);
96822
+ rows = await boundedQuery(db, scopedSql, params, {
96823
+ signal: ctx.abortSignal,
96824
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
96825
+ fence: scope
96427
96826
  });
96428
96827
  } catch (err) {
96828
+ if (ctx.abortSignal?.aborted) throw err;
96429
96829
  logger_default.warn({ err, orgId }, "[metric_series] query failed");
96430
96830
  const failure = classifyReadQueryFailure(err);
96431
96831
  throw new ToolUserError(failure.message, toolErrorHttpStatus(failure.code), failure.code);
@@ -96494,7 +96894,7 @@ async function metricSeriesImpl(args, _env, ctx) {
96494
96894
  const tabular = keptRows.map((r) => columns.map((c) => r[c]));
96495
96895
  return { columns, rows: tabular, data_quality: quality };
96496
96896
  }
96497
- var MetricSeriesSchema, STATEMENT_TIMEOUT_MS, MAX_ROWS, DEFAULT_RANGE_START_MS, DEFAULT_FUTURE_SLACK_MS, TIME_COLUMN_PATTERN, metricSeries;
96897
+ var MetricSeriesSchema, MAX_ROWS, DEFAULT_RANGE_START_MS, DEFAULT_FUTURE_SLACK_MS, TIME_COLUMN_PATTERN, metricSeries;
96498
96898
  var init_metric_series = __esm({
96499
96899
  "src/tools/admin/metric_series.ts"() {
96500
96900
  "use strict";
@@ -96502,6 +96902,7 @@ var init_metric_series = __esm({
96502
96902
  init_execute_data_sources();
96503
96903
  init_table_schema();
96504
96904
  init_bounded_read();
96905
+ init_content_read_bounds();
96505
96906
  init_errors2();
96506
96907
  init_logger2();
96507
96908
  init_scope();
@@ -96539,7 +96940,6 @@ var init_metric_series = __esm({
96539
96940
  })
96540
96941
  )
96541
96942
  });
96542
- STATEMENT_TIMEOUT_MS = 5e3;
96543
96943
  MAX_ROWS = 2e3;
96544
96944
  DEFAULT_RANGE_START_MS = Date.parse("2000-01-01T00:00:00Z");
96545
96945
  DEFAULT_FUTURE_SLACK_MS = 24 * 60 * 60 * 1e3;
@@ -96562,6 +96962,8 @@ async function queryMetricImpl(args, _env, ctx) {
96562
96962
  segment: args.segment,
96563
96963
  entityId: args.entity_id,
96564
96964
  userId: authzScopeFromToolContext(ctx).principal,
96965
+ signal: ctx.abortSignal,
96966
+ callerClass: sourceCallerClass(ctx),
96565
96967
  // Workspace-identity audit rows are owner/admin/system-only; ordinary
96566
96968
  // members must not move a declared metric by counting lifecycle events.
96567
96969
  excludeWorkspaceAudit: !canReadWorkspaceIdentity(ctx),
@@ -96578,6 +96980,7 @@ var QueryMetricSchema, queryMetric;
96578
96980
  var init_query_metric = __esm({
96579
96981
  "src/tools/admin/query_metric.ts"() {
96580
96982
  "use strict";
96983
+ init_source_admission();
96581
96984
  init_run_metric();
96582
96985
  init_access_control();
96583
96986
  init_scope();
@@ -104307,7 +104710,9 @@ async function queryConnection(ctx, isAdmin, connectionSlug, querySql2) {
104307
104710
  isAdmin,
104308
104711
  connectionSlug,
104309
104712
  query: querySql2.trim(),
104310
- limit: CLIENT_QUERY_MAX_ROWS
104713
+ limit: CLIENT_QUERY_MAX_ROWS,
104714
+ signal: ctx.abortSignal,
104715
+ callerClass: sourceCallerClass(ctx)
104311
104716
  });
104312
104717
  } catch (err) {
104313
104718
  throw pushdownFailureError(err, connectionSlug, "query");
@@ -104534,7 +104939,8 @@ function buildClientSDK(ctx, env, opts) {
104534
104939
  try {
104535
104940
  rows = await boundedQuery(getDb(), boundedSql, scoped.params, {
104536
104941
  signal: workspaceCtx.abortSignal,
104537
- statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS
104942
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
104943
+ fence: scoped.scope
104538
104944
  });
104539
104945
  } catch (error) {
104540
104946
  if (workspaceCtx.abortSignal?.aborted) throw error;
@@ -104565,6 +104971,7 @@ var init_client_sdk = __esm({
104565
104971
  init_errors2();
104566
104972
  init_url_builder();
104567
104973
  init_connector_pushdown();
104974
+ init_source_admission();
104568
104975
  init_content_read_bounds();
104569
104976
  init_method_metadata();
104570
104977
  init_workspace_activity();
@@ -110120,14 +110527,14 @@ ${event.options.map((o, i) => `${i + 1}. ${o}`).join("\n")}`;
110120
110527
  label: prompt.title
110121
110528
  })
110122
110529
  );
110123
- const card2 = Card3({ children: [Actions3(buttons)] });
110124
- const fallbackText = event.prompts.map((prompt, i) => `${i + 1}. ${prompt.title}`).join("\n");
110125
- await postWithFallback(
110126
- thread,
110127
- { card: card2, fallbackText },
110128
- connectionId,
110129
- "suggestion interaction"
110130
- );
110530
+ try {
110531
+ await thread.post({ card: Card3({ children: [Actions3(buttons)] }) });
110532
+ } catch (error) {
110533
+ logger60.warn(
110534
+ { connectionId, suggestionId: event.id, error: String(error) },
110535
+ "Failed to post suggestion interaction"
110536
+ );
110537
+ }
110131
110538
  }
110132
110539
  );
110133
110540
  interactionService.on("question:created", onQuestionCreated);
@@ -111811,7 +112218,7 @@ async function createPreviewClaim(c) {
111811
112218
  { err: errorMessage(err), platform },
111812
112219
  "[preview] create claim failed"
111813
112220
  );
111814
- return c.json({ error: errorMessage(err) }, 500);
112221
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
111815
112222
  }
111816
112223
  }
111817
112224
  return c.json({ error: "Could not allocate a unique preview code" }, 500);
@@ -112104,6 +112511,7 @@ var init_slack2 = __esm({
112104
112511
  init_chat_link_authorization();
112105
112512
  init_command_spelling();
112106
112513
  init_platforms();
112514
+ init_diagnostics();
112107
112515
  SLACK_PLATFORM = "slack";
112108
112516
  CLAIM_SCOPE = "slack-preview-claim";
112109
112517
  DEFAULT_TTL_MINUTES = 15;
@@ -115226,7 +115634,7 @@ async function heartbeat(c) {
115226
115634
  ...steer.length > 0 ? { steer } : {}
115227
115635
  });
115228
115636
  } catch (err) {
115229
- return c.json({ error: errorMessage(err) }, 500);
115637
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
115230
115638
  }
115231
115639
  }
115232
115640
  async function ingestConnectorItems(sql2, target, items, checkpoint) {
@@ -115778,7 +116186,7 @@ async function streamContent(c) {
115778
116186
  const message = browserRun ? sanitizeBrowserText(rawMessage) : rawMessage;
115779
116187
  const stack = browserRun ? sanitizeBrowserText(rawStack) : rawStack;
115780
116188
  console.error("[stream] Error:", message, stack);
115781
- return c.json({ error: message, stack }, 500);
116189
+ throw routeFailure(c.json({ error: message, stack }, 500), err);
115782
116190
  }
115783
116191
  }
115784
116192
  async function completeWorkerJob(c) {
@@ -115993,7 +116401,7 @@ async function completeWorkerJob(c) {
115993
116401
  return c.json({ success: true });
115994
116402
  } catch (err) {
115995
116403
  logger_default.error({ error: errorMessage(err) }, "[completeWorkerJob] Error");
115996
- return c.json({ error: errorMessage(err) }, 500);
116404
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
115997
116405
  }
115998
116406
  }
115999
116407
  async function completeAutomationRun(c) {
@@ -116425,7 +116833,7 @@ async function fetchEventsForEmbedding(c) {
116425
116833
  }))
116426
116834
  });
116427
116835
  } catch (err) {
116428
- return c.json({ error: errorMessage(err) }, 500);
116836
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116429
116837
  }
116430
116838
  }
116431
116839
  async function completeEmbeddings(c) {
@@ -116517,7 +116925,7 @@ async function completeEmbeddings(c) {
116517
116925
  return c.json({ success: failed === 0, updated, failed });
116518
116926
  } catch (err) {
116519
116927
  logger_default.error({ error: errorMessage(err) }, "[completeEmbeddings] Error");
116520
- return c.json({ error: errorMessage(err) }, 500);
116928
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116521
116929
  }
116522
116930
  }
116523
116931
  async function emitAuthArtifact(c) {
@@ -116532,7 +116940,7 @@ async function emitAuthArtifact(c) {
116532
116940
  `;
116533
116941
  return c.json({ success: true });
116534
116942
  } catch (err) {
116535
- return c.json({ error: errorMessage(err) }, 500);
116943
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116536
116944
  }
116537
116945
  }
116538
116946
  async function pollAuthSignal(c) {
@@ -116553,7 +116961,7 @@ async function pollAuthSignal(c) {
116553
116961
  });
116554
116962
  return c.json(consumed ? { signal: consumed } : {});
116555
116963
  } catch (err) {
116556
- return c.json({ error: errorMessage(err) }, 500);
116964
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116557
116965
  }
116558
116966
  }
116559
116967
  async function completeAuthRun(c) {
@@ -116631,7 +117039,7 @@ async function completeAuthRun(c) {
116631
117039
  return c.json({ success: true });
116632
117040
  } catch (err) {
116633
117041
  logger_default.error({ error: errorMessage(err) }, "[completeAuthRun] Error");
116634
- return c.json({ error: errorMessage(err) }, 500);
117042
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116635
117043
  }
116636
117044
  }
116637
117045
  async function completeActionRun(c) {
@@ -116713,7 +117121,7 @@ async function completeActionRun(c) {
116713
117121
  } catch (err) {
116714
117122
  await deleteMaterializedArtifacts(publishedActionArtifactIds);
116715
117123
  logger_default.error({ error: errorMessage(err) }, "[completeActionRun] Error");
116716
- return c.json({ error: errorMessage(err) }, 500);
117124
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116717
117125
  }
116718
117126
  }
116719
117127
  var DRY_RUN_PREVIEW_LIMIT, DRY_RUN_CONTENT_CHARS, MAX_ORIGIN_ID_BYTES, MISSING_COMPLETE_WINDOW_NUDGE;
@@ -116759,6 +117167,7 @@ var init_run_lifecycle = __esm({
116759
117167
  init_shared4();
116760
117168
  init_run_outcome();
116761
117169
  init_run_lease();
117170
+ init_diagnostics();
116762
117171
  DRY_RUN_PREVIEW_LIMIT = 50;
116763
117172
  DRY_RUN_CONTENT_CHARS = 500;
116764
117173
  MAX_ORIGIN_ID_BYTES = 2048;
@@ -128198,6 +128607,7 @@ var init_middleware = __esm({
128198
128607
  init_revoked_token_store();
128199
128608
  init_agent_turn_inputs();
128200
128609
  init_chat_turn_actor();
128610
+ init_diagnostics();
128201
128611
  authenticateWorker = async (c, next) => {
128202
128612
  const authHeader = c.req.header("authorization");
128203
128613
  if (!authHeader?.startsWith("Bearer ")) {
@@ -128225,7 +128635,7 @@ var init_middleware = __esm({
128225
128635
  if (error instanceof StaleAgentTurnAttemptError) {
128226
128636
  return c.json({ error: error.message }, 409);
128227
128637
  }
128228
- return c.json({ error: "Could not record the tool call for this turn; it was not executed" }, 503);
128638
+ throw routeFailure(c.json({ error: "Could not record the tool call for this turn; it was not executed" }, 503), error);
128229
128639
  }
128230
128640
  }
128231
128641
  c.set("worker", tokenData);
@@ -128466,11 +128876,11 @@ function createAudioRoutes(transcriptionService) {
128466
128876
  });
128467
128877
  } catch (error) {
128468
128878
  logger72.error("Audio synthesis error", { error });
128469
- return errorResponse(
128879
+ throw routeFailure(errorResponse(
128470
128880
  c,
128471
128881
  error instanceof Error ? error.message : "Failed to synthesize audio",
128472
128882
  500
128473
- );
128883
+ ), error);
128474
128884
  }
128475
128885
  });
128476
128886
  router.get("/internal/audio/capabilities", authenticateWorker, async (c) => {
@@ -128495,7 +128905,7 @@ function createAudioRoutes(transcriptionService) {
128495
128905
  });
128496
128906
  } catch (error) {
128497
128907
  logger72.error("Capabilities check error", { error });
128498
- return errorResponse(c, "Failed to check capabilities", 500);
128908
+ throw routeFailure(errorResponse(c, "Failed to check capabilities", 500), error);
128499
128909
  }
128500
128910
  });
128501
128911
  logger72.debug("Internal audio routes registered");
@@ -128510,6 +128920,7 @@ var init_audio = __esm({
128510
128920
  init_middleware();
128511
128921
  init_capture_mode();
128512
128922
  init_turn_write_once();
128923
+ init_diagnostics();
128513
128924
  logger72 = createLogger("internal-audio-routes");
128514
128925
  }
128515
128926
  });
@@ -128652,7 +129063,7 @@ function createConversationsRoutes() {
128652
129063
  return c.json({ conversations: targets.map(toPublicTarget) });
128653
129064
  } catch (error) {
128654
129065
  logger73.error(`list conversations failed: ${String(error)}`);
128655
- return errorResponse(c, "Internal server error", 500);
129066
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128656
129067
  }
128657
129068
  });
128658
129069
  router.get("/conversations/read", authenticateWorker, async (c) => {
@@ -128696,7 +129107,7 @@ function createConversationsRoutes() {
128696
129107
  return c.json({ messages: [], nextCursor: null, hasMore: false });
128697
129108
  } catch (error) {
128698
129109
  logger73.error(`read conversation failed: ${String(error)}`);
128699
- return errorResponse(c, "Internal server error", 500);
129110
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128700
129111
  }
128701
129112
  });
128702
129113
  router.post("/conversations/send", authenticateWorker, async (c) => {
@@ -128808,7 +129219,7 @@ function createConversationsRoutes() {
128808
129219
  });
128809
129220
  } catch (error) {
128810
129221
  logger73.error(`send conversation failed: ${String(error)}`);
128811
- return errorResponse(c, "Internal server error", 500);
129222
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128812
129223
  }
128813
129224
  });
128814
129225
  router.post("/conversations/present-event", authenticateWorker, async (c) => {
@@ -128883,7 +129294,7 @@ function createConversationsRoutes() {
128883
129294
  });
128884
129295
  } catch (error) {
128885
129296
  logger73.error(`present event failed: ${String(error)}`);
128886
- return errorResponse(c, "Internal server error", 500);
129297
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128887
129298
  }
128888
129299
  });
128889
129300
  router.post("/conversations/schedule-followup", authenticateWorker, async (c) => {
@@ -128976,7 +129387,7 @@ function createConversationsRoutes() {
128976
129387
  return c.json({ scheduled: true, schedule: schedule.schedule });
128977
129388
  } catch (error) {
128978
129389
  logger73.error(`schedule followup failed: ${String(error)}`);
128979
- return errorResponse(c, "Internal server error", 500);
129390
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128980
129391
  }
128981
129392
  });
128982
129393
  function messageRoute(label, handler) {
@@ -129050,7 +129461,7 @@ function createConversationsRoutes() {
129050
129461
  return await handler(c, target, body2);
129051
129462
  } catch (error) {
129052
129463
  logger73.error(`${label} failed: ${String(error)}`);
129053
- return errorResponse(c, "Internal server error", 500);
129464
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
129054
129465
  }
129055
129466
  };
129056
129467
  }
@@ -129142,6 +129553,7 @@ var init_conversations2 = __esm({
129142
129553
  init_capture_mode();
129143
129554
  init_turn_write_once();
129144
129555
  init_errors2();
129556
+ init_diagnostics();
129145
129557
  logger73 = createLogger("conversations-routes");
129146
129558
  MAX_CONTENT_LENGTH = 4e3;
129147
129559
  MASS_MENTION = /@(channel|here|everyone)\b|<!(channel|here|everyone|subteam)\b/i;
@@ -129280,7 +129692,7 @@ function createFileRoutes(platformRegistry2, artifactStore, publicGatewayUrl2) {
129280
129692
  error: getErrorMessage(error),
129281
129693
  stack: error instanceof Error ? error.stack : void 0
129282
129694
  });
129283
- return errorResponse(c, "Failed to upload file", 500);
129695
+ throw routeFailure(errorResponse(c, "Failed to upload file", 500), error);
129284
129696
  }
129285
129697
  });
129286
129698
  router.post("/upload-batch", limitArtifactUploadBody, authenticateWorker, async (c) => {
@@ -129383,7 +129795,7 @@ function createFileRoutes(platformRegistry2, artifactStore, publicGatewayUrl2) {
129383
129795
  error: getErrorMessage(error),
129384
129796
  stack: error instanceof Error ? error.stack : void 0
129385
129797
  });
129386
- return errorResponse(c, "Failed to batch upload files", 500);
129798
+ throw routeFailure(errorResponse(c, "Failed to batch upload files", 500), error);
129387
129799
  }
129388
129800
  });
129389
129801
  return router;
@@ -129398,6 +129810,7 @@ var init_files = __esm({
129398
129810
  init_middleware();
129399
129811
  init_capture_mode();
129400
129812
  init_turn_write_once();
129813
+ init_diagnostics();
129401
129814
  logger74 = createLogger("file-routes");
129402
129815
  MAX_ARTIFACT_UPLOAD_REQUEST_BYTES = MAX_ARTIFACT_BYTES + 1024 * 1024;
129403
129816
  limitArtifactUploadBody = bodyLimit({
@@ -129465,7 +129878,7 @@ function createImageRoutes(imageGenerationService) {
129465
129878
  });
129466
129879
  } catch (error) {
129467
129880
  logger75.error("Image generation error", { error });
129468
- return errorResponse(c, "Failed to generate image", 500);
129881
+ throw routeFailure(errorResponse(c, "Failed to generate image", 500), error);
129469
129882
  }
129470
129883
  });
129471
129884
  router.get("/internal/images/capabilities", authenticateWorker, async (c) => {
@@ -129490,7 +129903,7 @@ function createImageRoutes(imageGenerationService) {
129490
129903
  });
129491
129904
  } catch (error) {
129492
129905
  logger75.error("Image capabilities check error", { error });
129493
- return errorResponse(c, "Failed to check capabilities", 500);
129906
+ throw routeFailure(errorResponse(c, "Failed to check capabilities", 500), error);
129494
129907
  }
129495
129908
  });
129496
129909
  logger75.debug("Internal image routes registered");
@@ -129505,6 +129918,7 @@ var init_images = __esm({
129505
129918
  init_middleware();
129506
129919
  init_capture_mode();
129507
129920
  init_turn_write_once();
129921
+ init_diagnostics();
129508
129922
  logger75 = createLogger("internal-image-routes");
129509
129923
  }
129510
129924
  });
@@ -129649,7 +130063,7 @@ function createInteractionRoutes(interactionService) {
129649
130063
  error: getErrorMessage(error),
129650
130064
  stack: error instanceof Error ? error.stack : void 0
129651
130065
  });
129652
- return errorResponse(c, "Failed to post question", 500);
130066
+ throw routeFailure(errorResponse(c, "Failed to post question", 500), error);
129653
130067
  }
129654
130068
  }
129655
130069
  );
@@ -129669,6 +130083,7 @@ var init_interactions = __esm({
129669
130083
  init_middleware();
129670
130084
  init_capture_mode();
129671
130085
  init_turn_write_once();
130086
+ init_diagnostics();
129672
130087
  logger76 = createLogger("internal-interaction-routes");
129673
130088
  }
129674
130089
  });
@@ -132256,7 +132671,7 @@ function createAgentApi(config) {
132256
132671
  });
132257
132672
  } catch (error) {
132258
132673
  logger84.error("Failed to send platform message", { error });
132259
- return c.json({ success: false, error: "Internal server error" }, 500);
132674
+ throw routeFailure(c.json({ success: false, error: "Internal server error" }, 500), error);
132260
132675
  }
132261
132676
  }
132262
132677
  const session = preSession;
@@ -132415,6 +132830,7 @@ var init_agent = __esm({
132415
132830
  init_openapi_responses();
132416
132831
  init_settings_auth();
132417
132832
  init_activity_feed();
132833
+ init_diagnostics();
132418
132834
  SSE_PING_INTERVAL_MS = 3e4;
132419
132835
  logger84 = createLogger("agent-api");
132420
132836
  MAX_CONNECTIONS_PER_AGENT = 5;
@@ -134164,7 +134580,7 @@ function createAgentRoutes(config) {
134164
134580
  });
134165
134581
  } catch (error) {
134166
134582
  logger86.error("Failed to create agent", { error });
134167
- return errorResponse(c, "Internal server error", 500);
134583
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
134168
134584
  }
134169
134585
  });
134170
134586
  router.get("/", async (c) => {
@@ -134190,7 +134606,7 @@ function createAgentRoutes(config) {
134190
134606
  return c.json({ agents });
134191
134607
  } catch (error) {
134192
134608
  logger86.error("Failed to list agents", { error });
134193
- return errorResponse(c, "Failed to list agents", 500);
134609
+ throw routeFailure(errorResponse(c, "Failed to list agents", 500), error);
134194
134610
  }
134195
134611
  });
134196
134612
  const ownershipAccessConfig = {
@@ -134247,6 +134663,7 @@ var init_agents2 = __esm({
134247
134663
  init_org_context();
134248
134664
  init_agent_ownership();
134249
134665
  init_helpers();
134666
+ init_diagnostics();
134250
134667
  logger86 = createLogger("agent-routes");
134251
134668
  MAX_AGENTS_PER_USER = parseInt(
134252
134669
  process.env.MAX_AGENTS_PER_USER || "0",
@@ -135841,13 +136258,13 @@ function createAppInstallRoutes(deps) {
135841
136258
  },
135842
136259
  "GitHub App install callback failed"
135843
136260
  );
135844
- return c.html(
136261
+ throw routeFailure(c.html(
135845
136262
  renderOAuthErrorPage(
135846
136263
  "github_install_failed",
135847
136264
  error instanceof Error ? error.message : "GitHub App install failed."
135848
136265
  ),
135849
136266
  500
135850
- );
136267
+ ), error);
135851
136268
  }
135852
136269
  });
135853
136270
  return router;
@@ -135986,13 +136403,13 @@ function mountOAuthCodeExchangeRoutes(router, params) {
135986
136403
  { provider: provider3, error: String(error) },
135987
136404
  "OAuth install failed to park as pending"
135988
136405
  );
135989
- return c.html(
136406
+ throw routeFailure(c.html(
135990
136407
  renderOAuthErrorPage(
135991
136408
  `${provider3}_install_failed`,
135992
136409
  error instanceof Error ? error.message : `${display} install failed.`
135993
136410
  ),
135994
136411
  500
135995
- );
136412
+ ), error);
135996
136413
  }
135997
136414
  });
135998
136415
  }
@@ -136057,6 +136474,7 @@ var init_app_install = __esm({
136057
136474
  init_registry2();
136058
136475
  init_queue_service();
136059
136476
  init_github_team_graph();
136477
+ init_diagnostics();
136060
136478
  logger88 = createLogger("app-install-routes");
136061
136479
  GITHUB_CONNECTOR_KEY2 = "github";
136062
136480
  GITHUB_PROVIDER = "github";
@@ -136316,7 +136734,7 @@ function createAppWebhookRoutes(deps) {
136316
136734
  { provider: providerName, error: String(error) },
136317
136735
  "[app-webhook] handleDelivery failed"
136318
136736
  );
136319
- return json2(500, { error: "Failed to handle delivery" });
136737
+ throw routeFailure(json2(500, { error: "Failed to handle delivery" }), error);
136320
136738
  }
136321
136739
  }
136322
136740
  const tenant = provider3.extractTenant(rawBody, c.req.raw.headers);
@@ -136361,7 +136779,7 @@ function createAppWebhookRoutes(deps) {
136361
136779
  { provider: providerName, installationId: install.id, error: String(error) },
136362
136780
  "[app-webhook] onDelivery trigger failed"
136363
136781
  );
136364
- return json2(500, { error: "Failed to handle delivery" });
136782
+ throw routeFailure(json2(500, { error: "Failed to handle delivery" }), error);
136365
136783
  }
136366
136784
  });
136367
136785
  return router;
@@ -136372,6 +136790,7 @@ var init_app_webhooks = __esm({
136372
136790
  "use strict";
136373
136791
  init_src();
136374
136792
  init_client();
136793
+ init_diagnostics();
136375
136794
  init_webhook_delivery();
136376
136795
  init_webhook_ingest();
136377
136796
  logger89 = createLogger("app-webhook-routes");
@@ -136514,13 +136933,13 @@ function createConnectAuthRoutes(config) {
136514
136933
  return c.redirect(authUrl);
136515
136934
  } catch (error) {
136516
136935
  logger90.error("Failed to start browser OAuth handoff", { error });
136517
- return c.html(
136936
+ throw routeFailure(c.html(
136518
136937
  renderPage(
136519
136938
  "OAuth Login Failed",
136520
136939
  "The gateway could not start the browser OAuth flow."
136521
136940
  ),
136522
136941
  500
136523
- );
136942
+ ), error);
136524
136943
  }
136525
136944
  });
136526
136945
  router.get("/connect/claim", async (c) => {
@@ -136602,13 +137021,13 @@ function createConnectAuthRoutes(config) {
136602
137021
  return c.redirect(connectState.returnUrl);
136603
137022
  } catch (error) {
136604
137023
  logger90.error("Failed to complete browser OAuth handoff", { error });
136605
- return c.html(
137024
+ throw routeFailure(c.html(
136606
137025
  renderPage(
136607
137026
  "OAuth Login Failed",
136608
137027
  "The gateway could not complete the browser OAuth flow."
136609
137028
  ),
136610
137029
  500
136611
- );
137030
+ ), error);
136612
137031
  }
136613
137032
  });
136614
137033
  return router;
@@ -136623,6 +137042,7 @@ var init_connect_auth = __esm({
136623
137042
  init_oauth_templates();
136624
137043
  init_public_url();
136625
137044
  init_settings_auth();
137045
+ init_diagnostics();
136626
137046
  logger90 = createLogger("connect-auth-routes");
136627
137047
  AUTH_REQUEST_TTL_SECONDS = 10 * 60;
136628
137048
  CONNECT_OAUTH_TTL_SECONDS = 10 * 60;
@@ -136665,7 +137085,7 @@ function createConnectionWebhookRoutes(manager) {
136665
137085
  return await manager.handleWebhook(connectionId, c.req.raw);
136666
137086
  } catch (error) {
136667
137087
  logger91.error({ connectionId, error: String(error) }, "Webhook error");
136668
- return c.json({ error: "Webhook processing failed" }, 500);
137088
+ throw routeFailure(c.json({ error: "Webhook processing failed" }, 500), error);
136669
137089
  }
136670
137090
  });
136671
137091
  return router;
@@ -136700,6 +137120,7 @@ var init_connections3 = __esm({
136700
137120
  "src/gateway/routes/public/connections.ts"() {
136701
137121
  "use strict";
136702
137122
  init_src();
137123
+ init_diagnostics();
136703
137124
  logger91 = createLogger("connection-routes");
136704
137125
  LOCAL_TEST_PLATFORMS = ["slack", "telegram", "whatsapp"];
136705
137126
  }
@@ -136737,10 +137158,10 @@ function createPublicFileRoutes(artifactStore) {
136737
137158
  logger92.error("Artifact storage unavailable during download", {
136738
137159
  code: error instanceof ArtifactStorageError ? error.code : "UNKNOWN"
136739
137160
  });
136740
- return c.json(
137161
+ throw routeFailure(c.json(
136741
137162
  { success: false, error: "File storage temporarily unavailable" },
136742
137163
  503
136743
- );
137164
+ ), redactedFailure(error));
136744
137165
  }
136745
137166
  if (!artifact) {
136746
137167
  return c.json({ success: false, error: "File not found" }, 404);
@@ -136772,6 +137193,7 @@ var init_files2 = __esm({
136772
137193
  "src/gateway/routes/public/files.ts"() {
136773
137194
  "use strict";
136774
137195
  init_src();
137196
+ init_diagnostics();
136775
137197
  init_artifact_store();
136776
137198
  logger92 = createLogger("public-files");
136777
137199
  }
@@ -137241,6 +137663,10 @@ function errorResult(message, startTime, code = "VALIDATION") {
137241
137663
  retryable: isRetryable(code)
137242
137664
  };
137243
137665
  }
137666
+ function earliestDeadline(read, host2) {
137667
+ if (read === void 0) return host2;
137668
+ return host2 === void 0 ? read : Math.min(read, host2);
137669
+ }
137244
137670
  async function querySqlImpl(args, env, ctx, options) {
137245
137671
  const startTime = Date.now();
137246
137672
  const title = args.title?.trim() || void 0;
@@ -137307,7 +137733,9 @@ async function querySqlImpl(args, env, ctx, options) {
137307
137733
  query: baseSql,
137308
137734
  exactMatch: options?.exactMatch,
137309
137735
  selection: options?.selection,
137310
- deadlineAt: options?.deadlineAt,
137736
+ deadlineAt: earliestDeadline(options?.deadlineAt, ctx.deadlineAt),
137737
+ signal: ctx.abortSignal,
137738
+ callerClass: sourceCallerClass(ctx),
137311
137739
  limit: limit2,
137312
137740
  offset: offset2,
137313
137741
  sort: args.sort_by ? { column: args.sort_by, order: args.sort_order === "desc" ? "desc" : "asc" } : void 0
@@ -137331,6 +137759,7 @@ async function querySqlImpl(args, env, ctx, options) {
137331
137759
  const window2 = args.window_token ? await resolveWindowQueryContext(args.window_token, env, ctx, getDb()) : void 0;
137332
137760
  let scopedSql;
137333
137761
  let params;
137762
+ let scope;
137334
137763
  let tableRefs;
137335
137764
  try {
137336
137765
  const scoped = validateAndScopeQuery(baseSql, targetOrgId, {
@@ -137350,6 +137779,7 @@ async function querySqlImpl(args, env, ctx, options) {
137350
137779
  });
137351
137780
  scopedSql = scoped.sql;
137352
137781
  params = scoped.params;
137782
+ scope = scoped.scope;
137353
137783
  tableRefs = scoped.tableRefs;
137354
137784
  } catch (err) {
137355
137785
  return fail2(getErrorMessage(err), err instanceof ToolUserError ? err.code : void 0);
@@ -137406,7 +137836,8 @@ async function querySqlImpl(args, env, ctx, options) {
137406
137836
  const signal = ctx.abortSignal;
137407
137837
  const result = await boundedRead(getDb(), {
137408
137838
  signal,
137409
- statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS
137839
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
137840
+ fence: scope
137410
137841
  }, async (tx) => {
137411
137842
  const data = await cancellable(tx.unsafe(dataSql, params), signal);
137412
137843
  const rows2 = Array.isArray(data) ? data : [];
@@ -137490,6 +137921,7 @@ var init_query_sql = __esm({
137490
137921
  init_client();
137491
137922
  init_window_read_context();
137492
137923
  init_connector_pushdown();
137924
+ init_source_admission();
137493
137925
  init_execute_data_sources();
137494
137926
  init_logger2();
137495
137927
  init_bounded_read();
@@ -142813,7 +143245,7 @@ function createGatewayApp(options) {
142813
143245
  return await handler({ c, mod, providerId });
142814
143246
  } catch (error) {
142815
143247
  logger94.error(errorLabel, { error });
142816
- return c.json({ error: errorLabel }, 500);
143248
+ throw routeFailure(c.json({ error: errorLabel }, 500), error);
142817
143249
  }
142818
143250
  };
142819
143251
  authRouter.post(
@@ -143251,6 +143683,7 @@ var init_gateway = __esm({
143251
143683
  init_install_org();
143252
143684
  init_landing();
143253
143685
  init_settings_auth();
143686
+ init_diagnostics();
143254
143687
  logger94 = createLogger("gateway-startup");
143255
143688
  chatPendingInstallCompletions = {
143256
143689
  slack: completeSlackPendingInstall
@@ -147330,12 +147763,12 @@ async function handleListToolsAuthenticated(proxy, c, auth, mcpId) {
147330
147763
  return c.json({ tools, instructions });
147331
147764
  } catch (error) {
147332
147765
  logger107.error("Failed to list tools", { mcpId, error });
147333
- return c.json(
147766
+ throw routeFailure(c.json(
147334
147767
  {
147335
147768
  error: `Failed to connect to MCP '${mcpId}': ${error instanceof Error ? error.message : "Unknown error"}`
147336
147769
  },
147337
147770
  502
147338
- );
147771
+ ), error);
147339
147772
  }
147340
147773
  }
147341
147774
  async function handleCallTool(proxy, c) {
@@ -147472,14 +147905,14 @@ async function handleCallToolAuthenticated(proxy, c, auth, mcpId, toolName) {
147472
147905
  );
147473
147906
  }
147474
147907
  logger107.error("Failed to call tool", { mcpId, toolName, error });
147475
- return c.json(
147908
+ throw routeFailure(c.json(
147476
147909
  {
147477
147910
  content: [],
147478
147911
  isError: true,
147479
147912
  error: `Failed to connect to MCP '${mcpId}': ${error instanceof Error ? error.message : "Unknown error"}`
147480
147913
  },
147481
147914
  502
147482
- );
147915
+ ), error);
147483
147916
  }
147484
147917
  }
147485
147918
  async function handleListAllTools(proxy, c) {
@@ -147526,6 +147959,7 @@ var init_proxy_rest_routes = __esm({
147526
147959
  init_http_response();
147527
147960
  init_proxy_shared();
147528
147961
  init_proxy_upstream();
147962
+ init_diagnostics();
147529
147963
  logger107 = createLogger("mcp-proxy");
147530
147964
  }
147531
147965
  });
@@ -148440,7 +148874,7 @@ function createTranscriptRoutes() {
148440
148874
  logger113.error(
148441
148875
  `Snapshot INSERT failed: ${getErrorMessage(err)}`
148442
148876
  );
148443
- return c.json({ error: "Internal error" }, 500);
148877
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
148444
148878
  }
148445
148879
  });
148446
148880
  app2.delete("/snapshot", async (c) => {
@@ -148467,7 +148901,7 @@ function createTranscriptRoutes() {
148467
148901
  logger113.error(
148468
148902
  `Snapshot DELETE failed: ${getErrorMessage(err)}`
148469
148903
  );
148470
- return c.json({ error: "Internal error" }, 500);
148904
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
148471
148905
  }
148472
148906
  });
148473
148907
  return app2;
@@ -148480,6 +148914,7 @@ var init_transcript_routes = __esm({
148480
148914
  init_client();
148481
148915
  init_automation_run_intent();
148482
148916
  init_transcript_snapshot();
148917
+ init_diagnostics();
148483
148918
  logger113 = createLogger("worker-transcript");
148484
148919
  }
148485
148920
  });
@@ -148498,6 +148933,7 @@ var init_worker_gateway = __esm({
148498
148933
  init_turn_liveness();
148499
148934
  init_deployment_identity();
148500
148935
  init_transcript_routes();
148936
+ init_diagnostics();
148501
148937
  logger114 = createLogger("worker-gateway");
148502
148938
  WorkerGateway = class {
148503
148939
  app;
@@ -148710,7 +149146,7 @@ var init_worker_gateway = __esm({
148710
149146
  return c.json({ success: true });
148711
149147
  } catch (error) {
148712
149148
  logger114.error(`Error handling worker response: ${error}`);
148713
- return c.json({ error: "Failed to process response" }, 500);
149149
+ throw routeFailure(c.json({ error: "Failed to process response" }, 500), error);
148714
149150
  }
148715
149151
  }
148716
149152
  /**
@@ -148849,7 +149285,7 @@ var init_worker_gateway = __esm({
148849
149285
  });
148850
149286
  } catch (error) {
148851
149287
  logger114.error("Failed to generate session context", { err: error });
148852
- return c.json({ error: "session_context_error" }, 500);
149288
+ throw routeFailure(c.json({ error: "session_context_error" }, 500), error);
148853
149289
  }
148854
149290
  }
148855
149291
  async authenticateWorker(c) {
@@ -149506,6 +149942,7 @@ var init_grant_store = __esm({
149506
149942
  // src/gateway/proxy/secret-proxy.ts
149507
149943
  import { randomUUID as randomUUID33 } from "node:crypto";
149508
149944
  import { Hono as Hono21 } from "hono";
149945
+ import { HTTPException as HTTPException4 } from "hono/http-exception";
149509
149946
  function noProviderCredentials(c) {
149510
149947
  return c.json(
149511
149948
  {
@@ -149609,6 +150046,7 @@ var init_secret_proxy = __esm({
149609
150046
  init_turn_liveness();
149610
150047
  init_rate_limiter();
149611
150048
  init_provider_health_status();
150049
+ init_diagnostics();
149612
150050
  logger117 = createLogger("secret-proxy");
149613
150051
  RESOLVE_FAILURE_THRESHOLD = 20;
149614
150052
  RESOLVE_FAILURE_WINDOW_MS = 5 * 60 * 1e3;
@@ -149807,6 +150245,7 @@ var init_secret_proxy = __esm({
149807
150245
  try {
149808
150246
  return await this.forward(c);
149809
150247
  } catch (error) {
150248
+ if (error instanceof HTTPException4) throw error;
149810
150249
  logger117.error(
149811
150250
  {
149812
150251
  err: error instanceof Error ? { name: error.name, message: error.message, stack: error.stack } : error,
@@ -149814,7 +150253,7 @@ var init_secret_proxy = __esm({
149814
150253
  },
149815
150254
  "Secret proxy error"
149816
150255
  );
149817
- return c.json({ error: "Internal proxy error" }, 500);
150256
+ throw routeFailure(c.json({ error: "Internal proxy error" }, 500), error);
149818
150257
  }
149819
150258
  }
149820
150259
  /**
@@ -150053,10 +150492,10 @@ var init_secret_proxy = __esm({
150053
150492
  { urlAgentId, err: String(err) },
150054
150493
  "agentOrgResolver failed \u2014 rejecting request to preserve org isolation"
150055
150494
  );
150056
- return c.json(
150495
+ throw routeFailure(c.json(
150057
150496
  { error: "Service Unavailable: failed to resolve agent organization" },
150058
150497
  503
150059
- );
150498
+ ), err);
150060
150499
  }
150061
150500
  }
150062
150501
  if (providerContext?.organizationId && expectedOrganizationId && providerContext.organizationId !== expectedOrganizationId) {
@@ -150290,7 +150729,7 @@ var init_secret_proxy = __esm({
150290
150729
  { method, provider: resolvedSlug },
150291
150730
  "Custom provider request failed"
150292
150731
  );
150293
- return c.json({ error: "Internal proxy error" }, 500);
150732
+ throw routeFailure(c.json({ error: "Internal proxy error" }, 500), redactedFailure(error));
150294
150733
  }
150295
150734
  if (!response.ok) {
150296
150735
  logger117.warn(
@@ -154981,9 +155420,10 @@ async function enqueueAgentTurn(data, deps) {
154981
155420
  conversation_id: data.conversationId,
154982
155421
  platform: data.platform
154983
155422
  },
154984
- // Follow-up chips only where a person is waiting on this reply: never an
154985
- // Automation run or another server-dispatched (headless) turn.
154986
- ...!automationIntent && !isHeadlessSource(data.platformMetadata?.source) ? { follow_ups: true } : {}
155423
+ // Follow-up chips only where a person is waiting on this reply and can
155424
+ // tap them: never an Automation run, another server-dispatched (headless)
155425
+ // turn, or a platform that would render the buttons as an inert list.
155426
+ ...!automationIntent && !isHeadlessSource(data.platformMetadata?.source) && getPlatformDescriptor(data.platform)?.rendersActionButtons !== false ? { follow_ups: true } : {}
154987
155427
  };
154988
155428
  const settings = await agentSettings.getSettings(data.agentId, {
154989
155429
  organizationId: data.organizationId
@@ -155178,6 +155618,7 @@ var init_agent_turn_producer = __esm({
155178
155618
  init_agent_turn_inputs();
155179
155619
  init_initiator();
155180
155620
  init_automation_run_session();
155621
+ init_platforms();
155181
155622
  init_automation_run_intent();
155182
155623
  init_agent_turn_attachments();
155183
155624
  init_turn_liveness();
@@ -157051,8 +157492,8 @@ function createLobuOrgContextMiddleware() {
157051
157492
  let resolvedOrg;
157052
157493
  try {
157053
157494
  resolvedOrg = await getOrgBySlug(orgHeader);
157054
- } catch {
157055
- return c.json({ error: "Unable to resolve organization" }, 503);
157495
+ } catch (error) {
157496
+ throw routeFailure(c.json({ error: "Unable to resolve organization" }, 503), error);
157056
157497
  }
157057
157498
  if (!resolvedOrg) {
157058
157499
  return c.json({ error: `Unknown organization "${orgHeader}"` }, 404);
@@ -157082,11 +157523,11 @@ function createLobuOrgContextMiddleware() {
157082
157523
  if (!orgId) {
157083
157524
  try {
157084
157525
  orgId = await resolveDefaultOrgId(user.id);
157085
- } catch {
157086
- return c.json(
157526
+ } catch (error) {
157527
+ throw routeFailure(c.json(
157087
157528
  { error: "Unable to resolve organization membership" },
157088
157529
  503
157089
- );
157530
+ ), error);
157090
157531
  }
157091
157532
  if (!orgId) {
157092
157533
  return c.json({ error: "No organization membership found" }, 404);
@@ -157320,6 +157761,7 @@ var init_gateway2 = __esm({
157320
157761
  init_auth2();
157321
157762
  init_pat_auth();
157322
157763
  init_client();
157764
+ init_diagnostics();
157323
157765
  init_platform();
157324
157766
  init_gateway();
157325
157767
  init_app_install_credentials();
@@ -161235,22 +161677,22 @@ async function batchTotalContentCounts(db, opts) {
161235
161677
  const counts = /* @__PURE__ */ new Map();
161236
161678
  const entityIds = opts.entityIds;
161237
161679
  if (entityIds.length === 0) return counts;
161238
- const edgedRows = await db.unsafe(
161680
+ const edgedRows = await cancellable(db.unsafe(
161239
161681
  `SELECT v.id FROM (VALUES ${entityIds.map((eid) => `(${eid})`).join(",")}) v(id)
161240
161682
  WHERE EXISTS (SELECT 1 FROM entity_relationships ir WHERE ir.from_entity_id = v.id AND ir.deleted_at IS NULL)
161241
161683
  OR EXISTS (SELECT 1 FROM entity_relationships ir WHERE ir.to_entity_id = v.id AND ir.deleted_at IS NULL)`
161242
- );
161684
+ ), opts.signal);
161243
161685
  const edgedIds = edgedRows.map((row) => Number(row.id));
161244
161686
  const membersByEntity = new Map(entityIds.map((eid) => [eid, [eid]]));
161245
161687
  for (const eid of edgedIds) membersByEntity.set(eid, []);
161246
161688
  if (edgedIds.length > 0) {
161247
- const memberRows = await db.unsafe(
161689
+ const memberRows = await cancellable(db.unsafe(
161248
161690
  edgedIds.map((eid) => `SELECT ${eid}::bigint AS eid, members.id AS member_id FROM (${identityMemberIdsSql(`${eid}::bigint`)}) members`).join("\nUNION ALL\n")
161249
- );
161691
+ ), opts.signal);
161250
161692
  for (const row of memberRows) membersByEntity.get(Number(row.eid))?.push(Number(row.member_id));
161251
161693
  }
161252
161694
  const membersSql = (eid) => `'${pgBigintArray(membersByEntity.get(eid) ?? [eid])}'::bigint[]`;
161253
- const scopeRows = await db.unsafe(
161695
+ const scopeRows = await cancellable(db.unsafe(
161254
161696
  entityIds.map(
161255
161697
  (eid) => `SELECT ${eid}::bigint AS eid, identity.namespace, identity.identifier, identity.scope_key
161256
161698
  FROM entity_identities identity
@@ -161258,7 +161700,7 @@ async function batchTotalContentCounts(db, opts) {
161258
161700
  AND identity.deleted_at IS NULL
161259
161701
  AND identity.namespace = ANY('${pgTextArray([...STANDARD_IDENTITY_NAMESPACES])}'::text[])`
161260
161702
  ).join("\nUNION ALL\n")
161261
- );
161703
+ ), opts.signal);
161262
161704
  const scopesByEntity = /* @__PURE__ */ new Map();
161263
161705
  for (const row of scopeRows) {
161264
161706
  const eid = Number(row.eid);
@@ -161292,10 +161734,10 @@ async function batchTotalContentCounts(db, opts) {
161292
161734
  ${probed}
161293
161735
  ) u`);
161294
161736
  }
161295
- const rows = await db.unsafe(
161737
+ const rows = await cancellable(db.unsafe(
161296
161738
  arms.join("\nUNION ALL\n"),
161297
161739
  params
161298
- );
161740
+ ), opts.signal);
161299
161741
  for (const row of rows) counts.set(Number(row.eid), Number(row.cnt));
161300
161742
  return counts;
161301
161743
  }
@@ -161324,7 +161766,7 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161324
161766
  if (filters.filters?.length && !filters.entity_type) {
161325
161767
  throw new ToolUserError("Attribute filters require entity_type", 400, "VALIDATION");
161326
161768
  }
161327
- let segmentFilter = null;
161769
+ let segmentIds = null;
161328
161770
  if (filters.entity_type) {
161329
161771
  const etRows = await sql2`
161330
161772
  SELECT et.id, et.metrics_config, et.metadata_schema,
@@ -161351,10 +161793,15 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161351
161793
  "VALIDATION"
161352
161794
  );
161353
161795
  }
161354
- segmentFilter = compileEntitySegmentFilter(
161355
- filters.entity_type,
161356
- etRows[0] ? Number(etRows[0].id) : null,
161357
- etRows[0]?.metrics_config ?? null,
161796
+ segmentIds = await readEntitySegmentIds(
161797
+ sql2,
161798
+ compileEntitySegmentFilter(
161799
+ filters.entity_type,
161800
+ etRows[0] ? Number(etRows[0].id) : null,
161801
+ etRows[0]?.metrics_config ?? null,
161802
+ filters.segment,
161803
+ ctx
161804
+ ),
161358
161805
  filters.segment,
161359
161806
  ctx
161360
161807
  );
@@ -161371,7 +161818,7 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161371
161818
  }
161372
161819
  }
161373
161820
  const conditions = ["{e}.deleted_at IS NULL", identityRootSql("{e}")];
161374
- const params = segmentFilter ? [...segmentFilter.params] : [];
161821
+ const params = segmentIds ? [pgBigintArray(segmentIds)] : [];
161375
161822
  let paramIdx = params.length + 1;
161376
161823
  conditions.push(`{e}.organization_id = $${paramIdx++}`);
161377
161824
  params.push(ctx.organizationId);
@@ -161397,10 +161844,10 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161397
161844
  conditions.push(entityReadPolicySql(readRestrictions, "{e}", params));
161398
161845
  const renderWhere = (eAlias, etAlias) => conditions.map(
161399
161846
  (c) => c.replace(/\{e\}\./g, `${eAlias}.`).replace(/\{et\}\./g, `${etAlias}.`)
161400
- ).concat(memberConditions.length || segmentFilter ? [identityMemberExistsSql(
161847
+ ).concat(memberConditions.length || segmentIds ? [identityMemberExistsSql(
161401
161848
  `${eAlias}.id`,
161402
161849
  "member",
161403
- [...memberConditions, ...segmentFilter ? [`member.id IN (${segmentFilter.sql})`] : []].join(" AND ")
161850
+ [...memberConditions, ...segmentIds ? ["member.id = ANY($1::bigint[])"] : []].join(" AND ")
161404
161851
  )] : []).join(" AND ");
161405
161852
  const whereClause = renderWhere("e", "et");
161406
161853
  const sortColumnMap = {
@@ -161469,29 +161916,30 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161469
161916
  ${plainSort ? "" : `OFFSET ${offset}`}`;
161470
161917
  const fetchPage = async (db) => {
161471
161918
  if (!plainSort) {
161472
- const totalCountResult3 = await db.unsafe(
161919
+ const totalCountResult3 = await cancellable(db.unsafe(
161473
161920
  `SELECT CAST(COUNT(*) AS INTEGER) as total_count ${baseQuery}`,
161474
161921
  params
161475
- );
161476
- const result3 = await db.unsafe(pageQuery(), params);
161922
+ ), ctx.abortSignal);
161923
+ const result3 = await cancellable(db.unsafe(pageQuery(), params), ctx.abortSignal);
161477
161924
  return { totalCountResult: totalCountResult3, result: result3, hasMoreIds: null };
161478
161925
  }
161479
- const pageIds = (await db.unsafe(pageIdQuery, params.slice(0, filterParamCount))).map((row) => Number(row.id));
161926
+ const pageIds = (await cancellable(db.unsafe(pageIdQuery, params.slice(0, filterParamCount)), ctx.abortSignal)).map((row) => Number(row.id));
161480
161927
  const hasMoreIds2 = pageIds.length > limit;
161481
161928
  const ids = hasMoreIds2 ? pageIds.slice(0, limit) : pageIds;
161482
161929
  const [totalCountResult2, result2, contentCounts] = await Promise.all([
161483
- db.unsafe(
161930
+ cancellable(db.unsafe(
161484
161931
  `SELECT CAST(COUNT(*) AS INTEGER) as total_count ${countFrom}`,
161485
161932
  params.slice(0, filterParamCount)
161486
- ),
161487
- ids.length > 0 ? db.unsafe(
161933
+ ), ctx.abortSignal),
161934
+ ids.length > 0 ? cancellable(db.unsafe(
161488
161935
  pageQuery(`AND e.id = ANY('${pgBigintArray(ids)}'::bigint[])`),
161489
161936
  params.slice(0, enrichParamCount)
161490
- ) : Promise.resolve([]),
161937
+ ), ctx.abortSignal) : Promise.resolve([]),
161491
161938
  batchTotalContentCounts(db, {
161492
161939
  organizationId: ctx.organizationId,
161493
161940
  userId: ctx.userId ?? null,
161494
- entityIds: ids
161941
+ entityIds: ids,
161942
+ signal: ctx.abortSignal
161495
161943
  })
161496
161944
  ]);
161497
161945
  for (const row of result2) {
@@ -161499,24 +161947,31 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161499
161947
  }
161500
161948
  return { totalCountResult: totalCountResult2, result: result2, hasMoreIds: hasMoreIds2 };
161501
161949
  };
161502
- const { totalCountResult, result, hasMoreIds } = segmentFilter ? await sql2.begin(async (tx) => {
161503
- await tx.unsafe("SET TRANSACTION READ ONLY");
161504
- await tx.unsafe("SET LOCAL statement_timeout = '5s'");
161505
- return fetchPage(tx);
161506
- }).catch((error) => {
161950
+ const { totalCountResult, result, hasMoreIds } = await fetchPage(sql2);
161951
+ const hasMore = hasMoreIds ?? result.length > limit;
161952
+ const entities = hasMore ? result.slice(0, limit) : result;
161953
+ const totalCount = Number(totalCountResult[0]?.total_count || 0);
161954
+ const readableEntities = await filterEntityReadRows(sql2, await attachEntityIdentities(sql2, entities), readRestrictions);
161955
+ return { entities: readableEntities, hasMore, totalCount, limit, offset, sortBy, sortOrder: normalizedSortOrder };
161956
+ }
161957
+ async function readEntitySegmentIds(sql2, segment, segmentName, ctx) {
161958
+ try {
161959
+ const rows = await boundedQuery(sql2, segment.sql, segment.params, {
161960
+ signal: ctx.abortSignal,
161961
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
161962
+ fence: segment.scope
161963
+ });
161964
+ return rows.map((row) => Number(row.id));
161965
+ } catch (error) {
161966
+ if (ctx.abortSignal?.aborted) throw error;
161507
161967
  const code = classifyToolError({ pgCode: error?.code });
161508
161968
  if (code !== "VALIDATION" && code !== "UPSTREAM_TIMEOUT") throw error;
161509
161969
  throw new ToolUserError(
161510
- `Segment '${filters.segment}' failed: ${getErrorMessage(error)}`,
161970
+ `Segment '${segmentName}' failed: ${classifyReadQueryFailure(error).message}`,
161511
161971
  toolErrorHttpStatus(code),
161512
161972
  code
161513
161973
  );
161514
- }) : await fetchPage(sql2);
161515
- const hasMore = hasMoreIds ?? result.length > limit;
161516
- const entities = hasMore ? result.slice(0, limit) : result;
161517
- const totalCount = Number(totalCountResult[0]?.total_count || 0);
161518
- const readableEntities = await filterEntityReadRows(sql2, await attachEntityIdentities(sql2, entities), readRestrictions);
161519
- return { entities: readableEntities, hasMore, totalCount, limit, offset, sortBy, sortOrder: normalizedSortOrder };
161974
+ }
161520
161975
  }
161521
161976
  function compileEntitySegmentFilter(entityType, entityTypeId, metrics2, segmentName, ctx) {
161522
161977
  const segment = metrics2?.segments?.[segmentName];
@@ -161561,7 +162016,7 @@ function compileEntitySegmentFilter(entityType, entityTypeId, metrics2, segmentN
161561
162016
  "VALIDATION"
161562
162017
  );
161563
162018
  }
161564
- return { sql: scoped.sql, params: scoped.params };
162019
+ return { sql: scoped.sql, params: scoped.params, scope: scoped.scope };
161565
162020
  }
161566
162021
  function derivedRowSlug(row) {
161567
162022
  let raw;
@@ -161788,6 +162243,8 @@ var init_entity_management = __esm({
161788
162243
  init_entity_field_merge();
161789
162244
  init_entity_hooks();
161790
162245
  init_errors2();
162246
+ init_bounded_read();
162247
+ init_content_read_bounds();
161791
162248
  init_entity_write_denial_audit();
161792
162249
  init_execute_data_sources();
161793
162250
  init_logger2();
@@ -163272,6 +163729,7 @@ var init_routes = __esm({
163272
163729
  init_public_origin();
163273
163730
  init_resolve_session();
163274
163731
  init_deletion_state();
163732
+ init_diagnostics();
163275
163733
  oauthRoutes = new Hono23();
163276
163734
  INVALID_DEVICE_CODE_MESSAGE = "Invalid or expired user code";
163277
163735
  MAX_TOKEN_REQUEST_BYTES = 32 * 1024;
@@ -163342,7 +163800,7 @@ var init_routes = __esm({
163342
163800
  }
163343
163801
  } catch (err) {
163344
163802
  console.warn("[OAuth] Rate limit check failed:", err);
163345
- return c.json(createOAuthError("server_error", "Registration temporarily unavailable"), 503);
163803
+ throw routeFailure(c.json(createOAuthError("server_error", "Registration temporarily unavailable"), 503), err);
163346
163804
  }
163347
163805
  }
163348
163806
  let metadata;
@@ -163384,7 +163842,7 @@ var init_routes = __esm({
163384
163842
  return c.json(client2, 201);
163385
163843
  } catch (error) {
163386
163844
  console.error("[OAuth] Client registration failed:", error);
163387
- return c.json(createOAuthError("server_error", "Registration failed"), 500);
163845
+ throw routeFailure(c.json(createOAuthError("server_error", "Registration failed"), 500), error);
163388
163846
  }
163389
163847
  });
163390
163848
  oauthRoutes.get("/oauth/authorize", async (c) => {
@@ -163663,7 +164121,7 @@ var init_routes = __esm({
163663
164121
  return c.json({ redirect_url: redirectUrl.toString() });
163664
164122
  } catch (error) {
163665
164123
  console.error("[OAuth] Failed to create authorization code:", error);
163666
- return c.json(createOAuthError("server_error", "Failed to create authorization code"), 500);
164124
+ throw routeFailure(c.json(createOAuthError("server_error", "Failed to create authorization code"), 500), error);
163667
164125
  }
163668
164126
  });
163669
164127
  oauthRoutes.post("/oauth/device_authorization", async (c) => {
@@ -163729,7 +164187,7 @@ var init_routes = __esm({
163729
164187
  }
163730
164188
  } catch (err) {
163731
164189
  console.warn("[OAuth] Device-email rate limit check failed:", err);
163732
- return c.json(createOAuthError("server_error", "Temporarily unavailable"), 503);
164190
+ throw routeFailure(c.json(createOAuthError("server_error", "Temporarily unavailable"), 503), err);
163733
164191
  }
163734
164192
  }
163735
164193
  const parsed = await parseRequestBody(c);
@@ -165880,7 +166338,7 @@ function createChatIdentityRoutes(overrides = {}) {
165880
166338
  cookies = await deps.signOut(c.req.raw, c.env);
165881
166339
  } catch (error) {
165882
166340
  logger_default.warn({ error }, "Chat identity link could not sign the browser out to switch accounts");
165883
- return c.html(SWITCH_FAILED_PAGE, 502);
166341
+ throw routeFailure(c.html(SWITCH_FAILED_PAGE, 502), error);
165884
166342
  }
165885
166343
  for (const cookie of cookies) c.header("Set-Cookie", cookie, { append: true });
165886
166344
  return c.redirect(loginContinuation2(token, loginProviderForChatPlatform(claim.platform)), 303);
@@ -165929,6 +166387,7 @@ var init_chat_identity_routes = __esm({
165929
166387
  init_html();
165930
166388
  init_logger2();
165931
166389
  init_join_public();
166390
+ init_diagnostics();
165932
166391
  PATH = "/connect/chat-identity";
165933
166392
  DEFAULT_DEPS4 = {
165934
166393
  session: async (request2, env) => resolveSession(await createAuth(env, request2), request2.headers),
@@ -165951,7 +166410,7 @@ var init_chat_identity_routes = __esm({
165951
166410
 
165952
166411
  // src/connect/routes.ts
165953
166412
  import { Hono as Hono29 } from "hono";
165954
- import { HTTPException as HTTPException2 } from "hono/http-exception";
166413
+ import { HTTPException as HTTPException5 } from "hono/http-exception";
165955
166414
  import { createMiddleware } from "hono/factory";
165956
166415
  function getBaseUrl2(c) {
165957
166416
  return getPublicWebUrl(c.req.url) ?? "";
@@ -166553,14 +167012,14 @@ var init_routes4 = __esm({
166553
167012
  const queued = await createSyncRun(feedId, c.env, tx);
166554
167013
  if (!queued.ok) {
166555
167014
  const error = queued.reason === "connector_uninstalled" ? "The connector is no longer installed in this workspace." : queued.reason === "connector_version_unrunnable" ? "The connector version has no runnable code." : describeSyncRunSkip(queued.reason);
166556
- throw new HTTPException2(409, { res: c.json({ error }, 409) });
167015
+ throw new HTTPException5(409, { res: c.json({ error }, 409) });
166557
167016
  }
166558
167017
  const [current] = await tx`
166559
167018
  SELECT status, consecutive_failures FROM feeds
166560
167019
  WHERE id = ${feedId} AND deleted_at IS NULL
166561
167020
  `;
166562
167021
  if (!current || current.status === "paused" && shouldHardPauseFeed(Number(current.consecutive_failures))) {
166563
- throw new HTTPException2(409, { res: c.json({
167022
+ throw new HTTPException5(409, { res: c.json({
166564
167023
  error: "Resume a feed paused after repeated failures before validating this connection."
166565
167024
  }, 409) });
166566
167025
  }
@@ -170847,6 +171306,7 @@ var init_agent_routes = __esm({
170847
171306
  init_postgres_stores();
170848
171307
  init_postgres_secret_store();
170849
171308
  init_provider_secrets();
171309
+ init_diagnostics();
170850
171310
  routes2 = new Hono32();
170851
171311
  configStore2 = createPostgresAgentConfigStore();
170852
171312
  LEGACY_MODEL_FIELDS = [
@@ -171582,12 +172042,12 @@ var init_agent_routes = __esm({
171582
172042
  try {
171583
172043
  await reconcileAgentAuthProfiles(agentId, user.id, authProfiles);
171584
172044
  } catch (error) {
171585
- return c.json(
172045
+ throw routeFailure(c.json(
171586
172046
  {
171587
172047
  error: error instanceof Error ? error.message : "Failed to persist auth profiles"
171588
172048
  },
171589
172049
  503
171590
- );
172050
+ ), error);
171591
172051
  }
171592
172052
  }
171593
172053
  }
@@ -172704,7 +173164,7 @@ async function resolvePublicPath(...args) {
172704
173164
  if (eventIds.length > 0) {
172705
173165
  const systemRows = await getDb().unsafe(
172706
173166
  `WITH preview_events AS MATERIALIZED (
172707
- SELECT id, organization_id, entity_ids, metadata, linked_org_ids
173167
+ SELECT id, organization_id, entity_ids, metadata
172708
173168
  FROM events WHERE id IN (${eventIds.join(",")})
172709
173169
  )
172710
173170
  SELECT DISTINCT ev.id
@@ -172727,8 +173187,13 @@ async function resolvePublicPath(...args) {
172727
173187
  }
172728
173188
  return resolved;
172729
173189
  }
172730
- function buildToolContext(requestUrl, organizationId) {
172731
- return publicVisitorContext(organizationId, { requestUrl, baseUrl: getPublicOrigin(requestUrl) });
173190
+ function buildToolContext(requestUrl, organizationId, signal) {
173191
+ return publicVisitorContext(organizationId, {
173192
+ requestUrl,
173193
+ baseUrl: getPublicOrigin(requestUrl),
173194
+ abortSignal: signal,
173195
+ deadlineAt: Date.now() + PUBLIC_RENDER_DEADLINE_MS
173196
+ });
172732
173197
  }
172733
173198
  function escapeAttribute(value) {
172734
173199
  return escapeHtml(value);
@@ -172903,9 +173368,8 @@ async function getPublicEntityType(organizationId, slug) {
172903
173368
  );
172904
173369
  return rows[0] ?? null;
172905
173370
  }
172906
- async function getPublicEntityTypeList(organizationId, env, requestUrl, entityTypeSlug) {
173371
+ async function getPublicEntityTypeList(organizationId, env, ctx, entityTypeSlug) {
172907
173372
  const sql2 = getDb();
172908
- const ctx = buildToolContext(requestUrl, organizationId);
172909
173373
  const [result, entityTypeRow] = await Promise.all([
172910
173374
  listEntities(
172911
173375
  {
@@ -173367,7 +173831,7 @@ function applyBootstrapStrip(model, sub) {
173367
173831
  bootstrap: { ...model.bootstrap, path: stripSubdomainPrefix(model.bootstrap.path, sub) }
173368
173832
  };
173369
173833
  }
173370
- async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg) {
173834
+ async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg, signal) {
173371
173835
  const rawPath = `/${path15.replace(/^\/+|\/+$/g, "")}`;
173372
173836
  if (subdomainOrg && SUBDOMAIN_GLOBAL_ROUTES.has(rawPath.split("/")[1] ?? "")) return null;
173373
173837
  const normalizedPath = subdomainOrg && rawPath !== `/${subdomainOrg}` && !rawPath.startsWith(`/${subdomainOrg}/`) ? `/${subdomainOrg}${rawPath === "/" ? "" : rawPath}` : rawPath;
@@ -173379,7 +173843,7 @@ async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg) {
173379
173843
  if (segments[1] && PUBLIC_APP_ROUTE_PREFIXES.has(segments[1])) return null;
173380
173844
  const organization2 = await getPublicOrganizationBySlug(ownerSlug);
173381
173845
  if (!organization2) return null;
173382
- const toolCtx = buildToolContext(requestUrl, organization2.id);
173846
+ const toolCtx = buildToolContext(requestUrl, organization2.id, signal);
173383
173847
  const localPath = (target) => stripSubdomainPrefix(target, subdomainOrg);
173384
173848
  try {
173385
173849
  if (segments.length === 1) {
@@ -173403,7 +173867,7 @@ async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg) {
173403
173867
  }
173404
173868
  const [ownerResolvedPath, entityList] = await Promise.all([
173405
173869
  resolvePublicPath({ path: `/${organization2.slug}`, include_bootstrap: true }, env, toolCtx),
173406
- getPublicEntityTypeList(organization2.id, env, requestUrl, entityTypeDefinition.slug)
173870
+ getPublicEntityTypeList(organization2.id, env, toolCtx, entityTypeDefinition.slug)
173407
173871
  ]);
173408
173872
  const entityType = {
173409
173873
  ...entityTypeDefinition,
@@ -173598,7 +174062,7 @@ function buildSitemapXml(entries) {
173598
174062
  </urlset>
173599
174063
  `;
173600
174064
  }
173601
- var PUBLIC_HTML_CACHE_CONTROL, PUBLIC_XML_CACHE_CONTROL, PUBLIC_LIST_LIMIT, PUBLIC_APP_ROUTE_PREFIXES, SUBDOMAIN_GLOBAL_ROUTES, COUNT_PLURALS, OVERRIDDEN_META, PUBLIC_XML_CACHE;
174065
+ var PUBLIC_HTML_CACHE_CONTROL, PUBLIC_XML_CACHE_CONTROL, PUBLIC_LIST_LIMIT, PUBLIC_APP_ROUTE_PREFIXES, SUBDOMAIN_GLOBAL_ROUTES, PUBLIC_RENDER_DEADLINE_MS, COUNT_PLURALS, OVERRIDDEN_META, PUBLIC_XML_CACHE;
173602
174066
  var init_public_pages = __esm({
173603
174067
  "src/public-pages.ts"() {
173604
174068
  "use strict";
@@ -173619,6 +174083,7 @@ var init_public_pages = __esm({
173619
174083
  ...REMOVED_OWNER_SEGMENTS
173620
174084
  ]);
173621
174085
  SUBDOMAIN_GLOBAL_ROUTES = /* @__PURE__ */ new Set(["auth", "oauth", "account", "me"]);
174086
+ PUBLIC_RENDER_DEADLINE_MS = 2e4;
173622
174087
  COUNT_PLURALS = { entity: "entities" };
173623
174088
  OVERRIDDEN_META = [
173624
174089
  "description",
@@ -174937,7 +175402,7 @@ function createSmokeRoutes() {
174937
175402
  logger136.error(
174938
175403
  `Smoke dispatch INSERT failed: ${getErrorMessage(err)}`
174939
175404
  );
174940
- return c.json({ error: "Internal error" }, 500);
175405
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
174941
175406
  }
174942
175407
  });
174943
175408
  return app2;
@@ -174949,6 +175414,7 @@ var init_smoke = __esm({
174949
175414
  init_src();
174950
175415
  init_client();
174951
175416
  init_constant_time_equal();
175417
+ init_diagnostics();
174952
175418
  logger136 = createLogger("smoke-dispatch");
174953
175419
  FORWARDED_HEADERS = [
174954
175420
  "x-forwarded-for",
@@ -175019,8 +175485,8 @@ async function fetchWorkerHttp(c) {
175019
175485
  request: raw.request,
175020
175486
  signal: c.req.raw.signal
175021
175487
  }));
175022
- } catch {
175023
- return c.json({ error: "Gateway HTTP request failed" }, 502);
175488
+ } catch (error) {
175489
+ throw routeFailure(c.json({ error: "Gateway HTTP request failed" }, 502), redactedFailure(error));
175024
175490
  }
175025
175491
  }
175026
175492
  var HttpFetchRequestSchema;
@@ -175030,6 +175496,7 @@ var init_http_fetch = __esm({
175030
175496
  init_protocol();
175031
175497
  init_intervals();
175032
175498
  init_client();
175499
+ init_diagnostics();
175033
175500
  init_http_auth();
175034
175501
  HttpFetchRequestSchema = Type63.Object({
175035
175502
  worker_id: Type63.String({ minLength: 1 }),
@@ -177862,7 +178329,7 @@ async function getActiveAuthRun(c) {
177862
178329
  `;
177863
178330
  return c.json({ run_id: rows[0]?.id ?? null });
177864
178331
  } catch (err) {
177865
- return c.json({ error: errorMessage(err) }, 500);
178332
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
177866
178333
  }
177867
178334
  }
177868
178335
  async function getAuthRun(c) {
@@ -177920,7 +178387,7 @@ async function getAuthRun(c) {
177920
178387
  } : null
177921
178388
  });
177922
178389
  } catch (err) {
177923
- return c.json({ error: errorMessage(err) }, 500);
178390
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
177924
178391
  }
177925
178392
  }
177926
178393
  async function postAuthSignal(c) {
@@ -177968,7 +178435,7 @@ async function postAuthSignal(c) {
177968
178435
  }
177969
178436
  return c.json({ success: true });
177970
178437
  } catch (err) {
177971
- return c.json({ error: errorMessage(err) }, 500);
178438
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
177972
178439
  }
177973
178440
  }
177974
178441
  var init_auth_runs = __esm({
@@ -177978,6 +178445,7 @@ var init_auth_runs = __esm({
177978
178445
  init_client();
177979
178446
  init_errors2();
177980
178447
  init_resolve_session();
178448
+ init_diagnostics();
177981
178449
  }
177982
178450
  });
177983
178451
 
@@ -178018,7 +178486,7 @@ async function triggerAutomationForDevice(c) {
178018
178486
  resolvedDeviceWorkerId = device.id;
178019
178487
  } catch (err) {
178020
178488
  logger_default.error({ error: errorMessage(err) }, "[triggerAutomationForDevice] device lookup failed");
178021
- return c.json({ error: "Internal error" }, 500);
178489
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
178022
178490
  }
178023
178491
  const automationRows = await sql2`
178024
178492
  SELECT id, organization_id, managed_agent_id, status, device_worker_id::text AS device_worker_id
@@ -178069,7 +178537,7 @@ async function triggerAutomationForDevice(c) {
178069
178537
  { error: errorMessage(err), automationId },
178070
178538
  "[triggerAutomationForDevice] enqueue failed"
178071
178539
  );
178072
- return c.json({ error: errorMessage(err) }, 500);
178540
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
178073
178541
  }
178074
178542
  }
178075
178543
  var init_automation_trigger = __esm({
@@ -178079,6 +178547,7 @@ var init_automation_trigger = __esm({
178079
178547
  init_errors2();
178080
178548
  init_logger2();
178081
178549
  init_automation();
178550
+ init_diagnostics();
178082
178551
  }
178083
178552
  });
178084
178553
 
@@ -178146,7 +178615,7 @@ import { fileURLToPath as fileURLToPath8 } from "node:url";
178146
178615
  import { Hono as Hono38 } from "hono";
178147
178616
  import { compress } from "hono/compress";
178148
178617
  import { cors as cors2 } from "hono/cors";
178149
- import { HTTPException as HTTPException3 } from "hono/http-exception";
178618
+ import { HTTPException as HTTPException6 } from "hono/http-exception";
178150
178619
  async function resolveWebDistDirectory() {
178151
178620
  if (webDistDirectoryCache !== void 0) {
178152
178621
  return webDistDirectoryCache;
@@ -178271,7 +178740,7 @@ async function handleContentDistribution(c) {
178271
178740
  );
178272
178741
  return c.json({ distribution });
178273
178742
  } catch (error) {
178274
- return c.json({ error: errorMessage(error) }, 500);
178743
+ throw routeFailure(c.json({ error: errorMessage(error) }, 500), error);
178275
178744
  }
178276
178745
  }
178277
178746
  async function resolveClaimSessionUser(env, req) {
@@ -178383,6 +178852,7 @@ var init_index = __esm({
178383
178852
  init_chat_identity_routes();
178384
178853
  init_routes4();
178385
178854
  init_client();
178855
+ init_diagnostics();
178386
178856
  init_emitter();
178387
178857
  init_sse();
178388
178858
  init_sse_invalidation_auth();
@@ -178571,10 +179041,10 @@ var init_index = __esm({
178571
179041
  await checkDatabaseReadiness();
178572
179042
  return c.json({ status: "ok", service: "lobu-api" });
178573
179043
  } catch (error) {
178574
- return c.json(
179044
+ throw routeFailure(c.json(
178575
179045
  { status: "unready", service: "lobu-api", error: errorMessage(error) },
178576
179046
  503
178577
- );
179047
+ ), error);
178578
179048
  }
178579
179049
  });
178580
179050
  app.get("/health/scheduler", async (c) => {
@@ -178582,14 +179052,14 @@ var init_index = __esm({
178582
179052
  const health = await getSchedulerHealth(c.env);
178583
179053
  return c.json(health, health.healthy ? 200 : 503);
178584
179054
  } catch (error) {
178585
- return c.json(
179055
+ throw routeFailure(c.json(
178586
179056
  {
178587
179057
  healthy: false,
178588
179058
  issues: ["Failed to check scheduler health"],
178589
179059
  error: errorMessage(error)
178590
179060
  },
178591
179061
  500
178592
- );
179062
+ ), error);
178593
179063
  }
178594
179064
  });
178595
179065
  app.on(["GET", "POST"], "/api/auth/*", async (c) => {
@@ -178597,7 +179067,7 @@ var init_index = __esm({
178597
179067
  try {
178598
179068
  auth = await createAuth(c.env, c.req.raw);
178599
179069
  } catch (error) {
178600
- if (error instanceof HTTPException3) return error.getResponse();
179070
+ if (error instanceof HTTPException6) return error.getResponse();
178601
179071
  throw error;
178602
179072
  }
178603
179073
  return serveAuthRequest(auth, c.req.raw);
@@ -179340,19 +179810,38 @@ var init_index = __esm({
179340
179810
  const isSpaRoute = !hasFileExtension && !isExcludedSpaPath(requestPath);
179341
179811
  const shouldServeSpaFallback = (acceptsHtml || acceptsGenericResponse && hasSessionCookie) && isSpaRoute;
179342
179812
  if ((acceptsHtml || acceptsGenericResponse) && !hasSessionCookie && isSpaRoute) {
179813
+ try {
179814
+ enforcePublicReadLimit({
179815
+ userId: null,
179816
+ clientIP: getClientIP(c.req.raw, c.var.peerRemoteAddress)
179817
+ });
179818
+ } catch (error) {
179819
+ if (!(error instanceof ToolUserError) || error.code !== "RATE_LIMITED") {
179820
+ throw error;
179821
+ }
179822
+ c.header("Cache-Control", "no-store");
179823
+ c.header("Retry-After", String(error.retryAfterSeconds ?? 60));
179824
+ return c.text("Too many requests", 429);
179825
+ }
179343
179826
  let publicPageModel;
179344
179827
  try {
179345
179828
  publicPageModel = await buildPublicPageModel(
179346
179829
  requestPath,
179347
179830
  c.env,
179348
179831
  c.req.url,
179349
- c.get("subdomainOrg")
179832
+ c.get("subdomainOrg"),
179833
+ c.req.raw.signal
179350
179834
  );
179351
179835
  } catch (error) {
179352
179836
  logger_default.error({ error, path: requestPath }, "[public-pages] render failed");
179353
179837
  c.header("Cache-Control", "no-store");
179354
- c.header("Retry-After", "60");
179355
- return c.text("Temporarily unavailable", 503);
179838
+ c.header(
179839
+ "Retry-After",
179840
+ String(
179841
+ error instanceof ToolUserError && error.retryAfterSeconds !== void 0 ? error.retryAfterSeconds : 60
179842
+ )
179843
+ );
179844
+ throw routeFailure(c.text("Temporarily unavailable", 503), error);
179356
179845
  }
179357
179846
  if (publicPageModel) {
179358
179847
  const template = await loadAnySpaHtmlTemplate();
@@ -188006,7 +188495,7 @@ async function runWorkspacePurgeTask(payload, ctx) {
188006
188495
  return null;
188007
188496
  }
188008
188497
  const counts = { ...lease.removed };
188009
- const batch = (step, fn) => fencedBatch(sql2, ctx.taskRunId, owner, counts, step, fn);
188498
+ const batch = (step, fn) => fencedBatch(sql2, ctx.taskRunId, owner, counts, async (tx) => ({ [step]: await fn(tx) }));
188010
188499
  logger_default.info(
188011
188500
  { event: "workspace_purge_started", organizationId, taskRunId: ctx.taskRunId, resumed: !org },
188012
188501
  "[workspace-purge] Started"
@@ -188064,6 +188553,11 @@ async function runWorkspacePurgeTask(payload, ctx) {
188064
188553
  `;
188065
188554
  return deleted.count;
188066
188555
  }) > 0) ;
188556
+ while (await fencedBatch(sql2, ctx.taskRunId, owner, counts, async (tx) => {
188557
+ const outcome = await releaseClientHomedInOrganization(tx, organizationId);
188558
+ if (outcome === null) return {};
188559
+ return outcome === "deleted" ? { oauth_clients: 1 } : { oauth_clients_detached: 1 };
188560
+ }) > 0) ;
188067
188561
  await batch(
188068
188562
  "organization",
188069
188563
  (tx) => withAclPrivilege(tx, async () => {
@@ -188088,7 +188582,7 @@ async function runWorkspacePurgeTask(payload, ctx) {
188088
188582
  );
188089
188583
  return counts;
188090
188584
  }
188091
- async function fencedBatch(sql2, taskRunId, owner, counts, step, fn) {
188585
+ async function fencedBatch(sql2, taskRunId, owner, counts, fn) {
188092
188586
  return sql2.begin(async (tx) => {
188093
188587
  const held = await tx`
188094
188588
  SELECT 1 FROM runs
@@ -188096,9 +188590,13 @@ async function fencedBatch(sql2, taskRunId, owner, counts, step, fn) {
188096
188590
  FOR NO KEY UPDATE
188097
188591
  `;
188098
188592
  if (held.length === 0) throw new WorkspacePurgeLeaseLostError(taskRunId);
188099
- const removed = await fn(tx);
188593
+ let removed = 0;
188594
+ for (const [step, rows] of Object.entries(await fn(tx))) {
188595
+ if (rows <= 0) continue;
188596
+ counts[step] = (counts[step] ?? 0) + rows;
188597
+ removed += rows;
188598
+ }
188100
188599
  if (removed > 0) {
188101
- counts[step] = (counts[step] ?? 0) + removed;
188102
188600
  await tx`
188103
188601
  UPDATE runs
188104
188602
  SET action_output = COALESCE(action_output, '{}'::jsonb)
@@ -188120,6 +188618,7 @@ var WORKSPACE_PURGE_BATCH_SIZE, PURGE_BATCH_DELETES, WORKSPACE_PURGE_UNLINKED_TA
188120
188618
  var init_purge = __esm({
188121
188619
  "src/workspace/purge.ts"() {
188122
188620
  "use strict";
188621
+ init_clients();
188123
188622
  init_client();
188124
188623
  init_entity_management();
188125
188624
  init_relationship_claims();
@@ -188702,9 +189201,13 @@ import http3 from "node:http";
188702
189201
  import v8 from "node:v8";
188703
189202
  import { getRequestListener } from "@hono/node-server";
188704
189203
  import { Hono as Hono39 } from "hono";
189204
+ import { HTTPException as HTTPException7 } from "hono/http-exception";
188705
189205
  import { routePath as routePath2 } from "hono/route";
188706
189206
  import { pinoLogger } from "hono-pino";
188707
189207
  import { context as context4, propagation, ROOT_CONTEXT } from "@opentelemetry/api";
189208
+ function unexpectedError(c) {
189209
+ return c.error instanceof HTTPException7 || c.error instanceof DbClosedError ? void 0 : c.error;
189210
+ }
188708
189211
  function dbShutDownResponse(c) {
188709
189212
  requestsRefusedAfterDbShutdown.add(c.req.raw);
188710
189213
  c.header("Retry-After", "1");
@@ -188813,7 +189316,7 @@ function buildWrapperApp(env, lobuApp2, mountedMainApp = app) {
188813
189316
  } else if (c.res.status >= 500 && !await isUnreportedServerStatus(c)) {
188814
189317
  recordError(
188815
189318
  span,
188816
- { name: "HttpServerError", message: `HTTP ${c.res.status}`, httpStatus: c.res.status },
189319
+ routeFailureCauses.get(c.req.raw) ?? { name: "HttpServerError", message: `HTTP ${c.res.status}`, httpStatus: c.res.status },
188817
189320
  { scope: name }
188818
189321
  );
188819
189322
  }
@@ -188822,7 +189325,13 @@ function buildWrapperApp(env, lobuApp2, mountedMainApp = app) {
188822
189325
  }
188823
189326
  });
188824
189327
  });
188825
- wrapper.use("*", pinoLogger({ pino: logger_default }));
189328
+ wrapper.use("*", pinoLogger({
189329
+ pino: logger_default,
189330
+ http: {
189331
+ onResLevel: (c) => unexpectedError(c) ? "error" : "info",
189332
+ onResMessage: (c) => unexpectedError(c)?.message || "Request completed"
189333
+ }
189334
+ }));
188826
189335
  wrapper.use("*", async (c, next) => {
188827
189336
  await next();
188828
189337
  if (c.res.status >= 500 && !isErrorReported(c)) {
@@ -188848,6 +189357,10 @@ function buildWrapperApp(env, lobuApp2, mountedMainApp = app) {
188848
189357
  });
188849
189358
  wrapper.onError((err, c) => {
188850
189359
  if (err instanceof DbClosedError) return dbShutDownResponse(c);
189360
+ if (err instanceof HTTPException7) {
189361
+ if (err.status >= 500) routeFailureCauses.set(c.req.raw, err.cause ?? err);
189362
+ return err.getResponse();
189363
+ }
188851
189364
  recordError(getCurrentSpan(), err, { scope: httpSpanName(c) });
188852
189365
  requestsWithRecordedError.add(c.req.raw);
188853
189366
  if (!isErrorReported(c)) {
@@ -189037,7 +189550,7 @@ function createServerLifecycle(config) {
189037
189550
  };
189038
189551
  return { start };
189039
189552
  }
189040
- var requestsWithRecordedError, requestsRefusedAfterDbShutdown, HTTP_TRACE_METHODS;
189553
+ var requestsWithRecordedError, routeFailureCauses, requestsRefusedAfterDbShutdown, HTTP_TRACE_METHODS;
189041
189554
  var init_server_lifecycle = __esm({
189042
189555
  "src/server-lifecycle.ts"() {
189043
189556
  "use strict";
@@ -189057,6 +189570,7 @@ var init_server_lifecycle = __esm({
189057
189570
  init_logger2();
189058
189571
  init_workspace();
189059
189572
  requestsWithRecordedError = /* @__PURE__ */ new WeakSet();
189573
+ routeFailureCauses = /* @__PURE__ */ new WeakMap();
189060
189574
  requestsRefusedAfterDbShutdown = /* @__PURE__ */ new WeakSet();
189061
189575
  HTTP_TRACE_METHODS = /* @__PURE__ */ new Set(["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]);
189062
189576
  }