@lobu/runtime-server 24.10.0 → 24.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/dist/catalogs/connectors.json +1 -1
  2. package/dist/catalogs/skills.json +1 -1
  3. package/dist/component.json +1 -1
  4. package/dist/connectors/linkedin-inbox-adapter.js +13 -3
  5. package/dist/connectors/whatsapp-web-adapter.js +14 -13
  6. package/dist/connectors/whatsapp-web-helpers.ts +37 -1
  7. package/dist/connectors/whatsapp_web.ts +5 -5
  8. package/dist/connectors/x-dm-adapter.js +17 -3
  9. package/dist/db/migrations/20261113170000_member_sql_rls.sql +254 -0
  10. package/dist/db/migrations/20261113180000_member_sql_rls_parallel_plans.sql +192 -0
  11. package/dist/db/migrations/20261113190000_member_sql_schema_usage.sql +24 -0
  12. package/dist/db/migrations/20261114120000_events_owner_only_visibility.sql +39 -0
  13. package/dist/db/migrations/20261115120000_events_unbound_tool_audit_without_bridge.sql +40 -0
  14. package/dist/db/migrations/20261115120001_events_unbound_tool_audit_validate.sql +19 -0
  15. package/dist/db/migrations/20261115120002_drop_events_linked_org_ids.sql +119 -0
  16. package/dist/dependencies.bun.lock +10 -10
  17. package/dist/embeddings-server.mjs +1 -1
  18. package/dist/guest.bundle.js +1 -1
  19. package/dist/owletto/dist/assets/_-BDMUN9XZ.js +2 -0
  20. package/dist/owletto/dist/assets/_-CF5X4ANe.js +3 -0
  21. package/dist/owletto/dist/assets/{_agentId-DN0EwMAC.js → _agentId-CGScf8z_.js} +2 -2
  22. package/dist/owletto/dist/assets/_agentId-EQU2aUP0.js +2 -0
  23. package/dist/owletto/dist/assets/_automationId-PXZ33jsF.js +2 -0
  24. package/dist/owletto/dist/assets/{_connectorKey._connectionId-CVKfL9AG.js → _connectorKey._connectionId-DcI29kGy.js} +2 -2
  25. package/dist/owletto/dist/assets/_connectorKey.index-Cr2NDJWX.js +2 -0
  26. package/dist/owletto/dist/assets/{_conversationId-CPpNySjO.js → _conversationId-CnmLYlVS.js} +2 -2
  27. package/dist/owletto/dist/assets/_eventId-w5sDz5oa.js +2 -0
  28. package/dist/owletto/dist/assets/_owner-CkOZR4n0.js +3 -0
  29. package/dist/owletto/dist/assets/_shape-C_FmSf9G.js +2 -0
  30. package/dist/owletto/dist/assets/{_slug-DJx_8fsV.js → _slug-COPpRXLt.js} +2 -2
  31. package/dist/owletto/dist/assets/_viewKey-BVdJiilV.js +2 -0
  32. package/dist/owletto/dist/assets/_viewKey-mxxpqjtC.js +2 -0
  33. package/dist/owletto/dist/assets/{accept-invitation-Dwq1GAnG.js → accept-invitation-BKeIzZXE.js} +2 -2
  34. package/dist/owletto/dist/assets/{activity-route-location-C1jcXC7v.js → activity-route-location-sLvKaSCa.js} +2 -2
  35. package/dist/owletto/dist/assets/activity-route-view-msesKUwn.js +2 -0
  36. package/dist/owletto/dist/assets/{agent-connect-pages-DoI9UR0a.js → agent-connect-pages-DVq9nAR7.js} +3 -3
  37. package/dist/owletto/dist/assets/{agent-editor-form-DlavYg2q.js → agent-editor-form-DVFyyMyd.js} +2 -2
  38. package/dist/owletto/dist/assets/{agent-loading-shells-DYqQphN7.js → agent-loading-shells-BLNHIy-r.js} +2 -2
  39. package/dist/owletto/dist/assets/{agent-permissions-matrix-C1L8IcYR.js → agent-permissions-matrix-UBKRR5vs.js} +2 -2
  40. package/dist/owletto/dist/assets/{agent-skill-context-D1nMrVod.js → agent-skill-context-fqedKd0D.js} +2 -2
  41. package/dist/owletto/dist/assets/{agent-subpage-shell-2w7vTeXw.js → agent-subpage-shell-BUCoY2Nf.js} +2 -2
  42. package/dist/owletto/dist/assets/{agent-thread-BopD-2k1.js → agent-thread-Cqf9ITrT.js} +2 -2
  43. package/dist/owletto/dist/assets/app-bridge-B-L0rGz9.js +121 -0
  44. package/dist/owletto/dist/assets/{app._appId-BXeFXW1w.js → app._appId-ByIypCL9.js} +2 -2
  45. package/dist/owletto/dist/assets/{assist-composer-CL5x8pNt.js → assist-composer-kG_heHXo.js} +2 -2
  46. package/dist/owletto/dist/assets/{automation-run-now-MtxUTfzd.js → automation-run-now-C5XTS00o.js} +2 -2
  47. package/dist/owletto/dist/assets/{callback-BgfwP1Eo.js → callback-Pz5uS-k7.js} +2 -2
  48. package/dist/owletto/dist/assets/{card-DtLIFq7D.js → card-CAPpY9P5.js} +2 -2
  49. package/dist/owletto/dist/assets/{claim-CT3hYVMF.js → claim-DgWWK0KI.js} +2 -2
  50. package/dist/owletto/dist/assets/{client-activity-scopes-BPbRX-Pe.js → client-activity-scopes-Aqdo6Pdr.js} +2 -2
  51. package/dist/owletto/dist/assets/{client-rows-vrNA6FLs.js → client-rows-Dd5YV8vn.js} +2 -2
  52. package/dist/owletto/dist/assets/{clients-xnzZeEdZ.js → clients-Bf7ZgGro.js} +2 -2
  53. package/dist/owletto/dist/assets/{code-editor-mrKkAfcE.js → code-editor-z1Sy_hiX.js} +2 -2
  54. package/dist/owletto/dist/assets/connect-BFNp1y_s.js +2 -0
  55. package/dist/owletto/dist/assets/{connect-menu-C6iVtuSo.js → connect-menu-BWrAhMqO.js} +2 -2
  56. package/dist/owletto/dist/assets/connect._clientId-CSPfwYIN.js +2 -0
  57. package/dist/owletto/dist/assets/{connected._clientId-ROfVgp9h.js → connected._clientId-CuOeHafK.js} +2 -2
  58. package/dist/owletto/dist/assets/{connection-BMz740Wi.js → connection-CVeHmDLs.js} +2 -2
  59. package/dist/owletto/dist/assets/{connection-feed-detail-0VAJiZTP.js → connection-feed-detail-BYo7zdVD.js} +2 -2
  60. package/dist/owletto/dist/assets/{connector-page-shell-BFv21yuv.js → connector-page-shell-an3SYLim.js} +2 -2
  61. package/dist/owletto/dist/assets/{connector-provenance-b59RfBtk.js → connector-provenance-mSZCOud-.js} +2 -2
  62. package/dist/owletto/dist/assets/{connectors-nYS31lO2.js → connectors-DBEM9QQz.js} +2 -2
  63. package/dist/owletto/dist/assets/{consent-cPRF9JQv.js → consent-1ulwyJ3k.js} +2 -2
  64. package/dist/owletto/dist/assets/{copy-button-C3wMMv63.js → copy-button-Xhh7ZnjO.js} +2 -2
  65. package/dist/owletto/dist/assets/{core.esm-C9QlSrgK.js → core.esm-Ctg_pXLe.js} +2 -2
  66. package/dist/owletto/dist/assets/{create-CGOWfMk4.js → create-CGuoqPh8.js} +2 -2
  67. package/dist/owletto/dist/assets/create-Ccb5R-S4.js +2 -0
  68. package/dist/owletto/dist/assets/{create-ASRN3Obq.js → create-DmhbacIa.js} +2 -2
  69. package/dist/owletto/dist/assets/{create-automation-form-CLicoPH5.js → create-automation-form-CD6jSlWL.js} +2 -2
  70. package/dist/owletto/dist/assets/create._connectorKey-CZsAqj1p.js +2 -0
  71. package/dist/owletto/dist/assets/{custom-guardrail-edits-BUL7nmuO.js → custom-guardrail-edits-Ce_BwiwD.js} +2 -2
  72. package/dist/owletto/dist/assets/{definition-comparison-4UYMI6BK.js → definition-comparison-D_qP25jR.js} +2 -2
  73. package/dist/owletto/dist/assets/{detail-page-skeleton-C8v3rJXK.js → detail-page-skeleton-CPAfZLG0.js} +2 -2
  74. package/dist/owletto/dist/assets/{device-BBwsOi7q.js → device-DDl5XKvt.js} +2 -2
  75. package/dist/owletto/dist/assets/{device-pin-tombstone-Bcpe7nAA.js → device-pin-tombstone-Dkj7hrBE.js} +2 -2
  76. package/dist/owletto/dist/assets/{device._deviceId-DLT4jh0Z.js → device._deviceId-bNhTcops.js} +2 -2
  77. package/dist/owletto/dist/assets/{dynamic-schema-form-BDT8x0Vg.js → dynamic-schema-form-CRyUchXo.js} +2 -2
  78. package/dist/owletto/dist/assets/{entity-options-B9hm9V87.js → entity-options-D4t-NAcg.js} +2 -2
  79. package/dist/owletto/dist/assets/entity-page-BOOL_vy3.js +2 -0
  80. package/dist/owletto/dist/assets/{entity-pages-BWBpttz3.js → entity-pages-_nuesgnp.js} +2 -2
  81. package/dist/owletto/dist/assets/{entity-schema-graph-lMMx3HhR.js → entity-schema-graph-Cq96SJ3c.js} +2 -2
  82. package/dist/owletto/dist/assets/{entity-type-page-CkQm0yEu.js → entity-type-page-CkCSbkBx.js} +2 -2
  83. package/dist/owletto/dist/assets/event-detail-DUvlqn9b.js +2 -0
  84. package/dist/owletto/dist/assets/{events-feed-DmRzikZW.js → events-feed-DcKTkJVe.js} +2 -2
  85. package/dist/owletto/dist/assets/{filter-editors-CQoSj-20.js → filter-editors-DGVl9U4D.js} +3 -3
  86. package/dist/owletto/dist/assets/{full-page-spinner-CYyCnKve.js → full-page-spinner-CtVlF8GQ.js} +2 -2
  87. package/dist/owletto/dist/assets/index-BUlkNJzX.js +2 -0
  88. package/dist/owletto/dist/assets/{index-BS5Ty3tf.js → index-BifR-LE9.js} +2 -2
  89. package/dist/owletto/dist/assets/{index-DByaMzsG.js → index-BoqrvLHQ.js} +1383 -1383
  90. package/dist/owletto/dist/assets/index-CA9mW_ZM.js +2 -0
  91. package/dist/owletto/dist/assets/index-CH0GzG4i.js +2 -0
  92. package/dist/owletto/dist/assets/index-CK5GDX4B.js +2 -0
  93. package/dist/owletto/dist/assets/index-CtI5Eomq.js +2 -0
  94. package/dist/owletto/dist/assets/{index-CUndAH6o.js → index-DbjbHlDe.js} +2 -2
  95. package/dist/owletto/dist/assets/index-DmtQ0bds.js +2 -0
  96. package/dist/owletto/dist/assets/{index-CDyFQ32o.js → index-Du_J8hnx.js} +2 -2
  97. package/dist/owletto/dist/assets/{index-ittfA0k8.js → index-DvuJ_S_o.js} +2 -2
  98. package/dist/owletto/dist/assets/index-Pae_f9LM.css +1 -0
  99. package/dist/owletto/dist/assets/{index-C3hz9tzx.js → index-XETZnN7L.js} +2 -2
  100. package/dist/owletto/dist/assets/{json-diff-mcDgyct_.js → json-diff-OjtREegr.js} +2 -2
  101. package/dist/owletto/dist/assets/{list-skeleton-DsYGUHxi.js → list-skeleton-CH0qQBYk.js} +2 -2
  102. package/dist/owletto/dist/assets/{login-EoLq136v.js → login-DG0b9uSC.js} +2 -2
  103. package/dist/owletto/dist/assets/{logout-gLgEQOiX.js → logout-DfdgOLoM.js} +2 -2
  104. package/dist/owletto/dist/assets/{member-scope-gate-vvkgSAb2.js → member-scope-gate-Cxg2zGQT.js} +2 -2
  105. package/dist/owletto/dist/assets/memory-browse-page-qEDQ9Z18.js +74 -0
  106. package/dist/owletto/dist/assets/missing-view-xT0B-f5z.js +2 -0
  107. package/dist/owletto/dist/assets/{model-selector-D3vSMLO2.js → model-selector-D2OpDkwH.js} +2 -2
  108. package/dist/owletto/dist/assets/{needs-you-list-B5Bgd05M.js → needs-you-list-3uMsWcDv.js} +2 -2
  109. package/dist/owletto/dist/assets/{new-dLXsCHBd.js → new-AdGV6a8R.js} +2 -2
  110. package/dist/owletto/dist/assets/new-BdtIhBpo.js +2 -0
  111. package/dist/owletto/dist/assets/{new-Bk_flKQO.js → new-BjGwX6s6.js} +2 -2
  112. package/dist/owletto/dist/assets/{new-BPW3V0Y1.js → new-D-iMjV74.js} +2 -2
  113. package/dist/owletto/dist/assets/{organization-DBfgBkzq.js → organization-qaIpEiQg.js} +2 -2
  114. package/dist/owletto/dist/assets/peek-pane-content-CEsDVScl.js +2 -0
  115. package/dist/owletto/dist/assets/{pending-seed-CBhx2Ql-.js → pending-seed-BBACroge.js} +2 -2
  116. package/dist/owletto/dist/assets/{proposal-review-shell-B-jYcKfB.js → proposal-review-shell-C8ZfIAYn.js} +2 -2
  117. package/dist/owletto/dist/assets/public-shell-ready-K2R8iXSI.js +2 -0
  118. package/dist/owletto/dist/assets/{record-session-CAmGHMyM.js → record-session-BrM9cdXu.js} +2 -2
  119. package/dist/owletto/dist/assets/{renderer-olRv_HMI.js → renderer-CTKNMcXP.js} +4 -4
  120. package/dist/owletto/dist/assets/{reset-password-B9_xi8Pq.js → reset-password-DKBEneyR.js} +2 -2
  121. package/dist/owletto/dist/assets/{run-initiator-DhE5v4z0.js → run-initiator-BKSgI1o0.js} +2 -2
  122. package/dist/owletto/dist/assets/{runs-C8sZQr4o.js → runs-k2NpbZm8.js} +2 -2
  123. package/dist/owletto/dist/assets/runs-list-DUXRMkWN.js +2 -0
  124. package/dist/owletto/dist/assets/{schema-value-zTJGE4eh.js → schema-value-wjqGxXhv.js} +3 -3
  125. package/dist/owletto/dist/assets/{scoped-feed-bar-BKyJSa3_.js → scoped-feed-bar-DNFL0sYX.js} +2 -2
  126. package/dist/owletto/dist/assets/{settings-z02cvVS3.js → settings-V0m5Om5j.js} +2 -2
  127. package/dist/owletto/dist/assets/{source-record-panels-CGmKIJdN.js → source-record-panels-BMut9YIA.js} +2 -2
  128. package/dist/owletto/dist/assets/{status-variants-DyRCXBzM.js → status-variants-SzXYYedJ.js} +2 -2
  129. package/dist/owletto/dist/assets/subDays-9s9OEl5t.js +2 -0
  130. package/dist/owletto/dist/assets/{table-C637cQxG.js → table-ZuYMOjVR.js} +2 -2
  131. package/dist/owletto/dist/assets/{use-automations-CgWNoYio.js → use-automations-DfBtVzGa.js} +2 -2
  132. package/dist/owletto/dist/assets/{use-login-redirect-tDdhXTpt.js → use-login-redirect-BDiS3eyl.js} +2 -2
  133. package/dist/owletto/dist/assets/{use-mention-search-D-kIKchD.js → use-mention-search-khySpz_V.js} +2 -2
  134. package/dist/owletto/dist/assets/view-card-DiHWlypr.js +2 -0
  135. package/dist/owletto/dist/assets/view-param-filters-DGKxSr7r.js +2 -0
  136. package/dist/owletto/dist/assets/{views-access-required-C35Dyt91.js → views-access-required-HA-PiOwA.js} +2 -2
  137. package/dist/owletto/dist/index.html +2 -2
  138. package/dist/server-main.bundle.mjs +1099 -545
  139. package/npm-shrinkwrap.json +38 -38
  140. package/package.json +1 -1
  141. package/vendor/connector-sdk/package.json +1 -1
  142. package/vendor/core/package.json +1 -1
  143. package/vendor/views/package.json +1 -1
  144. package/dist/owletto/dist/assets/_-CYvj1y65.js +0 -3
  145. package/dist/owletto/dist/assets/_-CeLTSYYY.js +0 -2
  146. package/dist/owletto/dist/assets/_agentId-BB5E-L6T.js +0 -2
  147. package/dist/owletto/dist/assets/_automationId-DvUl9CSd.js +0 -2
  148. package/dist/owletto/dist/assets/_connectorKey.index-Cv6FzK1v.js +0 -2
  149. package/dist/owletto/dist/assets/_eventId-DZKicuq6.js +0 -2
  150. package/dist/owletto/dist/assets/_owner-Dauk3YuD.js +0 -3
  151. package/dist/owletto/dist/assets/_shape-cKrEID3T.js +0 -2
  152. package/dist/owletto/dist/assets/_viewKey-CPVzVKEf.js +0 -2
  153. package/dist/owletto/dist/assets/_viewKey-CW8gexOQ.js +0 -2
  154. package/dist/owletto/dist/assets/activity-route-view-D78Wj0RH.js +0 -2
  155. package/dist/owletto/dist/assets/app-bridge-C4nPtae3.js +0 -121
  156. package/dist/owletto/dist/assets/connect-NUCSay8X.js +0 -2
  157. package/dist/owletto/dist/assets/connect._clientId-Cp-d9Q5b.js +0 -2
  158. package/dist/owletto/dist/assets/create-CBcodaSO.js +0 -2
  159. package/dist/owletto/dist/assets/create._connectorKey-s4xkktTC.js +0 -2
  160. package/dist/owletto/dist/assets/entity-page-DZjzQ2V4.js +0 -2
  161. package/dist/owletto/dist/assets/event-detail-CkzfakTK.js +0 -2
  162. package/dist/owletto/dist/assets/index-BE7eb2kE.js +0 -2
  163. package/dist/owletto/dist/assets/index-BFR0uiKY.js +0 -2
  164. package/dist/owletto/dist/assets/index-C38OzBpB.js +0 -2
  165. package/dist/owletto/dist/assets/index-CiKysEhV.js +0 -2
  166. package/dist/owletto/dist/assets/index-DfdinB7B.js +0 -2
  167. package/dist/owletto/dist/assets/index-DgMM4Zt5.css +0 -1
  168. package/dist/owletto/dist/assets/index-Xk711gVC.js +0 -2
  169. package/dist/owletto/dist/assets/memory-browse-page-DvDtwrEI.js +0 -74
  170. package/dist/owletto/dist/assets/new-C5HtQdM_.js +0 -2
  171. package/dist/owletto/dist/assets/peek-pane-content-c2PG3TEX.js +0 -2
  172. package/dist/owletto/dist/assets/public-shell-ready-D8TijlRY.js +0 -2
  173. package/dist/owletto/dist/assets/record-activity-DnRVOrG2.js +0 -2
  174. package/dist/owletto/dist/assets/runs-list-CwtH-wmk.js +0 -2
  175. package/dist/owletto/dist/assets/subDays-D8nHthaS.js +0 -2
  176. 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.1",
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
  `;
@@ -11426,8 +11409,7 @@ var init_insert_event = __esm({
11426
11409
  content_length: "version",
11427
11410
  search_tsv: "version",
11428
11411
  identity_ns: "chain",
11429
- identity_key: "chain",
11430
- linked_org_ids: "version"
11412
+ identity_key: "chain"
11431
11413
  };
11432
11414
  INHERITED_COLUMNS = Object.keys(EVENT_SUPERSEDE_RULES).filter((column) => EVENT_SUPERSEDE_RULES[column] !== "version");
11433
11415
  AUDIT_IDEMPOTENCY_INDEX = "idx_events_org_idempotency_key";
@@ -31030,6 +31012,14 @@ function boundedRead(sql2, options, run) {
31030
31012
  const transaction = sql2.begin("read only", async (tx) => {
31031
31013
  options.signal?.throwIfAborted();
31032
31014
  await tx.unsafe(`SET LOCAL statement_timeout = ${timeoutMs}`);
31015
+ if (options.fence) {
31016
+ await tx.unsafe(
31017
+ `SELECT set_config('lobu.member_sql_org', $1, true),
31018
+ set_config('lobu.member_sql_principal', $2, true),
31019
+ set_config('role', 'lobu_member_sql', true)`,
31020
+ [options.fence.organizationId, options.fence.principal ?? ""]
31021
+ );
31022
+ }
31033
31023
  return run(tx);
31034
31024
  });
31035
31025
  return raceAbort(transaction, options.signal);
@@ -31059,6 +31049,12 @@ function classifyReadQueryFailure(error) {
31059
31049
  if (pgCode === "25006") {
31060
31050
  return { code: "VALIDATION", message: "Only read-only queries are allowed." };
31061
31051
  }
31052
+ if (pgCode === "42501") {
31053
+ return {
31054
+ code: "VALIDATION",
31055
+ message: "Only read-only queries over the workspace tables are allowed; the query used a relation or function outside them."
31056
+ };
31057
+ }
31062
31058
  const rawCode = error?.code;
31063
31059
  return {
31064
31060
  code: classifyToolError({
@@ -31087,13 +31083,120 @@ var init_bounded_read = __esm({
31087
31083
  }
31088
31084
  });
31089
31085
 
31090
- // src/utils/linked-org-ids.ts
31091
- function useLinkedOrgScope() {
31092
- return process.env.LOBU_LINKED_ORG_SCOPE === "1";
31086
+ // src/utils/content-read-bounds.ts
31087
+ function sqlRef(value) {
31088
+ if (!SAFE_SQL_REF.test(value)) throw new Error(`Unsafe SQL reference: ${value}`);
31089
+ return value;
31090
+ }
31091
+ function boundedPayloadTextSql(alias) {
31092
+ const a = sqlRef(alias);
31093
+ 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`;
31094
+ }
31095
+ function boundedJsonSql(alias, column) {
31096
+ const a = sqlRef(alias);
31097
+ const c = sqlRef(column);
31098
+ const ref = `${a}.${c}`;
31099
+ 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}`;
31100
+ }
31101
+ function boundedAttachmentsSql(alias) {
31102
+ const a = sqlRef(alias);
31103
+ const ref = `${a}.attachments`;
31104
+ 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`;
31105
+ }
31106
+ function truncateByCodePoint(value) {
31107
+ if (value.length <= CONTENT_TEXT_HEAD_CHARS) return { truncated: false };
31108
+ let length = 0;
31109
+ let head = "";
31110
+ for (const character of value) {
31111
+ if (length < CONTENT_TEXT_HEAD_CHARS) head += character;
31112
+ length += 1;
31113
+ }
31114
+ if (length <= CONTENT_TEXT_HEAD_CHARS) return { truncated: false };
31115
+ return { value: `${head}${TRUNCATION_SUFFIX}`, length, truncated: true };
31116
+ }
31117
+ function jsonBytes2(value) {
31118
+ try {
31119
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
31120
+ } catch {
31121
+ return Number.POSITIVE_INFINITY;
31122
+ }
31123
+ }
31124
+ function assignGeneratedSidecar(input, row, key2, value, collisions) {
31125
+ if (Object.prototype.hasOwnProperty.call(input, key2) && input[key2] !== value || Object.prototype.hasOwnProperty.call(row, key2) && row[key2] !== value) {
31126
+ collisions.add(key2);
31127
+ return;
31128
+ }
31129
+ row[key2] = value;
31130
+ }
31131
+ function finalizeDynamicQueryRows(inputRows, maxSerializedBytes = QUERY_SQL_RESULT_MAX_BYTES) {
31132
+ const boundedRows = [];
31133
+ const sidecarCollisions = /* @__PURE__ */ new Set();
31134
+ const truncatedColumns = /* @__PURE__ */ new Set();
31135
+ let serializedBytes = 2;
31136
+ for (const input of inputRows) {
31137
+ const row = { ...input };
31138
+ const rowTruncated = [];
31139
+ for (const key2 of Object.keys(row)) {
31140
+ const value = row[key2];
31141
+ if (typeof value === "string") {
31142
+ const bounded2 = truncateByCodePoint(value);
31143
+ if (!bounded2.truncated) continue;
31144
+ row[key2] = bounded2.value;
31145
+ rowTruncated.push(key2);
31146
+ if (key2 === "payload_text" || key2 === "text_content") {
31147
+ assignGeneratedSidecar(input, row, "content_length", bounded2.length, sidecarCollisions);
31148
+ assignGeneratedSidecar(input, row, "payload_truncated", true, sidecarCollisions);
31149
+ }
31150
+ continue;
31151
+ }
31152
+ if (value === null || typeof value !== "object") continue;
31153
+ const bytes = jsonBytes2(value);
31154
+ if (bytes <= CONTENT_JSON_MAX_BYTES) continue;
31155
+ rowTruncated.push(key2);
31156
+ if (key2 === "attachments") {
31157
+ row.attachments = null;
31158
+ assignGeneratedSidecar(input, row, "attachments_truncated", true, sidecarCollisions);
31159
+ assignGeneratedSidecar(
31160
+ input,
31161
+ row,
31162
+ "attachments_bytes",
31163
+ Number.isFinite(bytes) ? bytes : null,
31164
+ sidecarCollisions
31165
+ );
31166
+ } else {
31167
+ row[key2] = {
31168
+ _truncated: true,
31169
+ bytes: Number.isFinite(bytes) ? bytes : null
31170
+ };
31171
+ }
31172
+ }
31173
+ const encoded = JSON.stringify(row);
31174
+ const rowBytes = Buffer.byteLength(encoded, "utf8");
31175
+ const separatorBytes = boundedRows.length > 0 ? 1 : 0;
31176
+ if (serializedBytes + separatorBytes + rowBytes > maxSerializedBytes) break;
31177
+ boundedRows.push(row);
31178
+ serializedBytes += separatorBytes + rowBytes;
31179
+ for (const key2 of rowTruncated) truncatedColumns.add(key2);
31180
+ }
31181
+ return {
31182
+ rows: boundedRows,
31183
+ omittedRows: inputRows.length - boundedRows.length,
31184
+ sidecarCollisions: [...sidecarCollisions].sort(),
31185
+ truncatedColumns: [...truncatedColumns].sort()
31186
+ };
31093
31187
  }
