@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.
- package/dist/catalogs/connectors.json +1 -1
- package/dist/catalogs/skills.json +1 -1
- package/dist/component.json +1 -1
- package/dist/connectors/linkedin-inbox-adapter.js +13 -3
- package/dist/connectors/whatsapp-web-adapter.js +14 -13
- package/dist/connectors/whatsapp-web-helpers.ts +37 -1
- package/dist/connectors/whatsapp_web.ts +5 -5
- package/dist/connectors/x-dm-adapter.js +17 -3
- package/dist/db/migrations/20261113170000_member_sql_rls.sql +254 -0
- package/dist/db/migrations/20261113180000_member_sql_rls_parallel_plans.sql +192 -0
- package/dist/db/migrations/20261113190000_member_sql_schema_usage.sql +24 -0
- package/dist/db/migrations/20261114120000_events_owner_only_visibility.sql +39 -0
- package/dist/db/migrations/20261115120000_events_unbound_tool_audit_without_bridge.sql +40 -0
- package/dist/db/migrations/20261115120001_events_unbound_tool_audit_validate.sql +19 -0
- package/dist/db/migrations/20261115120002_drop_events_linked_org_ids.sql +119 -0
- package/dist/dependencies.bun.lock +10 -10
- package/dist/embeddings-server.mjs +1 -1
- package/dist/guest.bundle.js +1 -1
- package/dist/owletto/dist/assets/_-BDMUN9XZ.js +2 -0
- package/dist/owletto/dist/assets/_-CF5X4ANe.js +3 -0
- package/dist/owletto/dist/assets/{_agentId-DN0EwMAC.js → _agentId-CGScf8z_.js} +2 -2
- package/dist/owletto/dist/assets/_agentId-EQU2aUP0.js +2 -0
- package/dist/owletto/dist/assets/_automationId-PXZ33jsF.js +2 -0
- package/dist/owletto/dist/assets/{_connectorKey._connectionId-CVKfL9AG.js → _connectorKey._connectionId-DcI29kGy.js} +2 -2
- package/dist/owletto/dist/assets/_connectorKey.index-Cr2NDJWX.js +2 -0
- package/dist/owletto/dist/assets/{_conversationId-CPpNySjO.js → _conversationId-CnmLYlVS.js} +2 -2
- package/dist/owletto/dist/assets/_eventId-w5sDz5oa.js +2 -0
- package/dist/owletto/dist/assets/_owner-CkOZR4n0.js +3 -0
- package/dist/owletto/dist/assets/_shape-C_FmSf9G.js +2 -0
- package/dist/owletto/dist/assets/{_slug-DJx_8fsV.js → _slug-COPpRXLt.js} +2 -2
- package/dist/owletto/dist/assets/_viewKey-BVdJiilV.js +2 -0
- package/dist/owletto/dist/assets/_viewKey-mxxpqjtC.js +2 -0
- package/dist/owletto/dist/assets/{accept-invitation-Dwq1GAnG.js → accept-invitation-BKeIzZXE.js} +2 -2
- package/dist/owletto/dist/assets/{activity-route-location-C1jcXC7v.js → activity-route-location-sLvKaSCa.js} +2 -2
- package/dist/owletto/dist/assets/activity-route-view-msesKUwn.js +2 -0
- package/dist/owletto/dist/assets/{agent-connect-pages-DoI9UR0a.js → agent-connect-pages-DVq9nAR7.js} +3 -3
- package/dist/owletto/dist/assets/{agent-editor-form-DlavYg2q.js → agent-editor-form-DVFyyMyd.js} +2 -2
- package/dist/owletto/dist/assets/{agent-loading-shells-DYqQphN7.js → agent-loading-shells-BLNHIy-r.js} +2 -2
- package/dist/owletto/dist/assets/{agent-permissions-matrix-C1L8IcYR.js → agent-permissions-matrix-UBKRR5vs.js} +2 -2
- package/dist/owletto/dist/assets/{agent-skill-context-D1nMrVod.js → agent-skill-context-fqedKd0D.js} +2 -2
- package/dist/owletto/dist/assets/{agent-subpage-shell-2w7vTeXw.js → agent-subpage-shell-BUCoY2Nf.js} +2 -2
- package/dist/owletto/dist/assets/{agent-thread-BopD-2k1.js → agent-thread-Cqf9ITrT.js} +2 -2
- package/dist/owletto/dist/assets/app-bridge-B-L0rGz9.js +121 -0
- package/dist/owletto/dist/assets/{app._appId-BXeFXW1w.js → app._appId-ByIypCL9.js} +2 -2
- package/dist/owletto/dist/assets/{assist-composer-CL5x8pNt.js → assist-composer-kG_heHXo.js} +2 -2
- package/dist/owletto/dist/assets/{automation-run-now-MtxUTfzd.js → automation-run-now-C5XTS00o.js} +2 -2
- package/dist/owletto/dist/assets/{callback-BgfwP1Eo.js → callback-Pz5uS-k7.js} +2 -2
- package/dist/owletto/dist/assets/{card-DtLIFq7D.js → card-CAPpY9P5.js} +2 -2
- package/dist/owletto/dist/assets/{claim-CT3hYVMF.js → claim-DgWWK0KI.js} +2 -2
- package/dist/owletto/dist/assets/{client-activity-scopes-BPbRX-Pe.js → client-activity-scopes-Aqdo6Pdr.js} +2 -2
- package/dist/owletto/dist/assets/{client-rows-vrNA6FLs.js → client-rows-Dd5YV8vn.js} +2 -2
- package/dist/owletto/dist/assets/{clients-xnzZeEdZ.js → clients-Bf7ZgGro.js} +2 -2
- package/dist/owletto/dist/assets/{code-editor-mrKkAfcE.js → code-editor-z1Sy_hiX.js} +2 -2
- package/dist/owletto/dist/assets/connect-BFNp1y_s.js +2 -0
- package/dist/owletto/dist/assets/{connect-menu-C6iVtuSo.js → connect-menu-BWrAhMqO.js} +2 -2
- package/dist/owletto/dist/assets/connect._clientId-CSPfwYIN.js +2 -0
- package/dist/owletto/dist/assets/{connected._clientId-ROfVgp9h.js → connected._clientId-CuOeHafK.js} +2 -2
- package/dist/owletto/dist/assets/{connection-BMz740Wi.js → connection-CVeHmDLs.js} +2 -2
- package/dist/owletto/dist/assets/{connection-feed-detail-0VAJiZTP.js → connection-feed-detail-BYo7zdVD.js} +2 -2
- package/dist/owletto/dist/assets/{connector-page-shell-BFv21yuv.js → connector-page-shell-an3SYLim.js} +2 -2
- package/dist/owletto/dist/assets/{connector-provenance-b59RfBtk.js → connector-provenance-mSZCOud-.js} +2 -2
- package/dist/owletto/dist/assets/{connectors-nYS31lO2.js → connectors-DBEM9QQz.js} +2 -2
- package/dist/owletto/dist/assets/{consent-cPRF9JQv.js → consent-1ulwyJ3k.js} +2 -2
- package/dist/owletto/dist/assets/{copy-button-C3wMMv63.js → copy-button-Xhh7ZnjO.js} +2 -2
- package/dist/owletto/dist/assets/{core.esm-C9QlSrgK.js → core.esm-Ctg_pXLe.js} +2 -2
- package/dist/owletto/dist/assets/{create-CGOWfMk4.js → create-CGuoqPh8.js} +2 -2
- package/dist/owletto/dist/assets/create-Ccb5R-S4.js +2 -0
- package/dist/owletto/dist/assets/{create-ASRN3Obq.js → create-DmhbacIa.js} +2 -2
- package/dist/owletto/dist/assets/{create-automation-form-CLicoPH5.js → create-automation-form-CD6jSlWL.js} +2 -2
- package/dist/owletto/dist/assets/create._connectorKey-CZsAqj1p.js +2 -0
- package/dist/owletto/dist/assets/{custom-guardrail-edits-BUL7nmuO.js → custom-guardrail-edits-Ce_BwiwD.js} +2 -2
- package/dist/owletto/dist/assets/{definition-comparison-4UYMI6BK.js → definition-comparison-D_qP25jR.js} +2 -2
- package/dist/owletto/dist/assets/{detail-page-skeleton-C8v3rJXK.js → detail-page-skeleton-CPAfZLG0.js} +2 -2
- package/dist/owletto/dist/assets/{device-BBwsOi7q.js → device-DDl5XKvt.js} +2 -2
- package/dist/owletto/dist/assets/{device-pin-tombstone-Bcpe7nAA.js → device-pin-tombstone-Dkj7hrBE.js} +2 -2
- package/dist/owletto/dist/assets/{device._deviceId-DLT4jh0Z.js → device._deviceId-bNhTcops.js} +2 -2
- package/dist/owletto/dist/assets/{dynamic-schema-form-BDT8x0Vg.js → dynamic-schema-form-CRyUchXo.js} +2 -2
- package/dist/owletto/dist/assets/{entity-options-B9hm9V87.js → entity-options-D4t-NAcg.js} +2 -2
- package/dist/owletto/dist/assets/entity-page-BOOL_vy3.js +2 -0
- package/dist/owletto/dist/assets/{entity-pages-BWBpttz3.js → entity-pages-_nuesgnp.js} +2 -2
- package/dist/owletto/dist/assets/{entity-schema-graph-lMMx3HhR.js → entity-schema-graph-Cq96SJ3c.js} +2 -2
- package/dist/owletto/dist/assets/{entity-type-page-CkQm0yEu.js → entity-type-page-CkCSbkBx.js} +2 -2
- package/dist/owletto/dist/assets/event-detail-DUvlqn9b.js +2 -0
- package/dist/owletto/dist/assets/{events-feed-DmRzikZW.js → events-feed-DcKTkJVe.js} +2 -2
- package/dist/owletto/dist/assets/{filter-editors-CQoSj-20.js → filter-editors-DGVl9U4D.js} +3 -3
- package/dist/owletto/dist/assets/{full-page-spinner-CYyCnKve.js → full-page-spinner-CtVlF8GQ.js} +2 -2
- package/dist/owletto/dist/assets/index-BUlkNJzX.js +2 -0
- package/dist/owletto/dist/assets/{index-BS5Ty3tf.js → index-BifR-LE9.js} +2 -2
- package/dist/owletto/dist/assets/{index-DByaMzsG.js → index-BoqrvLHQ.js} +1383 -1383
- package/dist/owletto/dist/assets/index-CA9mW_ZM.js +2 -0
- package/dist/owletto/dist/assets/index-CH0GzG4i.js +2 -0
- package/dist/owletto/dist/assets/index-CK5GDX4B.js +2 -0
- package/dist/owletto/dist/assets/index-CtI5Eomq.js +2 -0
- package/dist/owletto/dist/assets/{index-CUndAH6o.js → index-DbjbHlDe.js} +2 -2
- package/dist/owletto/dist/assets/index-DmtQ0bds.js +2 -0
- package/dist/owletto/dist/assets/{index-CDyFQ32o.js → index-Du_J8hnx.js} +2 -2
- package/dist/owletto/dist/assets/{index-ittfA0k8.js → index-DvuJ_S_o.js} +2 -2
- package/dist/owletto/dist/assets/index-Pae_f9LM.css +1 -0
- package/dist/owletto/dist/assets/{index-C3hz9tzx.js → index-XETZnN7L.js} +2 -2
- package/dist/owletto/dist/assets/{json-diff-mcDgyct_.js → json-diff-OjtREegr.js} +2 -2
- package/dist/owletto/dist/assets/{list-skeleton-DsYGUHxi.js → list-skeleton-CH0qQBYk.js} +2 -2
- package/dist/owletto/dist/assets/{login-EoLq136v.js → login-DG0b9uSC.js} +2 -2
- package/dist/owletto/dist/assets/{logout-gLgEQOiX.js → logout-DfdgOLoM.js} +2 -2
- package/dist/owletto/dist/assets/{member-scope-gate-vvkgSAb2.js → member-scope-gate-Cxg2zGQT.js} +2 -2
- package/dist/owletto/dist/assets/memory-browse-page-qEDQ9Z18.js +74 -0
- package/dist/owletto/dist/assets/missing-view-xT0B-f5z.js +2 -0
- package/dist/owletto/dist/assets/{model-selector-D3vSMLO2.js → model-selector-D2OpDkwH.js} +2 -2
- package/dist/owletto/dist/assets/{needs-you-list-B5Bgd05M.js → needs-you-list-3uMsWcDv.js} +2 -2
- package/dist/owletto/dist/assets/{new-dLXsCHBd.js → new-AdGV6a8R.js} +2 -2
- package/dist/owletto/dist/assets/new-BdtIhBpo.js +2 -0
- package/dist/owletto/dist/assets/{new-Bk_flKQO.js → new-BjGwX6s6.js} +2 -2
- package/dist/owletto/dist/assets/{new-BPW3V0Y1.js → new-D-iMjV74.js} +2 -2
- package/dist/owletto/dist/assets/{organization-DBfgBkzq.js → organization-qaIpEiQg.js} +2 -2
- package/dist/owletto/dist/assets/peek-pane-content-CEsDVScl.js +2 -0
- package/dist/owletto/dist/assets/{pending-seed-CBhx2Ql-.js → pending-seed-BBACroge.js} +2 -2
- package/dist/owletto/dist/assets/{proposal-review-shell-B-jYcKfB.js → proposal-review-shell-C8ZfIAYn.js} +2 -2
- package/dist/owletto/dist/assets/public-shell-ready-K2R8iXSI.js +2 -0
- package/dist/owletto/dist/assets/{record-session-CAmGHMyM.js → record-session-BrM9cdXu.js} +2 -2
- package/dist/owletto/dist/assets/{renderer-olRv_HMI.js → renderer-CTKNMcXP.js} +4 -4
- package/dist/owletto/dist/assets/{reset-password-B9_xi8Pq.js → reset-password-DKBEneyR.js} +2 -2
- package/dist/owletto/dist/assets/{run-initiator-DhE5v4z0.js → run-initiator-BKSgI1o0.js} +2 -2
- package/dist/owletto/dist/assets/{runs-C8sZQr4o.js → runs-k2NpbZm8.js} +2 -2
- package/dist/owletto/dist/assets/runs-list-DUXRMkWN.js +2 -0
- package/dist/owletto/dist/assets/{schema-value-zTJGE4eh.js → schema-value-wjqGxXhv.js} +3 -3
- package/dist/owletto/dist/assets/{scoped-feed-bar-BKyJSa3_.js → scoped-feed-bar-DNFL0sYX.js} +2 -2
- package/dist/owletto/dist/assets/{settings-z02cvVS3.js → settings-V0m5Om5j.js} +2 -2
- package/dist/owletto/dist/assets/{source-record-panels-CGmKIJdN.js → source-record-panels-BMut9YIA.js} +2 -2
- package/dist/owletto/dist/assets/{status-variants-DyRCXBzM.js → status-variants-SzXYYedJ.js} +2 -2
- package/dist/owletto/dist/assets/subDays-9s9OEl5t.js +2 -0
- package/dist/owletto/dist/assets/{table-C637cQxG.js → table-ZuYMOjVR.js} +2 -2
- package/dist/owletto/dist/assets/{use-automations-CgWNoYio.js → use-automations-DfBtVzGa.js} +2 -2
- package/dist/owletto/dist/assets/{use-login-redirect-tDdhXTpt.js → use-login-redirect-BDiS3eyl.js} +2 -2
- package/dist/owletto/dist/assets/{use-mention-search-D-kIKchD.js → use-mention-search-khySpz_V.js} +2 -2
- package/dist/owletto/dist/assets/view-card-DiHWlypr.js +2 -0
- package/dist/owletto/dist/assets/view-param-filters-DGKxSr7r.js +2 -0
- package/dist/owletto/dist/assets/{views-access-required-C35Dyt91.js → views-access-required-HA-PiOwA.js} +2 -2
- package/dist/owletto/dist/index.html +2 -2
- package/dist/server-main.bundle.mjs +1099 -545
- package/npm-shrinkwrap.json +38 -38
- package/package.json +1 -1
- package/vendor/connector-sdk/package.json +1 -1
- package/vendor/core/package.json +1 -1
- package/vendor/views/package.json +1 -1
- package/dist/owletto/dist/assets/_-CYvj1y65.js +0 -3
- package/dist/owletto/dist/assets/_-CeLTSYYY.js +0 -2
- package/dist/owletto/dist/assets/_agentId-BB5E-L6T.js +0 -2
- package/dist/owletto/dist/assets/_automationId-DvUl9CSd.js +0 -2
- package/dist/owletto/dist/assets/_connectorKey.index-Cv6FzK1v.js +0 -2
- package/dist/owletto/dist/assets/_eventId-DZKicuq6.js +0 -2
- package/dist/owletto/dist/assets/_owner-Dauk3YuD.js +0 -3
- package/dist/owletto/dist/assets/_shape-cKrEID3T.js +0 -2
- package/dist/owletto/dist/assets/_viewKey-CPVzVKEf.js +0 -2
- package/dist/owletto/dist/assets/_viewKey-CW8gexOQ.js +0 -2
- package/dist/owletto/dist/assets/activity-route-view-D78Wj0RH.js +0 -2
- package/dist/owletto/dist/assets/app-bridge-C4nPtae3.js +0 -121
- package/dist/owletto/dist/assets/connect-NUCSay8X.js +0 -2
- package/dist/owletto/dist/assets/connect._clientId-Cp-d9Q5b.js +0 -2
- package/dist/owletto/dist/assets/create-CBcodaSO.js +0 -2
- package/dist/owletto/dist/assets/create._connectorKey-s4xkktTC.js +0 -2
- package/dist/owletto/dist/assets/entity-page-DZjzQ2V4.js +0 -2
- package/dist/owletto/dist/assets/event-detail-CkzfakTK.js +0 -2
- package/dist/owletto/dist/assets/index-BE7eb2kE.js +0 -2
- package/dist/owletto/dist/assets/index-BFR0uiKY.js +0 -2
- package/dist/owletto/dist/assets/index-C38OzBpB.js +0 -2
- package/dist/owletto/dist/assets/index-CiKysEhV.js +0 -2
- package/dist/owletto/dist/assets/index-DfdinB7B.js +0 -2
- package/dist/owletto/dist/assets/index-DgMM4Zt5.css +0 -1
- package/dist/owletto/dist/assets/index-Xk711gVC.js +0 -2
- package/dist/owletto/dist/assets/memory-browse-page-DvDtwrEI.js +0 -74
- package/dist/owletto/dist/assets/new-C5HtQdM_.js +0 -2
- package/dist/owletto/dist/assets/peek-pane-content-c2PG3TEX.js +0 -2
- package/dist/owletto/dist/assets/public-shell-ready-D8TijlRY.js +0 -2
- package/dist/owletto/dist/assets/record-activity-DnRVOrG2.js +0 -2
- package/dist/owletto/dist/assets/runs-list-CwtH-wmk.js +0 -2
- package/dist/owletto/dist/assets/subDays-D8nHthaS.js +0 -2
- package/dist/owletto/dist/assets/view-param-filters-CUCj9Df-.js +0 -2
|
@@ -21693,7 +21693,7 @@
|
|
|
21693
21693
|
],
|
|
21694
21694
|
"accountProbe": {
|
|
21695
21695
|
"url": "https://web.whatsapp.com/",
|
|
21696
|
-
"expression": "(async () => {\n (function whatsAppWebAdapterProgram() {\n const SYSTEM_TYPES = new Set([\n \"gp2\",\n \"notification_template\",\n \"e2e_notification\"\n ]);\n let readinessSignature = null, readinessStableSince = 0;\n const existing = globalThis.__owlettoWhatsAppAdapterV1;\n if (existing?.version === 28)\n return;\n existing?.detach?.(void 0, \"WhatsApp adapter was replaced; recovery is required\");\n const listeners = new Map;\n function detach(bindingId, reason) {\n const selected = bindingId ? [listeners.get(bindingId)] : [...listeners.values()];\n for (const state of selected) {\n if (!state)\n continue;\n if (reason) {\n state.error = reason;\n state.post({ sequence: ++state.sequence, record: { id: \"whatsapp-web:source-observation-error\", source_error: reason } });\n }\n for (const entry of state.pending.values())\n entry.reject?.(Error(reason ?? \"Source listener was detached\"));\n state.collection.off(\"add\", state.onAdd);\n state.collection.off(\"change\", state.onChange);\n window.removeEventListener(\"message\", state.onReply);\n listeners.delete(state.id);\n }\n }\n function assertAccount(account) {\n if (typeof account !== \"string\" || !account || widString(meUser()) !== account)\n throw Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n }\n async function digest(value) {\n const bytes = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n function listen(request) {\n assertAccount(request.account_id);\n const collection = requireFirst([\"WAWebCollections\"])?.Msg;\n if (typeof collection?.on !== \"function\" || typeof collection?.off !== \"function\")\n throw Error(\"WhatsApp message observation is unavailable in this build\");\n if (!request.bridge_id || !request.token)\n throw Error(\"A feed bridge is required\");\n const post = (state2, entry) => window.postMessage({\n type: \"lobu-feed-record\",\n token: state2.token,\n sequence: entry.sequence,\n record: entry.record\n }, location.origin), reportError = (state2, message, sequence = ++state2.sequence) => {\n state2.error = message;\n post(state2, {\n sequence,\n record: {\n id: \"whatsapp-web:source-observation-error\",\n source_error: message\n }\n });\n }, resident = listeners.get(request.bridge_id), previous = resident?.request.account_id === request.account_id && resident?.request.chat_filter === request.chat_filter && resident?.request.minimum_timestamp === request.minimum_timestamp ? resident : null;\n detach(request.bridge_id);\n const state = {\n ...previous ?? {\n id: request.bridge_id,\n collection,\n sequence: 0,\n pending: new Map,\n fingerprints: new Map,\n pendingBytes: 0,\n fingerprintBytes: 0,\n error: null\n },\n collection,\n error: null\n };\n state.token = request.token;\n state.request = request;\n state.post = (entry) => post(state, entry);\n const observe = (model) => {\n if (state.error)\n return;\n const sequence = ++state.sequence;\n new Promise((resolve) => {\n assertAccount(state.request.account_id);\n resolve(messageReference(model));\n }).then((record) => {\n if (listeners.get(state.id) !== state)\n return;\n assertAccount(state.request.account_id);\n if (!record || record.timestamp <= 0)\n return;\n if (state.request.chat_filter === \"group\" && !record.is_group)\n return;\n if (state.request.chat_filter === \"individual\" && record.is_group)\n return;\n if (state.request.minimum_timestamp != null && record.timestamp < state.request.minimum_timestamp)\n return;\n record = {\n id: record.id,\n events: [{\n id: record.id,\n event_type: \"message.created\",\n resource_ref: record.id,\n resource_type: \"message\",\n occurred_at: new Date(record.timestamp * 1000).toISOString()\n }]\n };\n const previous2 = state.pending.get(record.id), seen = state.fingerprints.get(record.id);\n if (seen && seen.sequence >= sequence)\n return;\n const fingerprint = JSON.stringify(record);\n if (seen?.fingerprint === fingerprint) {\n seen.sequence = sequence;\n return;\n }\n const bytes = new TextEncoder().encode(fingerprint).length;\n if (bytes > 131072 || state.pendingBytes - (previous2?.bytes ?? 0) + bytes > 16777216 || state.pending.size >= 1e4 && !previous2) {\n reportError(state, \"WhatsApp page observation buffer overflowed; recovery is required\", sequence);\n return;\n }\n const entry = { sequence, record, bytes };\n state.pendingBytes += bytes - (previous2?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.fingerprintBytes += bytes - (seen?.bytes ?? 0);\n state.fingerprints.delete(record.id);\n state.fingerprints.set(record.id, { fingerprint, sequence, bytes });\n while (state.fingerprints.size > 1e4 || state.fingerprintBytes > 16777216) {\n const oldest = state.fingerprints.keys().next().value;\n state.fingerprintBytes -= state.fingerprints.get(oldest).bytes;\n state.fingerprints.delete(oldest);\n }\n post(state, entry);\n }).catch(() => {\n if (listeners.get(state.id) !== state)\n return;\n reportError(state, \"WhatsApp source observation failed; recovery is required\", sequence);\n });\n };\n state.onAdd = (model) => observe(model);\n state.onChange = (model) => observe(model);\n state.onReply = (event) => {\n if (event.source !== window || event.origin !== location.origin || event.data?.token !== state.token)\n return;\n if (event.data.type === \"lobu-feed-record:stop\") {\n detach(state.id);\n return;\n }\n if (event.data.type !== \"lobu-feed-record:ack\")\n return;\n try {\n assertAccount(state.request.account_id);\n } catch {\n detach(state.id, \"WhatsApp saved account changed; recovery is required\");\n return;\n }\n for (const [id, entry] of state.pending) {\n if (entry.sequence !== event.data.sequence)\n continue;\n if (event.data.ok) {\n state.pendingBytes -= entry.bytes;\n state.pending.delete(id);\n entry.resolve?.();\n } else\n entry.reject?.(Error(\"Browser rejected the source reference batch\"));\n break;\n }\n };\n listeners.set(state.id, state);\n try {\n collection.on(\"add\", state.onAdd);\n collection.on(\"change\", state.onChange);\n window.addEventListener(\"message\", state.onReply);\n } catch (error) {\n reportError(state, \"WhatsApp source observation failed; recovery is required\");\n throw error;\n }\n if (previous?.error)\n post(state, {\n sequence: ++state.sequence,\n record: { id: \"whatsapp-web:source-observation-error\", source_error: previous.error }\n });\n for (const entry of state.pending.values())\n post(state, entry);\n return { ok: !0, listening: !0 };\n }\n async function publishChanges(request) {\n const state = listeners.get(request.bridge_id);\n if (!state || state.token !== request.token)\n throw Error(\"Source listener is unavailable\");\n assertAccount(state.request.account_id);\n const record = { ...request.batch, id: `replay:${await digest(JSON.stringify([request.transition ?? null, request.batch]))}` };\n if (listeners.get(state.id) !== state)\n throw Error(\"Source listener was replaced\");\n assertAccount(state.request.account_id);\n const bytes = new TextEncoder().encode(JSON.stringify(record)).length, previous = state.pending.get(record.id);\n if (bytes > 131072 || state.pendingBytes - (previous?.bytes ?? 0) + bytes > 16777216 || state.pending.size >= 1e4 && !previous)\n throw Error(\"Source replay buffer is full\");\n await new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(Error(\"Source replay was not accepted by the browser\")), 1e4), entry = {\n record,\n bytes,\n sequence: ++state.sequence,\n resolve: () => {\n clearTimeout(timer);\n resolve();\n },\n reject: (error) => {\n clearTimeout(timer);\n reject(error);\n }\n };\n state.pendingBytes += bytes - (previous?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.post(entry);\n });\n return { ok: !0 };\n }\n function requireFirst(names) {\n for (const name of names)\n try {\n const module2 = window.require?.(name);\n if (module2)\n return module2;\n } catch {}\n return null;\n }\n function meUser() {\n const module2 = requireFirst([\n \"WAWebUserPrefsMeUser\",\n \"WAWebUserPrefsMe\",\n \"WAWebUserPrefs\"\n ]);\n if (!module2)\n return null;\n for (const accessor of [\n \"getMaybeMePnUser\",\n \"getMaybeMeUser\",\n \"getMeUser\",\n \"getMeUserOrThrow\",\n \"getMaybeMeLidUser\"\n ])\n try {\n const value = module2[accessor]?.();\n if (value)\n return value;\n } catch {}\n try {\n return module2.me ?? null;\n } catch {}\n return null;\n }\n async function ownJids() {\n const module2 = requireFirst([\"WAWebUserPrefsMeUser\"]), candidates = [meUser()];\n for (const accessor of [\"getMaybeMePnUser\", \"getMaybeMeLidUser\"])\n try {\n candidates.push(module2?.[accessor]?.());\n } catch {}\n const forms = new Set;\n for (const value of candidates) {\n const own = await canonicalJid(value);\n if (own.jid)\n forms.add(own.jid);\n if (own.lid)\n forms.add(own.lid);\n }\n return forms;\n }\n async function mentionsOwnAccount(row) {\n const addressed = [\n ...Array.isArray(row.mentionedJidList) ? row.mentionedJidList : [],\n row.quotedParticipant\n ].filter(Boolean);\n if (addressed.length === 0)\n return !1;\n const own = await ownJids();\n for (const value of addressed) {\n const candidate = await canonicalJid(value);\n if (own.has(candidate.jid) || candidate.lid && own.has(candidate.lid))\n return !0;\n }\n return !1;\n }\n async function ownMentionJids(row) {\n const mentions = Array.isArray(row.mentionedJidList) ? row.mentionedJidList : [];\n if (mentions.length === 0)\n return [];\n const own = await ownJids(), mentioned = new Set;\n for (const value of mentions) {\n const candidate = await canonicalJid(value);\n for (const jid of [candidate.jid, candidate.lid])\n if (typeof jid === \"string\" && /^[0-9]{5,32}@(s\\.whatsapp\\.net|lid)$/.test(jid) && own.has(jid))\n mentioned.add(jid);\n }\n return [...mentioned].slice(0, 2);\n }\n const SEND_MODULES = [\n \"WAWebSendTextMsgChatAction\",\n \"WAWebSendMsgChatAction\",\n \"WAWebSendMessage\"\n ], REACTION_MODULES = [\n \"WAWebSendReactionMsgAction\",\n \"WAWebSendReactionMsg\",\n \"WAWebReactionAction\"\n ], REVOKE_MODULES = [\n \"WAWebChatSendMessages\",\n \"WAWebRevokeMsgAction\",\n \"WAWebDeleteChatAction\",\n \"WAWebRevokeMessage\"\n ], EDIT_MODULES = [\"WAWebSendMessageEditAction\", \"WAWebEditMessage\"], DRAFT_MODULES = [\n \"WAWebChatDraftUtils\",\n \"WAWebSetDraft\",\n \"WAWebComposeBoxActions\"\n ];\n function modelData(model) {\n return model?.attributes ?? model?._data ?? model ?? {};\n }\n function messageReference(model) {\n const row = modelData(model), key = row.id ?? model?.id, id = rawId(key), remote = widString(key?.remote ?? row.chatId ?? (key?.fromMe ? row.to : row.from));\n if (!id || !remote || isBroadcastOnlyJid(remote) || SYSTEM_TYPES.has(row.type))\n return null;\n return { id, timestamp: unixSeconds(row), is_group: remote.endsWith(\"@g.us\") };\n }\n async function observeMessages(input = {}) {\n const after = input.after ?? null;\n if (after !== null && (!Number.isSafeInteger(after) || after < 0))\n throw Error(\"Invalid WhatsApp observation cursor\");\n const pending = input.unresolved ?? [];\n if (!Array.isArray(pending) || pending.length > 32 || pending.some((row) => !Number.isSafeInteger(row.position) || row.position <= 0 || typeof row.id !== \"string\" || row.id.length > 512 || !Number.isSafeInteger(row.first_seen) || row.first_seen < 0))\n throw Error(\"Invalid WhatsApp pending placeholder cursor\");\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n }), now = Math.floor(Date.now() / 1000), gaps = [], gap = (reason, detail) => gaps.push({ reason, detail }), scan = (position, limit, direction = \"next\", inclusive = !1) => new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source observation aborted\"));\n const request = transaction.objectStore(\"message\").index(\"rowId\").openCursor(position === null ? null : IDBKeyRange.lowerBound(position, !inclusive), direction), page2 = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(page2);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\" || cursor.value.id.length > 512) {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n page2.push({ position: cursor.key, id: cursor.value.id, timestamp: unixSeconds(cursor.value), type: cursor.value.type });\n if (page2.length >= limit)\n resolve(page2);\n else\n cursor.continue();\n };\n });\n let rows, rechecks;\n try {\n if (after === null) {\n rows = await scan(null, 1, \"prev\");\n const head = rows[0];\n return {\n after: head?.position ?? 0,\n anchor: head?.id ?? null,\n unresolved: head?.timestamp === 0 ? [{ position: head.position, id: head.id, first_seen: now }] : [],\n references: [],\n gaps: [],\n hasMore: !1\n };\n }\n let start = after;\n if (after > 0) {\n const [anchor] = await scan(after, 1, \"next\", !0);\n if (!input.anchor || anchor?.position !== after || anchor.id !== input.anchor) {\n gap(\"history-continuity\", [after, input.anchor ?? null]);\n start = 0;\n }\n }\n rechecks = await Promise.all(pending.map(async (item) => ({ item, row: (await scan(item.position, 1, \"next\", !0))[0] })));\n rows = await scan(start, 501);\n } finally {\n database.close();\n }\n const page = rows.slice(0, 500), references = new Map, unresolved = new Map, keys = requireFirst([\"WAWebMsgKey\"]);\n if ((page.length || rechecks.length) && typeof keys?.fromString !== \"function\")\n throw Error(\"WhatsApp source message keys are unavailable\");\n const accept = (row, firstSeen = now) => {\n const reference = messageReference({ id: keys.fromString(row.id), t: row.timestamp, type: row.type });\n if (!reference)\n return;\n if (input.chat_filter === \"group\" && !reference.is_group)\n return;\n if (input.chat_filter === \"individual\" && reference.is_group)\n return;\n if (reference.timestamp <= 0) {\n if (now - firstSeen >= 604800)\n gap(\"placeholder-expired\", [row.position, row.id, firstSeen]);\n else if (unresolved.size < 32 || unresolved.has(row.id))\n unresolved.set(row.id, { position: row.position, id: row.id, first_seen: firstSeen });\n else\n gap(\"placeholder-capacity\", [row.position, row.id]);\n return;\n }\n if (reference.timestamp >= input.started_at)\n references.set(reference.id, reference);\n }, checked = new Set;\n for (const { item, row } of rechecks)\n if (!row || row.position !== item.position || row.id !== item.id)\n gap(\"placeholder-unavailable\", [item.position, item.id]);\n else {\n checked.add(item.id);\n accept(row, item.first_seen);\n }\n for (const row of page)\n if (!checked.has(row.id))\n accept(row);\n const last = page[page.length - 1], rebased = gaps.some((item) => item.reason === \"history-continuity\");\n return {\n after: last?.position ?? (rebased ? 0 : after),\n anchor: last?.id ?? (rebased ? null : input.anchor ?? null),\n unresolved: [...unresolved.values()],\n references: [...references.values()],\n hasMore: rows.length > 500,\n gaps: await Promise.all(gaps.map(async (item) => {\n const identity = await digest(JSON.stringify([input.account_id, input.started_at, input.chat_filter, item]));\n return {\n id: `gap:${identity}`,\n event_type: \"source.gap\",\n resource_type: \"message\",\n resource_ref: `whatsapp:${item.reason}:${identity}`\n };\n }))\n };\n }\n function models(collection) {\n if (Array.isArray(collection?._models))\n return collection._models;\n if (Array.isArray(collection?.models))\n return collection.models;\n if (typeof collection?.toArray === \"function\")\n try {\n return collection.toArray();\n } catch {}\n return [];\n }\n function isBroadcastOnlyJid(jid) {\n return jid === \"status@broadcast\" || jid.endsWith(\"@newsletter\") || jid === \"0@c.us\" || jid === \"0@s.whatsapp.net\";\n }\n function widString(value) {\n if (typeof value === \"string\")\n return value;\n if (!value)\n return null;\n if (typeof value._serialized === \"string\")\n return value._serialized;\n try {\n const rendered = value.toString?.();\n return rendered && rendered !== \"[object Object]\" ? String(rendered) : null;\n } catch {\n return null;\n }\n }\n function rawId(value) {\n if (typeof value === \"string\")\n return value && !/^(?:true|false)_/i.test(value) ? value : null;\n if (typeof value?.id === \"string\")\n return value.id && !/^(?:true|false)_/i.test(value.id) ? value.id : null;\n return null;\n }\n function unixSeconds(row) {\n const value = Number(row?.t ?? row?.timestamp ?? row?.ephemeralStartTimestamp ?? 0);\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n }\n async function canonicalJid(value) {\n const original = widString(value);\n if (!original)\n return { jid: null, lid: null };\n let jid = original.toLowerCase();\n if (jid.endsWith(\"@c.us\"))\n jid = `${jid.slice(0, -5)}@s.whatsapp.net`;\n if (!jid.endsWith(\"@lid\"))\n return { jid, lid: null };\n const migration = requireFirst([\n \"WAWebLidMigrationUtils\",\n \"WAWebLidMigration\"\n ]), toPn = migration?.toPn ?? migration?.getPnForLid ?? migration?.lidToPhone;\n if (typeof toPn === \"function\")\n try {\n const converted = await toPn.call(migration, value), phoneJid = widString(converted);\n if (phoneJid)\n return {\n jid: phoneJid.endsWith(\"@c.us\") ? `${phoneJid.slice(0, -5)}@s.whatsapp.net` : phoneJid,\n lid: jid\n };\n } catch {}\n return { jid, lid: jid };\n }\n function collectionByRawId(collection, id) {\n if (!id)\n return null;\n for (const model of models(collection)) {\n const row = modelData(model);\n if (rawId(row.id ?? model?.id) === id)\n return model;\n }\n return null;\n }\n function reactionTargetId(row) {\n return rawId(row.reactionParentKey) ?? rawId(row.parentMsgKey) ?? rawId(row.parentMessageKey) ?? (typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : null);\n }\n function normalizeReactions(row) {\n const source = row.reactions ?? row.reactionCollection ?? row.reactionsBySender;\n return (Array.isArray(source) ? source : models(source)).map((reaction) => {\n const data = modelData(reaction);\n return {\n emoji: data.text ?? data.reactionText ?? data.emoji ?? null,\n sender_jid: widString(data.senderUserJid ?? data.sender ?? data.author),\n from_me: Boolean(data.fromMe)\n };\n }).filter((reaction) => typeof reaction.emoji === \"string\" && reaction.emoji.length > 0);\n }\n function nameIndex(collections) {\n const byId = (collection) => {\n const map = new Map;\n for (const model of models(collection)) {\n const id = widString(modelData(model).id ?? model?.id);\n if (id && !map.has(id))\n map.set(id, model);\n }\n return map;\n };\n return { chats: byId(collections?.Chat), contacts: byId(collections?.Contact) };\n }\n function contactName(names, jid) {\n if (!jid)\n return null;\n const contact = names?.contacts?.get(jid);\n if (!contact)\n return null;\n const row = modelData(contact);\n return row.name ?? row.pushname ?? row.shortName ?? row.formattedName ?? null;\n }\n function chatName(names, jid) {\n if (!jid)\n return null;\n const chat = names?.chats?.get(jid);\n if (!chat)\n return null;\n const row = modelData(chat);\n return row.name ?? row.formattedTitle ?? row.contact?.name ?? row.contact?.pushname ?? null;\n }\n async function normalizeMessage(model, eventType = \"snapshot\", collectionsOverride = null, names = null) {\n const collections = collectionsOverride ?? requireFirst([\"WAWebCollections\"]);\n if (!collections)\n return null;\n const nameLookup = names ?? nameIndex(collections);\n let row = modelData(model), key = row.id ?? model?.id, id = rawId(key);\n if (!id)\n return null;\n if (row.type === \"reaction\") {\n const targetId = reactionTargetId(row), target = collectionByRawId(collections.Msg, targetId);\n if (target) {\n model = target;\n row = modelData(model);\n key = row.id ?? model?.id;\n id = rawId(key);\n }\n }\n const fromMe = Boolean(key?.fromMe ?? row.fromMe), remoteRaw = key?.remote ?? row.chatId, fromRaw = row.from, toRaw = row.to, authorRaw = row.author ?? key?.participant, chatRaw = remoteRaw ?? (fromMe ? toRaw : fromRaw), chat = await canonicalJid(chatRaw);\n if (!chat.jid || isBroadcastOnlyJid(chat.jid))\n return null;\n const senderRaw = fromMe ? fromRaw : authorRaw ?? fromRaw, sender = await canonicalJid(senderRaw), participant = await canonicalJid(key?.participant ?? row.participant ?? (fromMe ? toRaw : null)), timestamp = unixSeconds(row), body = typeof row.body === \"string\" ? row.body : \"\", caption = typeof row.caption === \"string\" ? row.caption : \"\", quotedId = typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : rawId(row.quotedMsg?.id ?? row.quotedMsgKey), type = typeof row.type === \"string\" ? row.type : \"unknown\";\n return {\n id,\n chat_jid: chat.jid,\n chat_lid: chat.lid,\n chat_name: chatName(nameLookup, widString(chatRaw)),\n sender_jid: sender.jid,\n sender_lid: sender.lid,\n push_name: contactName(nameLookup, widString(senderRaw)) ?? row.notifyName ?? null,\n participant: participant.jid,\n from_me: fromMe,\n is_group: chat.jid.endsWith(\"@g.us\"),\n timestamp,\n occurred_at: timestamp > 0 ? new Date(timestamp * 1000).toISOString() : null,\n body,\n caption,\n message_type: type,\n media_kind: type === \"ptt\" ? \"audio\" : [\"image\", \"video\", \"audio\", \"document\", \"sticker\"].includes(type) ? type : null,\n media_type: typeof row.mimetype === \"string\" ? row.mimetype : null,\n media_size: Number.isFinite(Number(row.size ?? row.fileSize)) ? Number(row.size ?? row.fileSize) : null,\n media_filename: row.filename ?? row.fileName ?? row.title ?? null,\n quoted_id: quotedId,\n mentions_me: await mentionsOwnAccount(row),\n own_mention_jids: await ownMentionJids(row),\n is_forwarded: Boolean(row.isForwarded || Number(row.forwardingScore) > 0),\n is_starred: Boolean(row.star ?? row.isStarred),\n is_system_event: SYSTEM_TYPES.has(type),\n edited: Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey),\n edit_timestamp: Number(row.editTimestamp ?? row.lastEditTimestamp) || null,\n revoked: Boolean(row.isRevoked || row.revoked || type === \"revoked\"),\n reactions: normalizeReactions(row),\n event_type: eventType\n };\n }\n function readiness() {\n if (typeof window.require !== \"function\")\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"whatsapp_runtime_unavailable\"\n };\n const collections = requireFirst([\"WAWebCollections\"]);\n if (!collections?.Msg || !collections?.Chat)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"collections_unavailable\"\n };\n const me = meUser(), qrVisible = Boolean(document.querySelector('[data-testid=\"qrcode\"], canvas[aria-label*=\"Scan\" i], [data-ref] canvas'));\n if (!me && qrVisible)\n return { ready: !1, state: \"logged_out\", reason: \"qr_code_visible\" };\n if (!me)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"authenticated_self_identity_unavailable\"\n };\n const socket = requireFirst([\"WAWebSocketModel\"])?.Socket, connection = socket ?? requireFirst([\"WAWebSocketState\", \"WAWebConn\", \"WAWebConnectionState\"]), connectionState = String(connection?.getSocketState?.() ?? connection?.state ?? connection?.socketState ?? \"\").toLowerCase();\n if (!connectionState)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"connection_state_unavailable\"\n };\n if (!/^(connected|open|ready|syncing)$/.test(connectionState))\n return {\n ready: !1,\n state: \"not_ready\",\n reason: `connection_${connectionState}`\n };\n if (socket) {\n const stream = String(socket.stream ?? \"\").toLowerCase();\n if (!stream)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"stream_state_unavailable\"\n };\n if (!/^(connected|open|ready)$/.test(stream))\n return { ready: !1, state: \"not_ready\", reason: `stream_${stream}` };\n if (socket.hasSynced === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n }\n const offlineDelivery = requireFirst([\n \"WAWebOfflineDelivery\",\n \"WAWebOfflineDeliveryState\"\n ]);\n if ((offlineDelivery?.isOfflineDeliveryComplete?.() ?? offlineDelivery?.offlineDeliveryComplete ?? offlineDelivery?.isComplete) === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"offline_delivery_incomplete\"\n };\n const hydration = requireFirst([\n \"WAWebInitialSyncInfo\",\n \"WAWebHistorySync\",\n \"WAWebAppState\"\n ]);\n if ((hydration?.isInitialSyncComplete?.() ?? hydration?.initialSyncComplete ?? hydration?.isHydrated ?? !0) !== !0)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n if (!Array.isArray(collections.Chat._models) && !Array.isArray(collections.Chat.models))\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"chat_store_placeholder\"\n };\n const signature = `${widString(me)}:${models(collections.Chat).length}:${models(collections.Msg).length}`;\n if (signature !== readinessSignature) {\n readinessSignature = signature;\n readinessStableSince = Date.now();\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n }\n if (Date.now() - readinessStableSince < 500)\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n return {\n ready: !0,\n state: \"ready\",\n message_count: models(collections.Msg).length,\n chat_count: models(collections.Chat).length\n };\n }\n function operationCapabilities() {\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]), draft = requireFirst(DRAFT_MODULES), send = requireFirst(SEND_MODULES), edit = requireFirst(EDIT_MODULES), reaction = requireFirst(REACTION_MODULES), revoke = requireFirst(REVOKE_MODULES), hasFunction = (module2, names) => names.some((name) => typeof module2?.[name] === \"function\");\n return {\n read_messages: typeof indexedDB < \"u\" && typeof requireFirst([\"WAWebMsgKey\"])?.fromString === \"function\" && typeof requireFirst([\"WAWebCollections\"])?.Msg?.getMessagesById === \"function\",\n search_messages: hasFunction(search, [\"searchMessages\", \"searchMsgs\", \"search\"]) || Boolean(requireFirst([\"WAWebCollections\"])?.Msg),\n draft_message: hasFunction(draft, [\n \"setDraft\",\n \"setChatDraft\",\n \"saveDraft\"\n ]),\n send_message: hasFunction(send, [\n \"sendTextMsgToChat\",\n \"sendMessage\",\n \"addAndSendTextMsg\"\n ]),\n edit_message: hasFunction(edit, [\"sendMessageEdit\", \"editMessage\"]),\n react_message: hasFunction(reaction, [\n \"sendReactionToMsg\",\n \"sendReaction\"\n ]),\n revoke_message: hasFunction(revoke, [\"sendRevokeMsgs\", \"revokeMessage\"])\n };\n }\n function uniqueMessageModels(collections) {\n const byId = new Map;\n for (const message of models(collections.Msg)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n for (const chat of models(collections.Chat))\n for (const message of models(modelData(chat).msgs ?? chat?.msgs)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n return [...byId.values()];\n }\n async function resolveChat(collections, input) {\n if (input?.self_chat === !0) {\n const me = meUser(), selfJid = (await canonicalJid(me)).jid;\n let self = null;\n for (const chat of models(collections.Chat))\n if ((await canonicalJid(modelData(chat).id ?? chat?.id)).jid === selfJid) {\n self = chat;\n break;\n }\n if (!self)\n throw Error(\"WhatsApp self chat is not loaded\");\n return self;\n }\n const requestedJidRaw = typeof input?.chat_jid === \"string\" ? input.chat_jid.trim().toLowerCase() : null, requestedJid = requestedJidRaw ? (await canonicalJid(requestedJidRaw)).jid : null, requestedName = typeof input?.chat_name === \"string\" ? input.chat_name.trim().toLowerCase() : null, matches = [];\n for (const chat of models(collections.Chat)) {\n const row = modelData(chat), jid = (await canonicalJid(row.id ?? chat?.id)).jid, name = String(row.name ?? row.formattedTitle ?? row.contact?.name ?? \"\").trim().toLowerCase();\n if (requestedJid ? jid === requestedJid : requestedName && name === requestedName)\n matches.push(chat);\n }\n if (matches.length === 0)\n throw Error(\"WhatsApp chat not found; pass an exact canonical chat_jid or exact chat_name\");\n if (matches.length > 1)\n throw Error(\"WhatsApp chat name is ambiguous; pass chat_jid\");\n return matches[0];\n }\n async function waitForPostState(check, label, timeoutMs = 2000) {\n const deadline = Date.now() + timeoutMs;\n do {\n if (check())\n return;\n await new Promise((resolve) => setTimeout(resolve, 50));\n } while (Date.now() < deadline);\n throw Error(`WhatsApp did not confirm ${label}`);\n }\n async function readMessages(input = {}, account) {\n const query = String(input.query ?? \"\").trim(), chatFilter = input.chat_filter ?? \"all\", limit = Math.min(100, Math.max(1, Math.trunc(Number(input.limit) || 50)));\n let before = null;\n if (input.cursor) {\n const cursor = JSON.parse(input.cursor);\n if (cursor.v !== 1 || !Number.isSafeInteger(cursor.before) || cursor.before <= 0 || cursor.query !== query || cursor.chat_filter !== chatFilter || cursor.account !== account)\n throw Error(\"Invalid WhatsApp source cursor or changed query scope\");\n before = cursor.before;\n }\n const keyModule = requireFirst([\"WAWebMsgKey\"]), exactId = query.startsWith(\"id:\") ? query.slice(3) : null;\n let chatJid = null;\n if (query.startsWith(\"chat:\")) {\n const chat = await resolveChat(requireFirst([\"WAWebCollections\"]), { chat_jid: query.slice(5) });\n chatJid = (await canonicalJid(modelData(chat).id ?? chat?.id)).jid;\n }\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n });\n let sourceRows;\n try {\n sourceRows = await new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source read aborted\"));\n const index = transaction.objectStore(\"message\").index(\"rowId\"), range = before === null ? null : IDBKeyRange.upperBound(before, !0), request = index.openCursor(range, \"prev\"), rows = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(rows);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\") {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n if (exactId !== null) {\n if (keyModule.fromString(cursor.value.id).id !== exactId) {\n cursor.continue();\n return;\n }\n resolve([{ position: cursor.key, id: cursor.value.id }]);\n return;\n }\n rows.push({ position: cursor.key, id: cursor.value.id });\n if (rows.length > (chatJid === null ? limit : 20000))\n resolve(rows);\n else\n cursor.continue();\n };\n });\n } finally {\n database.close();\n }\n let hasMore = sourceRows.length > limit, page = sourceRows.slice(0, limit), last = page[page.length - 1];\n if (chatJid !== null) {\n const examined = sourceRows.slice(0, 20000), canonical = new Map, matches = [];\n for (const row of examined) {\n const remote = keyModule.fromString(row.id).remote, raw = widString(remote);\n if (!canonical.has(raw))\n canonical.set(raw, (await canonicalJid(remote)).jid);\n if (canonical.get(raw) !== chatJid)\n continue;\n matches.push(row);\n if (matches.length > limit)\n break;\n }\n page = matches.slice(0, limit);\n hasMore = matches.length > limit || sourceRows.length > 20000;\n last = matches.length > limit ? page[page.length - 1] : examined[examined.length - 1];\n }\n const collections = requireFirst([\"WAWebCollections\"]), selected = [];\n for (const row of page) {\n const key = keyModule.fromString(row.id);\n if (exactId !== null && key.id !== exactId)\n continue;\n const remote = widString(key.remote);\n if (isBroadcastOnlyJid(remote))\n continue;\n const isGroup = remote.endsWith(\"@g.us\");\n if (chatFilter === \"group\" && !isGroup || chatFilter === \"individual\" && isGroup)\n continue;\n selected.push(row);\n }\n const results = [];\n if (selected.length) {\n const loaded = await collections.Msg.getMessagesById(selected.map((row) => row.id));\n if (loaded?.canceled || !Array.isArray(loaded?.messages))\n throw Error(\"Source message loading was canceled or unavailable\");\n const byKey = new Map(loaded.messages.map((model) => [String(model.id ?? modelData(model).id), model])), names = nameIndex(collections);\n for (const row of selected) {\n const model = byKey.get(row.id);\n if (!model)\n throw Error(\"Source message could not be loaded; retry the read\");\n const message = await normalizeMessage(model, \"snapshot\", collections, names);\n if (!message || message.timestamp <= 0)\n continue;\n if (exactId === null && chatJid === null && query && !`${message.body}\n${message.caption}`.toLowerCase().includes(query.toLowerCase()))\n continue;\n results.push(message);\n }\n }\n return {\n results,\n hasMore,\n ...hasMore ? { nextCursor: JSON.stringify({ v: 1, before: last.position, query, chat_filter: chatFilter, account }) } : {}\n };\n }\n async function searchMessages(input) {\n const collections = requireFirst([\"WAWebCollections\"]), query = String(input?.query ?? \"\").trim();\n if (!query)\n throw Error(\"query is required\");\n const offset = Math.max(0, Number(input?.offset) || 0), requestedLimit = Math.max(1, Math.min(Number(input?.limit) || 50, 100));\n if (offset >= 100)\n throw Error(\"WhatsApp source search supports only the first 100 matches\");\n const limit = Math.min(requestedLimit, 100 - offset), searchSourceLimit = 100, chatFilter = [\"all\", \"individual\", \"group\"].includes(input?.chat_filter) ? input.chat_filter : \"all\", chat = input?.chat_jid || input?.chat_name || input?.self_chat === !0 ? await resolveChat(collections, input) : null;\n let scopedChats = chat ? [chat] : void 0;\n if (!chat && chatFilter !== \"all\") {\n scopedChats = [];\n for (const candidate of models(collections.Chat)) {\n const jid = (await canonicalJid(modelData(candidate).id ?? candidate?.id)).jid;\n if (!jid || isBroadcastOnlyJid(jid))\n continue;\n const isGroup = jid.endsWith(\"@g.us\");\n if (chatFilter === \"group\" ? isGroup : !isGroup)\n scopedChats.push(candidate);\n }\n }\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]);\n let found = null;\n for (const fn of [\n search?.searchMessages,\n search?.searchMsgs,\n search?.search\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n found = await fn.call(search, query, scopedChats, searchSourceLimit);\n break;\n } catch {}\n }\n let source = \"whatsapp_fts\", candidates = Array.isArray(found) ? found : models(found?.messages ?? found);\n if (!found) {\n source = \"loaded_model_fallback\";\n const needle = query.toLowerCase();\n candidates = uniqueMessageModels(collections).filter((model) => {\n const row = modelData(model);\n if (chat) {\n const chatId = widString(modelData(chat).id ?? chat?.id);\n if (widString(row.id?.remote ?? row.chatId) !== chatId)\n return !1;\n }\n return String(row.body ?? row.caption ?? \"\").toLowerCase().includes(needle);\n });\n }\n const normalized = [], names = nameIndex(collections);\n for (const candidate of candidates) {\n const model = candidate?.msg ?? candidate?.message ?? candidate, message = await normalizeMessage(model, \"search\", collections, names);\n if (!message || Number(message.timestamp) <= 0)\n continue;\n if (chatFilter === \"group\" && !message.is_group)\n continue;\n if (chatFilter === \"individual\" && message.is_group)\n continue;\n normalized.push(message);\n if (normalized.length >= searchSourceLimit)\n break;\n }\n return {\n source,\n results: normalized.slice(offset, offset + limit),\n hasMore: offset + limit < normalized.length\n };\n }\n async function draftMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const draft = {\n body: text,\n timestamp: Math.floor(Date.now() / 1000),\n type: \"chat\",\n mentionedJidList: [],\n quotedMsg: null\n }, module2 = requireFirst(DRAFT_MODULES);\n let applied = !1;\n for (const fn of [\n module2?.setDraft,\n module2?.setChatDraft,\n module2?.saveDraft\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n assertAccount(account);\n await fn.call(module2, chat, draft);\n applied = !0;\n break;\n } catch {\n try {\n assertAccount(account);\n await fn.call(module2, draft, chat);\n applied = !0;\n break;\n } catch {}\n }\n }\n if (!applied && typeof chat?.setDraft === \"function\") {\n assertAccount(account);\n await chat.setDraft(draft);\n applied = !0;\n }\n if (!applied)\n throw Error(\"WhatsApp draft capability is unavailable in this web build\");\n const stored = modelData(chat).draft ?? chat.get?.(\"draft\") ?? null;\n if (!stored || typeof stored !== \"object\" || stored.body !== text)\n throw Error(\"WhatsApp rejected the persistent draft shape\");\n return {\n drafted: !0,\n sent: !1,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n draft\n };\n }\n async function sendMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), chatJid = (await canonicalJid(modelData(chat).id ?? chat?.id)).jid;\n if (chatJid && isBroadcastOnlyJid(chatJid))\n throw Error(`WhatsApp chat ${chatJid} does not accept messages`);\n const text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(SEND_MODULES);\n if (typeof module2?.createTextMsgData === \"function\" && typeof module2?.addAndSendTextMsg === \"function\") {\n const data = await module2.createTextMsgData(chat, text), plannedId = rawId(data?.id);\n if (!plannedId)\n throw Error(\"WhatsApp did not assign an id to the outgoing message\");\n assertAccount(account);\n await module2.addAndSendTextMsg(chat, data);\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: plannedId\n };\n }\n const fn = module2?.sendTextMsgToChat ?? module2?.sendMessage ?? chat?.sendMessage;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp send capability is unavailable in this web build\");\n assertAccount(account);\n const result = fn === chat?.sendMessage ? await fn.call(chat, text) : await fn.call(module2, chat, text), messageId = rawId(modelData(result).id ?? result?.id);\n if (!messageId)\n throw Error(\"WhatsApp send acknowledgment has no raw message ID\");\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: messageId\n };\n }\n function messageActionAllowed(message, predicateNames, legacyFlags) {\n const row = modelData(message);\n for (const flag of legacyFlags)\n if (row[flag] === !0)\n return !0;\n const capability = requireFirst([\"WAWebMsgActionCapability\"]);\n for (const name of predicateNames) {\n if (typeof capability?.[name] !== \"function\")\n continue;\n try {\n if (capability[name](message) === !0)\n return !0;\n } catch {}\n }\n return !1;\n }\n function resolveMessage(collections, id) {\n const raw = String(id ?? \"\").trim();\n if (!raw)\n throw Error(\"message_id is required\");\n const message = collectionByRawId(collections.Msg, raw);\n if (!message)\n throw Error(`WhatsApp message ${raw} is not loaded; read it with id:${raw} from the live messages feed or search it first`);\n return message;\n }\n async function editMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits editing outgoing messages\");\n if (!messageActionAllowed(message, [\"canEditText\", \"canEditCaption\", \"canEnterEditingFlow\"], [\"canEdit\", \"isEditable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently editable\");\n const text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(EDIT_MODULES), fn = module2?.sendMessageEdit ?? module2?.editMessage ?? message?.edit;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp edit capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.edit ? fn.call(message, text) : fn.call(module2, message, text, {}));\n await waitForPostState(() => {\n const row = modelData(message);\n return row.body === text && Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey);\n }, \"message edit\");\n return {\n edited: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function reactMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), emoji = input?.remove ? \"\" : String(input?.emoji ?? \"\");\n if (!input?.remove && !emoji)\n throw Error(\"emoji is required unless remove=true\");\n const module2 = requireFirst(REACTION_MODULES), fn = module2?.sendReactionToMsg ?? module2?.sendReaction ?? message?.react;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp reaction capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.react ? fn.call(message, emoji) : fn.call(module2, message, emoji));\n await waitForPostState(() => {\n const row = modelData(message), reactions = normalizeReactions(row);\n if (reactions.length > 0)\n return input?.remove ? !reactions.some((reaction) => reaction.from_me) : reactions.some((reaction) => reaction.from_me && reaction.emoji === emoji);\n return input?.remove ? !0 : row.hasReaction === !0;\n }, \"reaction state\");\n return {\n reacted: !0,\n confirmed: input?.remove ? normalizeReactions(modelData(message)).length > 0 : !0,\n removed: Boolean(input?.remove),\n emoji: emoji || null,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function revokeMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits revoking outgoing messages\");\n if (!messageActionAllowed(message, [\"canSenderRevokeMsg\", \"canAdminRevokeMsg\"], [\"canRevoke\", \"isRevokable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently revokable\");\n const module2 = requireFirst(REVOKE_MODULES), fn = module2?.sendRevokeMsgs ?? module2?.sendRevoke ?? module2?.revokeMessage ?? message?.sendRevoke ?? message?.revoke;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp revoke capability is unavailable in this web build\");\n assertAccount(account);\n if (fn === message?.sendRevoke || fn === message?.revoke)\n await fn.call(message);\n else\n await fn.call(module2, [message], modelData(message).id?.remote);\n await waitForPostState(() => {\n const row = modelData(message);\n return Boolean(row.isRevoked || row.revoked || row.type === \"revoked\");\n }, \"message revoke\");\n return {\n revoked: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function invoke(request) {\n try {\n if (Number(request?.adapter_version) !== 28)\n return {\n ok: !1,\n error: {\n state: \"adapter_mismatch\",\n reason: \"expected 28\"\n }\n };\n if (request.op === \"account_identity\") {\n const accountId = widString(meUser());\n return accountId ? { accountId } : null;\n }\n if (request.op === \"probe\") {\n const status = readiness();\n return status.ready ? { ok: !0, status, capabilities: operationCapabilities() } : { ok: !1, error: status };\n }\n assertAccount(request.account_id);\n const input = { ...request.input, account_id: request.account_id }, finish = async (promise) => {\n const value = await promise;\n assertAccount(request.account_id);\n return { ok: !0, ...value };\n };\n if (request.op === \"listen\")\n return listen(request);\n if (request.op === \"publish_changes\")\n return await publishChanges(request);\n if (request.op === \"observe_messages\")\n return await finish(observeMessages(input));\n if (operationCapabilities()[request.op] !== !0)\n return {\n ok: !1,\n error: {\n state: \"capability_unavailable\",\n reason: `${request.op} is unavailable in this WhatsApp Web build`\n }\n };\n if (request.op === \"read_messages\")\n return await finish(readMessages(input, request.account_id));\n if (request.op === \"search_messages\")\n return await finish(searchMessages(input));\n if (request.op === \"draft_message\")\n return await finish(draftMessage(input, request.account_id));\n if (request.op === \"send_message\")\n return await finish(sendMessage(input, request.account_id));\n if (request.op === \"edit_message\")\n return await finish(editMessage(input, request.account_id));\n if (request.op === \"react_message\")\n return await finish(reactMessage(input, request.account_id));\n if (request.op === \"revoke_message\")\n return await finish(revokeMessage(input, request.account_id));\n return {\n ok: !1,\n error: { state: \"unsupported_operation\", reason: String(request?.op) }\n };\n } catch (error) {\n if (request?.account_id && widString(meUser()) !== request.account_id)\n error = Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n return {\n ok: !1,\n error: {\n state: \"operation_failed\",\n reason: error instanceof Error ? error.message : String(error)\n }\n };\n }\n }\n globalThis.__owlettoWhatsAppAdapterV1 = { version: 28, invoke, detach };\n })();\n for (let i = 0; i < 40; i++) {\n const identity = await globalThis.__owlettoWhatsAppAdapterV1.invoke({ op: \"account_identity\", adapter_version: 28 });\n if (identity?.accountId) return identity;\n await new Promise(resolve => setTimeout(resolve, 250));\n }\n return null;\n })()"
|
|
21696
|
+
"expression": "(async () => {\n (function whatsAppWebAdapterProgram(adapterVersion) {\n const ADAPTER_VERSION = adapterVersion;\n if (typeof ADAPTER_VERSION !== \"string\" || !ADAPTER_VERSION)\n throw Error(\"WhatsApp adapter must be installed with its content version\");\n const SOURCE_ERROR_ID = \"whatsapp-web:source-observation-error\", CHAT_SCAN_ROWS = 20000, MAX_RECORD_BYTES = 131072, MAX_BUFFER_BYTES = 16777216, MAX_BUFFER_ENTRIES = 1e4, SYSTEM_TYPES = new Set([\n \"gp2\",\n \"notification_template\",\n \"e2e_notification\"\n ]);\n let readinessSignature = null, readinessStableSince = 0;\n const existing = globalThis.__owlettoWhatsAppAdapterV1;\n if (existing?.version === ADAPTER_VERSION)\n return;\n existing?.detach?.(void 0, \"WhatsApp adapter was replaced; recovery is required\");\n const listeners = new Map;\n function detach(bindingId, reason) {\n const selected = bindingId ? [listeners.get(bindingId)] : [...listeners.values()];\n for (const state of selected) {\n if (!state)\n continue;\n if (reason) {\n state.error = reason;\n state.post({ sequence: ++state.sequence, record: { id: SOURCE_ERROR_ID, source_error: reason } });\n }\n for (const entry of state.pending.values())\n entry.reject?.(Error(reason ?? \"Source listener was detached\"));\n state.collection.off(\"add\", state.onAdd);\n state.collection.off(\"change\", state.onChange);\n window.removeEventListener(\"message\", state.onReply);\n listeners.delete(state.id);\n }\n }\n function assertAccount(account) {\n if (typeof account !== \"string\" || !account || widString(meUser()) !== account)\n throw Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n }\n async function digest(value) {\n const bytes = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n function listen(request) {\n assertAccount(request.account_id);\n const collection = requireFirst([\"WAWebCollections\"])?.Msg;\n if (typeof collection?.on !== \"function\" || typeof collection?.off !== \"function\")\n throw Error(\"WhatsApp message observation is unavailable in this build\");\n if (!request.bridge_id || !request.token)\n throw Error(\"A feed bridge is required\");\n const post = (state2, entry) => window.postMessage({\n type: \"lobu-feed-record\",\n token: state2.token,\n sequence: entry.sequence,\n record: entry.record\n }, location.origin), reportError = (state2, message, sequence = ++state2.sequence) => {\n state2.error = message;\n post(state2, {\n sequence,\n record: {\n id: SOURCE_ERROR_ID,\n source_error: message\n }\n });\n }, resident = listeners.get(request.bridge_id), previous = resident?.request.account_id === request.account_id && resident?.request.chat_filter === request.chat_filter && resident?.request.minimum_timestamp === request.minimum_timestamp ? resident : null;\n detach(request.bridge_id);\n const state = {\n ...previous ?? {\n id: request.bridge_id,\n collection,\n sequence: 0,\n pending: new Map,\n fingerprints: new Map,\n pendingBytes: 0,\n fingerprintBytes: 0,\n error: null\n },\n collection,\n error: null\n };\n state.token = request.token;\n state.request = request;\n state.post = (entry) => post(state, entry);\n const observe = (model) => {\n if (state.error)\n return;\n const sequence = ++state.sequence;\n new Promise((resolve) => {\n assertAccount(state.request.account_id);\n resolve(messageReference(model));\n }).then((record) => {\n if (listeners.get(state.id) !== state)\n return;\n assertAccount(state.request.account_id);\n if (!record || record.timestamp <= 0)\n return;\n if (state.request.chat_filter === \"group\" && !record.is_group)\n return;\n if (state.request.chat_filter === \"individual\" && record.is_group)\n return;\n if (state.request.minimum_timestamp != null && record.timestamp < state.request.minimum_timestamp)\n return;\n record = {\n id: record.id,\n events: [{\n id: record.id,\n event_type: \"message.created\",\n resource_ref: record.id,\n resource_type: \"message\",\n occurred_at: new Date(record.timestamp * 1000).toISOString()\n }]\n };\n const previous2 = state.pending.get(record.id), seen = state.fingerprints.get(record.id);\n if (seen && seen.sequence >= sequence)\n return;\n const fingerprint = JSON.stringify(record);\n if (seen?.fingerprint === fingerprint) {\n seen.sequence = sequence;\n return;\n }\n const bytes = new TextEncoder().encode(fingerprint).length;\n if (bytes > MAX_RECORD_BYTES || state.pendingBytes - (previous2?.bytes ?? 0) + bytes > MAX_BUFFER_BYTES || state.pending.size >= MAX_BUFFER_ENTRIES && !previous2) {\n reportError(state, \"WhatsApp page observation buffer overflowed; recovery is required\", sequence);\n return;\n }\n const entry = { sequence, record, bytes };\n state.pendingBytes += bytes - (previous2?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.fingerprintBytes += bytes - (seen?.bytes ?? 0);\n state.fingerprints.delete(record.id);\n state.fingerprints.set(record.id, { fingerprint, sequence, bytes });\n while (state.fingerprints.size > MAX_BUFFER_ENTRIES || state.fingerprintBytes > MAX_BUFFER_BYTES) {\n const oldest = state.fingerprints.keys().next().value;\n state.fingerprintBytes -= state.fingerprints.get(oldest).bytes;\n state.fingerprints.delete(oldest);\n }\n post(state, entry);\n }).catch(() => {\n if (listeners.get(state.id) !== state)\n return;\n reportError(state, \"WhatsApp source observation failed; recovery is required\", sequence);\n });\n };\n state.onAdd = (model) => observe(model);\n state.onChange = (model) => observe(model);\n state.onReply = (event) => {\n if (event.source !== window || event.origin !== location.origin || event.data?.token !== state.token)\n return;\n if (event.data.type === \"lobu-feed-record:stop\") {\n detach(state.id);\n return;\n }\n if (event.data.type !== \"lobu-feed-record:ack\")\n return;\n try {\n assertAccount(state.request.account_id);\n } catch {\n detach(state.id, \"WhatsApp saved account changed; recovery is required\");\n return;\n }\n for (const [id, entry] of state.pending) {\n if (entry.sequence !== event.data.sequence)\n continue;\n if (event.data.ok) {\n state.pendingBytes -= entry.bytes;\n state.pending.delete(id);\n entry.resolve?.();\n } else\n entry.reject?.(Error(\"Browser rejected the source reference batch\"));\n break;\n }\n };\n listeners.set(state.id, state);\n try {\n collection.on(\"add\", state.onAdd);\n collection.on(\"change\", state.onChange);\n window.addEventListener(\"message\", state.onReply);\n } catch (error) {\n reportError(state, \"WhatsApp source observation failed; recovery is required\");\n throw error;\n }\n if (previous?.error)\n post(state, {\n sequence: ++state.sequence,\n record: { id: SOURCE_ERROR_ID, source_error: previous.error }\n });\n for (const entry of state.pending.values())\n post(state, entry);\n return { ok: !0, listening: !0 };\n }\n async function publishChanges(request) {\n const state = listeners.get(request.bridge_id);\n if (!state || state.token !== request.token)\n throw Error(\"Source listener is unavailable\");\n assertAccount(state.request.account_id);\n const record = { ...request.batch, id: `replay:${await digest(JSON.stringify([request.transition ?? null, request.batch]))}` };\n if (listeners.get(state.id) !== state)\n throw Error(\"Source listener was replaced\");\n assertAccount(state.request.account_id);\n const bytes = new TextEncoder().encode(JSON.stringify(record)).length, previous = state.pending.get(record.id);\n if (bytes > MAX_RECORD_BYTES || state.pendingBytes - (previous?.bytes ?? 0) + bytes > MAX_BUFFER_BYTES || state.pending.size >= MAX_BUFFER_ENTRIES && !previous)\n throw Error(\"Source replay buffer is full\");\n await new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(Error(\"Source replay was not accepted by the browser\")), 1e4), entry = {\n record,\n bytes,\n sequence: ++state.sequence,\n resolve: () => {\n clearTimeout(timer);\n resolve();\n },\n reject: (error) => {\n clearTimeout(timer);\n reject(error);\n }\n };\n state.pendingBytes += bytes - (previous?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.post(entry);\n });\n return { ok: !0 };\n }\n function requireFirst(names) {\n for (const name of names)\n try {\n const module2 = window.require?.(name);\n if (module2)\n return module2;\n } catch {}\n return null;\n }\n function meUser() {\n const module2 = requireFirst([\n \"WAWebUserPrefsMeUser\",\n \"WAWebUserPrefsMe\",\n \"WAWebUserPrefs\"\n ]);\n if (!module2)\n return null;\n for (const accessor of [\n \"getMaybeMePnUser\",\n \"getMaybeMeUser\",\n \"getMeUser\",\n \"getMeUserOrThrow\",\n \"getMaybeMeLidUser\"\n ])\n try {\n const value = module2[accessor]?.();\n if (value)\n return value;\n } catch {}\n try {\n return module2.me ?? null;\n } catch {}\n return null;\n }\n async function ownJids() {\n const module2 = requireFirst([\"WAWebUserPrefsMeUser\"]), candidates = [meUser()];\n for (const accessor of [\"getMaybeMePnUser\", \"getMaybeMeLidUser\"])\n try {\n candidates.push(module2?.[accessor]?.());\n } catch {}\n const forms = new Set;\n for (const value of candidates) {\n const own = await canonicalJid(value);\n if (own.jid)\n forms.add(own.jid);\n if (own.lid)\n forms.add(own.lid);\n }\n return forms;\n }\n async function mentionsOwnAccount(row) {\n const addressed = [\n ...Array.isArray(row.mentionedJidList) ? row.mentionedJidList : [],\n row.quotedParticipant\n ].filter(Boolean);\n if (addressed.length === 0)\n return !1;\n const own = await ownJids();\n for (const value of addressed) {\n const candidate = await canonicalJid(value);\n if (own.has(candidate.jid) || candidate.lid && own.has(candidate.lid))\n return !0;\n }\n return !1;\n }\n async function ownMentionJids(row) {\n const mentions = Array.isArray(row.mentionedJidList) ? row.mentionedJidList : [];\n if (mentions.length === 0)\n return [];\n const own = await ownJids(), mentioned = new Set;\n for (const value of mentions) {\n const candidate = await canonicalJid(value);\n for (const jid of [candidate.jid, candidate.lid])\n if (typeof jid === \"string\" && /^[0-9]{5,32}@(s\\.whatsapp\\.net|lid)$/.test(jid) && own.has(jid))\n mentioned.add(jid);\n }\n return [...mentioned].slice(0, 2);\n }\n const SEND_MODULES = [\n \"WAWebSendTextMsgChatAction\",\n \"WAWebSendMsgChatAction\",\n \"WAWebSendMessage\"\n ], REACTION_MODULES = [\n \"WAWebSendReactionMsgAction\",\n \"WAWebSendReactionMsg\",\n \"WAWebReactionAction\"\n ], REVOKE_MODULES = [\n \"WAWebChatSendMessages\",\n \"WAWebRevokeMsgAction\",\n \"WAWebDeleteChatAction\",\n \"WAWebRevokeMessage\"\n ], EDIT_MODULES = [\"WAWebSendMessageEditAction\", \"WAWebEditMessage\"], DRAFT_MODULES = [\n \"WAWebChatDraftUtils\",\n \"WAWebSetDraft\",\n \"WAWebComposeBoxActions\"\n ];\n function modelData(model) {\n return model?.attributes ?? model?._data ?? model ?? {};\n }\n function messageReference(model) {\n const row = modelData(model), key = row.id ?? model?.id, id = rawId(key), remote = widString(key?.remote ?? row.chatId ?? (key?.fromMe ? row.to : row.from));\n if (!id || !remote || isBroadcastOnlyJid(remote) || SYSTEM_TYPES.has(row.type))\n return null;\n return { id, timestamp: unixSeconds(row), is_group: remote.endsWith(\"@g.us\") };\n }\n async function observeMessages(input = {}) {\n const after = input.after ?? null;\n if (after !== null && (!Number.isSafeInteger(after) || after < 0))\n throw Error(\"Invalid WhatsApp observation cursor\");\n const pending = input.unresolved ?? [];\n if (!Array.isArray(pending) || pending.length > 32 || pending.some((row) => !Number.isSafeInteger(row.position) || row.position <= 0 || typeof row.id !== \"string\" || row.id.length > 512 || !Number.isSafeInteger(row.first_seen) || row.first_seen < 0))\n throw Error(\"Invalid WhatsApp pending placeholder cursor\");\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n }), now = Math.floor(Date.now() / 1000), gaps = [], gap = (reason, detail) => gaps.push({ reason, detail }), scan = (position, limit, direction = \"next\", inclusive = !1) => new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source observation aborted\"));\n const request = transaction.objectStore(\"message\").index(\"rowId\").openCursor(position === null ? null : IDBKeyRange.lowerBound(position, !inclusive), direction), page2 = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(page2);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\" || cursor.value.id.length > 512) {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n page2.push({ position: cursor.key, id: cursor.value.id, timestamp: unixSeconds(cursor.value), type: cursor.value.type });\n if (page2.length >= limit)\n resolve(page2);\n else\n cursor.continue();\n };\n });\n let rows, rechecks;\n try {\n if (after === null) {\n rows = await scan(null, 1, \"prev\");\n const head = rows[0];\n return {\n after: head?.position ?? 0,\n anchor: head?.id ?? null,\n unresolved: head?.timestamp === 0 ? [{ position: head.position, id: head.id, first_seen: now }] : [],\n references: [],\n gaps: [],\n hasMore: !1\n };\n }\n let start = after;\n if (after > 0) {\n const [anchor] = await scan(after, 1, \"next\", !0);\n if (!input.anchor || anchor?.position !== after || anchor.id !== input.anchor) {\n gap(\"history-continuity\", [after, input.anchor ?? null]);\n start = 0;\n }\n }\n rechecks = await Promise.all(pending.map(async (item) => ({ item, row: (await scan(item.position, 1, \"next\", !0))[0] })));\n rows = await scan(start, 501);\n } finally {\n database.close();\n }\n const page = rows.slice(0, 500), references = new Map, unresolved = new Map, keys = requireFirst([\"WAWebMsgKey\"]);\n if ((page.length || rechecks.length) && typeof keys?.fromString !== \"function\")\n throw Error(\"WhatsApp source message keys are unavailable\");\n const accept = (row, firstSeen = now) => {\n const reference = messageReference({ id: keys.fromString(row.id), t: row.timestamp, type: row.type });\n if (!reference)\n return;\n if (input.chat_filter === \"group\" && !reference.is_group)\n return;\n if (input.chat_filter === \"individual\" && reference.is_group)\n return;\n if (reference.timestamp <= 0) {\n if (now - firstSeen >= 604800)\n gap(\"placeholder-expired\", [row.position, row.id, firstSeen]);\n else if (unresolved.size < 32 || unresolved.has(row.id))\n unresolved.set(row.id, { position: row.position, id: row.id, first_seen: firstSeen });\n else\n gap(\"placeholder-capacity\", [row.position, row.id]);\n return;\n }\n if (reference.timestamp >= input.started_at)\n references.set(reference.id, reference);\n }, checked = new Set;\n for (const { item, row } of rechecks)\n if (!row || row.position !== item.position || row.id !== item.id)\n gap(\"placeholder-unavailable\", [item.position, item.id]);\n else {\n checked.add(item.id);\n accept(row, item.first_seen);\n }\n for (const row of page)\n if (!checked.has(row.id))\n accept(row);\n const last = page[page.length - 1], rebased = gaps.some((item) => item.reason === \"history-continuity\");\n return {\n after: last?.position ?? (rebased ? 0 : after),\n anchor: last?.id ?? (rebased ? null : input.anchor ?? null),\n unresolved: [...unresolved.values()],\n references: [...references.values()],\n hasMore: rows.length > 500,\n gaps: await Promise.all(gaps.map(async (item) => {\n const identity = await digest(JSON.stringify([input.account_id, input.started_at, input.chat_filter, item]));\n return {\n id: `gap:${identity}`,\n event_type: \"source.gap\",\n resource_type: \"message\",\n resource_ref: `whatsapp:${item.reason}:${identity}`\n };\n }))\n };\n }\n function models(collection) {\n if (Array.isArray(collection?._models))\n return collection._models;\n if (Array.isArray(collection?.models))\n return collection.models;\n if (typeof collection?.toArray === \"function\")\n try {\n return collection.toArray();\n } catch {}\n return [];\n }\n function isBroadcastOnlyJid(jid) {\n return jid === \"status@broadcast\" || jid.endsWith(\"@newsletter\") || jid === \"0@c.us\" || jid === \"0@s.whatsapp.net\";\n }\n function widString(value) {\n if (typeof value === \"string\")\n return value;\n if (!value)\n return null;\n if (typeof value._serialized === \"string\")\n return value._serialized;\n try {\n const rendered = value.toString?.();\n return rendered && rendered !== \"[object Object]\" ? String(rendered) : null;\n } catch {\n return null;\n }\n }\n function rawId(value) {\n if (typeof value === \"string\")\n return value && !/^(?:true|false)_/i.test(value) ? value : null;\n if (typeof value?.id === \"string\")\n return value.id && !/^(?:true|false)_/i.test(value.id) ? value.id : null;\n return null;\n }\n function unixSeconds(row) {\n const value = Number(row?.t ?? row?.timestamp ?? row?.ephemeralStartTimestamp ?? 0);\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n }\n async function canonicalJid(value) {\n const original = widString(value);\n if (!original)\n return { jid: null, lid: null };\n let jid = original.toLowerCase();\n if (jid.endsWith(\"@c.us\"))\n jid = `${jid.slice(0, -5)}@s.whatsapp.net`;\n if (!jid.endsWith(\"@lid\"))\n return { jid, lid: null };\n const migration = requireFirst([\n \"WAWebLidMigrationUtils\",\n \"WAWebLidMigration\"\n ]), toPn = migration?.toPn ?? migration?.getPnForLid ?? migration?.lidToPhone;\n if (typeof toPn === \"function\")\n try {\n const converted = await toPn.call(migration, value), phoneJid = widString(converted);\n if (phoneJid)\n return {\n jid: phoneJid.endsWith(\"@c.us\") ? `${phoneJid.slice(0, -5)}@s.whatsapp.net` : phoneJid,\n lid: jid\n };\n } catch {}\n return { jid, lid: jid };\n }\n function collectionByRawId(collection, id) {\n if (!id)\n return null;\n for (const model of models(collection)) {\n const row = modelData(model);\n if (rawId(row.id ?? model?.id) === id)\n return model;\n }\n return null;\n }\n function reactionTargetId(row) {\n return rawId(row.reactionParentKey) ?? rawId(row.parentMsgKey) ?? rawId(row.parentMessageKey) ?? (typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : null);\n }\n function normalizeReactions(row) {\n const source = row.reactions ?? row.reactionCollection ?? row.reactionsBySender;\n return (Array.isArray(source) ? source : models(source)).map((reaction) => {\n const data = modelData(reaction);\n return {\n emoji: data.text ?? data.reactionText ?? data.emoji ?? null,\n sender_jid: widString(data.senderUserJid ?? data.sender ?? data.author),\n from_me: Boolean(data.fromMe)\n };\n }).filter((reaction) => typeof reaction.emoji === \"string\" && reaction.emoji.length > 0);\n }\n function nameIndex(collections) {\n const byId = (collection) => {\n const map = new Map;\n for (const model of models(collection)) {\n const id = widString(modelData(model).id ?? model?.id);\n if (id && !map.has(id))\n map.set(id, model);\n }\n return map;\n };\n return { chats: byId(collections?.Chat), contacts: byId(collections?.Contact) };\n }\n function contactName(names, jid) {\n if (!jid)\n return null;\n const contact = names?.contacts?.get(jid);\n if (!contact)\n return null;\n const row = modelData(contact);\n return row.name ?? row.pushname ?? row.shortName ?? row.formattedName ?? null;\n }\n function chatName(names, jid) {\n if (!jid)\n return null;\n const chat = names?.chats?.get(jid);\n if (!chat)\n return null;\n const row = modelData(chat);\n return row.name ?? row.formattedTitle ?? row.contact?.name ?? row.contact?.pushname ?? null;\n }\n async function normalizeMessage(model, eventType = \"snapshot\", collectionsOverride = null, names = null) {\n const collections = collectionsOverride ?? requireFirst([\"WAWebCollections\"]);\n if (!collections)\n return null;\n const nameLookup = names ?? nameIndex(collections);\n let row = modelData(model), key = row.id ?? model?.id, id = rawId(key);\n if (!id)\n return null;\n if (row.type === \"reaction\") {\n const targetId = reactionTargetId(row), target = collectionByRawId(collections.Msg, targetId);\n if (target) {\n model = target;\n row = modelData(model);\n key = row.id ?? model?.id;\n id = rawId(key);\n }\n }\n const fromMe = Boolean(key?.fromMe ?? row.fromMe), remoteRaw = key?.remote ?? row.chatId, fromRaw = row.from, toRaw = row.to, authorRaw = row.author ?? key?.participant, chatRaw = remoteRaw ?? (fromMe ? toRaw : fromRaw), chat = await canonicalJid(chatRaw);\n if (!chat.jid || isBroadcastOnlyJid(chat.jid))\n return null;\n const senderRaw = fromMe ? fromRaw : authorRaw ?? fromRaw, sender = await canonicalJid(senderRaw), participant = await canonicalJid(key?.participant ?? row.participant ?? (fromMe ? toRaw : null)), timestamp = unixSeconds(row), body = typeof row.body === \"string\" ? row.body : \"\", caption = typeof row.caption === \"string\" ? row.caption : \"\", quotedId = typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : rawId(row.quotedMsg?.id ?? row.quotedMsgKey), type = typeof row.type === \"string\" ? row.type : \"unknown\";\n return {\n id,\n chat_jid: chat.jid,\n chat_lid: chat.lid,\n chat_name: chatName(nameLookup, widString(chatRaw)),\n sender_jid: sender.jid,\n sender_lid: sender.lid,\n push_name: contactName(nameLookup, widString(senderRaw)) ?? row.notifyName ?? null,\n participant: participant.jid,\n from_me: fromMe,\n is_group: chat.jid.endsWith(\"@g.us\"),\n timestamp,\n occurred_at: timestamp > 0 ? new Date(timestamp * 1000).toISOString() : null,\n body,\n caption,\n message_type: type,\n media_kind: type === \"ptt\" ? \"audio\" : [\"image\", \"video\", \"audio\", \"document\", \"sticker\"].includes(type) ? type : null,\n media_type: typeof row.mimetype === \"string\" ? row.mimetype : null,\n media_size: Number.isFinite(Number(row.size ?? row.fileSize)) ? Number(row.size ?? row.fileSize) : null,\n media_filename: row.filename ?? row.fileName ?? row.title ?? null,\n quoted_id: quotedId,\n mentions_me: await mentionsOwnAccount(row),\n own_mention_jids: await ownMentionJids(row),\n is_forwarded: Boolean(row.isForwarded || Number(row.forwardingScore) > 0),\n is_starred: Boolean(row.star ?? row.isStarred),\n is_system_event: SYSTEM_TYPES.has(type),\n edited: Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey),\n edit_timestamp: Number(row.editTimestamp ?? row.lastEditTimestamp) || null,\n revoked: Boolean(row.isRevoked || row.revoked || type === \"revoked\"),\n reactions: normalizeReactions(row),\n event_type: eventType\n };\n }\n function readiness() {\n if (typeof window.require !== \"function\")\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"whatsapp_runtime_unavailable\"\n };\n const collections = requireFirst([\"WAWebCollections\"]);\n if (!collections?.Msg || !collections?.Chat)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"collections_unavailable\"\n };\n const me = meUser(), qrVisible = Boolean(document.querySelector('[data-testid=\"qrcode\"], canvas[aria-label*=\"Scan\" i], [data-ref] canvas'));\n if (!me && qrVisible)\n return { ready: !1, state: \"logged_out\", reason: \"qr_code_visible\" };\n if (!me)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"authenticated_self_identity_unavailable\"\n };\n const socket = requireFirst([\"WAWebSocketModel\"])?.Socket, connection = socket ?? requireFirst([\"WAWebSocketState\", \"WAWebConn\", \"WAWebConnectionState\"]), connectionState = String(connection?.getSocketState?.() ?? connection?.state ?? connection?.socketState ?? \"\").toLowerCase();\n if (!connectionState)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"connection_state_unavailable\"\n };\n if (!/^(connected|open|ready|syncing)$/.test(connectionState))\n return {\n ready: !1,\n state: \"not_ready\",\n reason: `connection_${connectionState}`\n };\n if (socket) {\n const stream = String(socket.stream ?? \"\").toLowerCase();\n if (!stream)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"stream_state_unavailable\"\n };\n if (!/^(connected|open|ready)$/.test(stream))\n return { ready: !1, state: \"not_ready\", reason: `stream_${stream}` };\n if (socket.hasSynced === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n }\n const offlineDelivery = requireFirst([\n \"WAWebOfflineDelivery\",\n \"WAWebOfflineDeliveryState\"\n ]);\n if ((offlineDelivery?.isOfflineDeliveryComplete?.() ?? offlineDelivery?.offlineDeliveryComplete ?? offlineDelivery?.isComplete) === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"offline_delivery_incomplete\"\n };\n const hydration = requireFirst([\n \"WAWebInitialSyncInfo\",\n \"WAWebHistorySync\",\n \"WAWebAppState\"\n ]);\n if ((hydration?.isInitialSyncComplete?.() ?? hydration?.initialSyncComplete ?? hydration?.isHydrated ?? !0) !== !0)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n if (!Array.isArray(collections.Chat._models) && !Array.isArray(collections.Chat.models))\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"chat_store_placeholder\"\n };\n const signature = `${widString(me)}:${models(collections.Chat).length}:${models(collections.Msg).length}`;\n if (signature !== readinessSignature) {\n readinessSignature = signature;\n readinessStableSince = Date.now();\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n }\n if (Date.now() - readinessStableSince < 500)\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n return {\n ready: !0,\n state: \"ready\",\n message_count: models(collections.Msg).length,\n chat_count: models(collections.Chat).length\n };\n }\n function operationCapabilities() {\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]), draft = requireFirst(DRAFT_MODULES), send = requireFirst(SEND_MODULES), edit = requireFirst(EDIT_MODULES), reaction = requireFirst(REACTION_MODULES), revoke = requireFirst(REVOKE_MODULES), hasFunction = (module2, names) => names.some((name) => typeof module2?.[name] === \"function\");\n return {\n read_messages: typeof indexedDB < \"u\" && typeof requireFirst([\"WAWebMsgKey\"])?.fromString === \"function\" && typeof requireFirst([\"WAWebCollections\"])?.Msg?.getMessagesById === \"function\",\n search_messages: hasFunction(search, [\"searchMessages\", \"searchMsgs\", \"search\"]) || Boolean(requireFirst([\"WAWebCollections\"])?.Msg),\n draft_message: hasFunction(draft, [\n \"setDraft\",\n \"setChatDraft\",\n \"saveDraft\"\n ]),\n send_message: hasFunction(send, [\n \"sendTextMsgToChat\",\n \"sendMessage\",\n \"addAndSendTextMsg\"\n ]),\n edit_message: hasFunction(edit, [\"sendMessageEdit\", \"editMessage\"]),\n react_message: hasFunction(reaction, [\n \"sendReactionToMsg\",\n \"sendReaction\"\n ]),\n revoke_message: hasFunction(revoke, [\"sendRevokeMsgs\", \"revokeMessage\"])\n };\n }\n function uniqueMessageModels(collections) {\n const byId = new Map;\n for (const message of models(collections.Msg)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n for (const chat of models(collections.Chat))\n for (const message of models(modelData(chat).msgs ?? chat?.msgs)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n return [...byId.values()];\n }\n async function resolveChat(collections, input) {\n if (input?.self_chat === !0) {\n const me = meUser(), selfJid = (await canonicalJid(me)).jid;\n let self = null;\n for (const chat of models(collections.Chat))\n if ((await canonicalJid(modelData(chat).id ?? chat?.id)).jid === selfJid) {\n self = chat;\n break;\n }\n if (!self)\n throw Error(\"WhatsApp self chat is not loaded\");\n return self;\n }\n const requestedJidRaw = typeof input?.chat_jid === \"string\" ? input.chat_jid.trim().toLowerCase() : null, requestedJid = requestedJidRaw ? (await canonicalJid(requestedJidRaw)).jid : null, requestedName = typeof input?.chat_name === \"string\" ? input.chat_name.trim().toLowerCase() : null, matches = [];\n for (const chat of models(collections.Chat)) {\n const row = modelData(chat), jid = (await canonicalJid(row.id ?? chat?.id)).jid, name = String(row.name ?? row.formattedTitle ?? row.contact?.name ?? \"\").trim().toLowerCase();\n if (requestedJid ? jid === requestedJid : requestedName && name === requestedName)\n matches.push(chat);\n }\n if (matches.length === 0)\n throw Error(\"WhatsApp chat not found; pass an exact canonical chat_jid or exact chat_name\");\n if (matches.length > 1)\n throw Error(\"WhatsApp chat name is ambiguous; pass chat_jid\");\n return matches[0];\n }\n async function waitForPostState(check, label, timeoutMs = 2000) {\n const deadline = Date.now() + timeoutMs;\n do {\n if (check())\n return;\n await new Promise((resolve) => setTimeout(resolve, 50));\n } while (Date.now() < deadline);\n throw Error(`WhatsApp did not confirm ${label}`);\n }\n async function readMessages(input = {}, account) {\n const query = String(input.query ?? \"\").trim(), chatFilter = input.chat_filter ?? \"all\", limit = Math.min(100, Math.max(1, Math.trunc(Number(input.limit) || 50)));\n let before = null;\n if (input.cursor) {\n const cursor = JSON.parse(input.cursor);\n if (cursor.v !== 1 || !Number.isSafeInteger(cursor.before) || cursor.before <= 0 || cursor.query !== query || cursor.chat_filter !== chatFilter || cursor.account !== account)\n throw Error(\"Invalid WhatsApp source cursor or changed query scope\");\n before = cursor.before;\n }\n const keyModule = requireFirst([\"WAWebMsgKey\"]), exactId = query.startsWith(\"id:\") ? query.slice(3) : null;\n let chatJid = null;\n if (query.startsWith(\"chat:\")) {\n const chat = await resolveChat(requireFirst([\"WAWebCollections\"]), { chat_jid: query.slice(5) });\n chatJid = (await canonicalJid(modelData(chat).id ?? chat?.id)).jid;\n }\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n });\n let sourceRows;\n try {\n sourceRows = await new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source read aborted\"));\n const index = transaction.objectStore(\"message\").index(\"rowId\"), range = before === null ? null : IDBKeyRange.upperBound(before, !0), request = index.openCursor(range, \"prev\"), rows = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(rows);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\") {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n if (exactId !== null) {\n if (keyModule.fromString(cursor.value.id).id !== exactId) {\n cursor.continue();\n return;\n }\n resolve([{ position: cursor.key, id: cursor.value.id }]);\n return;\n }\n rows.push({ position: cursor.key, id: cursor.value.id });\n if (rows.length > (chatJid === null ? limit : CHAT_SCAN_ROWS))\n resolve(rows);\n else\n cursor.continue();\n };\n });\n } finally {\n database.close();\n }\n let hasMore = sourceRows.length > limit, page = sourceRows.slice(0, limit), last = page[page.length - 1];\n if (chatJid !== null) {\n const examined = sourceRows.slice(0, CHAT_SCAN_ROWS), canonical = new Map, matches = [];\n for (const row of examined) {\n const remote = keyModule.fromString(row.id).remote, raw = widString(remote);\n if (!canonical.has(raw))\n canonical.set(raw, (await canonicalJid(remote)).jid);\n if (canonical.get(raw) !== chatJid)\n continue;\n matches.push(row);\n if (matches.length > limit)\n break;\n }\n page = matches.slice(0, limit);\n hasMore = matches.length > limit || sourceRows.length > CHAT_SCAN_ROWS;\n last = matches.length > limit ? page[page.length - 1] : examined[examined.length - 1];\n }\n const collections = requireFirst([\"WAWebCollections\"]), selected = [];\n for (const row of page) {\n const key = keyModule.fromString(row.id);\n if (exactId !== null && key.id !== exactId)\n continue;\n const remote = widString(key.remote);\n if (isBroadcastOnlyJid(remote))\n continue;\n const isGroup = remote.endsWith(\"@g.us\");\n if (chatFilter === \"group\" && !isGroup || chatFilter === \"individual\" && isGroup)\n continue;\n selected.push(row);\n }\n const results = [];\n if (selected.length) {\n const loaded = await collections.Msg.getMessagesById(selected.map((row) => row.id));\n if (loaded?.canceled || !Array.isArray(loaded?.messages))\n throw Error(\"Source message loading was canceled or unavailable\");\n const byKey = new Map(loaded.messages.map((model) => [String(model.id ?? modelData(model).id), model])), names = nameIndex(collections);\n for (const row of selected) {\n const model = byKey.get(row.id);\n if (!model)\n throw Error(\"Source message could not be loaded; retry the read\");\n const message = await normalizeMessage(model, \"snapshot\", collections, names);\n if (!message || message.timestamp <= 0)\n continue;\n if (exactId === null && chatJid === null && query && !`${message.body}\n${message.caption}`.toLowerCase().includes(query.toLowerCase()))\n continue;\n results.push(message);\n }\n }\n return {\n results,\n hasMore,\n ...hasMore ? { nextCursor: JSON.stringify({ v: 1, before: last.position, query, chat_filter: chatFilter, account }) } : {}\n };\n }\n async function searchMessages(input) {\n const collections = requireFirst([\"WAWebCollections\"]), query = String(input?.query ?? \"\").trim();\n if (!query)\n throw Error(\"query is required\");\n const offset = Math.max(0, Number(input?.offset) || 0), requestedLimit = Math.max(1, Math.min(Number(input?.limit) || 50, 100));\n if (offset >= 100)\n throw Error(\"WhatsApp source search supports only the first 100 matches\");\n const limit = Math.min(requestedLimit, 100 - offset), searchSourceLimit = 100, chatFilter = [\"all\", \"individual\", \"group\"].includes(input?.chat_filter) ? input.chat_filter : \"all\", chat = input?.chat_jid || input?.chat_name || input?.self_chat === !0 ? await resolveChat(collections, input) : null;\n let scopedChats = chat ? [chat] : void 0;\n if (!chat && chatFilter !== \"all\") {\n scopedChats = [];\n for (const candidate of models(collections.Chat)) {\n const jid = (await canonicalJid(modelData(candidate).id ?? candidate?.id)).jid;\n if (!jid || isBroadcastOnlyJid(jid))\n continue;\n const isGroup = jid.endsWith(\"@g.us\");\n if (chatFilter === \"group\" ? isGroup : !isGroup)\n scopedChats.push(candidate);\n }\n }\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]);\n let found = null;\n for (const fn of [\n search?.searchMessages,\n search?.searchMsgs,\n search?.search\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n found = await fn.call(search, query, scopedChats, searchSourceLimit);\n break;\n } catch {}\n }\n let source = \"whatsapp_fts\", candidates = Array.isArray(found) ? found : models(found?.messages ?? found);\n if (!found) {\n source = \"loaded_model_fallback\";\n const needle = query.toLowerCase();\n candidates = uniqueMessageModels(collections).filter((model) => {\n const row = modelData(model);\n if (chat) {\n const chatId = widString(modelData(chat).id ?? chat?.id);\n if (widString(row.id?.remote ?? row.chatId) !== chatId)\n return !1;\n }\n return String(row.body ?? row.caption ?? \"\").toLowerCase().includes(needle);\n });\n }\n const normalized = [], names = nameIndex(collections);\n for (const candidate of candidates) {\n const model = candidate?.msg ?? candidate?.message ?? candidate, message = await normalizeMessage(model, \"search\", collections, names);\n if (!message || Number(message.timestamp) <= 0)\n continue;\n if (chatFilter === \"group\" && !message.is_group)\n continue;\n if (chatFilter === \"individual\" && message.is_group)\n continue;\n normalized.push(message);\n if (normalized.length >= searchSourceLimit)\n break;\n }\n return {\n source,\n results: normalized.slice(offset, offset + limit),\n hasMore: offset + limit < normalized.length\n };\n }\n async function draftMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const draft = {\n body: text,\n timestamp: Math.floor(Date.now() / 1000),\n type: \"chat\",\n mentionedJidList: [],\n quotedMsg: null\n }, module2 = requireFirst(DRAFT_MODULES);\n let applied = !1;\n for (const fn of [\n module2?.setDraft,\n module2?.setChatDraft,\n module2?.saveDraft\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n assertAccount(account);\n await fn.call(module2, chat, draft);\n applied = !0;\n break;\n } catch {\n try {\n assertAccount(account);\n await fn.call(module2, draft, chat);\n applied = !0;\n break;\n } catch {}\n }\n }\n if (!applied && typeof chat?.setDraft === \"function\") {\n assertAccount(account);\n await chat.setDraft(draft);\n applied = !0;\n }\n if (!applied)\n throw Error(\"WhatsApp draft capability is unavailable in this web build\");\n const stored = modelData(chat).draft ?? chat.get?.(\"draft\") ?? null;\n if (!stored || typeof stored !== \"object\" || stored.body !== text)\n throw Error(\"WhatsApp rejected the persistent draft shape\");\n return {\n drafted: !0,\n sent: !1,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n draft\n };\n }\n async function sendMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), chatJid = (await canonicalJid(modelData(chat).id ?? chat?.id)).jid;\n if (chatJid && isBroadcastOnlyJid(chatJid))\n throw Error(`WhatsApp chat ${chatJid} does not accept messages`);\n const text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(SEND_MODULES);\n if (typeof module2?.createTextMsgData === \"function\" && typeof module2?.addAndSendTextMsg === \"function\") {\n const data = await module2.createTextMsgData(chat, text), plannedId = rawId(data?.id);\n if (!plannedId)\n throw Error(\"WhatsApp did not assign an id to the outgoing message\");\n assertAccount(account);\n await module2.addAndSendTextMsg(chat, data);\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: plannedId\n };\n }\n const fn = module2?.sendTextMsgToChat ?? module2?.sendMessage ?? chat?.sendMessage;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp send capability is unavailable in this web build\");\n assertAccount(account);\n const result = fn === chat?.sendMessage ? await fn.call(chat, text) : await fn.call(module2, chat, text), messageId = rawId(modelData(result).id ?? result?.id);\n if (!messageId)\n throw Error(\"WhatsApp send acknowledgment has no raw message ID\");\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: messageId\n };\n }\n function messageActionAllowed(message, predicateNames, legacyFlags) {\n const row = modelData(message);\n for (const flag of legacyFlags)\n if (row[flag] === !0)\n return !0;\n const capability = requireFirst([\"WAWebMsgActionCapability\"]);\n for (const name of predicateNames) {\n if (typeof capability?.[name] !== \"function\")\n continue;\n try {\n if (capability[name](message) === !0)\n return !0;\n } catch {}\n }\n return !1;\n }\n function resolveMessage(collections, id) {\n const raw = String(id ?? \"\").trim();\n if (!raw)\n throw Error(\"message_id is required\");\n const message = collectionByRawId(collections.Msg, raw);\n if (!message)\n throw Error(`WhatsApp message ${raw} is not loaded; read it with id:${raw} from the live messages feed or search it first`);\n return message;\n }\n async function editMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits editing outgoing messages\");\n if (!messageActionAllowed(message, [\"canEditText\", \"canEditCaption\", \"canEnterEditingFlow\"], [\"canEdit\", \"isEditable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently editable\");\n const text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(EDIT_MODULES), fn = module2?.sendMessageEdit ?? module2?.editMessage ?? message?.edit;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp edit capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.edit ? fn.call(message, text) : fn.call(module2, message, text, {}));\n await waitForPostState(() => {\n const row = modelData(message);\n return row.body === text && Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey);\n }, \"message edit\");\n return {\n edited: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function reactMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), emoji = input?.remove ? \"\" : String(input?.emoji ?? \"\");\n if (!input?.remove && !emoji)\n throw Error(\"emoji is required unless remove=true\");\n const module2 = requireFirst(REACTION_MODULES), fn = module2?.sendReactionToMsg ?? module2?.sendReaction ?? message?.react;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp reaction capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.react ? fn.call(message, emoji) : fn.call(module2, message, emoji));\n await waitForPostState(() => {\n const row = modelData(message), reactions = normalizeReactions(row);\n if (reactions.length > 0)\n return input?.remove ? !reactions.some((reaction) => reaction.from_me) : reactions.some((reaction) => reaction.from_me && reaction.emoji === emoji);\n return input?.remove ? !0 : row.hasReaction === !0;\n }, \"reaction state\");\n return {\n reacted: !0,\n confirmed: input?.remove ? normalizeReactions(modelData(message)).length > 0 : !0,\n removed: Boolean(input?.remove),\n emoji: emoji || null,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function revokeMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits revoking outgoing messages\");\n if (!messageActionAllowed(message, [\"canSenderRevokeMsg\", \"canAdminRevokeMsg\"], [\"canRevoke\", \"isRevokable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently revokable\");\n const module2 = requireFirst(REVOKE_MODULES), fn = module2?.sendRevokeMsgs ?? module2?.sendRevoke ?? module2?.revokeMessage ?? message?.sendRevoke ?? message?.revoke;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp revoke capability is unavailable in this web build\");\n assertAccount(account);\n if (fn === message?.sendRevoke || fn === message?.revoke)\n await fn.call(message);\n else\n await fn.call(module2, [message], modelData(message).id?.remote);\n await waitForPostState(() => {\n const row = modelData(message);\n return Boolean(row.isRevoked || row.revoked || row.type === \"revoked\");\n }, \"message revoke\");\n return {\n revoked: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function invoke(request) {\n try {\n if (request?.adapter_version !== ADAPTER_VERSION)\n return {\n ok: !1,\n error: {\n state: \"adapter_mismatch\",\n reason: `expected ${ADAPTER_VERSION}`\n }\n };\n if (request.op === \"account_identity\") {\n const accountId = widString(meUser());\n return accountId ? { accountId } : null;\n }\n if (request.op === \"probe\") {\n const status = readiness();\n return status.ready ? { ok: !0, status, capabilities: operationCapabilities() } : { ok: !1, error: status };\n }\n assertAccount(request.account_id);\n const input = { ...request.input, account_id: request.account_id }, finish = async (promise) => {\n const value = await promise;\n assertAccount(request.account_id);\n return { ok: !0, ...value };\n };\n if (request.op === \"listen\")\n return listen(request);\n if (request.op === \"publish_changes\")\n return await publishChanges(request);\n if (request.op === \"observe_messages\")\n return await finish(observeMessages(input));\n if (operationCapabilities()[request.op] !== !0)\n return {\n ok: !1,\n error: {\n state: \"capability_unavailable\",\n reason: `${request.op} is unavailable in this WhatsApp Web build`\n }\n };\n if (request.op === \"read_messages\")\n return await finish(readMessages(input, request.account_id));\n if (request.op === \"search_messages\")\n return await finish(searchMessages(input));\n if (request.op === \"draft_message\")\n return await finish(draftMessage(input, request.account_id));\n if (request.op === \"send_message\")\n return await finish(sendMessage(input, request.account_id));\n if (request.op === \"edit_message\")\n return await finish(editMessage(input, request.account_id));\n if (request.op === \"react_message\")\n return await finish(reactMessage(input, request.account_id));\n if (request.op === \"revoke_message\")\n return await finish(revokeMessage(input, request.account_id));\n return {\n ok: !1,\n error: { state: \"unsupported_operation\", reason: String(request?.op) }\n };\n } catch (error) {\n if (request?.account_id && widString(meUser()) !== request.account_id)\n error = Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n return {\n ok: !1,\n error: {\n state: \"operation_failed\",\n reason: error instanceof Error ? error.message : String(error)\n }\n };\n }\n }\n globalThis.__owlettoWhatsAppAdapterV1 = { version: ADAPTER_VERSION, invoke, detach };\n })(\"src-zpvqgye2r\");\n for (let i = 0; i < 40; i++) {\n const identity = await globalThis.__owlettoWhatsAppAdapterV1.invoke({ op: \"account_identity\", adapter_version: \"src-zpvqgye2r\" });\n if (identity?.accountId) return identity;\n await new Promise(resolve => setTimeout(resolve, 250));\n }\n return null;\n })()"
|
|
21697
21697
|
}
|
|
21698
21698
|
},
|
|
21699
21699
|
"webhook": null,
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"version": "1.0.0",
|
|
9
9
|
"description": "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.",
|
|
10
10
|
"detail": {
|
|
11
|
-
"instructions": "# 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) — 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 — 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\" — 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\"** — 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 — 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 — 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='…' --arg script='…'` 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…\" />}\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’s 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’s 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 — 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 \"… [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` → `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 — 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```",
|
|
11
|
+
"instructions": "# 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) — 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 — 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\" — 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\"** — 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 — 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 — 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='…' --arg script='…'` 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…\" />}\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’s 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’s 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 — 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 \"… [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` → `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 — 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```",
|
|
12
12
|
"hidden": false
|
|
13
13
|
}
|
|
14
14
|
},
|
package/dist/component.json
CHANGED
|
@@ -20,6 +20,12 @@ export function linkedInInboxProgram() {
|
|
|
20
20
|
function fail(message) {
|
|
21
21
|
throw new Error(`LinkedIn inbox: ${message}`);
|
|
22
22
|
}
|
|
23
|
+
// A stop reason is durable evidence: keep the underlying failure instead of
|
|
24
|
+
// reporting only that the listener could not attach.
|
|
25
|
+
function errorDetail(error) {
|
|
26
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
27
|
+
return clean(message.replace(/^LinkedIn inbox: /, "")).slice(0, 300);
|
|
28
|
+
}
|
|
23
29
|
function headers() {
|
|
24
30
|
const cookie = document.cookie
|
|
25
31
|
.split("; ")
|
|
@@ -1018,6 +1024,7 @@ export function linkedInInboxProgram() {
|
|
|
1018
1024
|
clearTimeout(listener.timer);
|
|
1019
1025
|
window.removeEventListener("message", listener.onReply);
|
|
1020
1026
|
listeners.delete(listener.id);
|
|
1027
|
+
listener.stopReason = reason;
|
|
1021
1028
|
if (reason)
|
|
1022
1029
|
post(listener, {
|
|
1023
1030
|
id: `linkedin:${listener.feed}:source-observation-error`,
|
|
@@ -1053,10 +1060,10 @@ export function linkedInInboxProgram() {
|
|
|
1053
1060
|
listener.batches = await batchesOf(feed, checkpoint, result);
|
|
1054
1061
|
}
|
|
1055
1062
|
if (active(listener)) post(listener, listener.batches[0]);
|
|
1056
|
-
} catch {
|
|
1063
|
+
} catch (error) {
|
|
1057
1064
|
stop(
|
|
1058
1065
|
listener,
|
|
1059
|
-
|
|
1066
|
+
`LinkedIn source observation failed (${errorDetail(error)}); reconnect to recover without skipping changes`
|
|
1060
1067
|
);
|
|
1061
1068
|
}
|
|
1062
1069
|
if (active(listener))
|
|
@@ -1246,7 +1253,10 @@ export function linkedInInboxProgram() {
|
|
|
1246
1253
|
window.addEventListener("message", listener.onReply);
|
|
1247
1254
|
await poll(listener);
|
|
1248
1255
|
if (!listeners.has(listener.id))
|
|
1249
|
-
fail(
|
|
1256
|
+
fail(
|
|
1257
|
+
"Unable to attach source subscription: " +
|
|
1258
|
+
(listener.stopReason ?? "listener stopped")
|
|
1259
|
+
);
|
|
1250
1260
|
return { listening: true };
|
|
1251
1261
|
}
|
|
1252
1262
|
globalThis[key] = { version, read, listen, send, detach };
|