31094
- var init_linked_org_ids = __esm({
31095
- "src/utils/linked-org-ids.ts"() {
31188
+ 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;
31189
+ var init_content_read_bounds = __esm({
31190
+ "src/utils/content-read-bounds.ts"() {
31096
31191
  "use strict";
31192
+ CONTENT_TEXT_HEAD_CHARS = 4e3;
31193
+ CONTENT_JSON_MAX_BYTES = 16 * 1024;
31194
+ QUERY_SQL_RESULT_MAX_BYTES = 1048576;
31195
+ AUTOMATION_READ_MAX_BYTES = 1048576;
31196
+ CONTENT_READ_STATEMENT_TIMEOUT_MS = 15e3;
31197
+ QUERY_SQL_STATEMENT_TIMEOUT_MS = 5e3;
31198
+ TRUNCATION_SUFFIX = "\u2026 [truncated]";
31199
+ SAFE_SQL_REF = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
31097
31200
  }
31098
31201
  });
31099
31202
 
@@ -32135,6 +32238,10 @@ function validateAndScopeQuery(rawSql, organizationId, options) {
32135
32238
  function buildScopedQuery(userQuery, tableRefs, context5, options) {
32136
32239
  const params = [];
32137
32240
  let idx = 0;
32241
+ const scope = {
32242
+ organizationId: context5.organizationId,
32243
+ principal: context5.userId ?? null
32244
+ };
32138
32245
  let organizationP;
32139
32246
  const bindOrganization = () => {
32140
32247
  if (!organizationP) {
@@ -32182,12 +32289,8 @@ function buildScopedQuery(userQuery, tableRefs, context5, options) {
32182
32289
  if (/\$\d+/.test(userQuery)) {
32183
32290
  throw new ToolUserError("Positional parameters ($1, $2, ...) are not allowed in data source queries", 400, "VALIDATION");
32184
32291
  }
32185
- if (tableRefs.length === 0) return { sql: processedQuery, params };
32292
+ if (tableRefs.length === 0) return { sql: processedQuery, params, scope };
32186
32293
  const orgP = bindOrganization();
32187
- const scope = {
32188
- organizationId: context5.organizationId,
32189
- principal: context5.userId ?? null
32190
- };
32191
32294
  const eventConnVisibility = (alias) => {
32192
32295
  const vis = compileConnectionFkVisibility(scope, idx + 1, alias);
32193
32296
  params.push(...vis.params);
@@ -32200,12 +32303,7 @@ function buildScopedQuery(userQuery, tableRefs, context5, options) {
32200
32303
  idx += vis.params.length;
32201
32304
  return ` ${vis.sql}`;
32202
32305
  };
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}))`;
32306
+ const eventOrgScope = (alias) => `${alias}.organization_id = ${orgP}`;
32209
32307
  const channelMessagesVisibility = (alias) => {
32210
32308
  const vis = compileChannelMessagesVisibility(scope, idx + 1, alias);
32211
32309
  params.push(...vis.params);
@@ -32356,13 +32454,13 @@ function buildScopedQuery(userQuery, tableRefs, context5, options) {
32356
32454
  );
32357
32455
  }
32358
32456
  }
32359
- if (ctes.length === 0) return { sql: processedQuery, params };
32457
+ if (ctes.length === 0) return { sql: processedQuery, params, scope };
32360
32458
  const cteStr = `WITH ${ctes.join(",\n")}`;
32361
32459
  const body2 = stripLeadingComments(processedQuery).trim();
32362
32460
  const finalSql = /^WITH\b/i.test(body2) ? `${cteStr},
32363
32461
  ${body2.replace(/^WITH\s+/i, "")}` : `${cteStr}
32364
32462
  ${body2}`;
32365
- return { sql: finalSql, params };
32463
+ return { sql: finalSql, params, scope };
32366
32464
  }
32367
32465
  function queryProjectsIdColumn(query) {
32368
32466
  try {
@@ -32458,11 +32556,12 @@ async function executeDataSources(dataSources, context5, sql2, options) {
32458
32556
  }
32459
32557
  }
32460
32558
  }
32461
- let { sql: scopedQuery, params } = buildScopedQuery(query, tableRefs, context5, {
32559
+ const scoped = buildScopedQuery(query, tableRefs, context5, {
32462
32560
  safeColumns: SAFE_COLUMN_DEFS,
32463
32561
  excludeWorkspaceAudit: options?.excludeWorkspaceAudit,
32464
32562
  excludeMemberEntities: options?.excludeMemberEntities
32465
32563
  });
32564
+ let { sql: scopedQuery, params } = scoped;
32466
32565
  const placeholderMatches = scopedQuery.match(/\$(\d+)/g);
32467
32566
  if (placeholderMatches) {
32468
32567
  const maxPlaceholder = Math.max(
@@ -32483,10 +32582,9 @@ async function executeDataSources(dataSources, context5, sql2, options) {
32483
32582
  params = wrapped.params;
32484
32583
  }
32485
32584
  }
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);
32585
+ const rows = await boundedQuery(sql2, scopedQuery, params, {
32586
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
32587
+ fence: scoped.scope
32490
32588
  });
32491
32589
  const rowLimit = MAX_DATA_SOURCE_ROWS + (options?.includeOverflowRow ? 1 : 0);
32492
32590
  results[name] = Array.isArray(rows) ? rows.slice(0, rowLimit) : [];
@@ -32504,15 +32602,15 @@ async function executeDataSources(dataSources, context5, sql2, options) {
32504
32602
  );
32505
32603
  return results;
32506
32604
  }
32507
- var FORBIDDEN_OPS, FORBIDDEN_QUERY_FUNCTIONS, FORBIDDEN_QUERY_FUNCTION_PREFIXES, FORBIDDEN_QUERY_FUNCTION_INFIX, MAX_DATA_SOURCE_ROWS, QUERY_TIMEOUT_MS;
32605
+ var FORBIDDEN_OPS, FORBIDDEN_QUERY_FUNCTIONS, FORBIDDEN_QUERY_FUNCTION_PREFIXES, FORBIDDEN_QUERY_FUNCTION_INFIX, MAX_DATA_SOURCE_ROWS;
32508
32606
  var init_execute_data_sources = __esm({
32509
32607
  "src/utils/execute-data-sources.ts"() {
32510
32608
  "use strict";
32511
32609
  init_client();
32512
32610
  init_bounded_read();
32611
+ init_content_read_bounds();
32513
32612
  init_errors2();
32514
32613
  init_logger2();
32515
- init_linked_org_ids();
32516
32614
  init_connection_visibility();
32517
32615
  init_channel_messages_visibility();
32518
32616
  init_resource_visibility();
@@ -32538,124 +32636,6 @@ var init_execute_data_sources = __esm({
32538
32636
  FORBIDDEN_QUERY_FUNCTION_PREFIXES = ["pg_", "dblink", "lo_"];
32539
32637
  FORBIDDEN_QUERY_FUNCTION_INFIX = "_to_xml";
32540
32638
  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
32639
  }
32660
32640
  });
32661
32641
 
@@ -34377,12 +34357,16 @@ var init_manage_automations = __esm({
34377
34357
  });
34378
34358
 
34379
34359
  // 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[])`;
34360
+ function ownedByOrgSql(orgSql) {
34361
+ return `e2.organization_id = ${orgSql}`;
34382
34362
  }
34383
34363
  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)`;
34364
+ const entityOrgSql = "(SELECT organization_id FROM identity_members LIMIT 1)";
34365
+ const directBranch = directEntityLinkBranch(
34366
+ "ARRAY(SELECT id FROM identity_members)",
34367
+ entityOrgSql,
34368
+ eventSource
34369
+ );
34386
34370
  const standardBranches = STANDARD_IDENTITY_NAMESPACES.map(
34387
34371
  (ns) => `SELECT e2.id FROM ${eventSource} e2
34388
34372
  JOIN entity_identities ei
@@ -34391,7 +34375,7 @@ function entityLinkMatchSql(paramRef, alias = "f", eventSource = "events") {
34391
34375
  AND ei.deleted_at IS NULL
34392
34376
  WHERE e2.metadata ? '${ns}'
34393
34377
  AND e2.metadata->>'${ns}' = ei.identifier
34394
- AND ${visibleToOrgSql("(SELECT organization_id FROM identity_members LIMIT 1)")}
34378
+ AND ${ownedByOrgSql(entityOrgSql)}
34395
34379
  AND COALESCE((e2.metadata->'${IDENTITY_SCOPE_BY_NAMESPACE_METADATA_KEY}')->>'${ns}', '${ORGANIZATION_SCOPE_PROJECTION}') = COALESCE(ei.scope_key, '${ORGANIZATION_SCOPE_PROJECTION}')`
34396
34380
  );
34397
34381
  const branches = [directBranch, ...standardBranches].join("\n UNION\n ");
@@ -34401,11 +34385,10 @@ function entityLinkMatchSql(paramRef, alias = "f", eventSource = "events") {
34401
34385
  ${branches}
34402
34386
  ) SELECT id FROM entity_link_ids)`;
34403
34387
  }
34404
- function directEntityLinkBranch(entityRef) {
34405
- return `SELECT e2.id FROM events e2
34406
- WHERE e2.entity_ids && ARRAY(
34407
- ${identityMemberIdsSql(entityRef)}
34408
- )`;
34388
+ function directEntityLinkBranch(membersSql, orgSql, eventSource = "events") {
34389
+ return `SELECT e2.id FROM ${eventSource} e2
34390
+ WHERE e2.entity_ids && ${membersSql}
34391
+ AND e2.organization_id || '' = ${orgSql}`;
34409
34392
  }
34410
34393
  async function fetchEntityIdentityScopes(sql2, entityId) {
34411
34394
  const rows = await sql2.unsafe(`
@@ -34428,7 +34411,8 @@ function buildEntityLinkUnion(opts) {
34428
34411
  const { branches, params } = buildEntityLinkBranches({
34429
34412
  entityIdLiteral: opts.entityIdLiteral,
34430
34413
  scopes: opts.scopes,
34431
- baseParamIndex: opts.baseParamIndex
34414
+ baseParamIndex: opts.baseParamIndex,
34415
+ ownerOrganizationId: opts.ownerOrganizationId
34432
34416
  });
34433
34417
  return {
34434
34418
  sql: `${alias}.id IN (WITH entity_link_ids AS MATERIALIZED (
@@ -34438,17 +34422,28 @@ function buildEntityLinkUnion(opts) {
34438
34422
  };
34439
34423
  }
34440
34424
  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
34425
  const params = [];
34443
34426
  let paramIndex = opts.baseParamIndex;
34444
- const indexed = new Set(STANDARD_IDENTITY_NAMESPACES);
34445
34427
  const entityOrgSql = `(SELECT organization_id FROM entities WHERE id = ${opts.entityIdLiteral}::bigint)`;
34428
+ let ownerOrgSql = entityOrgSql;
34429
+ if (opts.ownerOrganizationId) {
34430
+ params.push(opts.ownerOrganizationId);
34431
+ ownerOrgSql = `$${paramIndex}::text`;
34432
+ paramIndex += 1;
34433
+ }
34434
+ const direct = directEntityLinkBranch(
34435
+ opts.directMembersSql ?? `ARRAY(
34436
+ ${identityMemberIdsSql(`${opts.entityIdLiteral}::bigint`)}
34437
+ )`,
34438
+ ownerOrgSql
34439
+ );
34440
+ const indexed = new Set(STANDARD_IDENTITY_NAMESPACES);
34446
34441
  const scopeBranches = [];
34447
34442
  for (const scope of opts.scopes) {
34448
34443
  if (!indexed.has(scope.namespace)) continue;
34449
34444
  params.push(scope.identifier, scope.scopeKey ?? ORGANIZATION_SCOPE_PROJECTION);
34450
34445
  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}`
34446
+ `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
34447
  );
34453
34448
  paramIndex += 2;
34454
34449
  }
@@ -34526,32 +34521,12 @@ function buildProducedByAutomationClause(producedByAutomationId, baseParamIndex)
34526
34521
  };
34527
34522
  }
34528
34523
  function buildOrgScopeWhere(options) {
34529
- if (!options.organization_id || options.entity_id && !options.strict_organization_scope) {
34530
- return { sql: "", params: [], branches: null };
34524
+ if (!options.organization_id) {
34525
+ return { sql: "", params: [] };
34531
34526
  }
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
34527
  return {
34552
- sql: `AND (${directCond} OR ${entityCond} OR ${connCond})`,
34553
- params: [options.organization_id],
34554
- branches: null
34528
+ sql: `AND f.organization_id = $${options.baseParamIndex}::text`,
34529
+ params: [options.organization_id]
34555
34530
  };
34556
34531
  }
34557
34532
  function buildConnectionVisibilityClause(options, tableAlias = "f") {
@@ -34576,7 +34551,6 @@ var init_visibility = __esm({
34576
34551
  "use strict";
34577
34552
  init_connection_visibility();
34578
34553
  init_resource_visibility();
34579
- init_linked_org_ids();
34580
34554
  init_sql_validation();
34581
34555
  }
34582
34556
  });
@@ -35188,7 +35162,7 @@ var init_sql_fragments = __esm({
35188
35162
 
35189
35163
  // src/utils/content-search/entity-types-filter.ts
35190
35164
  function buildEntityTypesFilterClause(options) {
35191
- if (!options.entity_types?.length || !options.organization_id) {
35165
+ if (!options.entity_types?.length || !options.organization_id || options.entity_id != null) {
35192
35166
  return { sql: "", predicate: "", params: [] };
35193
35167
  }
35194
35168
  const orgParam = `$${options.baseParamIndex}::text`;
@@ -35373,14 +35347,12 @@ async function executeListQuery(args) {
35373
35347
  statementTimeoutMs: CONTENT_READ_STATEMENT_TIMEOUT_MS
35374
35348
  });
35375
35349
  const whereExpr = `${args.whereExpr} ${args.orgScope.sql}`;
35376
- const countFrom = (scopeSql) => `FROM current_event_records f
35350
+ const orgWide = args.entityId == null && args.orgScope.sql !== "";
35351
+ const orgWideRangeSql = orgWide ? args.orgWideRangeSql : "";
35352
+ const countSql = `SELECT COUNT(*) as total FROM current_event_records f
35377
35353
  LEFT JOIN connections c ON c.id = f.connection_id
35378
35354
  ${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)}`;
35355
+ WHERE ${whereExpr} ${orgWideRangeSql}`;
35384
35356
  const cursorClause = buildDateCursorClause(
35385
35357
  args.cursor,
35386
35358
  "COALESCE(f.occurred_at, f.created_at)",
@@ -35405,19 +35377,9 @@ async function executeListQuery(args) {
35405
35377
  if (args.useDateFeed) {
35406
35378
  const candidateSetSql = buildDateCandidateSetSql({
35407
35379
  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 },
35380
+ whereExpr,
35412
35381
  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}`,
35382
+ rangeSql: orgWide ? `${cursorClause.rangeSql} ${orgWideRangeSql}` : "",
35421
35383
  cursor: args.cursor,
35422
35384
  limitParam: `$${limitIdx}`
35423
35385
  });
@@ -35521,42 +35483,17 @@ async function executeListQuery(args) {
35521
35483
  };
35522
35484
  }
35523
35485
  function buildDateCandidateSetSql(args) {
35524
- const arm = (scopeSql) => `SELECT
35486
+ return `SELECT
35525
35487
  f.id,
35526
35488
  f.occurred_at,
35527
35489
  f.created_at
35528
35490
  FROM current_event_records f
35529
35491
  LEFT JOIN connections c ON c.id = f.connection_id
35530
35492
  ${args.joinSql}
35531
- WHERE ${args.whereExpr} ${scopeSql}
35493
+ WHERE ${args.whereExpr} ${args.rangeSql}
35532
35494
  ${args.cursorSql}
35533
35495
  ORDER BY ${buildDateCandidateOrderBy(args.cursor, "f")}
35534
35496
  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
35497
  }
35561
35498
  async function listContentInternal(sql2, options, limit, offset) {
35562
35499
  const entityId = options.entity_id;
@@ -35612,7 +35549,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35612
35549
  const runFilterClause = buildRunFilter(runIdsArray);
35613
35550
  const baseConditions = [];
35614
35551
  const baseParams = [];
35615
- let orgScope3 = { sql: "", params: [], branches: null };
35552
+ let orgScope3 = { sql: "", params: [] };
35616
35553
  let threadEntityLinkSql;
35617
35554
  if (entityId != null) {
35618
35555
  const validatedId = validateNumericId(entityId, "entity_id");
@@ -35620,7 +35557,8 @@ async function listContentInternal(sql2, options, limit, offset) {
35620
35557
  entityIdLiteral: validatedId,
35621
35558
  scopes: entityScopes,
35622
35559
  alias: "f",
35623
- baseParamIndex: baseParams.length + 1
35560
+ baseParamIndex: baseParams.length + 1,
35561
+ ownerOrganizationId: organizationId
35624
35562
  });
35625
35563
  baseConditions.push(link.sql);
35626
35564
  baseParams.push(...link.params);
@@ -35631,16 +35569,17 @@ async function listContentInternal(sql2, options, limit, offset) {
35631
35569
  // params don't need fresh slots — they're the same identifier values
35632
35570
  // emitted by the outer `link` already in baseParams. We re-bind them
35633
35571
  // by reusing the same $N slots.
35634
- baseParamIndex: baseParams.length - link.params.length + 1
35572
+ baseParamIndex: baseParams.length - link.params.length + 1,
35573
+ ownerOrganizationId: organizationId
35635
35574
  }).sql;
35636
- } else if (organizationId) {
35637
- orgScope3 = buildOrgScopeWhere({
35638
- organization_id: organizationId,
35639
- baseParamIndex: baseParams.length + 1
35640
- });
35641
- baseParams.push(...orgScope3.params);
35575
+ } else {
35642
35576
  threadEntityLinkSql = "TRUE";
35643
35577
  }
35578
+ orgScope3 = buildOrgScopeWhere({
35579
+ organization_id: organizationId,
35580
+ baseParamIndex: baseParams.length + 1
35581
+ });
35582
+ baseParams.push(...orgScope3.params);
35644
35583
  baseConditions.push(connectionFilterClause);
35645
35584
  baseConditions.push(feedFilterClause);
35646
35585
  baseConditions.push(runFilterClause);
@@ -35706,6 +35645,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35706
35645
  ];
35707
35646
  const entityTypesClause2 = buildEntityTypesFilterClause({
35708
35647
  entity_types: options.entity_types,
35648
+ entity_id: entityId,
35709
35649
  organization_id: organizationId,
35710
35650
  baseParamIndex: filterParamsBeforeEntityTypes.length + 1
35711
35651
  });
@@ -35715,7 +35655,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35715
35655
  joinSql: "",
35716
35656
  whereExpr: `${whereSql} ${excludeClause2.sql}${producedClause.sql}${analyzedClause.sql} ${visibilityClause2.sql}${entityTypesClause2.sql} ${futureClause.sql}`,
35717
35657
  orgScope: orgScope3,
35718
- directArmRangeSql: buildEffectiveAtRangeSql(sinceParam, untilParam),
35658
+ orgWideRangeSql: buildEffectiveAtRangeSql(sinceParam, untilParam),
35719
35659
  countParams: allFilterParams,
35720
35660
  entityId: entityId ?? null,
35721
35661
  threadEntityLinkSqlForP: threadEntityLinkSql,
@@ -35746,7 +35686,8 @@ async function listContentInternal(sql2, options, limit, offset) {
35746
35686
  entityIdLiteral: validatedId,
35747
35687
  scopes: entityScopes,
35748
35688
  alias: "f",
35749
- baseParamIndex: standardParams.length + 1
35689
+ baseParamIndex: standardParams.length + 1,
35690
+ ownerOrganizationId: organizationId
35750
35691
  });
35751
35692
  standardEntityLinkSql = link.sql;
35752
35693
  standardEntityLinkParams = link.params;
@@ -35754,7 +35695,8 @@ async function listContentInternal(sql2, options, limit, offset) {
35754
35695
  entityIdLiteral: validatedId,
35755
35696
  scopes: entityScopes,
35756
35697
  alias: "p",
35757
- baseParamIndex: standardParams.length + 1
35698
+ baseParamIndex: standardParams.length + 1,
35699
+ ownerOrganizationId: organizationId
35758
35700
  }).sql;
35759
35701
  } else {
35760
35702
  standardEntityLinkSql = entityLinkMatchSql("$1::bigint");
@@ -35764,7 +35706,6 @@ async function listContentInternal(sql2, options, limit, offset) {
35764
35706
  });
35765
35707
  const paramsAfterEntityLink = [...standardParams, ...standardEntityLinkParams];
35766
35708
  const orgScope2 = buildOrgScopeWhere({
35767
- entity_id: entityId,
35768
35709
  organization_id: organizationId,
35769
35710
  baseParamIndex: paramsAfterEntityLink.length + 1
35770
35711
  });
@@ -35795,6 +35736,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35795
35736
  const paramsBeforeEntityTypes = [...paramsBeforeVisibility, ...visibilityClause.params];
35796
35737
  const entityTypesClause = buildEntityTypesFilterClause({
35797
35738
  entity_types: options.entity_types,
35739
+ entity_id: entityId,
35798
35740
  organization_id: organizationId,
35799
35741
  baseParamIndex: paramsBeforeEntityTypes.length + 1
35800
35742
  });
@@ -35827,7 +35769,7 @@ async function listContentInternal(sql2, options, limit, offset) {
35827
35769
  ${entityTypesClause.sql} ${resourceClause.sql} ${futureClause.sql}`,
35828
35770
  orgScope: orgScope2,
35829
35771
  // $3/$4 are buildStandardParams' since/until slots.
35830
- directArmRangeSql: buildEffectiveAtRangeSql("$3::timestamptz", "$4::timestamptz"),
35772
+ orgWideRangeSql: buildEffectiveAtRangeSql("$3::timestamptz", "$4::timestamptz"),
35831
35773
  countParams,
35832
35774
  threadEntityLinkSqlForP: standardEntityLinkSqlForP,
35833
35775
  needClassifications,
@@ -35984,14 +35926,39 @@ var init_embeddings = __esm({
35984
35926
  });
35985
35927
 
35986
35928
  // 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;
35929
+ function tsqueryTokens(queryText) {
35930
+ return queryText.toLowerCase().replace(/[^a-z0-9\s]+/g, " ").split(/\s+/).filter((t) => t.length > 0 && !STOPWORDS_SET.has(t));
35931
+ }
35932
+ function selectCandidateWords(tokens, frequencies, budget = CANDIDATE_TEXT_MATCH_BUDGET) {
35933
+ const stats = frequencies[0];
35934
+ if (!stats || stats.floor_frequency == null || !(stats.total_rows > 0)) return tokens;
35935
+ const unlistedFrequency = stats.floor_frequency / 2;
35936
+ const seen = /* @__PURE__ */ new Set();
35937
+ const estimated = [];
35938
+ for (const word of frequencies) {
35939
+ const key2 = [...word.lexemes].sort().join(" ");
35940
+ if (word.lexemes.length === 0 || seen.has(key2)) continue;
35941
+ seen.add(key2);
35942
+ estimated.push({
35943
+ token: word.token,
35944
+ rows: (word.frequency ?? unlistedFrequency) * stats.total_rows,
35945
+ position: estimated.length
35946
+ });
35947
+ }
35948
+ estimated.sort((a, b) => a.rows - b.rows || a.position - b.position);
35949
+ const kept = /* @__PURE__ */ new Set();
35950
+ let rows = 0;
35951
+ for (const word of estimated) {
35952
+ if (rows + word.rows > budget) break;
35953
+ rows += word.rows;
35954
+ kept.add(word.token);
35955
+ }
35956
+ return tokens.filter((token) => kept.has(token));
35990
35957
  }
35991
35958
  function buildSearchDocumentExpr(alias) {
35992
35959
  return `${alias}.search_tsv`;
35993
35960
  }
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;
35961
+ 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
35962
  var init_fts = __esm({
35996
35963
  "src/utils/content-search/fts.ts"() {
35997
35964
  "use strict";
@@ -36027,6 +35994,7 @@ var init_fts = __esm({
36027
35994
  "made"
36028
35995
  ];
36029
35996
  STOPWORDS_SET = new Set(STOPWORDS);
35997
+ CANDIDATE_TEXT_MATCH_BUDGET = 1e5;
36030
35998
  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
35999
  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
36000
  CANDIDATE_VECTOR_LIMIT = 200;
@@ -36058,6 +36026,18 @@ async function runBoundedRecallQuery(sql2, querySQL, queryParams, signal) {
36058
36026
  throw error;
36059
36027
  }
36060
36028
  }
36029
+ async function selectFulltextCandidateTsquery(sql2, queryText, signal, budget) {
36030
+ const tokens = tsqueryTokens(queryText);
36031
+ if (tokens.length === 0) return null;
36032
+ const frequencies = await runBoundedRecallQuery(
36033
+ sql2,
36034
+ QUERY_WORD_FREQUENCY_SQL,
36035
+ [pgTextArray(tokens)],
36036
+ signal
36037
+ );
36038
+ const words = selectCandidateWords(tokens, frequencies, budget);
36039
+ return words.length > 0 ? words.join(" | ") : null;
36040
+ }
36061
36041
  async function searchContentBySingleQuery(sql2, queryText, options, env) {
36062
36042
  const entityId = options.entity_id;
36063
36043
  const limit = Math.min(options.limit ?? 50, 500);
@@ -36089,9 +36069,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36089
36069
  const runCondition = buildRunFilter(runIdsArray);
36090
36070
  const searchEntityScopes = entityId != null ? await fetchEntityIdentityScopes(sql2, entityId) : [];
36091
36071
  const orgScope2 = buildOrgScopeWhere({
36092
- entity_id: entityId,
36093
36072
  organization_id: options.organization_id,
36094
- strict_organization_scope: options.strict_organization_scope,
36095
36073
  baseParamIndex: 14
36096
36074
  });
36097
36075
  const excludeParamIdx = 14 + orgScope2.params.length;
@@ -36118,6 +36096,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36118
36096
  const entityTypesParamIdx = visibilityParamIdx + visibilityClause.params.length;
36119
36097
  const entityTypesClause = buildEntityTypesFilterClause({
36120
36098
  entity_types: options.entity_types,
36099
+ entity_id: entityId,
36121
36100
  organization_id: options.organization_id,
36122
36101
  baseParamIndex: entityTypesParamIdx
36123
36102
  });
@@ -36131,7 +36110,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36131
36110
  entityIdLiteral: validatedId,
36132
36111
  scopes: searchEntityScopes,
36133
36112
  alias: "f",
36134
- baseParamIndex: entityLinkParamIdx
36113
+ baseParamIndex: entityLinkParamIdx,
36114
+ ownerOrganizationId: options.organization_id
36135
36115
  });
36136
36116
  searchEntityLinkSql = link.sql;
36137
36117
  searchEntityLinkParams = link.params;
@@ -36139,7 +36119,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36139
36119
  entityIdLiteral: validatedId,
36140
36120
  scopes: searchEntityScopes,
36141
36121
  alias: "p",
36142
- baseParamIndex: entityLinkParamIdx
36122
+ baseParamIndex: entityLinkParamIdx,
36123
+ ownerOrganizationId: options.organization_id
36143
36124
  }).sql;
36144
36125
  } else {
36145
36126
  searchEntityLinkSql = entityLinkMatchSql("$2::bigint");
@@ -36178,7 +36159,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36178
36159
  const vectorParamIdx = hasEmbedding ? baseParamIdx : null;
36179
36160
  const minSimilarityParamIdx = baseParamIdx + (hasEmbedding ? 1 : 0);
36180
36161
  const entityFilterSQL = entityId != null ? `${searchEntityLinkSql} AND ($2::bigint IS NOT NULL)` : `($2::bigint IS NULL OR ${searchEntityLinkSql})`;
36181
- const standardFiltersFor = (orgScopeSql) => `${entityFilterSQL}
36162
+ const standardFiltersSQL = `${entityFilterSQL}
36182
36163
  AND ${connectionCondition}
36183
36164
  AND ${feedCondition}
36184
36165
  AND ${runCondition}
@@ -36208,8 +36189,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36208
36189
  options.exclude_recall_bookkeeping && !options.semantic_type ? `AND ${RECALL_BOOKKEEPING_EXCLUSION_SQL}` : ""}
36209
36190
  ${classificationClause.sql}
36210
36191
  ${resourceClause.sql}
36211
- ${orgScopeSql}${entityTypesClause.sql}`;
36212
- const standardFiltersSQL = standardFiltersFor(orgScope2.sql);
36192
+ ${orgScope2.sql}${entityTypesClause.sql}`;
36213
36193
  const textDocumentExpr = buildSearchDocumentExpr("f");
36214
36194
  const resultDocumentExpr = buildSearchDocumentExpr("fi");
36215
36195
  const substringMatchExpr = hasEmbedding ? "text_match.substring_match" : `f.payload_text ILIKE '%' || $1 || '%'`;
@@ -36231,8 +36211,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36231
36211
  const bestSimSelect = hasEmbedding ? "chunk_score.best_sim" : "NULL";
36232
36212
  const substringMatchSelect = hasEmbedding ? "text_match.substring_match" : "NULL";
36233
36213
  const matchCondition = hasEmbedding ? `(${textMatchExpr} OR ${bestSimSelect} >= ${minSimilarityParam})` : textMatchExpr;
36234
- const searchWhereFor = (orgScopeSql) => `${matchCondition}
36235
- AND ${standardFiltersFor(orgScopeSql)}`;
36214
+ const searchWhereSQL = `${matchCondition}
36215
+ AND ${standardFiltersSQL}`;
36236
36216
  const rankedSubstringMatch = hasEmbedding ? "fi.substring_match" : `fi.payload_text ILIKE '%' || $1 || '%'`;
36237
36217
  const textRankExpr = `
36238
36218
  (CASE WHEN LENGTH($1) > 0 AND ${rankedSubstringMatch} THEN 0.5 ELSE 0.0 END)
@@ -36292,6 +36272,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36292
36272
  const validatedLimit = validateNumericId(limit, "limit");
36293
36273
  const useCandidatePath = options.approximate_candidate_search === true && options.agent_id == null && entityId == null && options.organization_id != null && !useDateFeed && effectiveOffset === 0 && hasEmbedding;
36294
36274
  const hasTextCandidates = useCandidatePath && trimmedQuery.length >= 3;
36275
+ const fulltextTsquery = hasTextCandidates ? await selectFulltextCandidateTsquery(sql2, trimmedQuery, options.signal) : null;
36295
36276
  let searchCandidatesCteSql = "";
36296
36277
  if (useCandidatePath) {
36297
36278
  const tsqueryParamIdx = offsetParamIdx + 1;
@@ -36301,12 +36282,38 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36301
36282
  AND ($6::int IS NOT NULL)
36302
36283
  AND iwf.run_id = $6::int`;
36303
36284
  const branches = [];
36285
+ const vectorScopeCtes = `vector_scope AS MATERIALIZED (
36286
+ SELECT f.id
36287
+ FROM current_event_records f
36288
+ ${candidateFilterJoins}
36289
+ WHERE ${standardFiltersSQL}
36290
+ LIMIT ${EXACT_RECALL_SCOPE_LIMIT + 1}
36291
+ ),
36292
+ vector_scope_size AS MATERIALIZED (
36293
+ SELECT COUNT(*) AS size FROM vector_scope
36294
+ ),
36295
+ `;
36296
+ branches.push(`SELECT scoped.id FROM vector_scope scoped
36297
+ CROSS JOIN LATERAL (
36298
+ SELECT MIN(emb.embedding <=> ${vecParam}) AS dist
36299
+ FROM event_embeddings emb
36300
+ WHERE emb.event_id = scoped.id AND ${modelScopeFor("emb")}
36301
+ ) nearest
36302
+ WHERE (SELECT size FROM vector_scope_size) <= ${EXACT_RECALL_SCOPE_LIMIT}
36303
+ AND (1 - nearest.dist) >= ${minSimilarityParam}
36304
+ ORDER BY nearest.dist
36305
+ LIMIT ${CANDIDATE_VECTOR_LIMIT}`);
36304
36306
  branches.push(`SELECT id FROM (
36305
36307
  SELECT emb.event_id AS id, (emb.embedding <=> ${vecParam}) AS dist
36306
36308
  FROM event_embeddings emb
36307
- JOIN current_event_records f ON f.id = emb.event_id
36308
- ${candidateFilterJoins}
36309
- WHERE ${standardFiltersSQL}
36309
+ JOIN LATERAL (
36310
+ SELECT f.id
36311
+ FROM current_event_records f
36312
+ ${candidateFilterJoins}
36313
+ WHERE f.id = emb.event_id AND ${standardFiltersSQL}
36314
+ OFFSET 0
36315
+ ) visible_event ON true
36316
+ WHERE (SELECT size FROM vector_scope_size) > ${EXACT_RECALL_SCOPE_LIMIT}
36310
36317
  AND ${modelScopeFor("emb")}
36311
36318
  AND (1 - (emb.embedding <=> ${vecParam})) >= ${minSimilarityParam}
36312
36319
  ORDER BY emb.embedding <=> ${vecParam}
@@ -36316,26 +36323,23 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36316
36323
  ORDER BY MIN(dist)
36317
36324
  LIMIT ${CANDIDATE_VECTOR_LIMIT}`);
36318
36325
  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
36326
+ const textCandidates = (matchSql, rankSql) => `SELECT ce.id AS id
36322
36327
  FROM events ce
36323
36328
  JOIN current_event_records f ON f.id = ce.id
36324
36329
  ${candidateFilterJoins}
36325
36330
  WHERE ${matchSql}
36326
- AND ${filters}
36331
+ AND ${standardFiltersSQL}
36327
36332
  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
- ));
36333
+ LIMIT ${CANDIDATE_VECTOR_LIMIT}`;
36334
+ if (fulltextTsquery !== null) {
36335
+ branches.push(textCandidates(
36336
+ `ce.search_tsv @@ to_tsquery('english', $${tsqueryParamIdx})`,
36337
+ `ts_rank_cd(ce.search_tsv, to_tsquery('english', $${tsqueryParamIdx}))`
36338
+ ));
36339
+ }
36336
36340
  branches.push(textCandidates(`ce.payload_text ILIKE '%' || $1 || '%'`, "ce.id + 0"));
36337
36341
  }
36338
- searchCandidatesCteSql = `search_candidates AS (
36342
+ searchCandidatesCteSql = `${vectorScopeCtes}search_candidates AS (
36339
36343
  ${branches.map((b) => `(${b})`).join("\n UNION\n ")}
36340
36344
  ),
36341
36345
  `;
@@ -36350,10 +36354,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36350
36354
  AND ($6::int IS NOT NULL)
36351
36355
  AND iwf.run_id = $6::int
36352
36356
  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));
36357
+ const exactFilteredIdsBody = filteredIdsSelect(searchWhereSQL);
36357
36358
  const nonDateFilteredIdsCteSql = `filtered_ids AS (
36358
36359
  ${useCandidatePath ? filteredIdsSelect(standardFiltersSQL, "JOIN search_candidates sc ON sc.id = f.id") : exactFilteredIdsBody}
36359
36360
  )`;
@@ -36496,8 +36497,8 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36496
36497
  ...cursorClause.params,
36497
36498
  ...useDateFeed ? [fetchLimit] : [includeTotal ? limit : limit + 1, effectiveOffset]
36498
36499
  ];
36499
- if (hasTextCandidates) {
36500
- queryParams.push(buildTsqueryString(trimmedQuery));
36500
+ if (fulltextTsquery !== null) {
36501
+ queryParams.push(fulltextTsquery);
36501
36502
  }
36502
36503
  let rawRows;
36503
36504
  const exactRead = { signal: options.signal, statementTimeoutMs: CONTENT_READ_STATEMENT_TIMEOUT_MS };
@@ -36532,6 +36533,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
36532
36533
  ...queryEmbeddingUnavailable && { query_embedding_unavailable: true }
36533
36534
  };
36534
36535
  }
36536
+ var EXACT_RECALL_SCOPE_LIMIT, QUERY_WORD_FREQUENCY_SQL;
36535
36537
  var init_search_path = __esm({
36536
36538
  "src/utils/content-search/search-path.ts"() {
36537
36539
  "use strict";
@@ -36555,6 +36557,26 @@ var init_search_path = __esm({
36555
36557
  init_types4();
36556
36558
  init_entity_types_filter();
36557
36559
  init_visibility();
36560
+ EXACT_RECALL_SCOPE_LIMIT = 4096;
36561
+ QUERY_WORD_FREQUENCY_SQL = `
36562
+ WITH stats AS MATERIALIZED (
36563
+ SELECT s.most_common_elems::text::text[] AS elems, s.most_common_elem_freqs AS freqs
36564
+ FROM pg_stats s
36565
+ JOIN pg_class c ON c.oid = 'events'::regclass
36566
+ JOIN pg_namespace n ON n.oid = c.relnamespace
36567
+ WHERE s.schemaname = n.nspname AND s.tablename = c.relname AND s.attname = 'search_tsv'
36568
+ ),
36569
+ words AS (
36570
+ SELECT t.token, tsvector_to_array(to_tsvector('english', t.token)) AS lexemes
36571
+ FROM unnest($1::text[]) AS t(token)
36572
+ )
36573
+ SELECT w.token, to_json(w.lexemes) AS lexemes,
36574
+ (SELECT max(e.freq) FROM stats, unnest(stats.elems, stats.freqs) AS e(elem, freq)
36575
+ WHERE e.elem = ANY(w.lexemes)) AS frequency,
36576
+ -- tsvector element frequencies are followed by their minimum and maximum.
36577
+ (SELECT stats.freqs[cardinality(stats.elems) + 1] FROM stats) AS floor_frequency,
36578
+ (SELECT c.reltuples FROM pg_class c WHERE c.oid = 'events'::regclass) AS total_rows
36579
+ FROM words w`;
36558
36580
  }
36559
36581
  });
36560
36582
 
@@ -51520,6 +51542,291 @@ var init_source_read_bridge = __esm({
51520
51542
  }
51521
51543
  });
51522
51544
 
51545
+ // src/lib/source-admission.ts
51546
+ function sourceCallerClassOfAccess(access) {
51547
+ return access === "public_visitor" ? "anonymous" : "member";
51548
+ }
51549
+ function sourceCallerClass(ctx) {
51550
+ return sourceCallerClassOfAccess(chatAccessOfToolContext(ctx));
51551
+ }
51552
+ 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;
51553
+ var init_source_admission = __esm({
51554
+ "src/lib/source-admission.ts"() {
51555
+ "use strict";
51556
+ init_src();
51557
+ init_device_access();
51558
+ init_race_abort();
51559
+ init_logger2();
51560
+ SOURCE_RUNS_PER_CONNECTION = 4;
51561
+ SOURCE_WAITERS_PER_CONNECTION = 32;
51562
+ MIN_RUN_BUDGET_MS = 2e3;
51563
+ RATE_LIMIT_STEP_MS = 3e4;
51564
+ REFUSAL_LOG_INTERVAL_MS = 1e4;
51565
+ DEFAULT_RUN_LATENCY_MS = 1e3;
51566
+ MAX_RETRY_AFTER_SECONDS = 30;
51567
+ SourceAdmissionRefusedError = class extends ToolError {
51568
+ constructor(message, retryAfterSeconds, outcome) {
51569
+ super("UPSTREAM_UNAVAILABLE", message);
51570
+ this.retryAfterSeconds = retryAfterSeconds;
51571
+ this.outcome = outcome;
51572
+ }
51573
+ retryAfterSeconds;
51574
+ outcome;
51575
+ };
51576
+ SourceAdmission = class {
51577
+ constructor(capacity = SOURCE_RUNS_PER_CONNECTION, maxWaiters = SOURCE_WAITERS_PER_CONNECTION) {
51578
+ this.capacity = capacity;
51579
+ this.maxWaiters = maxWaiters;
51580
+ }
51581
+ capacity;
51582
+ maxWaiters;
51583
+ connections = /* @__PURE__ */ new Map();
51584
+ reads = /* @__PURE__ */ new Map();
51585
+ lastRefusalLogAt = Number.NEGATIVE_INFINITY;
51586
+ unloggedRefusals = 0;
51587
+ /**
51588
+ * Run `start` once for every concurrent caller with the same `key`. A caller
51589
+ * that finds the read already running joins it and takes no slot. Each
51590
+ * participant waits under its own deadline and abort signal and receives its
51591
+ * own copy of the result; the shared run is aborted when every participant
51592
+ * has left or its original deadline expires. The entry is dropped when the
51593
+ * run settles.
51594
+ */
51595
+ async coalesce(key2, connectionId, participant, start) {
51596
+ participant.signal?.throwIfAborted();
51597
+ let shared = this.reads.get(key2);
51598
+ if (shared) {
51599
+ this.endSpan(this.startSpan(connectionId, participant.callerClass), "joined", 0, this.connections.get(connectionId));
51600
+ } else {
51601
+ const controller = new AbortController();
51602
+ const read2 = {
51603
+ participants: 0,
51604
+ controller,
51605
+ promise: Promise.resolve(),
51606
+ deadlineAt: participant.deadlineAt
51607
+ };
51608
+ const timer = setTimeout(() => controller.abort(Object.assign(
51609
+ new Error("source read timed out at the caller deadline"),
51610
+ { exitReason: "timeout" }
51611
+ )), Math.max(0, read2.deadlineAt - Date.now()));
51612
+ read2.promise = raceAbort((async () => start(controller.signal))(), controller.signal).finally(() => {
51613
+ clearTimeout(timer);
51614
+ if (this.reads.get(key2) === read2) this.reads.delete(key2);
51615
+ });
51616
+ this.reads.set(key2, read2);
51617
+ shared = read2;
51618
+ }
51619
+ const read = shared;
51620
+ read.participants += 1;
51621
+ return new Promise((resolve14, reject) => {
51622
+ let done = false;
51623
+ const settle = (finish) => {
51624
+ if (done) return;
51625
+ done = true;
51626
+ clearTimeout(timer);
51627
+ participant.signal?.removeEventListener("abort", onAbort);
51628
+ read.participants -= 1;
51629
+ finish();
51630
+ };
51631
+ const leave = (reason) => settle(() => {
51632
+ if (read.participants === 0) {
51633
+ if (this.reads.get(key2) === read) this.reads.delete(key2);
51634
+ read.controller.abort(reason);
51635
+ }
51636
+ reject(reason);
51637
+ });
51638
+ const onAbort = () => leave(participant.signal?.reason);
51639
+ const timer = participant.deadlineAt < read.deadlineAt ? setTimeout(
51640
+ () => leave(Object.assign(new Error("source read timed out at the caller deadline"), { exitReason: "timeout" })),
51641
+ Math.max(0, participant.deadlineAt - Date.now())
51642
+ ) : void 0;
51643
+ participant.signal?.addEventListener("abort", onAbort, { once: true });
51644
+ read.promise.then(
51645
+ (value) => settle(() => resolve14(structuredClone(value))),
51646
+ (error) => settle(() => reject(error))
51647
+ );
51648
+ });
51649
+ }
51650
+ /** Take a run slot on `connectionId`, waiting for one when the connection is full. */
51651
+ async acquire(connectionId, request2) {
51652
+ const startedAt = Date.now();
51653
+ const span = this.startSpan(connectionId, request2.callerClass);
51654
+ const state = this.state(connectionId);
51655
+ try {
51656
+ request2.signal?.throwIfAborted();
51657
+ this.pump(state);
51658
+ if (this.canRun(state, request2.callerClass)) {
51659
+ this.take(state, request2.callerClass);
51660
+ } else {
51661
+ if (state.waiters.length >= this.maxWaiters) throw this.refuse(connectionId, state, "refused_queue_full");
51662
+ const waitMs = request2.deadlineAt - MIN_RUN_BUDGET_MS - Date.now();
51663
+ if (waitMs <= 0) throw this.refuse(connectionId, state, "refused_deadline");
51664
+ await this.wait(connectionId, state, request2, waitMs);
51665
+ }
51666
+ } catch (error) {
51667
+ this.endSpan(
51668
+ span,
51669
+ error instanceof SourceAdmissionRefusedError ? error.outcome : "aborted",
51670
+ Date.now() - startedAt,
51671
+ state
51672
+ );
51673
+ this.forgetIdle(connectionId, state);
51674
+ throw error;
51675
+ }
51676
+ this.endSpan(span, "admitted", Date.now() - startedAt, state);
51677
+ return this.slot(connectionId, state, request2.callerClass);
51678
+ }
51679
+ state(connectionId) {
51680
+ let state = this.connections.get(connectionId);
51681
+ if (!state) {
51682
+ state = {
51683
+ running: 0,
51684
+ runningAnonymous: 0,
51685
+ waiters: [],
51686
+ limit: this.capacity,
51687
+ generation: 0,
51688
+ nextRestoreAt: 0,
51689
+ avgLatencyMs: null
51690
+ };
51691
+ this.connections.set(connectionId, state);
51692
+ }
51693
+ return state;
51694
+ }
51695
+ /** Drop a connection's state once nothing runs, waits, or is throttled on it. */
51696
+ forgetIdle(connectionId, state) {
51697
+ if (state.running === 0 && state.waiters.length === 0 && state.limit === this.capacity) {
51698
+ if (this.connections.get(connectionId) === state) this.connections.delete(connectionId);
51699
+ }
51700
+ }
51701
+ anonymousLimit(state) {
51702
+ return Math.max(1, state.limit - 1);
51703
+ }
51704
+ canRun(state, callerClass) {
51705
+ return state.running < state.limit && (callerClass === "member" || state.runningAnonymous < this.anonymousLimit(state));
51706
+ }
51707
+ take(state, callerClass) {
51708
+ state.running += 1;
51709
+ if (callerClass === "anonymous") state.runningAnonymous += 1;
51710
+ }
51711
+ /** Restore one slot per clean interval since the last 429, then admit whoever can run. */
51712
+ pump(state) {
51713
+ const now = Date.now();
51714
+ while (state.limit < this.capacity && now >= state.nextRestoreAt) {
51715
+ state.limit += 1;
51716
+ state.nextRestoreAt += RATE_LIMIT_STEP_MS;
51717
+ }
51718
+ for (; ; ) {
51719
+ if (state.running >= state.limit) return;
51720
+ let index = state.waiters.findIndex((waiter2) => waiter2.callerClass === "member");
51721
+ if (index < 0 && state.runningAnonymous < this.anonymousLimit(state)) index = 0;
51722
+ const waiter = index < 0 ? void 0 : state.waiters[index];
51723
+ if (!waiter) return;
51724
+ state.waiters.splice(index, 1);
51725
+ this.take(state, waiter.callerClass);
51726
+ waiter.admit();
51727
+ }
51728
+ }
51729
+ wait(connectionId, state, request2, waitMs) {
51730
+ return new Promise((resolve14, reject) => {
51731
+ const cleanup = () => {
51732
+ clearTimeout(timer);
51733
+ request2.signal?.removeEventListener("abort", onAbort);
51734
+ };
51735
+ const waiter = {
51736
+ callerClass: request2.callerClass,
51737
+ admit: () => {
51738
+ cleanup();
51739
+ resolve14();
51740
+ }
51741
+ };
51742
+ const leave = (error) => {
51743
+ const index = state.waiters.indexOf(waiter);
51744
+ if (index < 0) return;
51745
+ state.waiters.splice(index, 1);
51746
+ cleanup();
51747
+ reject(error);
51748
+ };
51749
+ const onAbort = () => leave(request2.signal?.reason);
51750
+ const timer = setTimeout(() => leave(this.refuse(connectionId, state, "refused_deadline")), waitMs);
51751
+ request2.signal?.addEventListener("abort", onAbort, { once: true });
51752
+ state.waiters.push(waiter);
51753
+ });
51754
+ }
51755
+ slot(connectionId, state, callerClass) {
51756
+ const generation = state.generation;
51757
+ const startedAt = Date.now();
51758
+ let released = false;
51759
+ return {
51760
+ release: ({ rateLimited }) => {
51761
+ if (released) return;
51762
+ released = true;
51763
+ state.running -= 1;
51764
+ if (callerClass === "anonymous") state.runningAnonymous -= 1;
51765
+ const latencyMs = Date.now() - startedAt;
51766
+ state.avgLatencyMs = state.avgLatencyMs === null ? latencyMs : state.avgLatencyMs * 0.8 + latencyMs * 0.2;
51767
+ if (rateLimited) {
51768
+ state.nextRestoreAt = Date.now() + RATE_LIMIT_STEP_MS;
51769
+ if (generation === state.generation) {
51770
+ state.limit = Math.max(1, Math.floor(state.limit / 2));
51771
+ state.generation += 1;
51772
+ }
51773
+ }
51774
+ this.pump(state);
51775
+ this.forgetIdle(connectionId, state);
51776
+ }
51777
+ };
51778
+ }
51779
+ /** Seconds until the queue ahead has likely drained at the current limit. */
51780
+ retryAfterSeconds(state) {
51781
+ const latencySeconds = (state.avgLatencyMs ?? DEFAULT_RUN_LATENCY_MS) / 1e3;
51782
+ const estimate = Math.ceil(state.waiters.length * latencySeconds / state.limit);
51783
+ return Math.min(MAX_RETRY_AFTER_SECONDS, Math.max(1, estimate));
51784
+ }
51785
+ refuse(connectionId, state, outcome) {
51786
+ const retryAfterSeconds = this.retryAfterSeconds(state);
51787
+ const now = Date.now();
51788
+ if (now - this.lastRefusalLogAt >= REFUSAL_LOG_INTERVAL_MS) {
51789
+ logger_default.warn({
51790
+ connectionId,
51791
+ outcome,
51792
+ running: state.running,
51793
+ waiting: state.waiters.length,
51794
+ limit: state.limit,
51795
+ refusedSinceLastLog: this.unloggedRefusals
51796
+ }, "[source-admission] refusing live source reads at the connection limit");
51797
+ this.lastRefusalLogAt = now;
51798
+ this.unloggedRefusals = 0;
51799
+ } else {
51800
+ this.unloggedRefusals += 1;
51801
+ }
51802
+ return new SourceAdmissionRefusedError(
51803
+ 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`,
51804
+ retryAfterSeconds,
51805
+ outcome
51806
+ );
51807
+ }
51808
+ startSpan(connectionId, callerClass) {
51809
+ return createSpan("source.admission", {
51810
+ "lobu.source.connection_id": connectionId,
51811
+ "lobu.source.admission.class": callerClass
51812
+ });
51813
+ }
51814
+ /** Close the admission span with what the caller got and what it found. */
51815
+ endSpan(span, outcome, waitMs, state) {
51816
+ span?.setAttributes({
51817
+ "lobu.source.admission.outcome": outcome,
51818
+ "lobu.source.admission.wait_ms": waitMs,
51819
+ "lobu.source.admission.inflight": state?.running ?? 0,
51820
+ "lobu.source.admission.queue_depth": state?.waiters.length ?? 0,
51821
+ "lobu.source.admission.limit": state?.limit ?? this.capacity
51822
+ });
51823
+ span?.end();
51824
+ }
51825
+ };
51826
+ sourceAdmission = new SourceAdmission();
51827
+ }
51828
+ });
51829
+
51523
51830
  // src/lib/connector-pushdown.ts
51524
51831
  import { createHash as createHash19 } from "node:crypto";
51525
51832
  function isTransientUpstreamFailure(error) {
@@ -51557,10 +51864,37 @@ async function runConnectorQuery(p) {
51557
51864
  );
51558
51865
  }
51559
51866
  const conn = connRows[0];
51560
- const compiledCode = await resolveConnectorCodeForKey(
51867
+ const readKey = createHash19("sha256").update(stableJson({
51868
+ connectionId: Number(conn.id),
51869
+ connectorKey: conn.connector_key,
51870
+ callerClass: p.callerClass,
51871
+ query: p.query,
51872
+ exactMatch: p.exactMatch ?? null,
51873
+ selection: p.selection ?? null,
51874
+ limit: p.limit ?? null,
51875
+ offset: p.offset ?? null,
51876
+ sort: p.sort ?? null,
51877
+ config: p.config ?? null
51878
+ })).digest("hex");
51879
+ const participant = { callerClass: p.callerClass, deadlineAt, signal: p.signal };
51880
+ return sourceAdmission.coalesce(readKey, Number(conn.id), participant, async (signal) => {
51881
+ const slot = await sourceAdmission.acquire(Number(conn.id), { ...participant, signal });
51882
+ let rateLimited = false;
51883
+ try {
51884
+ return await raceAbort(runAdmittedQuery(p, conn, deadlineAt, signal, () => {
51885
+ rateLimited = true;
51886
+ }), signal);
51887
+ } finally {
51888
+ slot.release({ rateLimited });
51889
+ }
51890
+ });
51891
+ }
51892
+ async function runAdmittedQuery(p, conn, deadlineAt, signal, onRateLimited) {
51893
+ signal.throwIfAborted();
51894
+ const compiledCode = await raceAbort(resolveConnectorCodeForKey(
51561
51895
  conn.connector_key,
51562
51896
  p.scope.organizationId
51563
- );
51897
+ ), signal);
51564
51898
  const authParams = {
51565
51899
  organizationId: p.scope.organizationId,
51566
51900
  connectionId: conn.id,
@@ -51570,8 +51904,9 @@ async function runConnectorQuery(p) {
51570
51904
  logContext: { connection: p.connectionSlug },
51571
51905
  logMessage: "Failed to resolve connector query credentials"
51572
51906
  };
51573
- let auth = await resolveExecutionAuth(authParams);
51907
+ let auth = await raceAbort(resolveExecutionAuth(authParams), signal);
51574
51908
  const execute = async (resolved) => {
51909
+ signal.throwIfAborted();
51575
51910
  const { credentials, connectionCredentials, sessionState, httpAuth, onHttpFetch } = resolved;
51576
51911
  return executeCompiledConnector({
51577
51912
  compiledCode,
@@ -51602,7 +51937,7 @@ async function runConnectorQuery(p) {
51602
51937
  offset: p.offset,
51603
51938
  sort: p.sort
51604
51939
  },
51605
- hooks: { onHttpFetch },
51940
+ hooks: { onHttpFetch, signal },
51606
51941
  timeoutMs: resolvePushdownTimeoutMs(deadlineAt)
51607
51942
  });
51608
51943
  };
@@ -51610,18 +51945,25 @@ async function runConnectorQuery(p) {
51610
51945
  try {
51611
51946
  result = await execute(auth);
51612
51947
  } catch (error) {
51948
+ signal.throwIfAborted();
51613
51949
  const status = error?.httpStatus;
51950
+ if (status === 429) onRateLimited();
51614
51951
  if (status === 401 && auth.credentials?.accessToken) {
51615
51952
  const rejectedAccessToken = auth.credentials.accessToken;
51616
- auth = await resolveExecutionAuth({ ...authParams, rejectedAccessToken });
51953
+ auth = await raceAbort(resolveExecutionAuth({ ...authParams, rejectedAccessToken }), signal);
51617
51954
  if (!auth.credentials?.accessToken || auth.credentials.accessToken === rejectedAccessToken) throw error;
51618
51955
  } else {
51619
51956
  if (!isTransientUpstreamFailure(error)) throw error;
51620
51957
  if (deadlineAt - Date.now() <= PUSHDOWN_RETRY_BACKOFF_MS) throw error;
51621
- await new Promise((resolve14) => setTimeout(resolve14, PUSHDOWN_RETRY_BACKOFF_MS));
51958
+ await raceAbort(new Promise((resolve14) => setTimeout(resolve14, PUSHDOWN_RETRY_BACKOFF_MS)), signal);
51622
51959
  }
51623
51960
  if (deadlineAt <= Date.now()) throw error;
51624
- result = await execute(auth);
51961
+ try {
51962
+ result = await execute(auth);
51963
+ } catch (retryError) {
51964
+ if (retryError?.httpStatus === 429) onRateLimited();
51965
+ throw retryError;
51966
+ }
51625
51967
  }
51626
51968
  if (result.mode !== "query") {
51627
51969
  throw new Error(`Expected query result, got mode=${result.mode}`);
@@ -51639,11 +51981,14 @@ function isCompletePushdownResult(result) {
51639
51981
  }
51640
51982
  function pushdownFailureError(err, connectionSlug, subject) {
51641
51983
  const code = classifyPushdownFailure(err);
51642
- return new ToolUserError(
51984
+ const failure = new ToolUserError(
51643
51985
  `connection pushdown failed (connection=${connectionSlug}): ${getErrorMessage(err)}. The ${subject} did not run against the source \u2014 this is not an empty result.`,
51644
51986
  toolErrorHttpStatus(code),
51645
51987
  code
51646
51988
  );
51989
+ const retryAfterSeconds = err?.retryAfterSeconds;
51990
+ if (typeof retryAfterSeconds === "number") failure.retryAfterSeconds = retryAfterSeconds;
51991
+ return failure;
51647
51992
  }
51648
51993
  function classifyPushdownFailure(err) {
51649
51994
  if (err instanceof ToolError) return err.code;
@@ -51664,8 +52009,9 @@ async function readSourceFeed(p) {
51664
52009
  let timer;
51665
52010
  const deadline = new Promise((_resolve, reject) => {
51666
52011
  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));
52012
+ const error = browserLeased ? new BrowserInterruptionError("timeout", `Browser source read ${p.feedId} timed out; no recovery handoff was issued.`) : sourceReadDeadlineError(p.feedId);
52013
+ controller.abort(error);
52014
+ reject(error);
51669
52015
  }, timeoutMs);
51670
52016
  });
51671
52017
  try {
@@ -51910,7 +52256,27 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51910
52256
  signal: p.signal
51911
52257
  });
51912
52258
  }
51913
- const adapterResult = p.recoveryId ? null : await readSourceFeedFromAdapter({
52259
+ if (feed.device_worker_id !== null) {
52260
+ return readLiveSourceFeed(p, feed, feedConfig, sourceRevision, sourceSubscription, finish, onBrowserLease);
52261
+ }
52262
+ const slot = await sourceAdmission.acquire(Number(feed.connection_id), {
52263
+ callerClass: sourceCallerClassOfAccess(p.scope.chatAccess),
52264
+ deadlineAt: p.deadlineAt,
52265
+ signal: p.signal
52266
+ });
52267
+ let rateLimited = false;
52268
+ try {
52269
+ return await raceAbort(readLiveSourceFeed(p, feed, feedConfig, sourceRevision, sourceSubscription, finish, onBrowserLease), p.signal);
52270
+ } catch (error) {
52271
+ rateLimited = error?.httpStatus === 429;
52272
+ throw error;
52273
+ } finally {
52274
+ slot.release({ rateLimited });
52275
+ }
52276
+ }
52277
+ async function readLiveSourceFeed(p, feed, feedConfig, sourceRevision, sourceSubscription, finish, onBrowserLease) {
52278
+ remainingReadMs(p);
52279
+ const adapterResult = p.recoveryId ? null : await raceAbort(readSourceFeedFromAdapter({
51914
52280
  organizationId: p.scope.organizationId,
51915
52281
  connectionId: Number(feed.connection_id),
51916
52282
  connectorKey: feed.connector_key,
@@ -51926,16 +52292,16 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51926
52292
  sort: p.sort,
51927
52293
  signal: p.signal,
51928
52294
  deadlineAt: p.deadlineAt
51929
- });
52295
+ }), p.signal);
51930
52296
  if (adapterResult) {
51931
52297
  return finish({ ...adapterResult, columns: adapterResult.columns ?? [] });
51932
52298
  }
51933
- const compiledCode = await resolveConnectorCodeForKey(
52299
+ const compiledCode = await raceAbort(resolveConnectorCodeForKey(
51934
52300
  feed.connector_key,
51935
52301
  p.scope.organizationId,
51936
52302
  feed.pinned_version ?? feed.definition_version
51937
- );
51938
- const { credentials, connectionCredentials, sessionState, httpAuth, onHttpFetch } = await resolveExecutionAuth({
52303
+ ), p.signal);
52304
+ const { credentials, connectionCredentials, sessionState, httpAuth, onHttpFetch } = await raceAbort(resolveExecutionAuth({
51939
52305
  organizationId: p.scope.organizationId,
51940
52306
  connectionId: feed.connection_id,
51941
52307
  authProfileId: Number(feed.auth_profile_id) || null,
@@ -51943,12 +52309,12 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51943
52309
  credentialDb: getDb(),
51944
52310
  logContext: { feedId: String(p.feedId) },
51945
52311
  logMessage: "Failed to resolve feed source-read credentials"
51946
- });
52312
+ }), p.signal);
51947
52313
  const config = {
51948
52314
  ...mergeExecutionConfig(feed.connection_config, connectionCredentials, feedConfig),
51949
52315
  ...dbEgressConfig()
51950
52316
  };
51951
- const timeoutMs = remainingReadMs(p);
52317
+ remainingReadMs(p);
51952
52318
  const artifactHash = computeCodeHash(compiledCode);
51953
52319
  const browser = createSourceReadBridge({ ...feed, selected_artifact_hash: artifactHash }, {
51954
52320
  scope: p.scope,
@@ -51985,7 +52351,7 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51985
52351
  config,
51986
52352
  env: { ...dbEgressConfig(), ...httpEgressAllowHostsEnv() },
51987
52353
  sessionState,
51988
- browser: await connectionBrowserGrant(p.scope.organizationId, feed.connection_id, feed.pinned_version ?? feed.definition_version),
52354
+ browser: await raceAbort(connectionBrowserGrant(p.scope.organizationId, feed.connection_id, feed.pinned_version ?? feed.definition_version), p.signal),
51989
52355
  credentials,
51990
52356
  httpAuth,
51991
52357
  limit: p.limit,
@@ -51998,7 +52364,7 @@ async function readSourceFeedWithinDeadline(p, onBrowserLease) {
51998
52364
  signal: p.signal,
51999
52365
  onChromeDispatch: browser.onChromeDispatch
52000
52366
  },
52001
- timeoutMs
52367
+ timeoutMs: remainingReadMs(p)
52002
52368
  });
52003
52369
  if (result.mode !== "read") {
52004
52370
  throw new Error(`Expected read result, got mode=${result.mode}`);
@@ -52035,6 +52401,7 @@ var init_connector_pushdown = __esm({
52035
52401
  init_connector_catalog();
52036
52402
  init_ensure_connector_installed();
52037
52403
  init_execution_context();
52404
+ init_race_abort();
52038
52405
  init_device_feed_read();
52039
52406
  init_source_feed_adapters();
52040
52407
  init_source_read_bridge();
@@ -52042,6 +52409,7 @@ var init_connector_pushdown = __esm({
52042
52409
  init_connector_execution_placement();
52043
52410
  init_compiler_core();
52044
52411
  init_source_feed_subscriptions();
52412
+ init_source_admission();
52045
52413
  PUSHDOWN_QUERY_TIMEOUT_MS = 3e4;
52046
52414
  PUSHDOWN_RETRY_BACKOFF_MS = 250;
52047
52415
  }
@@ -59822,20 +60190,6 @@ function stripChatLinkTriggers(triggers) {
59822
60190
  return true;
59823
60191
  });
59824
60192
  }
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
60193
  async function handleCreate(args, _env, ctx) {
59840
60194
  const sql2 = getDb();
59841
60195
  if (!args.slug) {
@@ -60322,17 +60676,17 @@ async function handleUpdate(args, _env, ctx, base) {
60322
60676
  const lockedCadenceChanged = lockedTouchesCadence && (lockedEffectiveSchedule !== locked.schedule || lockedEffectiveTimezone !== locked.timezone);
60323
60677
  const lockedNextRunAtVal = lockedTouchesCadence && lockedEffectiveSchedule ? nextRunAt(lockedEffectiveSchedule, /* @__PURE__ */ new Date(), lockedEffectiveTimezone) : null;
60324
60678
  const valueChangedFields = [];
60325
- if (has("execution_config") && stableJson2(patch.execution_config ?? null) !== stableJson2(locked.execution_config ?? null)) valueChangedFields.push("execution_config");
60679
+ if (has("execution_config") && stableJson(patch.execution_config ?? null) !== stableJson(locked.execution_config ?? null)) valueChangedFields.push("execution_config");
60326
60680
  if (has("triggers") && !lockedTriggersValueEqual) valueChangedFields.push("triggers");
60327
60681
  if (has("managed_agent_id") && (patch.managed_agent_id ?? null) !== (locked.managed_agent_id ?? null)) valueChangedFields.push("managed_agent_id");
60328
60682
  if (has("tags")) {
60329
60683
  const lockedTags = parsePgTextArray(locked.tags);
60330
60684
  const nextTags = patch.tags ?? [];
60331
- if (stableJson2([...lockedTags].sort()) !== stableJson2([...nextTags].sort())) valueChangedFields.push("tags");
60685
+ if (stableJson([...lockedTags].sort()) !== stableJson([...nextTags].sort())) valueChangedFields.push("tags");
60332
60686
  }
60333
60687
  if (has("device_worker_id") && (patch.device_worker_id ?? null) !== (locked.device_worker_id ?? null)) valueChangedFields.push("device_worker_id");
60334
60688
  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");
60689
+ if (has("delivery_target") && stableJson(patch.delivery_target ?? null) !== stableJson(locked.delivery_target ?? null)) valueChangedFields.push("delivery_target");
60336
60690
  if (has("min_cooldown_seconds") && Number(patch.min_cooldown_seconds ?? 0) !== Number(locked.min_cooldown_seconds ?? 0)) valueChangedFields.push("min_cooldown_seconds");
60337
60691
  if (lockedTouchesCadence) {
60338
60692
  if (lockedEffectiveSchedule !== locked.schedule) valueChangedFields.push("schedule");
@@ -64510,11 +64864,13 @@ async function runMetric(input) {
64510
64864
  });
64511
64865
  let rows;
64512
64866
  try {
64513
- rows = await sql2.begin(async (tx) => {
64514
- await tx`SET TRANSACTION READ ONLY`;
64515
- return tx.unsafe(scoped.sql, scoped.params);
64867
+ rows = await boundedQuery(sql2, scoped.sql, scoped.params, {
64868
+ signal: input.signal,
64869
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
64870
+ fence: scoped.scope
64516
64871
  });
64517
64872
  } catch (err) {
64873
+ if (input.signal?.aborted) throw err;
64518
64874
  const failure = classifyReadQueryFailure(err);
64519
64875
  throw new ToolUserError(failure.message, toolErrorHttpStatus(failure.code), failure.code);
64520
64876
  }
@@ -64543,7 +64899,9 @@ async function runPushdownMetric(input, metrics2, backingSql, backingSource) {
64543
64899
  isAdmin: input.isAdmin ?? false,
64544
64900
  connectionSlug: backingSource,
64545
64901
  query,
64546
- limit: METRIC_PUSHDOWN_MAX_ROWS
64902
+ limit: METRIC_PUSHDOWN_MAX_ROWS,
64903
+ signal: input.signal,
64904
+ callerClass: input.callerClass ?? "member"
64547
64905
  });
64548
64906
  } catch (err) {
64549
64907
  throw pushdownFailureError(err, backingSource, "metric");
@@ -64564,6 +64922,7 @@ var init_run_metric = __esm({
64564
64922
  init_client();
64565
64923
  init_connector_pushdown();
64566
64924
  init_bounded_read();
64925
+ init_content_read_bounds();
64567
64926
  init_errors2();
64568
64927
  init_execute_data_sources();
64569
64928
  init_table_schema();
@@ -74380,6 +74739,9 @@ function connectionOperationsExecutor(connection) {
74380
74739
  function connectorChatPlatform(defaultUserName, create2) {
74381
74740
  return {
74382
74741
  connectorTransport: true,
74742
+ // Replies are plain text sent through the connector; a card's buttons
74743
+ // would arrive as an untappable list.
74744
+ rendersActionButtons: false,
74383
74745
  parseSourceMessage: (adapter, row) => adapter.parseSourceRow(row),
74384
74746
  createAdapter: async (_config, context5) => {
74385
74747
  const connection = context5?.connection;
@@ -78823,12 +79185,28 @@ var init_tokens = __esm({
78823
79185
  });
78824
79186
 
78825
79187
  // src/diagnostics.ts
79188
+ import { HTTPException as HTTPException2 } from "hono/http-exception";
78826
79189
  function markErrorReported(c) {
78827
79190
  c.set(ERROR_REPORTED_FLAG, true);
78828
79191
  }
78829
79192
  function isErrorReported(c) {
78830
79193
  return Boolean(c.get(ERROR_REPORTED_FLAG));
78831
79194
  }
79195
+ function routeFailure(response, cause) {
79196
+ return new HTTPException2(response.status, { res: response, cause });
79197
+ }
79198
+ function redactedFailure(error) {
79199
+ const shape = error && typeof error === "object" ? error : {};
79200
+ const cause = shape.cause && typeof shape.cause === "object" ? shape.cause : {};
79201
+ const code = typeof shape.code === "string" ? shape.code : typeof cause.code === "string" ? cause.code : void 0;
79202
+ const frames = typeof shape.stack === "string" ? shape.stack.split("\n").filter((line) => line.trimStart().startsWith("at ")).join("\n") : "";
79203
+ return {
79204
+ name: typeof shape.name === "string" && shape.name ? shape.name : "Error",
79205
+ message: "details withheld at a credential boundary",
79206
+ ...code ? { code } : {},
79207
+ ...frames ? { stack: frames } : {}
79208
+ };
79209
+ }
78832
79210
  function captureServerError(c, error, source, httpStatus) {
78833
79211
  if (error instanceof ToolUserError || isErrorReported(c)) return;
78834
79212
  logger_default.error({
@@ -79155,6 +79533,7 @@ var init_agent_ownership = __esm({
79155
79533
  });
79156
79534
 
79157
79535
  // src/gateway/routes/shared/helpers.ts
79536
+ import { HTTPException as HTTPException3 } from "hono/http-exception";
79158
79537
  function errorResponse(c, message, status) {
79159
79538
  return c.json({ error: message }, status);
79160
79539
  }
@@ -79202,8 +79581,9 @@ async function withOwnedAgent(c, options, handler) {
79202
79581
  }
79203
79582
  return await handler({ session, agentId, access });
79204
79583
  } catch (error) {
79584
+ if (error instanceof HTTPException3) throw error;
79205
79585
  options.logger.error(options.errorLabel, { error, agentId });
79206
- return errorResponse(c, "Internal server error", 500);
79586
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
79207
79587
  }
79208
79588
  }
79209
79589
  var init_helpers = __esm({
@@ -79211,6 +79591,7 @@ var init_helpers = __esm({
79211
79591
  "use strict";
79212
79592
  init_settings_auth();
79213
79593
  init_agent_ownership();
79594
+ init_diagnostics();
79214
79595
  }
79215
79596
  });
79216
79597
 
@@ -79324,7 +79705,7 @@ async function listDeviceWorkers(c) {
79324
79705
  } catch (err) {
79325
79706
  logger_default.error({ error: errorMessage(err) }, "[listDeviceWorkers] Error");
79326
79707
  captureServerError(c, err, "listDeviceWorkers", 500);
79327
- return c.json({ error: errorMessage(err) }, 500);
79708
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79328
79709
  }
79329
79710
  }
79330
79711
  async function mintDeviceChildToken(c) {
@@ -79566,7 +79947,7 @@ async function mintDeviceChildToken(c) {
79566
79947
  } catch (err) {
79567
79948
  logger_default.error({ err: errorMessage(err) }, "[mintDeviceChildToken] failed");
79568
79949
  captureServerError(c, err, "mintDeviceChildToken", 500);
79569
- return c.json({ error: errorMessage(err) }, 500);
79950
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79570
79951
  }
79571
79952
  }
79572
79953
  async function updateDeviceWorkerOrg(c) {
@@ -79690,7 +80071,7 @@ async function updateDeviceWorkerOrg(c) {
79690
80071
  return c.json({ ok: true, ...hasLabel ? { label: nextLabel ?? null } : {} });
79691
80072
  } catch (err) {
79692
80073
  logger_default.error({ error: errorMessage(err) }, "[updateDeviceWorkerOrg] Error");
79693
- return c.json({ error: errorMessage(err) }, 500);
80074
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79694
80075
  }
79695
80076
  }
79696
80077
  async function deleteDeviceWorker(c) {
@@ -79793,7 +80174,7 @@ async function deleteDeviceWorker(c) {
79793
80174
  return c.json({ ok: true });
79794
80175
  } catch (err) {
79795
80176
  logger_default.error({ error: errorMessage(err) }, "[deleteDeviceWorker] Error");
79796
- return c.json({ error: errorMessage(err) }, 500);
80177
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
79797
80178
  }
79798
80179
  }
79799
80180
  var DEVICE_WORKER_ID_PATTERN, CHILD_PAT_EXPIRES_IN_DAYS, CHILD_SELF_MINT_ONLY, DEVICE_LABEL_MAX_LEN;
@@ -80098,7 +80479,8 @@ function publicVisitorContext(organizationId, request2) {
80098
80479
  directSearchFederation: false,
80099
80480
  requestUrl: request2.requestUrl,
80100
80481
  baseUrl: request2.baseUrl,
80101
- ...request2.abortSignal ? { abortSignal: request2.abortSignal } : {}
80482
+ ...request2.abortSignal ? { abortSignal: request2.abortSignal } : {},
80483
+ ...request2.deadlineAt !== void 0 ? { deadlineAt: request2.deadlineAt } : {}
80102
80484
  };
80103
80485
  }
80104
80486
  var init_public_browse_context = __esm({
@@ -89012,7 +89394,6 @@ async function buildExactIdScopeWhere(sql2, opts) {
89012
89394
  const params = [];
89013
89395
  const orgScope2 = buildOrgScopeWhere({
89014
89396
  organization_id: opts.organizationId,
89015
- strict_organization_scope: true,
89016
89397
  baseParamIndex: opts.baseParamIndex + params.length
89017
89398
  });
89018
89399
  params.push(...orgScope2.params);
@@ -89024,7 +89405,8 @@ async function buildExactIdScopeWhere(sql2, opts) {
89024
89405
  entityIdLiteral: validatedId,
89025
89406
  scopes,
89026
89407
  alias: "f",
89027
- baseParamIndex: opts.baseParamIndex + params.length
89408
+ baseParamIndex: opts.baseParamIndex + params.length,
89409
+ ownerOrganizationId: opts.organizationId
89028
89410
  });
89029
89411
  entityFilter = ` AND ${link.sql}`;
89030
89412
  params.push(...link.params);
@@ -90019,20 +90401,7 @@ async function getContentImpl(args, env, ctx) {
90019
90401
  ON et.id = e.entity_type_id
90020
90402
  AND et.deleted_at IS NULL
90021
90403
  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
- )
90404
+ AND ev.organization_id = ${ctx.organizationId}
90036
90405
  `;
90037
90406
  requestedRecords.push(...eventTypeRows.flatMap((row) => row.id === null ? [] : [{ id: row.id }]));
90038
90407
  for (const row of eventTypeRows) {
@@ -90305,7 +90674,7 @@ async function getContentImpl(args, env, ctx) {
90305
90674
  logger_default.info(`[get_content] ${args.query ? "Search query provided" : "Listing content"}`);
90306
90675
  const searchOptions = {
90307
90676
  entity_id: args.entity_id,
90308
- organization_id: !args.entity_id ? ctx.organizationId : void 0,
90677
+ organization_id: ctx.organizationId,
90309
90678
  connection_ids: effectiveConnectionIds,
90310
90679
  feed_ids: args.feed_ids,
90311
90680
  run_ids: args.run_ids,
@@ -92019,6 +92388,54 @@ function verifyClientSecret(secret, storedHash) {
92019
92388
  return false;
92020
92389
  }
92021
92390
  }
92391
+ async function releaseClientHomedInOrganization(tx, organizationId) {
92392
+ const [homed] = await tx`
92393
+ SELECT id FROM oauth_clients
92394
+ WHERE organization_id = ${organizationId}
92395
+ LIMIT 1
92396
+ FOR UPDATE
92397
+ `;
92398
+ if (!homed) return null;
92399
+ const clientId = homed.id;
92400
+ await new OAuthClientsStore(tx).revokeClientForOrganization(clientId, organizationId, null, tx);
92401
+ const [credentials] = await tx`
92402
+ SELECT (
92403
+ EXISTS (
92404
+ SELECT 1 FROM oauth_tokens
92405
+ WHERE client_id = ${clientId} AND revoked_at IS NULL AND expires_at > NOW()
92406
+ )
92407
+ OR EXISTS (
92408
+ SELECT 1 FROM oauth_authorization_codes
92409
+ WHERE client_id = ${clientId} AND expires_at > NOW()
92410
+ )
92411
+ OR EXISTS (
92412
+ SELECT 1 FROM oauth_device_codes
92413
+ WHERE client_id = ${clientId} AND expires_at > NOW()
92414
+ )
92415
+ OR EXISTS (
92416
+ SELECT 1 FROM mcp_sessions
92417
+ WHERE client_id = ${clientId} AND expires_at > NOW()
92418
+ )
92419
+ ) AS live
92420
+ `;
92421
+ if (credentials.live || await anyEventNamesClient(tx, clientId)) {
92422
+ await tx`
92423
+ UPDATE oauth_clients SET organization_id = NULL, updated_at = NOW()
92424
+ WHERE id = ${clientId}
92425
+ `;
92426
+ return "detached";
92427
+ }
92428
+ await tx`DELETE FROM oauth_clients WHERE id = ${clientId}`;
92429
+ return "deleted";
92430
+ }
92431
+ async function anyEventNamesClient(tx, clientId) {
92432
+ await tx`SET LOCAL enable_seqscan = off`;
92433
+ const [probe] = await tx`
92434
+ SELECT EXISTS (SELECT 1 FROM events WHERE client_id = ${clientId}) AS named
92435
+ `;
92436
+ await tx`SET LOCAL enable_seqscan TO DEFAULT`;
92437
+ return probe.named;
92438
+ }
92022
92439
  var OAuthClientsStore;
92023
92440
  var init_clients = __esm({
92024
92441
  "src/auth/oauth/clients.ts"() {
@@ -92197,9 +92614,12 @@ var init_clients = __esm({
92197
92614
  * the operation to the owner displayed in the connected-apps inventory.
92198
92615
  * Omitting `userId` retains the org-wide operation used by administrative
92199
92616
  * cleanup paths. The registration remains intact for other organizations.
92617
+ *
92618
+ * A caller that must commit the revoke together with its own writes passes
92619
+ * its open `transaction`; otherwise the revoke runs in one of its own.
92200
92620
  */
92201
- async revokeClientForOrganization(clientId, organizationId, userId) {
92202
- return this.sql.begin(async (tx) => {
92621
+ async revokeClientForOrganization(clientId, organizationId, userId, transaction) {
92622
+ const revoke = async (tx) => {
92203
92623
  const clientLock = await tx`
92204
92624
  SELECT id FROM oauth_clients WHERE id = ${clientId} FOR UPDATE
92205
92625
  `;
@@ -92319,7 +92739,8 @@ var init_clients = __esm({
92319
92739
  RETURNING session_id
92320
92740
  `;
92321
92741
  return revokedTokens.length > 0 || narrowedAuthorizationCodes.length > 0 || deletedAuthorizationCodes.length > 0 || narrowedDeviceCodes.length > 0 || deletedDeviceCodes.length > 0 || deletedSessions.length > 0;
92322
- });
92742
+ };
92743
+ return transaction ? revoke(transaction) : this.sql.begin(revoke);
92323
92744
  }
92324
92745
  /**
92325
92746
  * List clients for a user
@@ -94019,6 +94440,16 @@ var init_multi_tenant = __esm({
94019
94440
  401
94020
94441
  );
94021
94442
  }
94443
+ if (isPat && !authInfo.organizationId && (requestedOrgId || isMcpRoute || !isUnscopedRoute)) {
94444
+ return c.json(
94445
+ {
94446
+ error: "invalid_token",
94447
+ error_description: "PAT is not scoped to an organization \u2014 re-mint via `lobu token`"
94448
+ },
94449
+ 401,
94450
+ { "WWW-Authenticate": bearerChallenge("invalid_token") }
94451
+ );
94452
+ }
94022
94453
  if (!isPat && authInfo.resource) {
94023
94454
  const requestedResource = isMcpRoute ? getMcpResourceForRequest(publicMcpRequestUrl(c.req.raw)) : null;
94024
94455
  if (!requestedResource || authInfo.resource !== requestedResource) {
@@ -94915,10 +95346,7 @@ async function fetchContentSnippets(gate, workspaceSlug, query, contentLimit, en
94915
95346
  {
94916
95347
  organization_id: gate.organizationId,
94917
95348
  signal,
94918
- ...entityId != null && {
94919
- entity_id: entityId,
94920
- strict_organization_scope: true
94921
- },
95349
+ ...entityId != null && { entity_id: entityId },
94922
95350
  ...excludeWorkspaceAudit && { exclude_workspace_audit: true },
94923
95351
  ...excludeOperationalTrail && { exclude_operational_trail: true },
94924
95352
  // Recall is a memory surface, not an ops console: internal tool-invocation
@@ -95175,6 +95603,17 @@ async function coverageForLocalSources(gate, workspaceSlug, local_sources) {
95175
95603
  const [discovered] = await Promise.allSettled([discoverSourceFeeds(gate, workspaceSlug)]);
95176
95604
  return buildCoverage(workspaceSlug, local_sources, discovered);
95177
95605
  }
95606
+ function reportLocalRecallFailure(gate, store, reason) {
95607
+ const { name, code } = reason ?? {};
95608
+ const report = describeError(
95609
+ { name, code, message: `Local ${store} recall failed` },
95610
+ { scope: `search_memory ${store} recall` }
95611
+ );
95612
+ logger_default.error(
95613
+ { organization_id: gate.organizationId, ...errorReportLogFields(report) },
95614
+ `[search] local ${store} recall failed (pg_code=${report.code ?? "none"}): ${getErrorMessage(reason)}`
95615
+ );
95616
+ }
95178
95617
  async function gatherLocalRecall(gate, ctx) {
95179
95618
  const shouldSearchConversation = Boolean(ctx.query && gate.agentId && ctx.entityId == null);
95180
95619
  const contentPromise = fetchContentSnippets(
@@ -95211,10 +95650,7 @@ async function gatherLocalRecall(gate, ctx) {
95211
95650
  local_sources.push("events");
95212
95651
  } else {
95213
95652
  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
- );
95653
+ reportLocalRecallFailure(gate, "events", contentResult.reason);
95218
95654
  }
95219
95655
  if (shouldSearchConversation && conversationResult.status === "fulfilled") {
95220
95656
  local_sources.push("channel_messages");
@@ -95223,9 +95659,7 @@ async function gatherLocalRecall(gate, ctx) {
95223
95659
  }
95224
95660
  } else if (conversationResult.status === "rejected") {
95225
95661
  localRecallFailed = true;
95226
- logger_default.warn(
95227
- `[search] local conversation recall failed: ${getErrorMessage(conversationResult.reason)}`
95228
- );
95662
+ reportLocalRecallFailure(gate, "conversation", conversationResult.reason);
95229
95663
  }
95230
95664
  result.coverage = buildCoverage(
95231
95665
  ctx.workspaceSlug,
@@ -96402,7 +96836,7 @@ async function metricSeriesImpl(args, _env, ctx) {
96402
96836
  if (rangeEndMs <= rangeStartMs) {
96403
96837
  throw new ToolUserError("metric_series: end must be after start");
96404
96838
  }
96405
- const { sql: scopedSql, params } = validateAndScopeQuery(args.sql, orgId, {
96839
+ const { sql: scopedSql, params, scope } = validateAndScopeQuery(args.sql, orgId, {
96406
96840
  // Emit the safe column allowlist (not SELECT *) so a member charting e.g.
96407
96841
  // `connections` can't pull credential columns the allowlist withholds.
96408
96842
  safeColumns: SAFE_COLUMN_DEFS,
@@ -96420,12 +96854,13 @@ async function metricSeriesImpl(args, _env, ctx) {
96420
96854
  const db = getDb();
96421
96855
  let rows;
96422
96856
  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);
96857
+ rows = await boundedQuery(db, scopedSql, params, {
96858
+ signal: ctx.abortSignal,
96859
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
96860
+ fence: scope
96427
96861
  });
96428
96862
  } catch (err) {
96863
+ if (ctx.abortSignal?.aborted) throw err;
96429
96864
  logger_default.warn({ err, orgId }, "[metric_series] query failed");
96430
96865
  const failure = classifyReadQueryFailure(err);
96431
96866
  throw new ToolUserError(failure.message, toolErrorHttpStatus(failure.code), failure.code);
@@ -96494,7 +96929,7 @@ async function metricSeriesImpl(args, _env, ctx) {
96494
96929
  const tabular = keptRows.map((r) => columns.map((c) => r[c]));
96495
96930
  return { columns, rows: tabular, data_quality: quality };
96496
96931
  }
96497
- var MetricSeriesSchema, STATEMENT_TIMEOUT_MS, MAX_ROWS, DEFAULT_RANGE_START_MS, DEFAULT_FUTURE_SLACK_MS, TIME_COLUMN_PATTERN, metricSeries;
96932
+ var MetricSeriesSchema, MAX_ROWS, DEFAULT_RANGE_START_MS, DEFAULT_FUTURE_SLACK_MS, TIME_COLUMN_PATTERN, metricSeries;
96498
96933
  var init_metric_series = __esm({
96499
96934
  "src/tools/admin/metric_series.ts"() {
96500
96935
  "use strict";
@@ -96502,6 +96937,7 @@ var init_metric_series = __esm({
96502
96937
  init_execute_data_sources();
96503
96938
  init_table_schema();
96504
96939
  init_bounded_read();
96940
+ init_content_read_bounds();
96505
96941
  init_errors2();
96506
96942
  init_logger2();
96507
96943
  init_scope();
@@ -96539,7 +96975,6 @@ var init_metric_series = __esm({
96539
96975
  })
96540
96976
  )
96541
96977
  });
96542
- STATEMENT_TIMEOUT_MS = 5e3;
96543
96978
  MAX_ROWS = 2e3;
96544
96979
  DEFAULT_RANGE_START_MS = Date.parse("2000-01-01T00:00:00Z");
96545
96980
  DEFAULT_FUTURE_SLACK_MS = 24 * 60 * 60 * 1e3;
@@ -96562,6 +96997,8 @@ async function queryMetricImpl(args, _env, ctx) {
96562
96997
  segment: args.segment,
96563
96998
  entityId: args.entity_id,
96564
96999
  userId: authzScopeFromToolContext(ctx).principal,
97000
+ signal: ctx.abortSignal,
97001
+ callerClass: sourceCallerClass(ctx),
96565
97002
  // Workspace-identity audit rows are owner/admin/system-only; ordinary
96566
97003
  // members must not move a declared metric by counting lifecycle events.
96567
97004
  excludeWorkspaceAudit: !canReadWorkspaceIdentity(ctx),
@@ -96578,6 +97015,7 @@ var QueryMetricSchema, queryMetric;
96578
97015
  var init_query_metric = __esm({
96579
97016
  "src/tools/admin/query_metric.ts"() {
96580
97017
  "use strict";
97018
+ init_source_admission();
96581
97019
  init_run_metric();
96582
97020
  init_access_control();
96583
97021
  init_scope();
@@ -104307,7 +104745,9 @@ async function queryConnection(ctx, isAdmin, connectionSlug, querySql2) {
104307
104745
  isAdmin,
104308
104746
  connectionSlug,
104309
104747
  query: querySql2.trim(),
104310
- limit: CLIENT_QUERY_MAX_ROWS
104748
+ limit: CLIENT_QUERY_MAX_ROWS,
104749
+ signal: ctx.abortSignal,
104750
+ callerClass: sourceCallerClass(ctx)
104311
104751
  });
104312
104752
  } catch (err) {
104313
104753
  throw pushdownFailureError(err, connectionSlug, "query");
@@ -104534,7 +104974,8 @@ function buildClientSDK(ctx, env, opts) {
104534
104974
  try {
104535
104975
  rows = await boundedQuery(getDb(), boundedSql, scoped.params, {
104536
104976
  signal: workspaceCtx.abortSignal,
104537
- statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS
104977
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
104978
+ fence: scoped.scope
104538
104979
  });
104539
104980
  } catch (error) {
104540
104981
  if (workspaceCtx.abortSignal?.aborted) throw error;
@@ -104565,6 +105006,7 @@ var init_client_sdk = __esm({
104565
105006
  init_errors2();
104566
105007
  init_url_builder();
104567
105008
  init_connector_pushdown();
105009
+ init_source_admission();
104568
105010
  init_content_read_bounds();
104569
105011
  init_method_metadata();
104570
105012
  init_workspace_activity();
@@ -110120,14 +110562,14 @@ ${event.options.map((o, i) => `${i + 1}. ${o}`).join("\n")}`;
110120
110562
  label: prompt.title
110121
110563
  })
110122
110564
  );
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
- );
110565
+ try {
110566
+ await thread.post({ card: Card3({ children: [Actions3(buttons)] }) });
110567
+ } catch (error) {
110568
+ logger60.warn(
110569
+ { connectionId, suggestionId: event.id, error: String(error) },
110570
+ "Failed to post suggestion interaction"
110571
+ );
110572
+ }
110131
110573
  }
110132
110574
  );
110133
110575
  interactionService.on("question:created", onQuestionCreated);
@@ -111811,7 +112253,7 @@ async function createPreviewClaim(c) {
111811
112253
  { err: errorMessage(err), platform },
111812
112254
  "[preview] create claim failed"
111813
112255
  );
111814
- return c.json({ error: errorMessage(err) }, 500);
112256
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
111815
112257
  }
111816
112258
  }
111817
112259
  return c.json({ error: "Could not allocate a unique preview code" }, 500);
@@ -112104,6 +112546,7 @@ var init_slack2 = __esm({
112104
112546
  init_chat_link_authorization();
112105
112547
  init_command_spelling();
112106
112548
  init_platforms();
112549
+ init_diagnostics();
112107
112550
  SLACK_PLATFORM = "slack";
112108
112551
  CLAIM_SCOPE = "slack-preview-claim";
112109
112552
  DEFAULT_TTL_MINUTES = 15;
@@ -115226,7 +115669,7 @@ async function heartbeat(c) {
115226
115669
  ...steer.length > 0 ? { steer } : {}
115227
115670
  });
115228
115671
  } catch (err) {
115229
- return c.json({ error: errorMessage(err) }, 500);
115672
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
115230
115673
  }
115231
115674
  }
115232
115675
  async function ingestConnectorItems(sql2, target, items, checkpoint) {
@@ -115778,7 +116221,7 @@ async function streamContent(c) {
115778
116221
  const message = browserRun ? sanitizeBrowserText(rawMessage) : rawMessage;
115779
116222
  const stack = browserRun ? sanitizeBrowserText(rawStack) : rawStack;
115780
116223
  console.error("[stream] Error:", message, stack);
115781
- return c.json({ error: message, stack }, 500);
116224
+ throw routeFailure(c.json({ error: message, stack }, 500), err);
115782
116225
  }
115783
116226
  }
115784
116227
  async function completeWorkerJob(c) {
@@ -115993,7 +116436,7 @@ async function completeWorkerJob(c) {
115993
116436
  return c.json({ success: true });
115994
116437
  } catch (err) {
115995
116438
  logger_default.error({ error: errorMessage(err) }, "[completeWorkerJob] Error");
115996
- return c.json({ error: errorMessage(err) }, 500);
116439
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
115997
116440
  }
115998
116441
  }
115999
116442
  async function completeAutomationRun(c) {
@@ -116425,7 +116868,7 @@ async function fetchEventsForEmbedding(c) {
116425
116868
  }))
116426
116869
  });
116427
116870
  } catch (err) {
116428
- return c.json({ error: errorMessage(err) }, 500);
116871
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116429
116872
  }
116430
116873
  }
116431
116874
  async function completeEmbeddings(c) {
@@ -116517,7 +116960,7 @@ async function completeEmbeddings(c) {
116517
116960
  return c.json({ success: failed === 0, updated, failed });
116518
116961
  } catch (err) {
116519
116962
  logger_default.error({ error: errorMessage(err) }, "[completeEmbeddings] Error");
116520
- return c.json({ error: errorMessage(err) }, 500);
116963
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116521
116964
  }
116522
116965
  }
116523
116966
  async function emitAuthArtifact(c) {
@@ -116532,7 +116975,7 @@ async function emitAuthArtifact(c) {
116532
116975
  `;
116533
116976
  return c.json({ success: true });
116534
116977
  } catch (err) {
116535
- return c.json({ error: errorMessage(err) }, 500);
116978
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116536
116979
  }
116537
116980
  }
116538
116981
  async function pollAuthSignal(c) {
@@ -116553,7 +116996,7 @@ async function pollAuthSignal(c) {
116553
116996
  });
116554
116997
  return c.json(consumed ? { signal: consumed } : {});
116555
116998
  } catch (err) {
116556
- return c.json({ error: errorMessage(err) }, 500);
116999
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116557
117000
  }
116558
117001
  }
116559
117002
  async function completeAuthRun(c) {
@@ -116631,7 +117074,7 @@ async function completeAuthRun(c) {
116631
117074
  return c.json({ success: true });
116632
117075
  } catch (err) {
116633
117076
  logger_default.error({ error: errorMessage(err) }, "[completeAuthRun] Error");
116634
- return c.json({ error: errorMessage(err) }, 500);
117077
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116635
117078
  }
116636
117079
  }
116637
117080
  async function completeActionRun(c) {
@@ -116713,7 +117156,7 @@ async function completeActionRun(c) {
116713
117156
  } catch (err) {
116714
117157
  await deleteMaterializedArtifacts(publishedActionArtifactIds);
116715
117158
  logger_default.error({ error: errorMessage(err) }, "[completeActionRun] Error");
116716
- return c.json({ error: errorMessage(err) }, 500);
117159
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
116717
117160
  }
116718
117161
  }
116719
117162
  var DRY_RUN_PREVIEW_LIMIT, DRY_RUN_CONTENT_CHARS, MAX_ORIGIN_ID_BYTES, MISSING_COMPLETE_WINDOW_NUDGE;
@@ -116759,6 +117202,7 @@ var init_run_lifecycle = __esm({
116759
117202
  init_shared4();
116760
117203
  init_run_outcome();
116761
117204
  init_run_lease();
117205
+ init_diagnostics();
116762
117206
  DRY_RUN_PREVIEW_LIMIT = 50;
116763
117207
  DRY_RUN_CONTENT_CHARS = 500;
116764
117208
  MAX_ORIGIN_ID_BYTES = 2048;
@@ -128198,6 +128642,7 @@ var init_middleware = __esm({
128198
128642
  init_revoked_token_store();
128199
128643
  init_agent_turn_inputs();
128200
128644
  init_chat_turn_actor();
128645
+ init_diagnostics();
128201
128646
  authenticateWorker = async (c, next) => {
128202
128647
  const authHeader = c.req.header("authorization");
128203
128648
  if (!authHeader?.startsWith("Bearer ")) {
@@ -128225,7 +128670,7 @@ var init_middleware = __esm({
128225
128670
  if (error instanceof StaleAgentTurnAttemptError) {
128226
128671
  return c.json({ error: error.message }, 409);
128227
128672
  }
128228
- return c.json({ error: "Could not record the tool call for this turn; it was not executed" }, 503);
128673
+ throw routeFailure(c.json({ error: "Could not record the tool call for this turn; it was not executed" }, 503), error);
128229
128674
  }
128230
128675
  }
128231
128676
  c.set("worker", tokenData);
@@ -128466,11 +128911,11 @@ function createAudioRoutes(transcriptionService) {
128466
128911
  });
128467
128912
  } catch (error) {
128468
128913
  logger72.error("Audio synthesis error", { error });
128469
- return errorResponse(
128914
+ throw routeFailure(errorResponse(
128470
128915
  c,
128471
128916
  error instanceof Error ? error.message : "Failed to synthesize audio",
128472
128917
  500
128473
- );
128918
+ ), error);
128474
128919
  }
128475
128920
  });
128476
128921
  router.get("/internal/audio/capabilities", authenticateWorker, async (c) => {
@@ -128495,7 +128940,7 @@ function createAudioRoutes(transcriptionService) {
128495
128940
  });
128496
128941
  } catch (error) {
128497
128942
  logger72.error("Capabilities check error", { error });
128498
- return errorResponse(c, "Failed to check capabilities", 500);
128943
+ throw routeFailure(errorResponse(c, "Failed to check capabilities", 500), error);
128499
128944
  }
128500
128945
  });
128501
128946
  logger72.debug("Internal audio routes registered");
@@ -128510,6 +128955,7 @@ var init_audio = __esm({
128510
128955
  init_middleware();
128511
128956
  init_capture_mode();
128512
128957
  init_turn_write_once();
128958
+ init_diagnostics();
128513
128959
  logger72 = createLogger("internal-audio-routes");
128514
128960
  }
128515
128961
  });
@@ -128652,7 +129098,7 @@ function createConversationsRoutes() {
128652
129098
  return c.json({ conversations: targets.map(toPublicTarget) });
128653
129099
  } catch (error) {
128654
129100
  logger73.error(`list conversations failed: ${String(error)}`);
128655
- return errorResponse(c, "Internal server error", 500);
129101
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128656
129102
  }
128657
129103
  });
128658
129104
  router.get("/conversations/read", authenticateWorker, async (c) => {
@@ -128696,7 +129142,7 @@ function createConversationsRoutes() {
128696
129142
  return c.json({ messages: [], nextCursor: null, hasMore: false });
128697
129143
  } catch (error) {
128698
129144
  logger73.error(`read conversation failed: ${String(error)}`);
128699
- return errorResponse(c, "Internal server error", 500);
129145
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128700
129146
  }
128701
129147
  });
128702
129148
  router.post("/conversations/send", authenticateWorker, async (c) => {
@@ -128808,7 +129254,7 @@ function createConversationsRoutes() {
128808
129254
  });
128809
129255
  } catch (error) {
128810
129256
  logger73.error(`send conversation failed: ${String(error)}`);
128811
- return errorResponse(c, "Internal server error", 500);
129257
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128812
129258
  }
128813
129259
  });
128814
129260
  router.post("/conversations/present-event", authenticateWorker, async (c) => {
@@ -128883,7 +129329,7 @@ function createConversationsRoutes() {
128883
129329
  });
128884
129330
  } catch (error) {
128885
129331
  logger73.error(`present event failed: ${String(error)}`);
128886
- return errorResponse(c, "Internal server error", 500);
129332
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128887
129333
  }
128888
129334
  });
128889
129335
  router.post("/conversations/schedule-followup", authenticateWorker, async (c) => {
@@ -128976,7 +129422,7 @@ function createConversationsRoutes() {
128976
129422
  return c.json({ scheduled: true, schedule: schedule.schedule });
128977
129423
  } catch (error) {
128978
129424
  logger73.error(`schedule followup failed: ${String(error)}`);
128979
- return errorResponse(c, "Internal server error", 500);
129425
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
128980
129426
  }
128981
129427
  });
128982
129428
  function messageRoute(label, handler) {
@@ -129050,7 +129496,7 @@ function createConversationsRoutes() {
129050
129496
  return await handler(c, target, body2);
129051
129497
  } catch (error) {
129052
129498
  logger73.error(`${label} failed: ${String(error)}`);
129053
- return errorResponse(c, "Internal server error", 500);
129499
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
129054
129500
  }
129055
129501
  };
129056
129502
  }
@@ -129142,6 +129588,7 @@ var init_conversations2 = __esm({
129142
129588
  init_capture_mode();
129143
129589
  init_turn_write_once();
129144
129590
  init_errors2();
129591
+ init_diagnostics();
129145
129592
  logger73 = createLogger("conversations-routes");
129146
129593
  MAX_CONTENT_LENGTH = 4e3;
129147
129594
  MASS_MENTION = /@(channel|here|everyone)\b|<!(channel|here|everyone|subteam)\b/i;
@@ -129280,7 +129727,7 @@ function createFileRoutes(platformRegistry2, artifactStore, publicGatewayUrl2) {
129280
129727
  error: getErrorMessage(error),
129281
129728
  stack: error instanceof Error ? error.stack : void 0
129282
129729
  });
129283
- return errorResponse(c, "Failed to upload file", 500);
129730
+ throw routeFailure(errorResponse(c, "Failed to upload file", 500), error);
129284
129731
  }
129285
129732
  });
129286
129733
  router.post("/upload-batch", limitArtifactUploadBody, authenticateWorker, async (c) => {
@@ -129383,7 +129830,7 @@ function createFileRoutes(platformRegistry2, artifactStore, publicGatewayUrl2) {
129383
129830
  error: getErrorMessage(error),
129384
129831
  stack: error instanceof Error ? error.stack : void 0
129385
129832
  });
129386
- return errorResponse(c, "Failed to batch upload files", 500);
129833
+ throw routeFailure(errorResponse(c, "Failed to batch upload files", 500), error);
129387
129834
  }
129388
129835
  });
129389
129836
  return router;
@@ -129398,6 +129845,7 @@ var init_files = __esm({
129398
129845
  init_middleware();
129399
129846
  init_capture_mode();
129400
129847
  init_turn_write_once();
129848
+ init_diagnostics();
129401
129849
  logger74 = createLogger("file-routes");
129402
129850
  MAX_ARTIFACT_UPLOAD_REQUEST_BYTES = MAX_ARTIFACT_BYTES + 1024 * 1024;
129403
129851
  limitArtifactUploadBody = bodyLimit({
@@ -129465,7 +129913,7 @@ function createImageRoutes(imageGenerationService) {
129465
129913
  });
129466
129914
  } catch (error) {
129467
129915
  logger75.error("Image generation error", { error });
129468
- return errorResponse(c, "Failed to generate image", 500);
129916
+ throw routeFailure(errorResponse(c, "Failed to generate image", 500), error);
129469
129917
  }
129470
129918
  });
129471
129919
  router.get("/internal/images/capabilities", authenticateWorker, async (c) => {
@@ -129490,7 +129938,7 @@ function createImageRoutes(imageGenerationService) {
129490
129938
  });
129491
129939
  } catch (error) {
129492
129940
  logger75.error("Image capabilities check error", { error });
129493
- return errorResponse(c, "Failed to check capabilities", 500);
129941
+ throw routeFailure(errorResponse(c, "Failed to check capabilities", 500), error);
129494
129942
  }
129495
129943
  });
129496
129944
  logger75.debug("Internal image routes registered");
@@ -129505,6 +129953,7 @@ var init_images = __esm({
129505
129953
  init_middleware();
129506
129954
  init_capture_mode();
129507
129955
  init_turn_write_once();
129956
+ init_diagnostics();
129508
129957
  logger75 = createLogger("internal-image-routes");
129509
129958
  }
129510
129959
  });
@@ -129649,7 +130098,7 @@ function createInteractionRoutes(interactionService) {
129649
130098
  error: getErrorMessage(error),
129650
130099
  stack: error instanceof Error ? error.stack : void 0
129651
130100
  });
129652
- return errorResponse(c, "Failed to post question", 500);
130101
+ throw routeFailure(errorResponse(c, "Failed to post question", 500), error);
129653
130102
  }
129654
130103
  }
129655
130104
  );
@@ -129669,6 +130118,7 @@ var init_interactions = __esm({
129669
130118
  init_middleware();
129670
130119
  init_capture_mode();
129671
130120
  init_turn_write_once();
130121
+ init_diagnostics();
129672
130122
  logger76 = createLogger("internal-interaction-routes");
129673
130123
  }
129674
130124
  });
@@ -132256,7 +132706,7 @@ function createAgentApi(config) {
132256
132706
  });
132257
132707
  } catch (error) {
132258
132708
  logger84.error("Failed to send platform message", { error });
132259
- return c.json({ success: false, error: "Internal server error" }, 500);
132709
+ throw routeFailure(c.json({ success: false, error: "Internal server error" }, 500), error);
132260
132710
  }
132261
132711
  }
132262
132712
  const session = preSession;
@@ -132415,6 +132865,7 @@ var init_agent = __esm({
132415
132865
  init_openapi_responses();
132416
132866
  init_settings_auth();
132417
132867
  init_activity_feed();
132868
+ init_diagnostics();
132418
132869
  SSE_PING_INTERVAL_MS = 3e4;
132419
132870
  logger84 = createLogger("agent-api");
132420
132871
  MAX_CONNECTIONS_PER_AGENT = 5;
@@ -134164,7 +134615,7 @@ function createAgentRoutes(config) {
134164
134615
  });
134165
134616
  } catch (error) {
134166
134617
  logger86.error("Failed to create agent", { error });
134167
- return errorResponse(c, "Internal server error", 500);
134618
+ throw routeFailure(errorResponse(c, "Internal server error", 500), error);
134168
134619
  }
134169
134620
  });
134170
134621
  router.get("/", async (c) => {
@@ -134190,7 +134641,7 @@ function createAgentRoutes(config) {
134190
134641
  return c.json({ agents });
134191
134642
  } catch (error) {
134192
134643
  logger86.error("Failed to list agents", { error });
134193
- return errorResponse(c, "Failed to list agents", 500);
134644
+ throw routeFailure(errorResponse(c, "Failed to list agents", 500), error);
134194
134645
  }
134195
134646
  });
134196
134647
  const ownershipAccessConfig = {
@@ -134247,6 +134698,7 @@ var init_agents2 = __esm({
134247
134698
  init_org_context();
134248
134699
  init_agent_ownership();
134249
134700
  init_helpers();
134701
+ init_diagnostics();
134250
134702
  logger86 = createLogger("agent-routes");
134251
134703
  MAX_AGENTS_PER_USER = parseInt(
134252
134704
  process.env.MAX_AGENTS_PER_USER || "0",
@@ -135841,13 +136293,13 @@ function createAppInstallRoutes(deps) {
135841
136293
  },
135842
136294
  "GitHub App install callback failed"
135843
136295
  );
135844
- return c.html(
136296
+ throw routeFailure(c.html(
135845
136297
  renderOAuthErrorPage(
135846
136298
  "github_install_failed",
135847
136299
  error instanceof Error ? error.message : "GitHub App install failed."
135848
136300
  ),
135849
136301
  500
135850
- );
136302
+ ), error);
135851
136303
  }
135852
136304
  });
135853
136305
  return router;
@@ -135986,13 +136438,13 @@ function mountOAuthCodeExchangeRoutes(router, params) {
135986
136438
  { provider: provider3, error: String(error) },
135987
136439
  "OAuth install failed to park as pending"
135988
136440
  );
135989
- return c.html(
136441
+ throw routeFailure(c.html(
135990
136442
  renderOAuthErrorPage(
135991
136443
  `${provider3}_install_failed`,
135992
136444
  error instanceof Error ? error.message : `${display} install failed.`
135993
136445
  ),
135994
136446
  500
135995
- );
136447
+ ), error);
135996
136448
  }
135997
136449
  });
135998
136450
  }
@@ -136057,6 +136509,7 @@ var init_app_install = __esm({
136057
136509
  init_registry2();
136058
136510
  init_queue_service();
136059
136511
  init_github_team_graph();
136512
+ init_diagnostics();
136060
136513
  logger88 = createLogger("app-install-routes");
136061
136514
  GITHUB_CONNECTOR_KEY2 = "github";
136062
136515
  GITHUB_PROVIDER = "github";
@@ -136316,7 +136769,7 @@ function createAppWebhookRoutes(deps) {
136316
136769
  { provider: providerName, error: String(error) },
136317
136770
  "[app-webhook] handleDelivery failed"
136318
136771
  );
136319
- return json2(500, { error: "Failed to handle delivery" });
136772
+ throw routeFailure(json2(500, { error: "Failed to handle delivery" }), error);
136320
136773
  }
136321
136774
  }
136322
136775
  const tenant = provider3.extractTenant(rawBody, c.req.raw.headers);
@@ -136361,7 +136814,7 @@ function createAppWebhookRoutes(deps) {
136361
136814
  { provider: providerName, installationId: install.id, error: String(error) },
136362
136815
  "[app-webhook] onDelivery trigger failed"
136363
136816
  );
136364
- return json2(500, { error: "Failed to handle delivery" });
136817
+ throw routeFailure(json2(500, { error: "Failed to handle delivery" }), error);
136365
136818
  }
136366
136819
  });
136367
136820
  return router;
@@ -136372,6 +136825,7 @@ var init_app_webhooks = __esm({
136372
136825
  "use strict";
136373
136826
  init_src();
136374
136827
  init_client();
136828
+ init_diagnostics();
136375
136829
  init_webhook_delivery();
136376
136830
  init_webhook_ingest();
136377
136831
  logger89 = createLogger("app-webhook-routes");
@@ -136514,13 +136968,13 @@ function createConnectAuthRoutes(config) {
136514
136968
  return c.redirect(authUrl);
136515
136969
  } catch (error) {
136516
136970
  logger90.error("Failed to start browser OAuth handoff", { error });
136517
- return c.html(
136971
+ throw routeFailure(c.html(
136518
136972
  renderPage(
136519
136973
  "OAuth Login Failed",
136520
136974
  "The gateway could not start the browser OAuth flow."
136521
136975
  ),
136522
136976
  500
136523
- );
136977
+ ), error);
136524
136978
  }
136525
136979
  });
136526
136980
  router.get("/connect/claim", async (c) => {
@@ -136602,13 +137056,13 @@ function createConnectAuthRoutes(config) {
136602
137056
  return c.redirect(connectState.returnUrl);
136603
137057
  } catch (error) {
136604
137058
  logger90.error("Failed to complete browser OAuth handoff", { error });
136605
- return c.html(
137059
+ throw routeFailure(c.html(
136606
137060
  renderPage(
136607
137061
  "OAuth Login Failed",
136608
137062
  "The gateway could not complete the browser OAuth flow."
136609
137063
  ),
136610
137064
  500
136611
- );
137065
+ ), error);
136612
137066
  }
136613
137067
  });
136614
137068
  return router;
@@ -136623,6 +137077,7 @@ var init_connect_auth = __esm({
136623
137077
  init_oauth_templates();
136624
137078
  init_public_url();
136625
137079
  init_settings_auth();
137080
+ init_diagnostics();
136626
137081
  logger90 = createLogger("connect-auth-routes");
136627
137082
  AUTH_REQUEST_TTL_SECONDS = 10 * 60;
136628
137083
  CONNECT_OAUTH_TTL_SECONDS = 10 * 60;
@@ -136665,7 +137120,7 @@ function createConnectionWebhookRoutes(manager) {
136665
137120
  return await manager.handleWebhook(connectionId, c.req.raw);
136666
137121
  } catch (error) {
136667
137122
  logger91.error({ connectionId, error: String(error) }, "Webhook error");
136668
- return c.json({ error: "Webhook processing failed" }, 500);
137123
+ throw routeFailure(c.json({ error: "Webhook processing failed" }, 500), error);
136669
137124
  }
136670
137125
  });
136671
137126
  return router;
@@ -136700,6 +137155,7 @@ var init_connections3 = __esm({
136700
137155
  "src/gateway/routes/public/connections.ts"() {
136701
137156
  "use strict";
136702
137157
  init_src();
137158
+ init_diagnostics();
136703
137159
  logger91 = createLogger("connection-routes");
136704
137160
  LOCAL_TEST_PLATFORMS = ["slack", "telegram", "whatsapp"];
136705
137161
  }
@@ -136737,10 +137193,10 @@ function createPublicFileRoutes(artifactStore) {
136737
137193
  logger92.error("Artifact storage unavailable during download", {
136738
137194
  code: error instanceof ArtifactStorageError ? error.code : "UNKNOWN"
136739
137195
  });
136740
- return c.json(
137196
+ throw routeFailure(c.json(
136741
137197
  { success: false, error: "File storage temporarily unavailable" },
136742
137198
  503
136743
- );
137199
+ ), redactedFailure(error));
136744
137200
  }
136745
137201
  if (!artifact) {
136746
137202
  return c.json({ success: false, error: "File not found" }, 404);
@@ -136772,6 +137228,7 @@ var init_files2 = __esm({
136772
137228
  "src/gateway/routes/public/files.ts"() {
136773
137229
  "use strict";
136774
137230
  init_src();
137231
+ init_diagnostics();
136775
137232
  init_artifact_store();
136776
137233
  logger92 = createLogger("public-files");
136777
137234
  }
@@ -137241,6 +137698,10 @@ function errorResult(message, startTime, code = "VALIDATION") {
137241
137698
  retryable: isRetryable(code)
137242
137699
  };
137243
137700
  }
137701
+ function earliestDeadline(read, host2) {
137702
+ if (read === void 0) return host2;
137703
+ return host2 === void 0 ? read : Math.min(read, host2);
137704
+ }
137244
137705
  async function querySqlImpl(args, env, ctx, options) {
137245
137706
  const startTime = Date.now();
137246
137707
  const title = args.title?.trim() || void 0;
@@ -137307,7 +137768,9 @@ async function querySqlImpl(args, env, ctx, options) {
137307
137768
  query: baseSql,
137308
137769
  exactMatch: options?.exactMatch,
137309
137770
  selection: options?.selection,
137310
- deadlineAt: options?.deadlineAt,
137771
+ deadlineAt: earliestDeadline(options?.deadlineAt, ctx.deadlineAt),
137772
+ signal: ctx.abortSignal,
137773
+ callerClass: sourceCallerClass(ctx),
137311
137774
  limit: limit2,
137312
137775
  offset: offset2,
137313
137776
  sort: args.sort_by ? { column: args.sort_by, order: args.sort_order === "desc" ? "desc" : "asc" } : void 0
@@ -137331,6 +137794,7 @@ async function querySqlImpl(args, env, ctx, options) {
137331
137794
  const window2 = args.window_token ? await resolveWindowQueryContext(args.window_token, env, ctx, getDb()) : void 0;
137332
137795
  let scopedSql;
137333
137796
  let params;
137797
+ let scope;
137334
137798
  let tableRefs;
137335
137799
  try {
137336
137800
  const scoped = validateAndScopeQuery(baseSql, targetOrgId, {
@@ -137350,6 +137814,7 @@ async function querySqlImpl(args, env, ctx, options) {
137350
137814
  });
137351
137815
  scopedSql = scoped.sql;
137352
137816
  params = scoped.params;
137817
+ scope = scoped.scope;
137353
137818
  tableRefs = scoped.tableRefs;
137354
137819
  } catch (err) {
137355
137820
  return fail2(getErrorMessage(err), err instanceof ToolUserError ? err.code : void 0);
@@ -137406,7 +137871,8 @@ async function querySqlImpl(args, env, ctx, options) {
137406
137871
  const signal = ctx.abortSignal;
137407
137872
  const result = await boundedRead(getDb(), {
137408
137873
  signal,
137409
- statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS
137874
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
137875
+ fence: scope
137410
137876
  }, async (tx) => {
137411
137877
  const data = await cancellable(tx.unsafe(dataSql, params), signal);
137412
137878
  const rows2 = Array.isArray(data) ? data : [];
@@ -137490,6 +137956,7 @@ var init_query_sql = __esm({
137490
137956
  init_client();
137491
137957
  init_window_read_context();
137492
137958
  init_connector_pushdown();
137959
+ init_source_admission();
137493
137960
  init_execute_data_sources();
137494
137961
  init_logger2();
137495
137962
  init_bounded_read();
@@ -142813,7 +143280,7 @@ function createGatewayApp(options) {
142813
143280
  return await handler({ c, mod, providerId });
142814
143281
  } catch (error) {
142815
143282
  logger94.error(errorLabel, { error });
142816
- return c.json({ error: errorLabel }, 500);
143283
+ throw routeFailure(c.json({ error: errorLabel }, 500), error);
142817
143284
  }
142818
143285
  };
142819
143286
  authRouter.post(
@@ -143251,6 +143718,7 @@ var init_gateway = __esm({
143251
143718
  init_install_org();
143252
143719
  init_landing();
143253
143720
  init_settings_auth();
143721
+ init_diagnostics();
143254
143722
  logger94 = createLogger("gateway-startup");
143255
143723
  chatPendingInstallCompletions = {
143256
143724
  slack: completeSlackPendingInstall
@@ -147330,12 +147798,12 @@ async function handleListToolsAuthenticated(proxy, c, auth, mcpId) {
147330
147798
  return c.json({ tools, instructions });
147331
147799
  } catch (error) {
147332
147800
  logger107.error("Failed to list tools", { mcpId, error });
147333
- return c.json(
147801
+ throw routeFailure(c.json(
147334
147802
  {
147335
147803
  error: `Failed to connect to MCP '${mcpId}': ${error instanceof Error ? error.message : "Unknown error"}`
147336
147804
  },
147337
147805
  502
147338
- );
147806
+ ), error);
147339
147807
  }
147340
147808
  }
147341
147809
  async function handleCallTool(proxy, c) {
@@ -147472,14 +147940,14 @@ async function handleCallToolAuthenticated(proxy, c, auth, mcpId, toolName) {
147472
147940
  );
147473
147941
  }
147474
147942
  logger107.error("Failed to call tool", { mcpId, toolName, error });
147475
- return c.json(
147943
+ throw routeFailure(c.json(
147476
147944
  {
147477
147945
  content: [],
147478
147946
  isError: true,
147479
147947
  error: `Failed to connect to MCP '${mcpId}': ${error instanceof Error ? error.message : "Unknown error"}`
147480
147948
  },
147481
147949
  502
147482
- );
147950
+ ), error);
147483
147951
  }
147484
147952
  }
147485
147953
  async function handleListAllTools(proxy, c) {
@@ -147526,6 +147994,7 @@ var init_proxy_rest_routes = __esm({
147526
147994
  init_http_response();
147527
147995
  init_proxy_shared();
147528
147996
  init_proxy_upstream();
147997
+ init_diagnostics();
147529
147998
  logger107 = createLogger("mcp-proxy");
147530
147999
  }
147531
148000
  });
@@ -148440,7 +148909,7 @@ function createTranscriptRoutes() {
148440
148909
  logger113.error(
148441
148910
  `Snapshot INSERT failed: ${getErrorMessage(err)}`
148442
148911
  );
148443
- return c.json({ error: "Internal error" }, 500);
148912
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
148444
148913
  }
148445
148914
  });
148446
148915
  app2.delete("/snapshot", async (c) => {
@@ -148467,7 +148936,7 @@ function createTranscriptRoutes() {
148467
148936
  logger113.error(
148468
148937
  `Snapshot DELETE failed: ${getErrorMessage(err)}`
148469
148938
  );
148470
- return c.json({ error: "Internal error" }, 500);
148939
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
148471
148940
  }
148472
148941
  });
148473
148942
  return app2;
@@ -148480,6 +148949,7 @@ var init_transcript_routes = __esm({
148480
148949
  init_client();
148481
148950
  init_automation_run_intent();
148482
148951
  init_transcript_snapshot();
148952
+ init_diagnostics();
148483
148953
  logger113 = createLogger("worker-transcript");
148484
148954
  }
148485
148955
  });
@@ -148498,6 +148968,7 @@ var init_worker_gateway = __esm({
148498
148968
  init_turn_liveness();
148499
148969
  init_deployment_identity();
148500
148970
  init_transcript_routes();
148971
+ init_diagnostics();
148501
148972
  logger114 = createLogger("worker-gateway");
148502
148973
  WorkerGateway = class {
148503
148974
  app;
@@ -148710,7 +149181,7 @@ var init_worker_gateway = __esm({
148710
149181
  return c.json({ success: true });
148711
149182
  } catch (error) {
148712
149183
  logger114.error(`Error handling worker response: ${error}`);
148713
- return c.json({ error: "Failed to process response" }, 500);
149184
+ throw routeFailure(c.json({ error: "Failed to process response" }, 500), error);
148714
149185
  }
148715
149186
  }
148716
149187
  /**
@@ -148849,7 +149320,7 @@ var init_worker_gateway = __esm({
148849
149320
  });
148850
149321
  } catch (error) {
148851
149322
  logger114.error("Failed to generate session context", { err: error });
148852
- return c.json({ error: "session_context_error" }, 500);
149323
+ throw routeFailure(c.json({ error: "session_context_error" }, 500), error);
148853
149324
  }
148854
149325
  }
148855
149326
  async authenticateWorker(c) {
@@ -149506,6 +149977,7 @@ var init_grant_store = __esm({
149506
149977
  // src/gateway/proxy/secret-proxy.ts
149507
149978
  import { randomUUID as randomUUID33 } from "node:crypto";
149508
149979
  import { Hono as Hono21 } from "hono";
149980
+ import { HTTPException as HTTPException4 } from "hono/http-exception";
149509
149981
  function noProviderCredentials(c) {
149510
149982
  return c.json(
149511
149983
  {
@@ -149609,6 +150081,7 @@ var init_secret_proxy = __esm({
149609
150081
  init_turn_liveness();
149610
150082
  init_rate_limiter();
149611
150083
  init_provider_health_status();
150084
+ init_diagnostics();
149612
150085
  logger117 = createLogger("secret-proxy");
149613
150086
  RESOLVE_FAILURE_THRESHOLD = 20;
149614
150087
  RESOLVE_FAILURE_WINDOW_MS = 5 * 60 * 1e3;
@@ -149807,6 +150280,7 @@ var init_secret_proxy = __esm({
149807
150280
  try {
149808
150281
  return await this.forward(c);
149809
150282
  } catch (error) {
150283
+ if (error instanceof HTTPException4) throw error;
149810
150284
  logger117.error(
149811
150285
  {
149812
150286
  err: error instanceof Error ? { name: error.name, message: error.message, stack: error.stack } : error,
@@ -149814,7 +150288,7 @@ var init_secret_proxy = __esm({
149814
150288
  },
149815
150289
  "Secret proxy error"
149816
150290
  );
149817
- return c.json({ error: "Internal proxy error" }, 500);
150291
+ throw routeFailure(c.json({ error: "Internal proxy error" }, 500), error);
149818
150292
  }
149819
150293
  }
149820
150294
  /**
@@ -150053,10 +150527,10 @@ var init_secret_proxy = __esm({
150053
150527
  { urlAgentId, err: String(err) },
150054
150528
  "agentOrgResolver failed \u2014 rejecting request to preserve org isolation"
150055
150529
  );
150056
- return c.json(
150530
+ throw routeFailure(c.json(
150057
150531
  { error: "Service Unavailable: failed to resolve agent organization" },
150058
150532
  503
150059
- );
150533
+ ), err);
150060
150534
  }
150061
150535
  }
150062
150536
  if (providerContext?.organizationId && expectedOrganizationId && providerContext.organizationId !== expectedOrganizationId) {
@@ -150290,7 +150764,7 @@ var init_secret_proxy = __esm({
150290
150764
  { method, provider: resolvedSlug },
150291
150765
  "Custom provider request failed"
150292
150766
  );
150293
- return c.json({ error: "Internal proxy error" }, 500);
150767
+ throw routeFailure(c.json({ error: "Internal proxy error" }, 500), redactedFailure(error));
150294
150768
  }
150295
150769
  if (!response.ok) {
150296
150770
  logger117.warn(
@@ -154981,9 +155455,10 @@ async function enqueueAgentTurn(data, deps) {
154981
155455
  conversation_id: data.conversationId,
154982
155456
  platform: data.platform
154983
155457
  },
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 } : {}
155458
+ // Follow-up chips only where a person is waiting on this reply and can
155459
+ // tap them: never an Automation run, another server-dispatched (headless)
155460
+ // turn, or a platform that would render the buttons as an inert list.
155461
+ ...!automationIntent && !isHeadlessSource(data.platformMetadata?.source) && getPlatformDescriptor(data.platform)?.rendersActionButtons !== false ? { follow_ups: true } : {}
154987
155462
  };
154988
155463
  const settings = await agentSettings.getSettings(data.agentId, {
154989
155464
  organizationId: data.organizationId
@@ -155178,6 +155653,7 @@ var init_agent_turn_producer = __esm({
155178
155653
  init_agent_turn_inputs();
155179
155654
  init_initiator();
155180
155655
  init_automation_run_session();
155656
+ init_platforms();
155181
155657
  init_automation_run_intent();
155182
155658
  init_agent_turn_attachments();
155183
155659
  init_turn_liveness();
@@ -157051,8 +157527,8 @@ function createLobuOrgContextMiddleware() {
157051
157527
  let resolvedOrg;
157052
157528
  try {
157053
157529
  resolvedOrg = await getOrgBySlug(orgHeader);
157054
- } catch {
157055
- return c.json({ error: "Unable to resolve organization" }, 503);
157530
+ } catch (error) {
157531
+ throw routeFailure(c.json({ error: "Unable to resolve organization" }, 503), error);
157056
157532
  }
157057
157533
  if (!resolvedOrg) {
157058
157534
  return c.json({ error: `Unknown organization "${orgHeader}"` }, 404);
@@ -157082,11 +157558,11 @@ function createLobuOrgContextMiddleware() {
157082
157558
  if (!orgId) {
157083
157559
  try {
157084
157560
  orgId = await resolveDefaultOrgId(user.id);
157085
- } catch {
157086
- return c.json(
157561
+ } catch (error) {
157562
+ throw routeFailure(c.json(
157087
157563
  { error: "Unable to resolve organization membership" },
157088
157564
  503
157089
- );
157565
+ ), error);
157090
157566
  }
157091
157567
  if (!orgId) {
157092
157568
  return c.json({ error: "No organization membership found" }, 404);
@@ -157320,6 +157796,7 @@ var init_gateway2 = __esm({
157320
157796
  init_auth2();
157321
157797
  init_pat_auth();
157322
157798
  init_client();
157799
+ init_diagnostics();
157323
157800
  init_platform();
157324
157801
  init_gateway();
157325
157802
  init_app_install_credentials();
@@ -161235,22 +161712,22 @@ async function batchTotalContentCounts(db, opts) {
161235
161712
  const counts = /* @__PURE__ */ new Map();
161236
161713
  const entityIds = opts.entityIds;
161237
161714
  if (entityIds.length === 0) return counts;
161238
- const edgedRows = await db.unsafe(
161715
+ const edgedRows = await cancellable(db.unsafe(
161239
161716
  `SELECT v.id FROM (VALUES ${entityIds.map((eid) => `(${eid})`).join(",")}) v(id)
161240
161717
  WHERE EXISTS (SELECT 1 FROM entity_relationships ir WHERE ir.from_entity_id = v.id AND ir.deleted_at IS NULL)
161241
161718
  OR EXISTS (SELECT 1 FROM entity_relationships ir WHERE ir.to_entity_id = v.id AND ir.deleted_at IS NULL)`
161242
- );
161719
+ ), opts.signal);
161243
161720
  const edgedIds = edgedRows.map((row) => Number(row.id));
161244
161721
  const membersByEntity = new Map(entityIds.map((eid) => [eid, [eid]]));
161245
161722
  for (const eid of edgedIds) membersByEntity.set(eid, []);
161246
161723
  if (edgedIds.length > 0) {
161247
- const memberRows = await db.unsafe(
161724
+ const memberRows = await cancellable(db.unsafe(
161248
161725
  edgedIds.map((eid) => `SELECT ${eid}::bigint AS eid, members.id AS member_id FROM (${identityMemberIdsSql(`${eid}::bigint`)}) members`).join("\nUNION ALL\n")
161249
- );
161726
+ ), opts.signal);
161250
161727
  for (const row of memberRows) membersByEntity.get(Number(row.eid))?.push(Number(row.member_id));
161251
161728
  }
161252
161729
  const membersSql = (eid) => `'${pgBigintArray(membersByEntity.get(eid) ?? [eid])}'::bigint[]`;
161253
- const scopeRows = await db.unsafe(
161730
+ const scopeRows = await cancellable(db.unsafe(
161254
161731
  entityIds.map(
161255
161732
  (eid) => `SELECT ${eid}::bigint AS eid, identity.namespace, identity.identifier, identity.scope_key
161256
161733
  FROM entity_identities identity
@@ -161258,7 +161735,7 @@ async function batchTotalContentCounts(db, opts) {
161258
161735
  AND identity.deleted_at IS NULL
161259
161736
  AND identity.namespace = ANY('${pgTextArray([...STANDARD_IDENTITY_NAMESPACES])}'::text[])`
161260
161737
  ).join("\nUNION ALL\n")
161261
- );
161738
+ ), opts.signal);
161262
161739
  const scopesByEntity = /* @__PURE__ */ new Map();
161263
161740
  for (const row of scopeRows) {
161264
161741
  const eid = Number(row.eid);
@@ -161292,10 +161769,10 @@ async function batchTotalContentCounts(db, opts) {
161292
161769
  ${probed}
161293
161770
  ) u`);
161294
161771
  }
161295
- const rows = await db.unsafe(
161772
+ const rows = await cancellable(db.unsafe(
161296
161773
  arms.join("\nUNION ALL\n"),
161297
161774
  params
161298
- );
161775
+ ), opts.signal);
161299
161776
  for (const row of rows) counts.set(Number(row.eid), Number(row.cnt));
161300
161777
  return counts;
161301
161778
  }
@@ -161324,7 +161801,7 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161324
161801
  if (filters.filters?.length && !filters.entity_type) {
161325
161802
  throw new ToolUserError("Attribute filters require entity_type", 400, "VALIDATION");
161326
161803
  }
161327
- let segmentFilter = null;
161804
+ let segmentIds = null;
161328
161805
  if (filters.entity_type) {
161329
161806
  const etRows = await sql2`
161330
161807
  SELECT et.id, et.metrics_config, et.metadata_schema,
@@ -161351,10 +161828,15 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161351
161828
  "VALIDATION"
161352
161829
  );
161353
161830
  }
161354
- segmentFilter = compileEntitySegmentFilter(
161355
- filters.entity_type,
161356
- etRows[0] ? Number(etRows[0].id) : null,
161357
- etRows[0]?.metrics_config ?? null,
161831
+ segmentIds = await readEntitySegmentIds(
161832
+ sql2,
161833
+ compileEntitySegmentFilter(
161834
+ filters.entity_type,
161835
+ etRows[0] ? Number(etRows[0].id) : null,
161836
+ etRows[0]?.metrics_config ?? null,
161837
+ filters.segment,
161838
+ ctx
161839
+ ),
161358
161840
  filters.segment,
161359
161841
  ctx
161360
161842
  );
@@ -161371,7 +161853,7 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161371
161853
  }
161372
161854
  }
161373
161855
  const conditions = ["{e}.deleted_at IS NULL", identityRootSql("{e}")];
161374
- const params = segmentFilter ? [...segmentFilter.params] : [];
161856
+ const params = segmentIds ? [pgBigintArray(segmentIds)] : [];
161375
161857
  let paramIdx = params.length + 1;
161376
161858
  conditions.push(`{e}.organization_id = $${paramIdx++}`);
161377
161859
  params.push(ctx.organizationId);
@@ -161397,10 +161879,10 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161397
161879
  conditions.push(entityReadPolicySql(readRestrictions, "{e}", params));
161398
161880
  const renderWhere = (eAlias, etAlias) => conditions.map(
161399
161881
  (c) => c.replace(/\{e\}\./g, `${eAlias}.`).replace(/\{et\}\./g, `${etAlias}.`)
161400
- ).concat(memberConditions.length || segmentFilter ? [identityMemberExistsSql(
161882
+ ).concat(memberConditions.length || segmentIds ? [identityMemberExistsSql(
161401
161883
  `${eAlias}.id`,
161402
161884
  "member",
161403
- [...memberConditions, ...segmentFilter ? [`member.id IN (${segmentFilter.sql})`] : []].join(" AND ")
161885
+ [...memberConditions, ...segmentIds ? ["member.id = ANY($1::bigint[])"] : []].join(" AND ")
161404
161886
  )] : []).join(" AND ");
161405
161887
  const whereClause = renderWhere("e", "et");
161406
161888
  const sortColumnMap = {
@@ -161469,29 +161951,30 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161469
161951
  ${plainSort ? "" : `OFFSET ${offset}`}`;
161470
161952
  const fetchPage = async (db) => {
161471
161953
  if (!plainSort) {
161472
- const totalCountResult3 = await db.unsafe(
161954
+ const totalCountResult3 = await cancellable(db.unsafe(
161473
161955
  `SELECT CAST(COUNT(*) AS INTEGER) as total_count ${baseQuery}`,
161474
161956
  params
161475
- );
161476
- const result3 = await db.unsafe(pageQuery(), params);
161957
+ ), ctx.abortSignal);
161958
+ const result3 = await cancellable(db.unsafe(pageQuery(), params), ctx.abortSignal);
161477
161959
  return { totalCountResult: totalCountResult3, result: result3, hasMoreIds: null };
161478
161960
  }
161479
- const pageIds = (await db.unsafe(pageIdQuery, params.slice(0, filterParamCount))).map((row) => Number(row.id));
161961
+ const pageIds = (await cancellable(db.unsafe(pageIdQuery, params.slice(0, filterParamCount)), ctx.abortSignal)).map((row) => Number(row.id));
161480
161962
  const hasMoreIds2 = pageIds.length > limit;
161481
161963
  const ids = hasMoreIds2 ? pageIds.slice(0, limit) : pageIds;
161482
161964
  const [totalCountResult2, result2, contentCounts] = await Promise.all([
161483
- db.unsafe(
161965
+ cancellable(db.unsafe(
161484
161966
  `SELECT CAST(COUNT(*) AS INTEGER) as total_count ${countFrom}`,
161485
161967
  params.slice(0, filterParamCount)
161486
- ),
161487
- ids.length > 0 ? db.unsafe(
161968
+ ), ctx.abortSignal),
161969
+ ids.length > 0 ? cancellable(db.unsafe(
161488
161970
  pageQuery(`AND e.id = ANY('${pgBigintArray(ids)}'::bigint[])`),
161489
161971
  params.slice(0, enrichParamCount)
161490
- ) : Promise.resolve([]),
161972
+ ), ctx.abortSignal) : Promise.resolve([]),
161491
161973
  batchTotalContentCounts(db, {
161492
161974
  organizationId: ctx.organizationId,
161493
161975
  userId: ctx.userId ?? null,
161494
- entityIds: ids
161976
+ entityIds: ids,
161977
+ signal: ctx.abortSignal
161495
161978
  })
161496
161979
  ]);
161497
161980
  for (const row of result2) {
@@ -161499,24 +161982,31 @@ async function listEntities(filters, _env, ctx, readRestrictions = []) {
161499
161982
  }
161500
161983
  return { totalCountResult: totalCountResult2, result: result2, hasMoreIds: hasMoreIds2 };
161501
161984
  };
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) => {
161985
+ const { totalCountResult, result, hasMoreIds } = await fetchPage(sql2);
161986
+ const hasMore = hasMoreIds ?? result.length > limit;
161987
+ const entities = hasMore ? result.slice(0, limit) : result;
161988
+ const totalCount = Number(totalCountResult[0]?.total_count || 0);
161989
+ const readableEntities = await filterEntityReadRows(sql2, await attachEntityIdentities(sql2, entities), readRestrictions);
161990
+ return { entities: readableEntities, hasMore, totalCount, limit, offset, sortBy, sortOrder: normalizedSortOrder };
161991
+ }
161992
+ async function readEntitySegmentIds(sql2, segment, segmentName, ctx) {
161993
+ try {
161994
+ const rows = await boundedQuery(sql2, segment.sql, segment.params, {
161995
+ signal: ctx.abortSignal,
161996
+ statementTimeoutMs: QUERY_SQL_STATEMENT_TIMEOUT_MS,
161997
+ fence: segment.scope
161998
+ });
161999
+ return rows.map((row) => Number(row.id));
162000
+ } catch (error) {
162001
+ if (ctx.abortSignal?.aborted) throw error;
161507
162002
  const code = classifyToolError({ pgCode: error?.code });
161508
162003
  if (code !== "VALIDATION" && code !== "UPSTREAM_TIMEOUT") throw error;
161509
162004
  throw new ToolUserError(
161510
- `Segment '${filters.segment}' failed: ${getErrorMessage(error)}`,
162005
+ `Segment '${segmentName}' failed: ${classifyReadQueryFailure(error).message}`,
161511
162006
  toolErrorHttpStatus(code),
161512
162007
  code
161513
162008
  );
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 };
162009
+ }
161520
162010
  }
161521
162011
  function compileEntitySegmentFilter(entityType, entityTypeId, metrics2, segmentName, ctx) {
161522
162012
  const segment = metrics2?.segments?.[segmentName];
@@ -161561,7 +162051,7 @@ function compileEntitySegmentFilter(entityType, entityTypeId, metrics2, segmentN
161561
162051
  "VALIDATION"
161562
162052
  );
161563
162053
  }
161564
- return { sql: scoped.sql, params: scoped.params };
162054
+ return { sql: scoped.sql, params: scoped.params, scope: scoped.scope };
161565
162055
  }
161566
162056
  function derivedRowSlug(row) {
161567
162057
  let raw;
@@ -161788,6 +162278,8 @@ var init_entity_management = __esm({
161788
162278
  init_entity_field_merge();
161789
162279
  init_entity_hooks();
161790
162280
  init_errors2();
162281
+ init_bounded_read();
162282
+ init_content_read_bounds();
161791
162283
  init_entity_write_denial_audit();
161792
162284
  init_execute_data_sources();
161793
162285
  init_logger2();
@@ -163272,6 +163764,7 @@ var init_routes = __esm({
163272
163764
  init_public_origin();
163273
163765
  init_resolve_session();
163274
163766
  init_deletion_state();
163767
+ init_diagnostics();
163275
163768
  oauthRoutes = new Hono23();
163276
163769
  INVALID_DEVICE_CODE_MESSAGE = "Invalid or expired user code";
163277
163770
  MAX_TOKEN_REQUEST_BYTES = 32 * 1024;
@@ -163342,7 +163835,7 @@ var init_routes = __esm({
163342
163835
  }
163343
163836
  } catch (err) {
163344
163837
  console.warn("[OAuth] Rate limit check failed:", err);
163345
- return c.json(createOAuthError("server_error", "Registration temporarily unavailable"), 503);
163838
+ throw routeFailure(c.json(createOAuthError("server_error", "Registration temporarily unavailable"), 503), err);
163346
163839
  }
163347
163840
  }
163348
163841
  let metadata;
@@ -163384,7 +163877,7 @@ var init_routes = __esm({
163384
163877
  return c.json(client2, 201);
163385
163878
  } catch (error) {
163386
163879
  console.error("[OAuth] Client registration failed:", error);
163387
- return c.json(createOAuthError("server_error", "Registration failed"), 500);
163880
+ throw routeFailure(c.json(createOAuthError("server_error", "Registration failed"), 500), error);
163388
163881
  }
163389
163882
  });
163390
163883
  oauthRoutes.get("/oauth/authorize", async (c) => {
@@ -163663,7 +164156,7 @@ var init_routes = __esm({
163663
164156
  return c.json({ redirect_url: redirectUrl.toString() });
163664
164157
  } catch (error) {
163665
164158
  console.error("[OAuth] Failed to create authorization code:", error);
163666
- return c.json(createOAuthError("server_error", "Failed to create authorization code"), 500);
164159
+ throw routeFailure(c.json(createOAuthError("server_error", "Failed to create authorization code"), 500), error);
163667
164160
  }
163668
164161
  });
163669
164162
  oauthRoutes.post("/oauth/device_authorization", async (c) => {
@@ -163729,7 +164222,7 @@ var init_routes = __esm({
163729
164222
  }
163730
164223
  } catch (err) {
163731
164224
  console.warn("[OAuth] Device-email rate limit check failed:", err);
163732
- return c.json(createOAuthError("server_error", "Temporarily unavailable"), 503);
164225
+ throw routeFailure(c.json(createOAuthError("server_error", "Temporarily unavailable"), 503), err);
163733
164226
  }
163734
164227
  }
163735
164228
  const parsed = await parseRequestBody(c);
@@ -165880,7 +166373,7 @@ function createChatIdentityRoutes(overrides = {}) {
165880
166373
  cookies = await deps.signOut(c.req.raw, c.env);
165881
166374
  } catch (error) {
165882
166375
  logger_default.warn({ error }, "Chat identity link could not sign the browser out to switch accounts");
165883
- return c.html(SWITCH_FAILED_PAGE, 502);
166376
+ throw routeFailure(c.html(SWITCH_FAILED_PAGE, 502), error);
165884
166377
  }
165885
166378
  for (const cookie of cookies) c.header("Set-Cookie", cookie, { append: true });
165886
166379
  return c.redirect(loginContinuation2(token, loginProviderForChatPlatform(claim.platform)), 303);
@@ -165929,6 +166422,7 @@ var init_chat_identity_routes = __esm({
165929
166422
  init_html();
165930
166423
  init_logger2();
165931
166424
  init_join_public();
166425
+ init_diagnostics();
165932
166426
  PATH = "/connect/chat-identity";
165933
166427
  DEFAULT_DEPS4 = {
165934
166428
  session: async (request2, env) => resolveSession(await createAuth(env, request2), request2.headers),
@@ -165951,7 +166445,7 @@ var init_chat_identity_routes = __esm({
165951
166445
 
165952
166446
  // src/connect/routes.ts
165953
166447
  import { Hono as Hono29 } from "hono";
165954
- import { HTTPException as HTTPException2 } from "hono/http-exception";
166448
+ import { HTTPException as HTTPException5 } from "hono/http-exception";
165955
166449
  import { createMiddleware } from "hono/factory";
165956
166450
  function getBaseUrl2(c) {
165957
166451
  return getPublicWebUrl(c.req.url) ?? "";
@@ -166553,14 +167047,14 @@ var init_routes4 = __esm({
166553
167047
  const queued = await createSyncRun(feedId, c.env, tx);
166554
167048
  if (!queued.ok) {
166555
167049
  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) });
167050
+ throw new HTTPException5(409, { res: c.json({ error }, 409) });
166557
167051
  }
166558
167052
  const [current] = await tx`
166559
167053
  SELECT status, consecutive_failures FROM feeds
166560
167054
  WHERE id = ${feedId} AND deleted_at IS NULL
166561
167055
  `;
166562
167056
  if (!current || current.status === "paused" && shouldHardPauseFeed(Number(current.consecutive_failures))) {
166563
- throw new HTTPException2(409, { res: c.json({
167057
+ throw new HTTPException5(409, { res: c.json({
166564
167058
  error: "Resume a feed paused after repeated failures before validating this connection."
166565
167059
  }, 409) });
166566
167060
  }
@@ -168755,7 +169249,7 @@ var LOBU_SKILL_MARKDOWN;
168755
169249
  var init_lobu_skill_generated = __esm({
168756
169250
  "src/skills/lobu-skill.generated.ts"() {
168757
169251
  "use strict";
168758
- LOBU_SKILL_MARKDOWN = '---\nname: lobu\ndescription: "Set up new Lobu agents end to end and operate existing Lobu projects and memory: interview, scaffold, validate, authenticate, connect feeds, execute operations, and test Automations."\n---\n\n# Lobu\n\nUse this skill when setting up a brand-new Lobu agent from scratch (follow "Onboarding a New Project" below) or when running, validating, evaluating, or connecting an existing Lobu project, or operating Lobu memory from a coding agent.\n\nThe `AGENTS.md` generated into a new project is the source of truth for the config API (the `define*` helpers, connectors, auth, Automations, memory) \u2014 this skill does not duplicate it. For an existing project, jump to "Core Model" + the relevant reference section below.\n\n## Onboarding a New Project\n\nUse this playbook when a new user asks you to build them a Lobu agent from scratch. Set it up end to end: ground yourself in what the user already has, interview, discover, scaffold, prove the complete local path, then offer the deployment choice. Do not call the setup complete until every path the user selected has actually passed end to end. If an external provider, authorization, deployment, or rate limit blocks the proof, name the exact blocker and leave the setup as blocked rather than claiming success.\n\n### 1. Ground yourself in what the user already has\n\nBefore interviewing, look at what already exists so your questions and suggestions are personal rather than a blank slate. This is discovery, not a design decision \u2014 do not let it skip the interview.\n\n- Local: run `lobu context list` to see existing contexts (`--json` adds `loggedIn`, which reports stored credentials, not session validity); check the current directory and home for existing Lobu projects (`lobu.config.ts`), configured MCP servers, and CLI auth state. Note what the user already set up.\n- Cloud: if the user has an active session (do not create one just to look), call `client.organizations.list()`, `client.agents.list()` for each org, `client.catalog.listInstalled({ kinds: ["connectors"] })`, and `search_memory` for prior knowledge. This reveals existing agents, connectors, and memory you can build on.\n- Tell the user what you are looking at so they can correct you, and let what you find shape the options you offer. Never treat this discovery as an identity signal: orgs, emails, or domains never prove a company or product, and never mention a competitor or third party unless it actually appears in what you found.\n\nDo NOT ask for a login email during the interview. Email is only needed when a managed connector actually requires a session (step 3) or when the user chooses cloud deployment (step 6); ask for it at that point. Treat identity only as identity; never infer a company from an email address or domain.\n\n### 2. Interview with concrete, personalized options\n\nInterview the user one question at a time; wait for each answer, do not guess, and do not batch the questions. Anchor each question in what you found in step 1. Instead of asking "what agent do you want?" as a blank slate, summarize what you see and offer two or three concrete alternatives to choose from:\n\n- "You already have org X with connectors A and B installed and N existing agents. Do you want to (a) add a new agent on top of those, (b) extend one of the existing agents, or (c) start something standalone?"\n- "For what it should do, the common shapes are (a) a triage agent that reads incoming chat and files a ticket, (b) a scheduled report that summarizes new activity each morning, (c) a research agent that answers questions from your connected tools. Which fits, or what would you change?"\n\nOffer a default so the user can answer "the first one" \u2014 decisive users and undecided users both move faster with a concrete menu.\n\n- What company or product is this for?\n- What does it do, and who does it serve?\n- What is its public domain? (optional for a personal project)\n- Do I have permission to research the public website and other public sources?\n- What is the agent for?\n- What should we call it?\n- Who uses it: just me, my team, or each of my customers?\n- How should it behave, and what may it do unattended versus only with approval?\n- What should it remember? Model this as one to three entity types.\n- Where does its data come from? Pick one connector or custom source to start.\n- Where should people talk to it? Offer Web UI, API or SDK, MCP, Slack, Teams, WhatsApp, Discord, Google Chat, and Telegram without forcing a chat platform. If Slack is chosen, ask whether to join Lobu\'s hosted workspace for a quick start, install Lobu into an existing workspace, or use a custom Slack app; then ask whether to test the DM with Lobu, a named channel, or both, and whether people knowledge means conversation participants, bound-channel members, or the full workspace directory.\n- Should anything run on a schedule?\n- Which supported LLM provider credential does the user have?\n\nIf the user gave permission to research and has a public domain, research the company before proposing the design. Summarize its product, customers, workflows, and useful signals, and cite the public sources you used. Then propose one to three entity types, their relationships, the first data source, one or two useful Automations, and suitable interaction channels. Play back a short numbered plan and wait for confirmation before scaffolding anything.\n\n### 3. Discover the surface before choosing how to scaffold\n\nCheck Node is 26.x, then run `lobu context list` and identify the named Lobu Cloud context; do not assume the active context still points to cloud after a local run. If a managed or cloud connector was chosen and there is no session, ask for the login email at that point, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`. The person approving must sign in with that same email; knowing an address never grants access. After a successful login, an empty organization membership list is a tenancy/discovery result, not an authentication failure: call `client.organizations.list()` and explain the result. Never revoke or repeat login with `--force` unless the user separately approves that re-authentication.\n\nUse ClientSDK through Lobu MCP with the explicit cloud context. From the CLI, account discovery works before selecting an active org with `lobu memory run query_sdk \'{"title":"Find managed connection providers","script":"export default async (_ctx, client) => client.organizations.list()"}\'`; `lobu call` over REST requires an active org. Call `client.organizations.list()` to find public organizations offering managed connections. Call `client.catalog.listInstalled({ kinds: ["connectors"] })`; if the connector is not installed, call `client.catalog.listCatalog({ kinds: ["connectors"] })`. Inspect the selected entry\'s `detail.auth_schema`, `detail.options_schema`, `detail.feeds_schema`, and `detail.automation_events` instead of guessing field names. On account-scoped `/mcp`, select an authorized home workspace first with `const home = await client.org(homeSlug)` and call `home.connections.connectManaged`; put the public provider org in `managed_by_org`, rather than selecting that provider org with `client.org`. This call runs against cloud, not the embedded runtime. If a matching live managed offer exists, explain it and call `client.connections.connectManaged` only after consent. Complete the returned user authorization, then run `lobu context use <cloud-name>` immediately before executing its `local_bootstrap_command` from the parent directory where the new project should be created; use `--here` only after entering an empty directory, and do not create a blank Lobu scaffold first. Ask for bring-your-own OAuth credentials only if no managed offer exists or the user prefers their own app.\n\n**If no connector in the catalog matches the data source, do not report "no integration exists"** \u2014 author a custom connector: write `connectors/<name>.connector.ts` in the project, register it with `connectorFromFile("./connectors/<name>.connector.ts")`, and model it on the [npm downloads example](https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/npm-downloads.connector.ts). See [Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md) for the full contract; the end-to-end entity/event/Automation model is in [Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md).\n\n### 4. Scaffold and build from the confirmed plan\n\nIf managed auth supplied a `local_bootstrap_command`, use the project it generated. Otherwise run `npx @lobu/cli@latest init` with the confirmed name and provider. Postgres is built in, so `lobu run` starts an embedded database; ask for `DATABASE_URL` only if the user chooses external Postgres. Read the generated `AGENTS.md` completely before editing `lobu.config.ts`. Use the canonical reference at `https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/lobu.config.ts` when needed; do not assume that example exists in the new project\'s filesystem. Briefly explain how the chosen feed may use checkpoints to collect incrementally, emits events, builds shared entity memory, and gives both chat and Automations the same governed context.\n\n`feeds_schema.<feed>.eventKinds` are the default Automation trigger catalog for feed connectors: every declared kind is a subscribable event type (`event_type` = the kind slug) for any feed that emits the kind. A feed\'s first successful non-dry sync establishes its baseline without activation; later inserts of a matching kind activate subscribers. A kind with `updatedEvent: true` also offers `<kind>.updated` for supersedes whose `occurred_at` strictly advances past the previous head. The original kind stays insert-only; unchanged rows, volatile-only updates and same-time reformats stay quiet. Subscribe to both types for new items and later activity. Feed-scoped filtering is not yet available (events dedupe by connection + origin id, so a `feed_key` match would miss origins first seen by another feed). `automation_events` (now derived from eventKinds when a connector declares none) is the trigger picker\'s list. If no declared kind matches the use case, use a scheduled Automation with a bounded named SQL source and read event text from `payload_text`. Validate the query against the running local schema before relying on it. If `feeds_schema` is empty, do not invent or trigger a feed; chat integrations such as Slack can deliver incoming messages directly. For Slack or Telegram, prefer `defineConnection` with `credentialMode: "hosted"` so no bot token is required; `lobu run` prints the exact hosted-workspace join URL, own-workspace install URL when available, and short-lived link command. This hosted chat path requires a cloud session and the agent applied to that cloud workspace; the link targets the cloud agent. It does not create a local Slack data connection or prove local Slack search. Use those returned values instead of constructing URLs. A printed `/lobu link <code>` is one-time: redeem it in the first selected DM or channel. In an installed workspace whose installer is linked to Lobu, bind each additional surface with `/lobu link <agent-id>`; otherwise generate a fresh code for that surface. Mention Lobu in a channel test and verify the App Home separately. Lobu email login and Slack installation are separate: the email link authorizes Lobu CLI access, while an existing-workspace install requires the user or workspace admin to approve Slack\'s OAuth screen. Never describe Slack consent as an email approval. Use `credentialMode: "byo"` only if the user chooses their own app. Tell the user once which remaining secrets are required and add only `secret("ENV_NAME")` placeholders to config. Never open or request permission to read `.env`; inspect `.env.example` when present and declared secret placeholder names only. Never read, print, invent, or paste a real secret into source or chat.\n\nIf the user wants the agent to know people in Slack, ask whether that means conversation participants, members of bound channels, or the full workspace directory. Installing the app proves none of those by itself. Verify the selected scope by inspecting the people or member entities Lobu actually materialized and by asking the agent a roster question. If human-readable names or non-participants are unavailable, identify that exact product gap; never claim the complete workspace directory was synced.\n\n### 5. Prove the complete local path\n\nChange into the generated project directory and verify `pwd` contains the intended `lobu.config.ts`; never run project commands from its parent. Run `npx @lobu/cli@latest validate`, boot with `npx @lobu/cli@latest run`, and verify health and the local Web UI. With the embedded database default, `lobu run` creates and selects the local context and auto-applies the project; with an external `DATABASE_URL`, it does neither, so authenticate and apply to that runtime explicitly. Send a harmless direct chat message without tools.\n\nBefore consent to access provider data, inspect only catalog, connection, auth-profile, and feed metadata. For browser access, inspect the paired device and connection metadata without invoking browser actions. Durable managed OAuth and env-profile credentials stay at the gateway. Do not run a feed or connector dry-run before consent, because a dry-run may still read provider data. Ask explicitly before accessing real provider data. Only after approval, dry-run the connector or feed server-side and trigger the selected feed manually if that connector actually declares one. A feed dry-run records its run but persists no collected events, entities, attachments, checkpoint changes, or feed sync state. Run each Automation once, poll `client.operations.getRun` with its returned `run_id`, and show each completed run plus any declared result event or entity. For a run-result-only or reaction-only Automation, use the completed run and the Automation `view_url` returned by Lobu. For Slack, treat DM, channel mention, App Home, and requested member discovery as four separate checks. Keep actions in approval mode unless the user explicitly approves execution. If any step fails, fix it and rerun that step; do not silently substitute a different path.\n\n### 6. Offer the deployment choice\n\nAfter the local proof, ask the user whether to keep running locally or deploy to Lobu Cloud. Explain that the embedded local runtime and Lobu Cloud are separate targets, and that keeping it local needs no further setup. Only if the user chooses cloud deployment, ask for the login email to identify the deployer, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`; the person approving must sign in with that same email. Because `lobu apply` has no context flag, use `lobu context list` and then `lobu context use <cloud-name>` to select an explicit cloud context before deployment. Run `lobu apply --dry-run` first, show the target organization and exact plan, and wait for confirmation before applying. After apply, use only authoritative `view_url` values and link commands returned by Lobu; never construct URLs. Present the working access choices: Web UI, direct agent chat, API or SDK, MCP, and any channels the user selected.\n\n## Core Model\n\n- **Lobu** is the agent framework, runtime, deployment layer, and memory surface.\n- Keep framework configuration in `lobu.config.ts` (TypeScript, `defineConfig` from `@lobu/cli/config`).\n- Keep agent identity and instructions in `IDENTITY.md`, `SOUL.md`, and `USER.md`.\n- Keep reusable capability bundles in `skills/<name>/SKILL.md` or `agents/<agent>/skills/<name>/SKILL.md`.\n- Use `lobu login` for CLI authentication. Do not use a separate memory login command.\n- Use `lobu connect` for MCP client and skill setup.\n- Use `lobu memory ...` for memory operations, seeding, and direct tool calls.\n\nReference the canonical docs before guessing how a feature works:\n[Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md)\n(entities vs events, identity, end-to-end lifecycle),\n[Automations](https://github.com/lobu-ai/lobu/blob/main/docs/AUTOMATIONS.md)\n(trigger/source/output contract), and\n[Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md)\n(custom connectors).\n\n## Project Checklist\n\n1. Read `lobu.config.ts` first.\n2. Read the active agent files under `agents/<id>/`.\n3. Check local skills under `skills/` and `agents/<id>/skills/`.\n4. Use `lobu validate` after config changes.\n5. Discover the live SDK and connector surface with `search_sdk`; never guess a method, connector key, feed key, connection id, or operation key.\n6. When prompt or Automation changes, run evals via promptfoo (see `examples/personal-finance/evals/promptfooconfig.yaml`). The in-house `lobu eval` command has been removed.\n\n## Common Commands\n\n```bash\nnpx @lobu/cli@latest init my-agent\nnpx @lobu/cli@latest run\nnpx @lobu/cli@latest validate\nnpx @lobu/cli@latest login\n```\n\n## Authentication\n\n- Interactive (human at a terminal): `lobu login` runs the device-code flow with a browser approval.\n- CI / your own automation: `LOBU_API_TOKEN`, or `lobu login --token <pat>`.\n- Local `lobu run`: the CLI mints credentials automatically over loopback \u2014 no prompt.\n- Headless, on a *user\'s* behalf: `lobu login --email <address>`. The server emails the user a one-click approval link and the CLI polls until they approve, then stores the scoped credential \u2014 no TTY, no pre-minted token. This is the auth.md "user_claimed" flow.\n\nAn external agent not using this CLI can drive the same flow over HTTP: read `<origin>/auth.md` (linked from the `agent_auth` block in `<origin>/.well-known/oauth-authorization-server`) for the endpoints. Today only the email user_claimed flow exists (no zero-touch ID-JAG). Never fabricate a token.\n\n## Organization Deletion\n\nTreat organization deletion as permanent and restricted to organization owners. The supported path is the **Organization settings** page, opened from that workspace\'s settings button in the organization switcher. ClientSDK and Lobu CLI intentionally expose no organization-delete method. When asked to delete organizations, identify each exact target and its data impact read-only, surface one production organization at a time for explicit confirmation, then direct an owner to that page or use their logged-in browser only when explicitly authorized. Never invent a hosted URL, call the raw Better Auth route, bypass a failed authorization check, delete organization rows directly, or batch confirmations.\n\nCloud CLI OAuth/PAT credentials are not a Better Auth browser session. A `401` or `403` is a stop signal: report the authorization boundary and leave the organization intact.\n\n<!-- lobu-memory-guidance:start -->\n## Memory Defaults\n\nYour long-term memory is powered by Lobu. Do NOT use local files (memory/, MEMORY.md) for memory.\n- Lobu automatically recalls relevant memories when you receive a message.\n- To save something, call save_memory with the content and an appropriate semantic_type.\n- To search, call search_memory. Results include view_url links to the web interface.\n- NEVER construct Lobu URLs yourself. When the user asks for a link, call search_memory to get the correct view_url.\n- When the user says "remember this", save it to Lobu immediately.\n- When a message changes a fact you already stored (an updated preference, status, count, location, or plan), first search_memory for the prior memory to get its id, then save_memory the new value with supersedes_event_id set to that id. This replaces the stale value so future recalls return the current one; the old value stays in history but is hidden from normal search.\n<!-- lobu-memory-guidance:end -->\n\n## Lobu Memory\n\nConfigure project-scoped memory in `lobu.config.ts` by setting the org on `defineConfig` and declaring the schema with the `define*` helpers:\n\n```ts\nimport { defineConfig, defineEntityType } from "@lobu/cli/config";\n\nconst ticket = defineEntityType({\n key: "ticket",\n name: "Ticket",\n properties: {\n subject: {\n type: "string",\n title: "Subject",\n "x-table-label": "Subject",\n "x-table-column": true,\n },\n },\n});\n\nexport default defineConfig({\n org: "my-org",\n orgName: "My workspace",\n agents: [/* ... */],\n entities: [ticket],\n});\n```\n\nThe entity schema also renders the record page form. Give every array `items` and every object `properties` (bare ones render as raw JSON), put the label in `title` and help text in `description`, mark derived fields `readOnly: true`, and declare every field an Automation writes.\n\nFor a "when did this field last change" timestamp, declare root `metadata_schema["x-lobu-stamps"]: { "stage_at": "stage" }` instead of writing it from an Automation. The stamp field must be a declared `{ type: "string", format: "date-time" }` property (not listed in `required`) and the tracked field a declared property. Every writer (agent, SDK, Automation, connector projection, view action, approval) then gets it for free: the server sets `stage_at` when a record is created with `stage` set or when `stage` changes value, and discards any value a caller sends for `stage_at`. `readOnly` alone is presentation only; it is not enforced.\n\nSeed data records still live as YAML under `./data`. Then seed or operate the memory workspace with:\n\n```bash\nlobu login\nlobu memory org set <org-slug>\nlobu memory health --org <org-slug>\nlobu memory seed --org <org-slug>\nlobu memory run search_memory \'{"query":"Acme"}\' --org <org-slug>\n```\n\nUse `search_memory` first when the user asks about a specific entity or workspace memory. Use `save_memory` to persist durable memory. To update existing knowledge, search first, then save with `supersedes_event_id` so the old row is tombstoned rather than deleted.\n\n## MCP Client Setup\n\nUse the actual MCP URL for the user\'s runtime. Never hardcode a hosted URL unless the user explicitly asks for that instance.\n\nCommon setup commands:\n\n```bash\n# Claude Code\nlobu connect claude-code --url <mcp-url>\n\n# Codex\nlobu connect codex --url <mcp-url>\n\n# Antigravity\nlobu connect antigravity --url <mcp-url>\n\n# OpenCode\nlobu connect opencode --url <mcp-url>\n```\n\nRun `lobu connect --url <mcp-url>` without a client id to choose interactively. For ChatGPT, Claude Desktop, Cursor, and other browser-managed clients, the same command applies the safe local configuration it can and prints the exact remaining client handoff. Complete OAuth in the client, not through a separate Lobu CLI login.\n\n## Browser-Authenticated Connectors\n\nFor connectors that need a signed-in browser, pair the Owletto Chrome extension\nand sign in on the source site in that browser. Browser operations run through\nthat paired device; external remote-debugging endpoints and CLI browser-auth\ncapture are no longer supported.\n\nNothing answers a JS dialog (alert, confirm, prompt, beforeunload) on the\nagent\'s behalf. A browser action it blocks fails, and the failed result\'s\n`output` carries `tab_id` and `dialog` (`dialog_id`, `type`, `message`). In\n`run_sdk`, catch the `operations.execute` error and read `error.details.output`\nrather than parsing the error text (an uncaught failure returns the same value\nas the `run_sdk` result\'s `error.details`, and a background run\'s\n`operations.getRun` returns the same `output`), then answer with the\nconnection\'s `handle_dialog` operation. An unanswered dialog is handed to the user after two minutes.\n\nTo test a configured feed without writing ingested data, discover the current\nfeed methods with `search_sdk`, then use `client.feeds.trigger({ feed_id, dry_run: true })`\nthrough `run_sdk` or `lobu call run_sdk` (with a `title` arg). Inspect `client.feeds.get({ feed_id })`\nfor the completed run\'s preview. The dry run uses normal device routing and\nauthorization checks and may access the upstream provider, so obtain consent first.\n\n## Agent-Facing Tool Surface\n\nThe normal MCP surface is intentionally small. Flat administrative tools are not advertised to agents; compose through these tools instead:\n\n- `search_memory` and `save_memory` for direct knowledge recall and persistence.\n- `search_sdk` to discover current ClientSDK methods, signatures, connector feed keys, operations, access requirements, and examples. Pass `mode: "read"` when you only need methods safe for `query_sdk`.\n- `query_sdk` for read-only TypeScript and `query_sql` for governed, paginated SQL reads.\n- `run_sdk` for mutations and external operations. Use `lobu call run_sdk --arg title=\'\u2026\' --arg script=\'\u2026\'` from the CLI for the same ClientSDK scripting workflow; `run_sdk`, `query_sdk`, and `query_sql` calls need a short `title` naming them in the activity feed.\n\nSearch before create to avoid duplicates. Prefer a read or dry run before mutations, never fabricate returned URLs or identifiers, and never delete from `events`; supersede or tombstone instead.\n\n## Custom Views\n\nBefore authoring UI, inspect available native entity/event pages, existing views (`client.views.list()` and `client.views.get({ key })`), and the project\'s shared components and overrides. Honor explicit user designs and reuse UI from the top down:\n\n1. Use the largest existing surface or component that meets the task. Configure its segment, filters, search, saved preset and layout before replacing its UI.\n2. If that surface cannot meet a concrete requirement, compose its exported parts, such as an individual table, board, graph or shared collection controls when available. Preserve shared selection and action handling instead of rebuilding that logic.\n3. If those parts still do not fit, use smaller shared primitives and write custom UI only for the remaining gap. Explain the unmet requirement that forced each step down.\n\nCheck the current exports and target host before choosing an import; native renderer registrations do not imply React exports. Surface a missing export as a platform gap rather than inventing an API or silently copying the native implementation. `@lobu/views/components` currently supplies theme-aware defaults such as `Card`, `DataTable`, filters, charts, links and query-state components. `LoadingState` draws skeleton lines in the host\'s style; `Skeleton` is a pulsing block to size like the content it stands for (a figure, a row, a chart), so a slow read keeps the page\'s shape instead of showing text. When exploration needs specialized linked charts, drilldowns, scenario controls or Canvas/SVG, compose a React view from the suitable existing components.\n\nNative JSON templates use the target renderer\'s registered component names and overrides; inspect what that host actually supplies. React views compose imported components in their own bundle, independently of that native renderer map.\n\nViews are custom React panels attached to entity types, records, events, or the workspace Data hub. They render in the web app and MCP hosts (Claude and other MCP Apps hosts); chat channels get links to views, not the views themselves. Author them in `views/<type>/<key>.tsx` and ship with `lobu apply` (list them via `viewFromFile` in `defineConfig`), or set sources over MCP with `client.views.set` (owner/admin only).\n\nModule shape (the server resolves React, React DOM, `@lobu/views` and `@lobu/views/components`; other dependencies need the CLI path with `node_modules` present):\n\n```tsx\nimport { defineView, tool, useAction, useParams, useQuery } from "@lobu/views";\nimport {\n Card,\n DataTable,\n EmptyState,\n ErrorState,\n FilterBar,\n LoadingState,\n SearchField,\n TruncatedNotice,\n} from "@lobu/views/components";\n\nexport const view = defineView({\n key: "pipeline",\n attach: [{ collection: "deal" }],\n params: { stage: { type: "string", default: "open" } },\n actions: { markWon: { emits: "deal.won" } },\n});\n\nexport default function Pipeline() {\n const [params, setParams] = useParams();\n const deals = useQuery(tool("manage_entity", { action: "list", entity_type: "deal", filters: [{ field: "stage", op: "eq", value: String(params.stage) }], limit: 100 }));\n const markWon = useAction("markWon");\n const rows = deals.data?.entities ?? [];\n // Keep the filter mounted across query states: an early return on\n // loading/error would unmount the focused input on every keystroke\n // (each keystroke re-queries). Render states inline instead.\n return (\n <Card\n title="Pipeline"\n actions={<button type="button" onClick={() => markWon({})}>Mark won</button>}\n >\n <FilterBar><SearchField label="Stage" value={String(params.stage)} onChange={(v) => setParams({ stage: v })} /></FilterBar>\n {deals.loading && <LoadingState text="Loading deals\u2026" />}\n {deals.error && <ErrorState message={deals.error} errorCode={deals.errorCode} />}\n {!deals.loading && !deals.error && rows.length === 0 && (\n <EmptyState title="No deals in this stage." />\n )}\n {!deals.loading && !deals.error && rows.length > 0 && (\n <DataTable columns={[{ key: "name", header: "Name" }]} rows={rows} keyOf={(r) => r.id ?? r.slug} />\n )}\n {deals.truncated && <TruncatedNotice shown={rows.length} />}\n </Card>\n );\n}\n```\n\n`defineView` is the view\'s only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params`, `actions` and `resources` are read from it, never passed separately. `views.set` always requires `source_code` containing the entrypoint module, including when retaining multiple files. Write `defineView` out as a literal (no variables, spreads or `${}` templates): the server reads it without running the module.\n\nA view makes no network requests of its own; data comes through `useQuery`. The one exception is images: `resources: ["https://tile.openstreetmap.org"]` declares origins the view may load images (map tiles, logos) from. Each entry is a bare `https://` origin with a public hostname (no path, wildcard, localhost or IP), at most 8. The images-only limit is a save-time check: `views.set` renders the view\'s empty, error and loading states in an offline browser and refuses the save if anything other than an image from a declared origin is requested. It is not enforced at runtime. MCP hosts receive the origins as the MCP Apps `resourceDomains` CSP, which allows scripts, styles, fonts and media from them as well as images, and the Lobu web app applies no runtime CSP to views. Declare only image or tile CDN origins you trust. Hosts that render through the generic `ui://lobu/views` loader use its CSP, which declares no image origins, so declared images may not load there.\n\nFor a multi-file view, `files` maps relative paths to complete source strings and `entrypoint` names the view module. Include all three inputs below; `source_code` must exactly equal `files[entrypoint]`:\n\n```ts\nawait client.views.set({\n source_code: files[entrypoint],\n source_files: { entrypoint, files },\n dependencies: {}, // Local files and the host-provided runtime need no extra packages.\n});\n```\n\n`attach` lists the pages a view appears on, one per entry: `{ record: "deal" }` is a card on every deal\'s page above its activity (`{ record: "deal", id: 7 }` pins one record), `{ collection: "deal", when? }` a tab on the deal list page, `{ workspace: true }` a Data hub tab, `{ event: "deal.won", type? }` one event\'s page. One view can list several pages and branch on `useScope()` when it answers the same question at each scale. A record card renders with `useHost().displayMode === "inline"` inside `container.maxHeight` (the host clips past it): render a summary there with a "See all" that calls `requestDisplayMode("fullscreen")`, and the full view when `displayMode` is `"fullscreen"` (the peek, a full page, a tab).\n\nWorkspace attachment does not render individual events. For an event presentation, attach to its specific `semantic_type` (event kind), optionally restricted to a linked entity type with `type`; a metadata schema name does not select the view. Avoid binding a specialized renderer to a generic kind such as `summary`. Register a dedicated kind in the workspace\'s event-kind registry and have its producer emit it. On event pages and event peeks, read `useScope().event` by exact ID and select that ID from the returned lineage; never substitute the latest event or let a URL date param change the subject. A shared workspace/event module should branch on `scope.event`, keeping history selection on its workspace surface. Preserve a readable stored body for fallback and evidence.\n\nBefore reporting a view working, open each attached surface, including an event page and peek when declared. Exercise filtering, drilldown, keyboard navigation, and a narrow pane; check loading, missing/error, and truncated data states. Refresh and reopen an earlier event of the kind to verify the view stays on that event rather than jumping to the newest one. Views render in an iframe, so an empty parent-page DOM is not evidence the view is empty; inspect the frame through an authorized browser or accessibility surface. A successful compile proves only that the bundle was built.\n\nImport reusable UI from **`@lobu/views/components`**. Discover this kit with `search_sdk({ query: "@lobu/views/components" })` or a component name. Start with the largest suitable native surface; compose smaller parts only for needs it does not cover:\n\n| Need | Component and minimum input |\n| --- | --- |\n| Complete entity list | `EntityListPage title={title} table={tableProps}` |\n| SQL, computed TypeScript or local rows | `EntityListPage title={title}` with `DataTable columns={columns} rows={rows} keyOf={keyOf}` as children |\n| Complete record body | `EntityRecordPage entity={entity} owner={workspace} schema={schema}` |\n| Entity table or individual fields | `EntityTableView`, `RecordSpecSheet`, `SchemaValue`, `EntityAvatar` |\n| Workspace schema, proposed schema or schema diff | `SchemaGraph`, `SchemaGraph schema={spec}`, `SchemaGraph schema={spec} base="workspace"`, or `SchemaGraph schema={after} base={before}` |\n| Saved resource identity and navigation | `AutomationReference`, `AgentReference`, `ConnectorReference` |\n| Automation instructions, sources, triggers, outputs and code | `AutomationDefinition value={definition}` |\n| Agent identity, models and settings | `AgentDefinition value={definition}` |\n| Connector actions, feeds, schemas and source | `ConnectorDefinition value={definition}` |\n| Current / Proposed comparison | Existing `Tabs` with the same definition component in each panel |\n| Optional technical details | `JsonDiff before={current} after={proposed}` inside collapsed `<details>` |\n\nThe host supplies native JS/CSS, React and live theme. Do not copy product markup or bundle a second React. Exported prop types describe the shared contracts. Use `Button`, `Badge`, `Card`, chart and state components for surrounding UI.\n\n**Page bodies are controlled.** Supply data and slots; they fetch nothing and authorize no writes. `EntityListPage` accepts `title`, optional `actions`/`controls`, and either `table: EntityTableViewProps` or `children`. Its `loading`, `error`, `onRetry` and `empty` affect only results, keeping controls mounted. Native table props include rows, schema, linked lookups, sorting and pagination; honor `metadata.has_more`. For SQL/TypeScript rows use `DataTable`, without inventing entity IDs or types. `EntityRecordPage` renders the native title/avatar and schema fields; `actions`, `details`, `summary`, and `children` supply editing, links, activity and tabs. Default `layout="record"` adapts to width; `layout="content"` retains the header while children own the layout. A `null` title/details/summary hides that slot. Preserve zero and false.\n\n**SchemaGraph is read-only.** It reuses the native schema canvas. Omit props for the mounted workspace schema, pass `schema` for a supplied snapshot, add `base="workspace"` to compare a proposal with the live workspace, or pass another spec as `base`. A spec is `{ entityTypes: [{ slug, name?, description?, metadata_schema?, event_kinds? }], relationshipTypes: [{ slug, name?, metadata_schema?, rules: [{ source_entity_type_slug, target_entity_type_slug }] }] }`. Specs are full snapshots: an omitted type is removed in a diff. Added, removed and changed types/rules remain visible; inspect type details for metadata fields, event kinds and rule changes. Existing entity types open their native pages; unsaved types show details in place. Live reads use the visiting user\u2019s session and permissions through the existing broker; supplied snapshots still render when workspace reads are unavailable. No edits or schema writes are performed. The leaf names match `entitySchema`: list responses use `entity_types` / `relationship_types`; attach `listRules` results to the matching relationship by ID. To apply a reviewed spec, use existing `createType` / `createRelType` (both require `name`) and `addRule({ slug, ...rule })` separately. The graph\u2019s optional name falls back to slug for display only. Hosts without native components throw the standard unavailable-native error.\n\n**References resolve saved identity.** Pass `mode="live"`, mounted `workspace`, optional `appearance="inline" | "row"` (default row), and `automationId` (positive decimal string), `agentId`, or `connectorKey` plus optional numeric `connectionId`. Discover IDs first. These reuse product rows and visiting-user permission checks; they accept no authored name/status or mutation callbacks. Invalid selectors, another workspace, missing records and refused reads show unavailable. A connector definition does not imply a connected account. Reads refresh on mount, focus, reconnect and host invalidation, without interval polling.\n\n**Definitions render supplied objects.** All three have the same signature: `{ value: Record<string, unknown> }`. Pass the existing saved definition or complete proposed snapshot, not a patch. Automation fields include `name`, `description`, `prompt`, `sources`, `triggers`, `outputs`, `reaction_script`; Agent fields include `name`, `description`, `identity_md`, `settings`; Connector fields include `name`, `description`, `version`, `actions_schema`, `feeds_schema`, `source_code`. Remaining nested settings stay inspectable. Missing fields differ from empty values. Bodies fetch nothing, execute no supplied code, and add no save/approval controls. Label authored objects as Snapshot or Proposal preview; use a reference for live identity. Never supply credentials.\n\nShow changes as **Current / Proposed**, defaulting to Proposed, with the same native body on both sides. Keep JSON diff optional. Rendering does not save or apply anything and needs no new proposal endpoint. For an existing approval, render its held current/proposed snapshots; do not merge in newer live values. Writes remain on existing declared `useAction` paths or native authorized editor/review pages. An authored preview must not imply a held approval or authority to apply it.\n\n```tsx\nimport {\n Card, ConnectorDefinition, JsonDiff,\n Tabs, TabsList, TabsTrigger, TabsContent,\n} from "@lobu/views/components";\n\n// current and proposed are complete definition objects from authorized reads\n// and the requested edit. Use AgentDefinition or AutomationDefinition identically.\n<Card title="Connector proposal preview" description="Nothing has been applied.">\n <Tabs defaultValue="proposed">\n <TabsList label="Definition version">\n <TabsTrigger value="current">Current</TabsTrigger>\n <TabsTrigger value="proposed">Proposed</TabsTrigger>\n </TabsList>\n <TabsContent value="current"><ConnectorDefinition value={current} /></TabsContent>\n <TabsContent value="proposed"><ConnectorDefinition value={proposed} /></TabsContent>\n </Tabs>\n <details><summary>Technical diff</summary><JsonDiff before={current} after={proposed} /></details>\n</Card>\n```\n\nUse `useHost().openRecord({ entity_id, entity_type? }, { mode: "peek" })` for a record\'s native peek. String source keys require the type. The promise reports the actual `{ mode: "peek" | "page" }`; a host without native peek opens the server-returned record URL. Errors remain errors. `useHost().theme` follows live theme changes; native components inherit the host palette and typography automatically. Use semantic host style variables and avoid hardcoded light/dark colors.\n\nRules that are load-bearing, not style:\n\n- Use structured reads: `useQuery(tool("manage_entity", { action: "list", entity_type: type, filters, limit: 100 }))`. The host admits entity `list/get/list_links` and entity-type schema `list/get` reads; tools marked read-only are also available. Use existing tool input/result contracts and preserve server authorization. Send structured arguments, never TypeScript inside a string. `sql` remains available; script-string queries are compatibility support for installed views. `query_sql` allows 500 rows max with a 5 second timeout \u2014 branch on the typed `errorCode` (e.g. `UPSTREAM_TIMEOUT`), never on message text, and render `truncated` honestly instead of passing partial data off as complete. Each `query_sql` cell is bounded too: strings keep their first 4,000 Unicode code points plus "\u2026 [truncated]"; JSON values over 16 KiB become `{ _truncated: true, bytes }` (attachments become null with `attachments_truncated`). `truncatedColumns` names the affected columns. Select smaller elements or fields, for example one array element per row with `jsonb_array_elements(...)`, and paginate as needed; each returned cell is still subject to these limits.\n- Never aggregate history in a view: no `GROUP BY`, `DISTINCT ON`, per-row regexp, or leading-wildcard `LIKE` over `events` or other growing tables. For "latest state" views, have an Automation maintain keyed event outputs (each run supersedes the previous event with the same key) and read the current head with `read_knowledge`.\n- `run_sdk` is not exposed to views. Writes go only through declared view actions (`useAction` \u2192 `invoke_view_action`). An action declares `emits` (append that event kind, which can activate workspace-triggered Automations), `updates: { entityType, fields }` (write those metadata fields on one record), or both, which commit in one transaction. An `updates` action takes `value: { entity_id, set: { field: value } }`; the view must attach to `entityType`, `set` may only name declared fields, and schema-stamped fields are refused. Pass `{ expected }` as the second argument with the values the view read: a stale read returns 409 `PRECONDITION_FAILED` and writes nothing. The write runs as the clicking user without claiming field ownership, so a human-owned field comes back as `pending_approval` instead of `applied`. Do not add an Automation that only copies an action\'s event onto the record; declare `updates` instead. Action `value` payloads are capped at 4000 JSON chars \u2014 save content first, then pass the id. A subject shown from a superseded event rejects with 409; refetch and ask the user to re-confirm rather than retrying blindly.\n\n ```tsx\n // actions: { markWon: { emits: "deal.won", updates: { entityType: "deal", fields: ["stage"] } } }\n const markWon = useAction("markWon");\n const sent = await markWon({ entity_id: deal.id, set: { stage: "won" } }, { expected: { stage: deal.metadata.stage } });\n // sent.result.applied: { entity_id, fields } with server stamps; sent.result.pending_approval when held\n ```\n- Link with `Link` from `@lobu/views/components` (or `useHost().openLink`): `href="<type>/<slug>"` opens that record in the workspace, supported links within the same workspace open in the peek pane, other app links navigate normally, and external URLs open a new tab. A plain `<a href>` goes nowhere inside the sandboxed frame.\n- For several offers, publish one event with a card for each held proposal. Obtain the real pending approval through the existing agent/Automation write method under its normal policy, then read its returned event ID to obtain the canonical review URL. Link each card to that exact review; the host opens it in peek. Each offer has its own run and decision. Use native Current/Proposed fields for updates and the proposed definition for creation. A resource snapshot alone is a preview, not an approval: never fabricate Approve/Reject buttons or imply that a missing resource ID creates anything. Existing settings `?run_id=` links remain compatible; new offers use the proposal review instead of the settings page.\n- Views run in a sandboxed frame with no direct network: no fetch, no third-party calls at runtime. Reuse local React components through relative imports and `source_files: { entrypoint, files }` plus `dependencies: {}` for local-only components with `views.set`, or use `viewFromFile` + `lobu apply`. Extra npm dependencies need the CLI-bundled `compiled_code`; listing `dependencies` alone does not install packages.\n- Never early-return the whole view on loading/error: each filter keystroke re-queries, so an early return unmounts the focused input mid-typing. Keep filters mounted and render query states inline in the results area.\n- Before calling a view verified, exercise the exact compiled artifact and host runtime in a sandboxed browser: representative data, loading, empty and error states, filters, sort/pagination, links/peek, declared actions, light/dark and narrow layouts. Fix failures and rerun. Registration compiles the module and requires an isolated browser check of the exact candidate against bounded empty/error/loading fixtures in light/dark themes and inline/fullscreen modes for every distinct attached scope (at most eight per module; each scope is its own bounded runner request). A failed check returns 422; an unavailable runner returns 503; both preserve the saved view. Fixture validation does not prove successful workspace data or every interaction. Distinguish compiled, browser-verified, stored and deployed; never claim more than the evidence.\n- Params sync to the URL on Lobu hosts only; elsewhere they stay frame-local. `refetch()` re-reads on demand; only Lobu hosts push live data-changed refreshes.\n\n## Connectors, Feeds, and Operations\n\nConnectors are the primary integration path for third-party services. The\nend-to-end model (entities vs events, the run lifecycle) is in\n`docs/CONCEPTS.md`; authoring a new connector when none matches is in\n`docs/connector-authoring.md`. Do not freeze a connector lifecycle in project\ninstructions because it can drift from the deployed SDK:\n\n1. Call `search_sdk` with the service name immediately before acting. It returns installed and installable connectors, declared feed keys, readiness, and the caller-aware live lifecycle. Then, before requesting app credentials, call `client.connections.setupOptions({ connector_key })` against the selected runtime: it discovers verified cloud-managed OAuth and hosted chat alongside local setup, so follow the URLs and instructions it returns. `cloud_status: "unavailable"` is a discovery outage, not evidence that managed auth is absent. Options are offers, not connected accounts.\n2. Always follow the methods it returns in order instead of relying on a remembered connect/feed/operation sequence. Repeat discovery after authorization or state changes so the next step reflects the live connector and current caller.\n3. Treat `access: operate` as `mcp:write` and `access: administer` as workspace owner/admin plus `mcp:admin`. If discovery asks for MCP reauthorization or an owner/admin handoff, follow that instruction; never attempt methods it withheld as unavailable.\n\nSource-backed feeds query the provider only through an explicit `client.feeds.readMany({ reads: [...] })` call; `search_memory` stays local and reports unqueried source feeds in `coverage`, while `client.feeds.get` returns metadata without source access. Feeds with `sync` may persist events for search and relational queries. For connector actions, use the live discovery result\'s operation target and readiness. If readiness is disconnected, follow the returned next action instead of guessing a connection. Surface approval-gated `pending_approval` as a waiting state, not a failure.\n\n## Data Ingestion\n\n- Use `lobu memory seed` for small declarative YAML datasets under `./data`; it processes records sequentially and is not a bulk-backfill path.\n- Use `client.knowledge.save` for schema-less semantic history such as messages, notes, observations, and content. Pass `supersedes_event_id` when replacing an existing fact.\n- Use `client.entities.create` / `client.entities.update` only for strict structured records that match declared entity schemas.\n- For large backfills, send bounded chunks through `run_sdk` / `lobu call run_sdk` and use `Promise.allSettled` so conflicts and partial failures remain visible.\n\n```ts\nexport default async (_ctx, client) => {\n const records = [\n { content: "...", semantic_type: "note" },\n { content: "...", semantic_type: "observation" },\n ];\n return Promise.allSettled(records.map((record) => client.knowledge.save(record)));\n};\n```\n';
169252
+ LOBU_SKILL_MARKDOWN = '---\nname: lobu\ndescription: "Set up new Lobu agents end to end and operate existing Lobu projects and memory: interview, scaffold, validate, authenticate, connect feeds, execute operations, and test Automations."\n---\n\n# Lobu\n\nUse this skill when setting up a brand-new Lobu agent from scratch (follow "Onboarding a New Project" below) or when running, validating, evaluating, or connecting an existing Lobu project, or operating Lobu memory from a coding agent.\n\nThe `AGENTS.md` generated into a new project is the source of truth for the config API (the `define*` helpers, connectors, auth, Automations, memory) \u2014 this skill does not duplicate it. For an existing project, jump to "Core Model" + the relevant reference section below.\n\n## Onboarding a New Project\n\nUse this playbook when a new user asks you to build them a Lobu agent from scratch. Set it up end to end: ground yourself in what the user already has, interview, discover, scaffold, prove the complete local path, then offer the deployment choice. Do not call the setup complete until every path the user selected has actually passed end to end. If an external provider, authorization, deployment, or rate limit blocks the proof, name the exact blocker and leave the setup as blocked rather than claiming success.\n\n### 1. Ground yourself in what the user already has\n\nBefore interviewing, look at what already exists so your questions and suggestions are personal rather than a blank slate. This is discovery, not a design decision \u2014 do not let it skip the interview.\n\n- Local: run `lobu context list` to see existing contexts (`--json` adds `loggedIn`, which reports stored credentials, not session validity); check the current directory and home for existing Lobu projects (`lobu.config.ts`), configured MCP servers, and CLI auth state. Note what the user already set up.\n- Cloud: if the user has an active session (do not create one just to look), call `client.organizations.list()`, `client.agents.list()` for each org, `client.catalog.listInstalled({ kinds: ["connectors"] })`, and `search_memory` for prior knowledge. This reveals existing agents, connectors, and memory you can build on.\n- Tell the user what you are looking at so they can correct you, and let what you find shape the options you offer. Never treat this discovery as an identity signal: orgs, emails, or domains never prove a company or product, and never mention a competitor or third party unless it actually appears in what you found.\n\nDo NOT ask for a login email during the interview. Email is only needed when a managed connector actually requires a session (step 3) or when the user chooses cloud deployment (step 6); ask for it at that point. Treat identity only as identity; never infer a company from an email address or domain.\n\n### 2. Interview with concrete, personalized options\n\nInterview the user one question at a time; wait for each answer, do not guess, and do not batch the questions. Anchor each question in what you found in step 1. Instead of asking "what agent do you want?" as a blank slate, summarize what you see and offer two or three concrete alternatives to choose from:\n\n- "You already have org X with connectors A and B installed and N existing agents. Do you want to (a) add a new agent on top of those, (b) extend one of the existing agents, or (c) start something standalone?"\n- "For what it should do, the common shapes are (a) a triage agent that reads incoming chat and files a ticket, (b) a scheduled report that summarizes new activity each morning, (c) a research agent that answers questions from your connected tools. Which fits, or what would you change?"\n\nOffer a default so the user can answer "the first one" \u2014 decisive users and undecided users both move faster with a concrete menu.\n\n- What company or product is this for?\n- What does it do, and who does it serve?\n- What is its public domain? (optional for a personal project)\n- Do I have permission to research the public website and other public sources?\n- What is the agent for?\n- What should we call it?\n- Who uses it: just me, my team, or each of my customers?\n- How should it behave, and what may it do unattended versus only with approval?\n- What should it remember? Model this as one to three entity types.\n- Where does its data come from? Pick one connector or custom source to start.\n- Where should people talk to it? Offer Web UI, API or SDK, MCP, Slack, Teams, WhatsApp, Discord, Google Chat, and Telegram without forcing a chat platform. If Slack is chosen, ask whether to join Lobu\'s hosted workspace for a quick start, install Lobu into an existing workspace, or use a custom Slack app; then ask whether to test the DM with Lobu, a named channel, or both, and whether people knowledge means conversation participants, bound-channel members, or the full workspace directory.\n- Should anything run on a schedule?\n- Which supported LLM provider credential does the user have?\n\nIf the user gave permission to research and has a public domain, research the company before proposing the design. Summarize its product, customers, workflows, and useful signals, and cite the public sources you used. Then propose one to three entity types, their relationships, the first data source, one or two useful Automations, and suitable interaction channels. Play back a short numbered plan and wait for confirmation before scaffolding anything.\n\n### 3. Discover the surface before choosing how to scaffold\n\nCheck Node is 26.x, then run `lobu context list` and identify the named Lobu Cloud context; do not assume the active context still points to cloud after a local run. If a managed or cloud connector was chosen and there is no session, ask for the login email at that point, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`. The person approving must sign in with that same email; knowing an address never grants access. After a successful login, an empty organization membership list is a tenancy/discovery result, not an authentication failure: call `client.organizations.list()` and explain the result. Never revoke or repeat login with `--force` unless the user separately approves that re-authentication.\n\nUse ClientSDK through Lobu MCP with the explicit cloud context. From the CLI, account discovery works before selecting an active org with `lobu memory run query_sdk \'{"title":"Find managed connection providers","script":"export default async (_ctx, client) => client.organizations.list()"}\'`; `lobu call` over REST requires an active org. Call `client.organizations.list()` to find public organizations offering managed connections. Call `client.catalog.listInstalled({ kinds: ["connectors"] })`; if the connector is not installed, call `client.catalog.listCatalog({ kinds: ["connectors"] })`. Inspect the selected entry\'s `detail.auth_schema`, `detail.options_schema`, `detail.feeds_schema`, and `detail.automation_events` instead of guessing field names. On account-scoped `/mcp`, select an authorized home workspace first with `const home = await client.org(homeSlug)` and call `home.connections.connectManaged`; put the public provider org in `managed_by_org`, rather than selecting that provider org with `client.org`. This call runs against cloud, not the embedded runtime. If a matching live managed offer exists, explain it and call `client.connections.connectManaged` only after consent. Complete the returned user authorization, then run `lobu context use <cloud-name>` immediately before executing its `local_bootstrap_command` from the parent directory where the new project should be created; use `--here` only after entering an empty directory, and do not create a blank Lobu scaffold first. Ask for bring-your-own OAuth credentials only if no managed offer exists or the user prefers their own app.\n\n**If no connector in the catalog matches the data source, do not report "no integration exists"** \u2014 author a custom connector: write `connectors/<name>.connector.ts` in the project, register it with `connectorFromFile("./connectors/<name>.connector.ts")`, and model it on the [npm downloads example](https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/npm-downloads.connector.ts). See [Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md) for the full contract; the end-to-end entity/event/Automation model is in [Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md).\n\n### 4. Scaffold and build from the confirmed plan\n\nIf managed auth supplied a `local_bootstrap_command`, use the project it generated. Otherwise run `npx @lobu/cli@latest init` with the confirmed name and provider. Postgres is built in, so `lobu run` starts an embedded database; ask for `DATABASE_URL` only if the user chooses external Postgres. Read the generated `AGENTS.md` completely before editing `lobu.config.ts`. Use the canonical reference at `https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/lobu.config.ts` when needed; do not assume that example exists in the new project\'s filesystem. Briefly explain how the chosen feed may use checkpoints to collect incrementally, emits events, builds shared entity memory, and gives both chat and Automations the same governed context.\n\n`feeds_schema.<feed>.eventKinds` are the default Automation trigger catalog for feed connectors: every declared kind is a subscribable event type (`event_type` = the kind slug) for any feed that emits the kind. A feed\'s first successful non-dry sync establishes its baseline without activation; later inserts of a matching kind activate subscribers. A kind with `updatedEvent: true` also offers `<kind>.updated` for supersedes whose `occurred_at` strictly advances past the previous head. The original kind stays insert-only; unchanged rows, volatile-only updates and same-time reformats stay quiet. Subscribe to both types for new items and later activity. Feed-scoped filtering is not yet available (events dedupe by connection + origin id, so a `feed_key` match would miss origins first seen by another feed). `automation_events` (now derived from eventKinds when a connector declares none) is the trigger picker\'s list. If no declared kind matches the use case, use a scheduled Automation with a bounded named SQL source and read event text from `payload_text`. Validate the query against the running local schema before relying on it. If `feeds_schema` is empty, do not invent or trigger a feed; chat integrations such as Slack can deliver incoming messages directly. For Slack or Telegram, prefer `defineConnection` with `credentialMode: "hosted"` so no bot token is required; `lobu run` prints the exact hosted-workspace join URL, own-workspace install URL when available, and short-lived link command. This hosted chat path requires a cloud session and the agent applied to that cloud workspace; the link targets the cloud agent. It does not create a local Slack data connection or prove local Slack search. Use those returned values instead of constructing URLs. A printed `/lobu link <code>` is one-time: redeem it in the first selected DM or channel. In an installed workspace whose installer is linked to Lobu, bind each additional surface with `/lobu link <agent-id>`; otherwise generate a fresh code for that surface. Mention Lobu in a channel test and verify the App Home separately. Lobu email login and Slack installation are separate: the email link authorizes Lobu CLI access, while an existing-workspace install requires the user or workspace admin to approve Slack\'s OAuth screen. Never describe Slack consent as an email approval. Use `credentialMode: "byo"` only if the user chooses their own app. Tell the user once which remaining secrets are required and add only `secret("ENV_NAME")` placeholders to config. Never open or request permission to read `.env`; inspect `.env.example` when present and declared secret placeholder names only. Never read, print, invent, or paste a real secret into source or chat.\n\nIf the user wants the agent to know people in Slack, ask whether that means conversation participants, members of bound channels, or the full workspace directory. Installing the app proves none of those by itself. Verify the selected scope by inspecting the people or member entities Lobu actually materialized and by asking the agent a roster question. If human-readable names or non-participants are unavailable, identify that exact product gap; never claim the complete workspace directory was synced.\n\n### 5. Prove the complete local path\n\nChange into the generated project directory and verify `pwd` contains the intended `lobu.config.ts`; never run project commands from its parent. Run `npx @lobu/cli@latest validate`, boot with `npx @lobu/cli@latest run`, and verify health and the local Web UI. With the embedded database default, `lobu run` creates and selects the local context and auto-applies the project; with an external `DATABASE_URL`, it does neither, so authenticate and apply to that runtime explicitly. Send a harmless direct chat message without tools.\n\nBefore consent to access provider data, inspect only catalog, connection, auth-profile, and feed metadata. For browser access, inspect the paired device and connection metadata without invoking browser actions. Durable managed OAuth and env-profile credentials stay at the gateway. Do not run a feed or connector dry-run before consent, because a dry-run may still read provider data. Ask explicitly before accessing real provider data. Only after approval, dry-run the connector or feed server-side and trigger the selected feed manually if that connector actually declares one. A feed dry-run records its run but persists no collected events, entities, attachments, checkpoint changes, or feed sync state. Run each Automation once, poll `client.operations.getRun` with its returned `run_id`, and show each completed run plus any declared result event or entity. For a run-result-only or reaction-only Automation, use the completed run and the Automation `view_url` returned by Lobu. For Slack, treat DM, channel mention, App Home, and requested member discovery as four separate checks. Keep actions in approval mode unless the user explicitly approves execution. If any step fails, fix it and rerun that step; do not silently substitute a different path.\n\n### 6. Offer the deployment choice\n\nAfter the local proof, ask the user whether to keep running locally or deploy to Lobu Cloud. Explain that the embedded local runtime and Lobu Cloud are separate targets, and that keeping it local needs no further setup. Only if the user chooses cloud deployment, ask for the login email to identify the deployer, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`; the person approving must sign in with that same email. Because `lobu apply` has no context flag, use `lobu context list` and then `lobu context use <cloud-name>` to select an explicit cloud context before deployment. Run `lobu apply --dry-run` first, show the target organization and exact plan, and wait for confirmation before applying. After apply, use only authoritative `view_url` values and link commands returned by Lobu; never construct URLs. Present the working access choices: Web UI, direct agent chat, API or SDK, MCP, and any channels the user selected.\n\n## Core Model\n\n- **Lobu** is the agent framework, runtime, deployment layer, and memory surface.\n- Keep framework configuration in `lobu.config.ts` (TypeScript, `defineConfig` from `@lobu/cli/config`).\n- Keep agent identity and instructions in `IDENTITY.md`, `SOUL.md`, and `USER.md`.\n- Keep reusable capability bundles in `skills/<name>/SKILL.md` or `agents/<agent>/skills/<name>/SKILL.md`.\n- Use `lobu login` for CLI authentication. Do not use a separate memory login command.\n- Use `lobu connect` for MCP client and skill setup.\n- Use `lobu memory ...` for memory operations, seeding, and direct tool calls.\n\nReference the canonical docs before guessing how a feature works:\n[Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md)\n(entities vs events, identity, end-to-end lifecycle),\n[Automations](https://github.com/lobu-ai/lobu/blob/main/docs/AUTOMATIONS.md)\n(trigger/source/output contract), and\n[Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md)\n(custom connectors).\n\n## Project Checklist\n\n1. Read `lobu.config.ts` first.\n2. Read the active agent files under `agents/<id>/`.\n3. Check local skills under `skills/` and `agents/<id>/skills/`.\n4. Use `lobu validate` after config changes.\n5. Discover the live SDK and connector surface with `search_sdk`; never guess a method, connector key, feed key, connection id, or operation key.\n6. When prompt or Automation changes, run evals via promptfoo (see `examples/personal-finance/evals/promptfooconfig.yaml`). The in-house `lobu eval` command has been removed.\n\n## Common Commands\n\n```bash\nnpx @lobu/cli@latest init my-agent\nnpx @lobu/cli@latest run\nnpx @lobu/cli@latest validate\nnpx @lobu/cli@latest login\n```\n\n## Authentication\n\n- Interactive (human at a terminal): `lobu login` runs the device-code flow with a browser approval.\n- CI / your own automation: `LOBU_API_TOKEN`, or `lobu login --token <pat>`.\n- Local `lobu run`: the CLI mints credentials automatically over loopback \u2014 no prompt.\n- Headless, on a *user\'s* behalf: `lobu login --email <address>`. The server emails the user a one-click approval link and the CLI polls until they approve, then stores the scoped credential \u2014 no TTY, no pre-minted token. This is the auth.md "user_claimed" flow.\n\nAn external agent not using this CLI can drive the same flow over HTTP: read `<origin>/auth.md` (linked from the `agent_auth` block in `<origin>/.well-known/oauth-authorization-server`) for the endpoints. Today only the email user_claimed flow exists (no zero-touch ID-JAG). Never fabricate a token.\n\n## Organization Deletion\n\nTreat organization deletion as permanent and restricted to organization owners. The supported path is the **Organization settings** page, opened from that workspace\'s settings button in the organization switcher. ClientSDK and Lobu CLI intentionally expose no organization-delete method. When asked to delete organizations, identify each exact target and its data impact read-only, surface one production organization at a time for explicit confirmation, then direct an owner to that page or use their logged-in browser only when explicitly authorized. Never invent a hosted URL, call the raw Better Auth route, bypass a failed authorization check, delete organization rows directly, or batch confirmations.\n\nCloud CLI OAuth/PAT credentials are not a Better Auth browser session. A `401` or `403` is a stop signal: report the authorization boundary and leave the organization intact.\n\n<!-- lobu-memory-guidance:start -->\n## Memory Defaults\n\nYour long-term memory is powered by Lobu. Do NOT use local files (memory/, MEMORY.md) for memory.\n- Lobu automatically recalls relevant memories when you receive a message.\n- To save something, call save_memory with the content and an appropriate semantic_type.\n- To search, call search_memory. Results include view_url links to the web interface.\n- NEVER construct Lobu URLs yourself. When the user asks for a link, call search_memory to get the correct view_url.\n- When the user says "remember this", save it to Lobu immediately.\n- When a message changes a fact you already stored (an updated preference, status, count, location, or plan), first search_memory for the prior memory to get its id, then save_memory the new value with supersedes_event_id set to that id. This replaces the stale value so future recalls return the current one; the old value stays in history but is hidden from normal search.\n<!-- lobu-memory-guidance:end -->\n\n## Lobu Memory\n\nConfigure project-scoped memory in `lobu.config.ts` by setting the org on `defineConfig` and declaring the schema with the `define*` helpers:\n\n```ts\nimport { defineConfig, defineEntityType } from "@lobu/cli/config";\n\nconst ticket = defineEntityType({\n key: "ticket",\n name: "Ticket",\n properties: {\n subject: {\n type: "string",\n title: "Subject",\n "x-table-label": "Subject",\n "x-table-column": true,\n },\n },\n});\n\nexport default defineConfig({\n org: "my-org",\n orgName: "My workspace",\n agents: [/* ... */],\n entities: [ticket],\n});\n```\n\nThe entity schema also renders the record page form. Give every array `items` and every object `properties` (bare ones render as raw JSON), put the label in `title` and help text in `description`, mark derived fields `readOnly: true`, and declare every field an Automation writes.\n\nFor a "when did this field last change" timestamp, declare root `metadata_schema["x-lobu-stamps"]: { "stage_at": "stage" }` instead of writing it from an Automation. The stamp field must be a declared `{ type: "string", format: "date-time" }` property (not listed in `required`) and the tracked field a declared property. Every writer (agent, SDK, Automation, connector projection, view action, approval) then gets it for free: the server sets `stage_at` when a record is created with `stage` set or when `stage` changes value, and discards any value a caller sends for `stage_at`. `readOnly` alone is presentation only; it is not enforced.\n\nSeed data records still live as YAML under `./data`. Then seed or operate the memory workspace with:\n\n```bash\nlobu login\nlobu memory org set <org-slug>\nlobu memory health --org <org-slug>\nlobu memory seed --org <org-slug>\nlobu memory run search_memory \'{"query":"Acme"}\' --org <org-slug>\n```\n\nUse `search_memory` first when the user asks about a specific entity or workspace memory. Use `save_memory` to persist durable memory. To update existing knowledge, search first, then save with `supersedes_event_id` so the old row is tombstoned rather than deleted.\n\n### Answering questions about a record\n\nRecent events can contain only counters or timestamp updates; a relevant linked record may hold the investigation, decision, or outcome. Use the existing read APIs to gather that context:\n\n1. Start with `search_memory` to resolve the record and its workspace. Discover the current signatures with `search_sdk`, then use `query_sdk` with the selected workspace\'s `entities.get` and `knowledge.read`. Event `entity_ids` identify records the event concerns; co-occurrence does not assert a relationship.\n2. When relationships could answer the question, call `entities.listLinks` on the resolved record or relevant event-linked records. Use relationship type and direction to select context relevant to the question, rather than expanding every event. Keep expansion to one hop and fetch at most five distinct related records in total with `entities.get`. Bound link pages too: start with `limit: 20` and inspect at most two pages total; use the returned offset/page metadata for stored records and `next_cursor` for source-backed records. Deduplicate records by workspace, type, and ID/key. If the budget ends while more results remain, say the context is partial.\n3. For stored event evidence in current-state questions, use live heads (`is_superseded: false`), not the first row of an exact-ID read: `content_ids` can return the supersede history before its current head. If no live head is returned, follow the returned pagination for at most two pages total, then report current evidence unavailable if it is still missing. Keep historical versions when the question asks what happened at an earlier time. An event ID identifies a stored version; a source item\'s stable identity is its connection/source plus `origin_id`.\n4. Preserve the meaning and direction of each relationship. Skip `acl_managed` links for ordinary business context unless the question concerns permissions. An identity association or a shared email address does not by itself verify the same human; a shared support mailbox can represent several people. Neither proves employment or collaboration. Fetch supporting evidence when that distinction matters, and distinguish a stored assertion from a verified source fact.\n5. Cite returned record/event URLs or source links for the answer. Treat `relationship_failures`, `record_failures`, unreadable linked records, and unfinished pages as coverage limits, not proof that no relationship or evidence exists. Respect the selected workspace and caller\'s access; do not switch workspaces or fall back to raw SQL to bypass a denied read. Manual claims and connector configuration ownership are not automatically supporting event evidence.\n\nFor example, when asked what happened with an issue, follow an explicitly returned investigation/task relationship and read that record\'s conclusion as well as the issue\'s recent activity. Report a stored task\'s conclusion as recorded context; it does not independently prove that a repair is currently deployed. This workflow reads context only; it does not create links or merge records.\n\n## MCP Client Setup\n\nUse the actual MCP URL for the user\'s runtime. Never hardcode a hosted URL unless the user explicitly asks for that instance.\n\nCommon setup commands:\n\n```bash\n# Claude Code\nlobu connect claude-code --url <mcp-url>\n\n# Codex\nlobu connect codex --url <mcp-url>\n\n# Antigravity\nlobu connect antigravity --url <mcp-url>\n\n# OpenCode\nlobu connect opencode --url <mcp-url>\n```\n\nRun `lobu connect --url <mcp-url>` without a client id to choose interactively. For ChatGPT, Claude Desktop, Cursor, and other browser-managed clients, the same command applies the safe local configuration it can and prints the exact remaining client handoff. Complete OAuth in the client, not through a separate Lobu CLI login.\n\n## Browser-Authenticated Connectors\n\nFor connectors that need a signed-in browser, pair the Owletto Chrome extension\nand sign in on the source site in that browser. Browser operations run through\nthat paired device; external remote-debugging endpoints and CLI browser-auth\ncapture are no longer supported.\n\nNothing answers a JS dialog (alert, confirm, prompt, beforeunload) on the\nagent\'s behalf. A browser action it blocks fails, and the failed result\'s\n`output` carries `tab_id` and `dialog` (`dialog_id`, `type`, `message`). In\n`run_sdk`, catch the `operations.execute` error and read `error.details.output`\nrather than parsing the error text (an uncaught failure returns the same value\nas the `run_sdk` result\'s `error.details`, and a background run\'s\n`operations.getRun` returns the same `output`), then answer with the\nconnection\'s `handle_dialog` operation. An unanswered dialog is handed to the user after two minutes.\n\nTo test a configured feed without writing ingested data, discover the current\nfeed methods with `search_sdk`, then use `client.feeds.trigger({ feed_id, dry_run: true })`\nthrough `run_sdk` or `lobu call run_sdk` (with a `title` arg). Inspect `client.feeds.get({ feed_id })`\nfor the completed run\'s preview. The dry run uses normal device routing and\nauthorization checks and may access the upstream provider, so obtain consent first.\n\n## Agent-Facing Tool Surface\n\nThe normal MCP surface is intentionally small. Flat administrative tools are not advertised to agents; compose through these tools instead:\n\n- `search_memory` and `save_memory` for direct knowledge recall and persistence.\n- `search_sdk` to discover current ClientSDK methods, signatures, connector feed keys, operations, access requirements, and examples. Pass `mode: "read"` when you only need methods safe for `query_sdk`.\n- `query_sdk` for read-only TypeScript and `query_sql` for governed, paginated SQL reads.\n- `run_sdk` for mutations and external operations. Use `lobu call run_sdk --arg title=\'\u2026\' --arg script=\'\u2026\'` from the CLI for the same ClientSDK scripting workflow; `run_sdk`, `query_sdk`, and `query_sql` calls need a short `title` naming them in the activity feed.\n\nSearch before create to avoid duplicates. Prefer a read or dry run before mutations, never fabricate returned URLs or identifiers, and never delete from `events`; supersede or tombstone instead.\n\n## Custom Views\n\nBefore authoring UI, inspect available native entity/event pages, existing views (`client.views.list()` and `client.views.get({ key })`), and the project\'s shared components and overrides. Honor explicit user designs and reuse UI from the top down:\n\n1. Use the largest existing surface or component that meets the task. Configure its segment, filters, search, saved preset and layout before replacing its UI.\n2. If that surface cannot meet a concrete requirement, compose its exported parts, such as an individual table, board, graph or shared collection controls when available. Preserve shared selection and action handling instead of rebuilding that logic.\n3. If those parts still do not fit, use smaller shared primitives and write custom UI only for the remaining gap. Explain the unmet requirement that forced each step down.\n\nCheck the current exports and target host before choosing an import; native renderer registrations do not imply React exports. Surface a missing export as a platform gap rather than inventing an API or silently copying the native implementation. `@lobu/views/components` currently supplies theme-aware defaults such as `Card`, `DataTable`, filters, charts, links and query-state components. `LoadingState` draws skeleton lines in the host\'s style; `Skeleton` is a pulsing block to size like the content it stands for (a figure, a row, a chart), so a slow read keeps the page\'s shape instead of showing text. When exploration needs specialized linked charts, drilldowns, scenario controls or Canvas/SVG, compose a React view from the suitable existing components.\n\nNative JSON templates use the target renderer\'s registered component names and overrides; inspect what that host actually supplies. React views compose imported components in their own bundle, independently of that native renderer map.\n\nViews are custom React panels attached to entity types, records, events, or the workspace Data hub. They render in the web app and MCP hosts (Claude and other MCP Apps hosts); chat channels get links to views, not the views themselves. Author them in `views/<type>/<key>.tsx` and ship with `lobu apply` (list them via `viewFromFile` in `defineConfig`), or set sources over MCP with `client.views.set` (owner/admin only).\n\nModule shape (the server resolves React, React DOM, `@lobu/views` and `@lobu/views/components`; other dependencies need the CLI path with `node_modules` present):\n\n```tsx\nimport { defineView, tool, useAction, useParams, useQuery } from "@lobu/views";\nimport {\n Card,\n DataTable,\n EmptyState,\n ErrorState,\n FilterBar,\n LoadingState,\n SearchField,\n TruncatedNotice,\n} from "@lobu/views/components";\n\nexport const view = defineView({\n key: "pipeline",\n attach: [{ collection: "deal" }],\n params: { stage: { type: "string", default: "open" } },\n actions: { markWon: { emits: "deal.won" } },\n});\n\nexport default function Pipeline() {\n const [params, setParams] = useParams();\n const deals = useQuery(tool("manage_entity", { action: "list", entity_type: "deal", filters: [{ field: "stage", op: "eq", value: String(params.stage) }], limit: 100 }));\n const markWon = useAction("markWon");\n const rows = deals.data?.entities ?? [];\n // Keep the filter mounted across query states: an early return on\n // loading/error would unmount the focused input on every keystroke\n // (each keystroke re-queries). Render states inline instead.\n return (\n <Card\n title="Pipeline"\n actions={<button type="button" onClick={() => markWon({})}>Mark won</button>}\n >\n <FilterBar><SearchField label="Stage" value={String(params.stage)} onChange={(v) => setParams({ stage: v })} /></FilterBar>\n {deals.loading && <LoadingState text="Loading deals\u2026" />}\n {deals.error && <ErrorState message={deals.error} errorCode={deals.errorCode} />}\n {!deals.loading && !deals.error && rows.length === 0 && (\n <EmptyState title="No deals in this stage." />\n )}\n {!deals.loading && !deals.error && rows.length > 0 && (\n <DataTable columns={[{ key: "name", header: "Name" }]} rows={rows} keyOf={(r) => r.id ?? r.slug} />\n )}\n {deals.truncated && <TruncatedNotice shown={rows.length} />}\n </Card>\n );\n}\n```\n\n`defineView` is the view\'s only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params`, `actions` and `resources` are read from it, never passed separately. `views.set` always requires `source_code` containing the entrypoint module, including when retaining multiple files. Write `defineView` out as a literal (no variables, spreads or `${}` templates): the server reads it without running the module.\n\nA view makes no network requests of its own; data comes through `useQuery`. The one exception is images: `resources: ["https://tile.openstreetmap.org"]` declares origins the view may load images (map tiles, logos) from. Each entry is a bare `https://` origin with a public hostname (no path, wildcard, localhost or IP), at most 8. The images-only limit is a save-time check: `views.set` renders the view\'s empty, error and loading states in an offline browser and refuses the save if anything other than an image from a declared origin is requested. It is not enforced at runtime. MCP hosts receive the origins as the MCP Apps `resourceDomains` CSP, which allows scripts, styles, fonts and media from them as well as images, and the Lobu web app applies no runtime CSP to views. Declare only image or tile CDN origins you trust. Hosts that render through the generic `ui://lobu/views` loader use its CSP, which declares no image origins, so declared images may not load there.\n\nFor a multi-file view, `files` maps relative paths to complete source strings and `entrypoint` names the view module. Include all three inputs below; `source_code` must exactly equal `files[entrypoint]`:\n\n```ts\nawait client.views.set({\n source_code: files[entrypoint],\n source_files: { entrypoint, files },\n dependencies: {}, // Local files and the host-provided runtime need no extra packages.\n});\n```\n\n`attach` lists the pages a view appears on, one per entry: `{ record: "deal" }` is a card on every deal\'s page above its activity (`{ record: "deal", id: 7 }` pins one record), `{ collection: "deal", when? }` a tab on the deal list page, `{ workspace: true }` a Data hub tab, `{ event: "deal.won", type? }` one event\'s page. One view can list several pages and branch on `useScope()` when it answers the same question at each scale. A record card renders with `useHost().displayMode === "inline"` inside `container.maxHeight` (the host clips past it): render a summary there with a "See all" that calls `requestDisplayMode("fullscreen")`, and the full view when `displayMode` is `"fullscreen"` (the peek, a full page, a tab).\n\nWorkspace attachment does not render individual events. For an event presentation, attach to its specific `semantic_type` (event kind), optionally restricted to a linked entity type with `type`; a metadata schema name does not select the view. Avoid binding a specialized renderer to a generic kind such as `summary`. Register a dedicated kind in the workspace\'s event-kind registry and have its producer emit it. On event pages and event peeks, read `useScope().event` by exact ID and select that ID from the returned lineage; never substitute the latest event or let a URL date param change the subject. A shared workspace/event module should branch on `scope.event`, keeping history selection on its workspace surface. Preserve a readable stored body for fallback and evidence.\n\nBefore reporting a view working, open each attached surface, including an event page and peek when declared. Exercise filtering, drilldown, keyboard navigation, and a narrow pane; check loading, missing/error, and truncated data states. Refresh and reopen an earlier event of the kind to verify the view stays on that event rather than jumping to the newest one. Views render in an iframe, so an empty parent-page DOM is not evidence the view is empty; inspect the frame through an authorized browser or accessibility surface. A successful compile proves only that the bundle was built.\n\nImport reusable UI from **`@lobu/views/components`**. Discover this kit with `search_sdk({ query: "@lobu/views/components" })` or a component name. Start with the largest suitable native surface; compose smaller parts only for needs it does not cover:\n\n| Need | Component and minimum input |\n| --- | --- |\n| Complete entity list | `EntityListPage title={title} table={tableProps}` |\n| SQL, computed TypeScript or local rows | `EntityListPage title={title}` with `DataTable columns={columns} rows={rows} keyOf={keyOf}` as children |\n| Complete record body | `EntityRecordPage entity={entity} owner={workspace} schema={schema}` |\n| Entity table or individual fields | `EntityTableView`, `RecordSpecSheet`, `SchemaValue`, `EntityAvatar` |\n| Workspace schema, proposed schema or schema diff | `SchemaGraph`, `SchemaGraph schema={spec}`, `SchemaGraph schema={spec} base="workspace"`, or `SchemaGraph schema={after} base={before}` |\n| Saved resource identity and navigation | `AutomationReference`, `AgentReference`, `ConnectorReference` |\n| Automation instructions, sources, triggers, outputs and code | `AutomationDefinition value={definition}` |\n| Agent identity, models and settings | `AgentDefinition value={definition}` |\n| Connector actions, feeds, schemas and source | `ConnectorDefinition value={definition}` |\n| Current / Proposed comparison | Existing `Tabs` with the same definition component in each panel |\n| Optional technical details | `JsonDiff before={current} after={proposed}` inside collapsed `<details>` |\n\nThe host supplies native JS/CSS, React and live theme. Do not copy product markup or bundle a second React. Exported prop types describe the shared contracts. Use `Button`, `Badge`, `Card`, chart and state components for surrounding UI.\n\n**Page bodies are controlled.** Supply data and slots; they fetch nothing and authorize no writes. `EntityListPage` accepts `title`, optional `actions`/`controls`, and either `table: EntityTableViewProps` or `children`. Its `loading`, `error`, `onRetry` and `empty` affect only results, keeping controls mounted. Native table props include rows, schema, linked lookups, sorting and pagination; honor `metadata.has_more`. For SQL/TypeScript rows use `DataTable`, without inventing entity IDs or types. `EntityRecordPage` renders the native title/avatar and schema fields; `actions`, `details`, `summary`, and `children` supply editing, links, activity and tabs. Default `layout="record"` adapts to width; `layout="content"` retains the header while children own the layout. A `null` title/details/summary hides that slot. Preserve zero and false.\n\n**SchemaGraph is read-only.** It reuses the native schema canvas. Omit props for the mounted workspace schema, pass `schema` for a supplied snapshot, add `base="workspace"` to compare a proposal with the live workspace, or pass another spec as `base`. A spec is `{ entityTypes: [{ slug, name?, description?, metadata_schema?, event_kinds? }], relationshipTypes: [{ slug, name?, metadata_schema?, rules: [{ source_entity_type_slug, target_entity_type_slug }] }] }`. Specs are full snapshots: an omitted type is removed in a diff. Added, removed and changed types/rules remain visible; inspect type details for metadata fields, event kinds and rule changes. Existing entity types open their native pages; unsaved types show details in place. Live reads use the visiting user\u2019s session and permissions through the existing broker; supplied snapshots still render when workspace reads are unavailable. No edits or schema writes are performed. The leaf names match `entitySchema`: list responses use `entity_types` / `relationship_types`; attach `listRules` results to the matching relationship by ID. To apply a reviewed spec, use existing `createType` / `createRelType` (both require `name`) and `addRule({ slug, ...rule })` separately. The graph\u2019s optional name falls back to slug for display only. Hosts without native components throw the standard unavailable-native error.\n\n**References resolve saved identity.** Pass `mode="live"`, mounted `workspace`, optional `appearance="inline" | "row"` (default row), and `automationId` (positive decimal string), `agentId`, or `connectorKey` plus optional numeric `connectionId`. Discover IDs first. These reuse product rows and visiting-user permission checks; they accept no authored name/status or mutation callbacks. Invalid selectors, another workspace, missing records and refused reads show unavailable. A connector definition does not imply a connected account. Reads refresh on mount, focus, reconnect and host invalidation, without interval polling.\n\n**Definitions render supplied objects.** All three have the same signature: `{ value: Record<string, unknown> }`. Pass the existing saved definition or complete proposed snapshot, not a patch. Automation fields include `name`, `description`, `prompt`, `sources`, `triggers`, `outputs`, `reaction_script`; Agent fields include `name`, `description`, `identity_md`, `settings`; Connector fields include `name`, `description`, `version`, `actions_schema`, `feeds_schema`, `source_code`. Remaining nested settings stay inspectable. Missing fields differ from empty values. Bodies fetch nothing, execute no supplied code, and add no save/approval controls. Label authored objects as Snapshot or Proposal preview; use a reference for live identity. Never supply credentials.\n\nShow changes as **Current / Proposed**, defaulting to Proposed, with the same native body on both sides. Keep JSON diff optional. Rendering does not save or apply anything and needs no new proposal endpoint. For an existing approval, render its held current/proposed snapshots; do not merge in newer live values. Writes remain on existing declared `useAction` paths or native authorized editor/review pages. An authored preview must not imply a held approval or authority to apply it.\n\n```tsx\nimport {\n Card, ConnectorDefinition, JsonDiff,\n Tabs, TabsList, TabsTrigger, TabsContent,\n} from "@lobu/views/components";\n\n// current and proposed are complete definition objects from authorized reads\n// and the requested edit. Use AgentDefinition or AutomationDefinition identically.\n<Card title="Connector proposal preview" description="Nothing has been applied.">\n <Tabs defaultValue="proposed">\n <TabsList label="Definition version">\n <TabsTrigger value="current">Current</TabsTrigger>\n <TabsTrigger value="proposed">Proposed</TabsTrigger>\n </TabsList>\n <TabsContent value="current"><ConnectorDefinition value={current} /></TabsContent>\n <TabsContent value="proposed"><ConnectorDefinition value={proposed} /></TabsContent>\n </Tabs>\n <details><summary>Technical diff</summary><JsonDiff before={current} after={proposed} /></details>\n</Card>\n```\n\nUse `useHost().openRecord({ entity_id, entity_type? }, { mode: "peek" })` for a record\'s native peek. String source keys require the type. The promise reports the actual `{ mode: "peek" | "page" }`; a host without native peek opens the server-returned record URL. Errors remain errors. `useHost().theme` follows live theme changes; native components inherit the host palette and typography automatically. Use semantic host style variables and avoid hardcoded light/dark colors.\n\nRules that are load-bearing, not style:\n\n- Use structured reads: `useQuery(tool("manage_entity", { action: "list", entity_type: type, filters, limit: 100 }))`. The host admits entity `list/get/list_links` and entity-type schema `list/get` reads; tools marked read-only are also available. Use existing tool input/result contracts and preserve server authorization. Send structured arguments, never TypeScript inside a string. `sql` remains available; script-string queries are compatibility support for installed views. `query_sql` allows 500 rows max with a 5 second timeout \u2014 branch on the typed `errorCode` (e.g. `UPSTREAM_TIMEOUT`), never on message text, and render `truncated` honestly instead of passing partial data off as complete. Each `query_sql` cell is bounded too: strings keep their first 4,000 Unicode code points plus "\u2026 [truncated]"; JSON values over 16 KiB become `{ _truncated: true, bytes }` (attachments become null with `attachments_truncated`). `truncatedColumns` names the affected columns. Select smaller elements or fields, for example one array element per row with `jsonb_array_elements(...)`, and paginate as needed; each returned cell is still subject to these limits.\n- Never aggregate history in a view: no `GROUP BY`, `DISTINCT ON`, per-row regexp, or leading-wildcard `LIKE` over `events` or other growing tables. For "latest state" views, have an Automation maintain keyed event outputs (each run supersedes the previous event with the same key) and read the current head with `read_knowledge`.\n- `run_sdk` is not exposed to views. Writes go only through declared view actions (`useAction` \u2192 `invoke_view_action`). An action declares `emits` (append that event kind, which can activate workspace-triggered Automations), `updates: { entityType, fields }` (write those metadata fields on one record), or both, which commit in one transaction. An `updates` action takes `value: { entity_id, set: { field: value } }`; the view must attach to `entityType`, `set` may only name declared fields, and schema-stamped fields are refused. Pass `{ expected }` as the second argument with the values the view read: a stale read returns 409 `PRECONDITION_FAILED` and writes nothing. The write runs as the clicking user without claiming field ownership, so a human-owned field comes back as `pending_approval` instead of `applied`. Do not add an Automation that only copies an action\'s event onto the record; declare `updates` instead. Action `value` payloads are capped at 4000 JSON chars \u2014 save content first, then pass the id. A subject shown from a superseded event rejects with 409; refetch and ask the user to re-confirm rather than retrying blindly.\n\n ```tsx\n // actions: { markWon: { emits: "deal.won", updates: { entityType: "deal", fields: ["stage"] } } }\n const markWon = useAction("markWon");\n const sent = await markWon({ entity_id: deal.id, set: { stage: "won" } }, { expected: { stage: deal.metadata.stage } });\n // sent.result.applied: { entity_id, fields } with server stamps; sent.result.pending_approval when held\n ```\n- Link with `Link` from `@lobu/views/components` (or `useHost().openLink`): `href="<type>/<slug>"` opens that record in the workspace, supported links within the same workspace open in the peek pane, other app links navigate normally, and external URLs open a new tab. A plain `<a href>` goes nowhere inside the sandboxed frame.\n- For several offers, publish one event with a card for each held proposal. Obtain the real pending approval through the existing agent/Automation write method under its normal policy, then read its returned event ID to obtain the canonical review URL. Link each card to that exact review; the host opens it in peek. Each offer has its own run and decision. Use native Current/Proposed fields for updates and the proposed definition for creation. A resource snapshot alone is a preview, not an approval: never fabricate Approve/Reject buttons or imply that a missing resource ID creates anything. Existing settings `?run_id=` links remain compatible; new offers use the proposal review instead of the settings page.\n- Views run in a sandboxed frame with no direct network: no fetch, no third-party calls at runtime. Reuse local React components through relative imports and `source_files: { entrypoint, files }` plus `dependencies: {}` for local-only components with `views.set`, or use `viewFromFile` + `lobu apply`. Extra npm dependencies need the CLI-bundled `compiled_code`; listing `dependencies` alone does not install packages.\n- Never early-return the whole view on loading/error: each filter keystroke re-queries, so an early return unmounts the focused input mid-typing. Keep filters mounted and render query states inline in the results area.\n- Before calling a view verified, exercise the exact compiled artifact and host runtime in a sandboxed browser: representative data, loading, empty and error states, filters, sort/pagination, links/peek, declared actions, light/dark and narrow layouts. Fix failures and rerun. Registration compiles the module and requires an isolated browser check of the exact candidate against bounded empty/error/loading fixtures in light/dark themes and inline/fullscreen modes for every distinct attached scope (at most eight per module; each scope is its own bounded runner request). A failed check returns 422; an unavailable runner returns 503; both preserve the saved view. Fixture validation does not prove successful workspace data or every interaction. Distinguish compiled, browser-verified, stored and deployed; never claim more than the evidence.\n- Params sync to the URL on Lobu hosts only; elsewhere they stay frame-local. `refetch()` re-reads on demand; only Lobu hosts push live data-changed refreshes.\n\n## Connectors, Feeds, and Operations\n\nConnectors are the primary integration path for third-party services. The\nend-to-end model (entities vs events, the run lifecycle) is in\n`docs/CONCEPTS.md`; authoring a new connector when none matches is in\n`docs/connector-authoring.md`. Do not freeze a connector lifecycle in project\ninstructions because it can drift from the deployed SDK:\n\n1. Call `search_sdk` with the service name immediately before acting. It returns installed and installable connectors, declared feed keys, readiness, and the caller-aware live lifecycle. Then, before requesting app credentials, call `client.connections.setupOptions({ connector_key })` against the selected runtime: it discovers verified cloud-managed OAuth and hosted chat alongside local setup, so follow the URLs and instructions it returns. `cloud_status: "unavailable"` is a discovery outage, not evidence that managed auth is absent. Options are offers, not connected accounts.\n2. Always follow the methods it returns in order instead of relying on a remembered connect/feed/operation sequence. Repeat discovery after authorization or state changes so the next step reflects the live connector and current caller.\n3. Treat `access: operate` as `mcp:write` and `access: administer` as workspace owner/admin plus `mcp:admin`. If discovery asks for MCP reauthorization or an owner/admin handoff, follow that instruction; never attempt methods it withheld as unavailable.\n\nSource-backed feeds query the provider only through an explicit `client.feeds.readMany({ reads: [...] })` call; `search_memory` stays local and reports unqueried source feeds in `coverage`, while `client.feeds.get` returns metadata without source access. Feeds with `sync` may persist events for search and relational queries. For connector actions, use the live discovery result\'s operation target and readiness. If readiness is disconnected, follow the returned next action instead of guessing a connection. Surface approval-gated `pending_approval` as a waiting state, not a failure.\n\n## Data Ingestion\n\n- Use `lobu memory seed` for small declarative YAML datasets under `./data`; it processes records sequentially and is not a bulk-backfill path.\n- Use `client.knowledge.save` for schema-less semantic history such as messages, notes, observations, and content. Pass `supersedes_event_id` when replacing an existing fact.\n- Use `client.entities.create` / `client.entities.update` only for strict structured records that match declared entity schemas.\n- For large backfills, send bounded chunks through `run_sdk` / `lobu call run_sdk` and use `Promise.allSettled` so conflicts and partial failures remain visible.\n\n```ts\nexport default async (_ctx, client) => {\n const records = [\n { content: "...", semantic_type: "note" },\n { content: "...", semantic_type: "observation" },\n ];\n return Promise.allSettled(records.map((record) => client.knowledge.save(record)));\n};\n```\n';
168759
169253
  }
168760
169254
  });
168761
169255
 
@@ -170847,6 +171341,7 @@ var init_agent_routes = __esm({
170847
171341
  init_postgres_stores();
170848
171342
  init_postgres_secret_store();
170849
171343
  init_provider_secrets();
171344
+ init_diagnostics();
170850
171345
  routes2 = new Hono32();
170851
171346
  configStore2 = createPostgresAgentConfigStore();
170852
171347
  LEGACY_MODEL_FIELDS = [
@@ -171582,12 +172077,12 @@ var init_agent_routes = __esm({
171582
172077
  try {
171583
172078
  await reconcileAgentAuthProfiles(agentId, user.id, authProfiles);
171584
172079
  } catch (error) {
171585
- return c.json(
172080
+ throw routeFailure(c.json(
171586
172081
  {
171587
172082
  error: error instanceof Error ? error.message : "Failed to persist auth profiles"
171588
172083
  },
171589
172084
  503
171590
- );
172085
+ ), error);
171591
172086
  }
171592
172087
  }
171593
172088
  }
@@ -172704,7 +173199,7 @@ async function resolvePublicPath(...args) {
172704
173199
  if (eventIds.length > 0) {
172705
173200
  const systemRows = await getDb().unsafe(
172706
173201
  `WITH preview_events AS MATERIALIZED (
172707
- SELECT id, organization_id, entity_ids, metadata, linked_org_ids
173202
+ SELECT id, organization_id, entity_ids, metadata
172708
173203
  FROM events WHERE id IN (${eventIds.join(",")})
172709
173204
  )
172710
173205
  SELECT DISTINCT ev.id
@@ -172727,8 +173222,13 @@ async function resolvePublicPath(...args) {
172727
173222
  }
172728
173223
  return resolved;
172729
173224
  }
172730
- function buildToolContext(requestUrl, organizationId) {
172731
- return publicVisitorContext(organizationId, { requestUrl, baseUrl: getPublicOrigin(requestUrl) });
173225
+ function buildToolContext(requestUrl, organizationId, signal) {
173226
+ return publicVisitorContext(organizationId, {
173227
+ requestUrl,
173228
+ baseUrl: getPublicOrigin(requestUrl),
173229
+ abortSignal: signal,
173230
+ deadlineAt: Date.now() + PUBLIC_RENDER_DEADLINE_MS
173231
+ });
172732
173232
  }
172733
173233
  function escapeAttribute(value) {
172734
173234
  return escapeHtml(value);
@@ -172903,9 +173403,8 @@ async function getPublicEntityType(organizationId, slug) {
172903
173403
  );
172904
173404
  return rows[0] ?? null;
172905
173405
  }
172906
- async function getPublicEntityTypeList(organizationId, env, requestUrl, entityTypeSlug) {
173406
+ async function getPublicEntityTypeList(organizationId, env, ctx, entityTypeSlug) {
172907
173407
  const sql2 = getDb();
172908
- const ctx = buildToolContext(requestUrl, organizationId);
172909
173408
  const [result, entityTypeRow] = await Promise.all([
172910
173409
  listEntities(
172911
173410
  {
@@ -173367,7 +173866,7 @@ function applyBootstrapStrip(model, sub) {
173367
173866
  bootstrap: { ...model.bootstrap, path: stripSubdomainPrefix(model.bootstrap.path, sub) }
173368
173867
  };
173369
173868
  }
173370
- async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg) {
173869
+ async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg, signal) {
173371
173870
  const rawPath = `/${path15.replace(/^\/+|\/+$/g, "")}`;
173372
173871
  if (subdomainOrg && SUBDOMAIN_GLOBAL_ROUTES.has(rawPath.split("/")[1] ?? "")) return null;
173373
173872
  const normalizedPath = subdomainOrg && rawPath !== `/${subdomainOrg}` && !rawPath.startsWith(`/${subdomainOrg}/`) ? `/${subdomainOrg}${rawPath === "/" ? "" : rawPath}` : rawPath;
@@ -173379,7 +173878,7 @@ async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg) {
173379
173878
  if (segments[1] && PUBLIC_APP_ROUTE_PREFIXES.has(segments[1])) return null;
173380
173879
  const organization2 = await getPublicOrganizationBySlug(ownerSlug);
173381
173880
  if (!organization2) return null;
173382
- const toolCtx = buildToolContext(requestUrl, organization2.id);
173881
+ const toolCtx = buildToolContext(requestUrl, organization2.id, signal);
173383
173882
  const localPath = (target) => stripSubdomainPrefix(target, subdomainOrg);
173384
173883
  try {
173385
173884
  if (segments.length === 1) {
@@ -173403,7 +173902,7 @@ async function buildPublicPageModel(path15, env, requestUrl, subdomainOrg) {
173403
173902
  }
173404
173903
  const [ownerResolvedPath, entityList] = await Promise.all([
173405
173904
  resolvePublicPath({ path: `/${organization2.slug}`, include_bootstrap: true }, env, toolCtx),
173406
- getPublicEntityTypeList(organization2.id, env, requestUrl, entityTypeDefinition.slug)
173905
+ getPublicEntityTypeList(organization2.id, env, toolCtx, entityTypeDefinition.slug)
173407
173906
  ]);
173408
173907
  const entityType = {
173409
173908
  ...entityTypeDefinition,
@@ -173598,7 +174097,7 @@ function buildSitemapXml(entries) {
173598
174097
  </urlset>
173599
174098
  `;
173600
174099
  }
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;
174100
+ 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
174101
  var init_public_pages = __esm({
173603
174102
  "src/public-pages.ts"() {
173604
174103
  "use strict";
@@ -173619,6 +174118,7 @@ var init_public_pages = __esm({
173619
174118
  ...REMOVED_OWNER_SEGMENTS
173620
174119
  ]);
173621
174120
  SUBDOMAIN_GLOBAL_ROUTES = /* @__PURE__ */ new Set(["auth", "oauth", "account", "me"]);
174121
+ PUBLIC_RENDER_DEADLINE_MS = 2e4;
173622
174122
  COUNT_PLURALS = { entity: "entities" };
173623
174123
  OVERRIDDEN_META = [
173624
174124
  "description",
@@ -174937,7 +175437,7 @@ function createSmokeRoutes() {
174937
175437
  logger136.error(
174938
175438
  `Smoke dispatch INSERT failed: ${getErrorMessage(err)}`
174939
175439
  );
174940
- return c.json({ error: "Internal error" }, 500);
175440
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
174941
175441
  }
174942
175442
  });
174943
175443
  return app2;
@@ -174949,6 +175449,7 @@ var init_smoke = __esm({
174949
175449
  init_src();
174950
175450
  init_client();
174951
175451
  init_constant_time_equal();
175452
+ init_diagnostics();
174952
175453
  logger136 = createLogger("smoke-dispatch");
174953
175454
  FORWARDED_HEADERS = [
174954
175455
  "x-forwarded-for",
@@ -175019,8 +175520,8 @@ async function fetchWorkerHttp(c) {
175019
175520
  request: raw.request,
175020
175521
  signal: c.req.raw.signal
175021
175522
  }));
175022
- } catch {
175023
- return c.json({ error: "Gateway HTTP request failed" }, 502);
175523
+ } catch (error) {
175524
+ throw routeFailure(c.json({ error: "Gateway HTTP request failed" }, 502), redactedFailure(error));
175024
175525
  }
175025
175526
  }
175026
175527
  var HttpFetchRequestSchema;
@@ -175030,6 +175531,7 @@ var init_http_fetch = __esm({
175030
175531
  init_protocol();
175031
175532
  init_intervals();
175032
175533
  init_client();
175534
+ init_diagnostics();
175033
175535
  init_http_auth();
175034
175536
  HttpFetchRequestSchema = Type63.Object({
175035
175537
  worker_id: Type63.String({ minLength: 1 }),
@@ -177862,7 +178364,7 @@ async function getActiveAuthRun(c) {
177862
178364
  `;
177863
178365
  return c.json({ run_id: rows[0]?.id ?? null });
177864
178366
  } catch (err) {
177865
- return c.json({ error: errorMessage(err) }, 500);
178367
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
177866
178368
  }
177867
178369
  }
177868
178370
  async function getAuthRun(c) {
@@ -177920,7 +178422,7 @@ async function getAuthRun(c) {
177920
178422
  } : null
177921
178423
  });
177922
178424
  } catch (err) {
177923
- return c.json({ error: errorMessage(err) }, 500);
178425
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
177924
178426
  }
177925
178427
  }
177926
178428
  async function postAuthSignal(c) {
@@ -177968,7 +178470,7 @@ async function postAuthSignal(c) {
177968
178470
  }
177969
178471
  return c.json({ success: true });
177970
178472
  } catch (err) {
177971
- return c.json({ error: errorMessage(err) }, 500);
178473
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
177972
178474
  }
177973
178475
  }
177974
178476
  var init_auth_runs = __esm({
@@ -177978,6 +178480,7 @@ var init_auth_runs = __esm({
177978
178480
  init_client();
177979
178481
  init_errors2();
177980
178482
  init_resolve_session();
178483
+ init_diagnostics();
177981
178484
  }
177982
178485
  });
177983
178486
 
@@ -178018,7 +178521,7 @@ async function triggerAutomationForDevice(c) {
178018
178521
  resolvedDeviceWorkerId = device.id;
178019
178522
  } catch (err) {
178020
178523
  logger_default.error({ error: errorMessage(err) }, "[triggerAutomationForDevice] device lookup failed");
178021
- return c.json({ error: "Internal error" }, 500);
178524
+ throw routeFailure(c.json({ error: "Internal error" }, 500), err);
178022
178525
  }
178023
178526
  const automationRows = await sql2`
178024
178527
  SELECT id, organization_id, managed_agent_id, status, device_worker_id::text AS device_worker_id
@@ -178069,7 +178572,7 @@ async function triggerAutomationForDevice(c) {
178069
178572
  { error: errorMessage(err), automationId },
178070
178573
  "[triggerAutomationForDevice] enqueue failed"
178071
178574
  );
178072
- return c.json({ error: errorMessage(err) }, 500);
178575
+ throw routeFailure(c.json({ error: errorMessage(err) }, 500), err);
178073
178576
  }
178074
178577
  }
178075
178578
  var init_automation_trigger = __esm({
@@ -178079,6 +178582,7 @@ var init_automation_trigger = __esm({
178079
178582
  init_errors2();
178080
178583
  init_logger2();
178081
178584
  init_automation();
178585
+ init_diagnostics();
178082
178586
  }
178083
178587
  });
178084
178588
 
@@ -178146,7 +178650,7 @@ import { fileURLToPath as fileURLToPath8 } from "node:url";
178146
178650
  import { Hono as Hono38 } from "hono";
178147
178651
  import { compress } from "hono/compress";
178148
178652
  import { cors as cors2 } from "hono/cors";
178149
- import { HTTPException as HTTPException3 } from "hono/http-exception";
178653
+ import { HTTPException as HTTPException6 } from "hono/http-exception";
178150
178654
  async function resolveWebDistDirectory() {
178151
178655
  if (webDistDirectoryCache !== void 0) {
178152
178656
  return webDistDirectoryCache;
@@ -178271,7 +178775,7 @@ async function handleContentDistribution(c) {
178271
178775
  );
178272
178776
  return c.json({ distribution });
178273
178777
  } catch (error) {
178274
- return c.json({ error: errorMessage(error) }, 500);
178778
+ throw routeFailure(c.json({ error: errorMessage(error) }, 500), error);
178275
178779
  }
178276
178780
  }
178277
178781
  async function resolveClaimSessionUser(env, req) {
@@ -178383,6 +178887,7 @@ var init_index = __esm({
178383
178887
  init_chat_identity_routes();
178384
178888
  init_routes4();
178385
178889
  init_client();
178890
+ init_diagnostics();
178386
178891
  init_emitter();
178387
178892
  init_sse();
178388
178893
  init_sse_invalidation_auth();
@@ -178571,10 +179076,10 @@ var init_index = __esm({
178571
179076
  await checkDatabaseReadiness();
178572
179077
  return c.json({ status: "ok", service: "lobu-api" });
178573
179078
  } catch (error) {
178574
- return c.json(
179079
+ throw routeFailure(c.json(
178575
179080
  { status: "unready", service: "lobu-api", error: errorMessage(error) },
178576
179081
  503
178577
- );
179082
+ ), error);
178578
179083
  }
178579
179084
  });
178580
179085
  app.get("/health/scheduler", async (c) => {
@@ -178582,14 +179087,14 @@ var init_index = __esm({
178582
179087
  const health = await getSchedulerHealth(c.env);
178583
179088
  return c.json(health, health.healthy ? 200 : 503);
178584
179089
  } catch (error) {
178585
- return c.json(
179090
+ throw routeFailure(c.json(
178586
179091
  {
178587
179092
  healthy: false,
178588
179093
  issues: ["Failed to check scheduler health"],
178589
179094
  error: errorMessage(error)
178590
179095
  },
178591
179096
  500
178592
- );
179097
+ ), error);
178593
179098
  }
178594
179099
  });
178595
179100
  app.on(["GET", "POST"], "/api/auth/*", async (c) => {
@@ -178597,7 +179102,7 @@ var init_index = __esm({
178597
179102
  try {
178598
179103
  auth = await createAuth(c.env, c.req.raw);
178599
179104
  } catch (error) {
178600
- if (error instanceof HTTPException3) return error.getResponse();
179105
+ if (error instanceof HTTPException6) return error.getResponse();
178601
179106
  throw error;
178602
179107
  }
178603
179108
  return serveAuthRequest(auth, c.req.raw);
@@ -179340,19 +179845,38 @@ var init_index = __esm({
179340
179845
  const isSpaRoute = !hasFileExtension && !isExcludedSpaPath(requestPath);
179341
179846
  const shouldServeSpaFallback = (acceptsHtml || acceptsGenericResponse && hasSessionCookie) && isSpaRoute;
179342
179847
  if ((acceptsHtml || acceptsGenericResponse) && !hasSessionCookie && isSpaRoute) {
179848
+ try {
179849
+ enforcePublicReadLimit({
179850
+ userId: null,
179851
+ clientIP: getClientIP(c.req.raw, c.var.peerRemoteAddress)
179852
+ });
179853
+ } catch (error) {
179854
+ if (!(error instanceof ToolUserError) || error.code !== "RATE_LIMITED") {
179855
+ throw error;
179856
+ }
179857
+ c.header("Cache-Control", "no-store");
179858
+ c.header("Retry-After", String(error.retryAfterSeconds ?? 60));
179859
+ return c.text("Too many requests", 429);
179860
+ }
179343
179861
  let publicPageModel;
179344
179862
  try {
179345
179863
  publicPageModel = await buildPublicPageModel(
179346
179864
  requestPath,
179347
179865
  c.env,
179348
179866
  c.req.url,
179349
- c.get("subdomainOrg")
179867
+ c.get("subdomainOrg"),
179868
+ c.req.raw.signal
179350
179869
  );
179351
179870
  } catch (error) {
179352
179871
  logger_default.error({ error, path: requestPath }, "[public-pages] render failed");
179353
179872
  c.header("Cache-Control", "no-store");
179354
- c.header("Retry-After", "60");
179355
- return c.text("Temporarily unavailable", 503);
179873
+ c.header(
179874
+ "Retry-After",
179875
+ String(
179876
+ error instanceof ToolUserError && error.retryAfterSeconds !== void 0 ? error.retryAfterSeconds : 60
179877
+ )
179878
+ );
179879
+ throw routeFailure(c.text("Temporarily unavailable", 503), error);
179356
179880
  }
179357
179881
  if (publicPageModel) {
179358
179882
  const template = await loadAnySpaHtmlTemplate();
@@ -188006,7 +188530,7 @@ async function runWorkspacePurgeTask(payload, ctx) {
188006
188530
  return null;
188007
188531
  }
188008
188532
  const counts = { ...lease.removed };
188009
- const batch = (step, fn) => fencedBatch(sql2, ctx.taskRunId, owner, counts, step, fn);
188533
+ const batch = (step, fn) => fencedBatch(sql2, ctx.taskRunId, owner, counts, async (tx) => ({ [step]: await fn(tx) }));
188010
188534
  logger_default.info(
188011
188535
  { event: "workspace_purge_started", organizationId, taskRunId: ctx.taskRunId, resumed: !org },
188012
188536
  "[workspace-purge] Started"
@@ -188064,9 +188588,19 @@ async function runWorkspacePurgeTask(payload, ctx) {
188064
188588
  `;
188065
188589
  return deleted.count;
188066
188590
  }) > 0) ;
188591
+ while (await fencedBatch(sql2, ctx.taskRunId, owner, counts, async (tx) => {
188592
+ const outcome = await releaseClientHomedInOrganization(tx, organizationId);
188593
+ if (outcome === null) return {};
188594
+ return outcome === "deleted" ? { oauth_clients: 1 } : { oauth_clients_detached: 1 };
188595
+ }) > 0) ;
188067
188596
  await batch(
188068
188597
  "organization",
188069
188598
  (tx) => withAclPrivilege(tx, async () => {
188599
+ await tx`SELECT id FROM organization WHERE id = ${organizationId} FOR UPDATE`;
188600
+ await tx`
188601
+ UPDATE personal_access_tokens SET revoked_at = NOW(), updated_at = NOW()
188602
+ WHERE organization_id = ${organizationId} AND revoked_at IS NULL
188603
+ `;
188070
188604
  const deleted = await tx`DELETE FROM organization WHERE id = ${organizationId}`;
188071
188605
  return deleted.count;
188072
188606
  })
@@ -188088,7 +188622,7 @@ async function runWorkspacePurgeTask(payload, ctx) {
188088
188622
  );
188089
188623
  return counts;
188090
188624
  }
188091
- async function fencedBatch(sql2, taskRunId, owner, counts, step, fn) {
188625
+ async function fencedBatch(sql2, taskRunId, owner, counts, fn) {
188092
188626
  return sql2.begin(async (tx) => {
188093
188627
  const held = await tx`
188094
188628
  SELECT 1 FROM runs
@@ -188096,9 +188630,13 @@ async function fencedBatch(sql2, taskRunId, owner, counts, step, fn) {
188096
188630
  FOR NO KEY UPDATE
188097
188631
  `;
188098
188632
  if (held.length === 0) throw new WorkspacePurgeLeaseLostError(taskRunId);
188099
- const removed = await fn(tx);
188633
+ let removed = 0;
188634
+ for (const [step, rows] of Object.entries(await fn(tx))) {
188635
+ if (rows <= 0) continue;
188636
+ counts[step] = (counts[step] ?? 0) + rows;
188637
+ removed += rows;
188638
+ }
188100
188639
  if (removed > 0) {
188101
- counts[step] = (counts[step] ?? 0) + removed;
188102
188640
  await tx`
188103
188641
  UPDATE runs
188104
188642
  SET action_output = COALESCE(action_output, '{}'::jsonb)
@@ -188120,6 +188658,7 @@ var WORKSPACE_PURGE_BATCH_SIZE, PURGE_BATCH_DELETES, WORKSPACE_PURGE_UNLINKED_TA
188120
188658
  var init_purge = __esm({
188121
188659
  "src/workspace/purge.ts"() {
188122
188660
  "use strict";
188661
+ init_clients();
188123
188662
  init_client();
188124
188663
  init_entity_management();
188125
188664
  init_relationship_claims();
@@ -188702,9 +189241,13 @@ import http3 from "node:http";
188702
189241
  import v8 from "node:v8";
188703
189242
  import { getRequestListener } from "@hono/node-server";
188704
189243
  import { Hono as Hono39 } from "hono";
189244
+ import { HTTPException as HTTPException7 } from "hono/http-exception";
188705
189245
  import { routePath as routePath2 } from "hono/route";
188706
189246
  import { pinoLogger } from "hono-pino";
188707
189247
  import { context as context4, propagation, ROOT_CONTEXT } from "@opentelemetry/api";
189248
+ function unexpectedError(c) {
189249
+ return c.error instanceof HTTPException7 || c.error instanceof DbClosedError ? void 0 : c.error;
189250
+ }
188708
189251
  function dbShutDownResponse(c) {
188709
189252
  requestsRefusedAfterDbShutdown.add(c.req.raw);
188710
189253
  c.header("Retry-After", "1");
@@ -188813,7 +189356,7 @@ function buildWrapperApp(env, lobuApp2, mountedMainApp = app) {
188813
189356
  } else if (c.res.status >= 500 && !await isUnreportedServerStatus(c)) {
188814
189357
  recordError(
188815
189358
  span,
188816
- { name: "HttpServerError", message: `HTTP ${c.res.status}`, httpStatus: c.res.status },
189359
+ routeFailureCauses.get(c.req.raw) ?? { name: "HttpServerError", message: `HTTP ${c.res.status}`, httpStatus: c.res.status },
188817
189360
  { scope: name }
188818
189361
  );
188819
189362
  }
@@ -188822,7 +189365,13 @@ function buildWrapperApp(env, lobuApp2, mountedMainApp = app) {
188822
189365
  }
188823
189366
  });
188824
189367
  });
188825
- wrapper.use("*", pinoLogger({ pino: logger_default }));
189368
+ wrapper.use("*", pinoLogger({
189369
+ pino: logger_default,
189370
+ http: {
189371
+ onResLevel: (c) => unexpectedError(c) ? "error" : "info",
189372
+ onResMessage: (c) => unexpectedError(c)?.message || "Request completed"
189373
+ }
189374
+ }));
188826
189375
  wrapper.use("*", async (c, next) => {
188827
189376
  await next();
188828
189377
  if (c.res.status >= 500 && !isErrorReported(c)) {
@@ -188848,6 +189397,10 @@ function buildWrapperApp(env, lobuApp2, mountedMainApp = app) {
188848
189397
  });
188849
189398
  wrapper.onError((err, c) => {
188850
189399
  if (err instanceof DbClosedError) return dbShutDownResponse(c);
189400
+ if (err instanceof HTTPException7) {
189401
+ if (err.status >= 500) routeFailureCauses.set(c.req.raw, err.cause ?? err);
189402
+ return err.getResponse();
189403
+ }
188851
189404
  recordError(getCurrentSpan(), err, { scope: httpSpanName(c) });
188852
189405
  requestsWithRecordedError.add(c.req.raw);
188853
189406
  if (!isErrorReported(c)) {
@@ -189037,7 +189590,7 @@ function createServerLifecycle(config) {
189037
189590
  };
189038
189591
  return { start };
189039
189592
  }
189040
- var requestsWithRecordedError, requestsRefusedAfterDbShutdown, HTTP_TRACE_METHODS;
189593
+ var requestsWithRecordedError, routeFailureCauses, requestsRefusedAfterDbShutdown, HTTP_TRACE_METHODS;
189041
189594
  var init_server_lifecycle = __esm({
189042
189595
  "src/server-lifecycle.ts"() {
189043
189596
  "use strict";
@@ -189057,6 +189610,7 @@ var init_server_lifecycle = __esm({
189057
189610
  init_logger2();
189058
189611
  init_workspace();
189059
189612
  requestsWithRecordedError = /* @__PURE__ */ new WeakSet();
189613
+ routeFailureCauses = /* @__PURE__ */ new WeakMap();
189060
189614
  requestsRefusedAfterDbShutdown = /* @__PURE__ */ new WeakSet();
189061
189615
  HTTP_TRACE_METHODS = /* @__PURE__ */ new Set(["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]);
189062
189616
  }