@lobu/runtime-device 24.1.1 → 24.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +46 -134
  3. package/npm-shrinkwrap.json +229 -730
  4. package/package.json +1 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +20 -5
  6. package/vendor/cli/dist/chrome-extension/accessibility-tree.js +834 -0
  7. package/vendor/cli/dist/chrome-extension/ambient-context.js +53 -0
  8. package/vendor/cli/dist/chrome-extension/auth-refresh.js +167 -0
  9. package/vendor/cli/dist/chrome-extension/automation-run.js +13 -0
  10. package/vendor/cli/dist/chrome-extension/background.js +1155 -0
  11. package/vendor/cli/dist/chrome-extension/bridge.js +140 -0
  12. package/vendor/cli/dist/chrome-extension/browser-origin-policy.js +62 -0
  13. package/vendor/cli/dist/chrome-extension/browser-recovery.js +260 -0
  14. package/vendor/cli/dist/chrome-extension/browser-url-sanitizer.js +284 -0
  15. package/vendor/cli/dist/chrome-extension/completion-response.js +12 -0
  16. package/vendor/cli/dist/chrome-extension/config.js +144 -0
  17. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome.json +1516 -0
  18. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_bookmarks.json +84 -0
  19. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_downloads.json +86 -0
  20. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_history.json +78 -0
  21. package/vendor/cli/dist/chrome-extension/connector-manifests.js +1767 -0
  22. package/vendor/cli/dist/chrome-extension/console-capture.js +627 -0
  23. package/vendor/cli/dist/chrome-extension/control-activity.js +70 -0
  24. package/vendor/cli/dist/chrome-extension/debugger-lease.js +439 -0
  25. package/vendor/cli/dist/chrome-extension/feed-listener.js +488 -0
  26. package/vendor/cli/dist/chrome-extension/feed-transaction.js +48 -0
  27. package/vendor/cli/dist/chrome-extension/feeds.js +632 -0
  28. package/vendor/cli/dist/chrome-extension/focus-tab.js +25 -0
  29. package/vendor/cli/dist/chrome-extension/fonts/dm-mono-latin-500-normal.woff2 +0 -0
  30. package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-400-normal.woff2 +0 -0
  31. package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-600-normal.woff2 +0 -0
  32. package/vendor/cli/dist/chrome-extension/heartbeat.js +140 -0
  33. package/vendor/cli/dist/chrome-extension/icons/icon-128-rec.png +0 -0
  34. package/vendor/cli/dist/chrome-extension/icons/icon-128.png +0 -0
  35. package/vendor/cli/dist/chrome-extension/icons/icon-16-rec.png +0 -0
  36. package/vendor/cli/dist/chrome-extension/icons/icon-16.png +0 -0
  37. package/vendor/cli/dist/chrome-extension/icons/icon-32-rec.png +0 -0
  38. package/vendor/cli/dist/chrome-extension/icons/icon-32.png +0 -0
  39. package/vendor/cli/dist/chrome-extension/icons/icon-48-rec.png +0 -0
  40. package/vendor/cli/dist/chrome-extension/icons/icon-48.png +0 -0
  41. package/vendor/cli/dist/chrome-extension/lens-page.js +135 -0
  42. package/vendor/cli/dist/chrome-extension/lens-target.js +20 -0
  43. package/vendor/cli/dist/chrome-extension/manifest.json +76 -0
  44. package/vendor/cli/dist/chrome-extension/network-intercept.js +657 -0
  45. package/vendor/cli/dist/chrome-extension/page-activation.js +120 -0
  46. package/vendor/cli/dist/chrome-extension/page-dialogs.js +125 -0
  47. package/vendor/cli/dist/chrome-extension/page-url.js +11 -0
  48. package/vendor/cli/dist/chrome-extension/panel-session.js +184 -0
  49. package/vendor/cli/dist/chrome-extension/poll-auth.js +85 -0
  50. package/vendor/cli/dist/chrome-extension/poll-backoff.js +22 -0
  51. package/vendor/cli/dist/chrome-extension/run-fence.js +117 -0
  52. package/vendor/cli/dist/chrome-extension/setup-status.js +71 -0
  53. package/vendor/cli/dist/chrome-extension/side-panel-action-click.js +65 -0
  54. package/vendor/cli/dist/chrome-extension/sidepanel-context.js +50 -0
  55. package/vendor/cli/dist/chrome-extension/sidepanel.html +680 -0
  56. package/vendor/cli/dist/chrome-extension/sidepanel.js +1643 -0
  57. package/vendor/cli/dist/chrome-extension/tab-labels.js +233 -0
  58. package/vendor/cli/dist/chrome-extension/tools.js +3354 -0
  59. package/vendor/cli/dist/chrome-extension/watch-observer.js +354 -0
  60. package/vendor/cli/dist/chrome-extension/watch-redact.js +96 -0
  61. package/vendor/cli/dist/chrome-extension/watch.js +348 -0
  62. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +6 -4
  63. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +5 -3
  64. package/vendor/cli/dist/commands/_lib/apply/diff.js +4 -3
  65. package/vendor/cli/dist/commands/_lib/chrome-for-testing.d.ts +13 -0
  66. package/vendor/cli/dist/commands/_lib/chrome-for-testing.js +226 -0
  67. package/vendor/cli/dist/commands/_lib/device-credential.d.ts +34 -0
  68. package/vendor/cli/dist/commands/_lib/device-credential.js +157 -0
  69. package/vendor/cli/dist/commands/_lib/device-wizard.d.ts +17 -0
  70. package/vendor/cli/dist/commands/_lib/device-wizard.js +11 -2
  71. package/vendor/cli/dist/commands/_lib/native-messaging.d.ts +7 -0
  72. package/vendor/cli/dist/commands/_lib/native-messaging.js +40 -0
  73. package/vendor/cli/dist/commands/browser.d.ts +23 -0
  74. package/vendor/cli/dist/commands/browser.js +492 -0
  75. package/vendor/cli/dist/commands/call.d.ts +12 -0
  76. package/vendor/cli/dist/commands/call.js +48 -26
  77. package/vendor/cli/dist/commands/chat.d.ts +0 -12
  78. package/vendor/cli/dist/commands/chat.js +1 -1
  79. package/vendor/cli/dist/commands/context.d.ts +3 -1
  80. package/vendor/cli/dist/commands/context.js +13 -2
  81. package/vendor/cli/dist/commands/daemon.js +38 -171
  82. package/vendor/cli/dist/commands/doctor.d.ts +0 -6
  83. package/vendor/cli/dist/commands/doctor.js +1 -1
  84. package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +4 -1
  85. package/vendor/cli/dist/commands/memory/_lib/errors.js +9 -1
  86. package/vendor/cli/dist/commands/memory/_lib/mcp.d.ts +0 -9
  87. package/vendor/cli/dist/commands/memory/_lib/mcp.js +1 -23
  88. package/vendor/cli/dist/commands/memory/_lib/memory-auth.d.ts +20 -4
  89. package/vendor/cli/dist/commands/memory/_lib/memory-auth.js +21 -17
  90. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.d.ts +0 -8
  91. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +7 -18
  92. package/vendor/cli/dist/commands/memory/run.js +4 -25
  93. package/vendor/cli/dist/config/define.d.ts +1 -1
  94. package/vendor/cli/dist/connectors/gchat.ts +31 -1
  95. package/vendor/cli/dist/connectors/google_gmail.ts +70 -41
  96. package/vendor/cli/dist/connectors/google_gmail_references.ts +406 -0
  97. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +107 -36
  98. package/vendor/cli/dist/connectors/linkedin-inbox.ts +13 -0
  99. package/vendor/cli/dist/connectors/linkedin.ts +1 -1
  100. package/vendor/cli/dist/connectors/postgres.ts +14 -8
  101. package/vendor/cli/dist/connectors/reddit.ts +171 -5
  102. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +147 -61
  103. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +6 -2
  104. package/vendor/cli/dist/connectors/whatsapp_web.ts +48 -17
  105. package/vendor/cli/dist/connectors/x-dm-adapter.js +252 -35
  106. package/vendor/cli/dist/connectors/x.ts +189 -13
  107. package/vendor/cli/dist/index.js +46 -6
  108. package/vendor/cli/dist/internal/cli-update-check.d.ts +33 -0
  109. package/vendor/cli/dist/internal/cli-update-check.js +98 -0
  110. package/vendor/cli/dist/internal/credentials.js +10 -36
  111. package/vendor/cli/dist/internal/device-state.d.ts +2 -0
  112. package/vendor/cli/dist/internal/device-state.js +4 -0
  113. package/vendor/cli/dist/internal/gateway-url.d.ts +0 -8
  114. package/vendor/cli/dist/internal/gateway-url.js +1 -1
  115. package/vendor/cli/dist/runtime-components.json +4 -4
  116. package/vendor/cli/dist/templates/AGENTS.md.tmpl +3 -1
  117. package/vendor/cli/dist/templates/TESTING.md.tmpl +8 -8
  118. package/vendor/cli/package.json +1 -1
  119. package/vendor/connector-sdk/dist/browser-requirement.js +1 -1
  120. package/vendor/connector-sdk/dist/connector-types.d.ts +34 -1
  121. package/vendor/connector-sdk/dist/index.d.ts +3 -1
  122. package/vendor/connector-sdk/dist/index.js +4 -0
  123. package/vendor/connector-sdk/dist/redact.d.ts +10 -0
  124. package/vendor/{connector-worker/dist/executor → connector-sdk/dist}/redact.js +0 -49
  125. package/vendor/connector-sdk/dist/types.d.ts +2 -1
  126. package/vendor/connector-sdk/package.json +6 -1
  127. package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +9 -0
  128. package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +23 -2
  129. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +14 -6
  130. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +62 -25
  131. package/vendor/connector-worker/dist/agent-turn/media-tools.d.ts +1 -0
  132. package/vendor/connector-worker/dist/agent-turn/media-tools.js +5 -2
  133. package/vendor/connector-worker/dist/bin.js +2 -0
  134. package/vendor/connector-worker/dist/daemon/acp-adapters/THIRD_PARTY_LICENSES.txt +1 -1
  135. package/vendor/connector-worker/dist/daemon/acp-adapters/claude.js +7339 -2136
  136. package/vendor/connector-worker/dist/daemon/agent-turn.js +52 -17
  137. package/vendor/connector-worker/dist/daemon/automation.js +3 -13
  138. package/vendor/connector-worker/dist/daemon/client.d.ts +23 -3
  139. package/vendor/connector-worker/dist/daemon/client.js +59 -5
  140. package/vendor/connector-worker/dist/daemon/executor.d.ts +0 -28
  141. package/vendor/connector-worker/dist/daemon/executor.js +27 -12
  142. package/vendor/connector-worker/dist/daemon/index.d.ts +1 -1
  143. package/vendor/connector-worker/dist/daemon/index.js +1 -1
  144. package/vendor/connector-worker/dist/daemon/interactive-session.js +29 -6
  145. package/vendor/connector-worker/dist/daemon/poll-loop.js +29 -2
  146. package/vendor/connector-worker/dist/daemon/start.d.ts +0 -1
  147. package/vendor/connector-worker/dist/daemon/start.js +1 -1
  148. package/vendor/connector-worker/dist/daemon/terminal-delivery.d.ts +6 -10
  149. package/vendor/connector-worker/dist/daemon/terminal-delivery.js +59 -23
  150. package/vendor/connector-worker/dist/daemon/terminal-failure.js +2 -2
  151. package/vendor/connector-worker/dist/executor/isolate.js +4 -1
  152. package/vendor/connector-worker/dist/isolate/bridge.d.ts +6 -2
  153. package/vendor/connector-worker/dist/isolate/bridge.js +14 -8
  154. package/vendor/connector-worker/package.json +2 -2
  155. package/vendor/core/dist/agent-tooling.d.ts +8 -0
  156. package/vendor/core/dist/agent-tooling.js +9 -1
  157. package/vendor/core/dist/capabilities.d.ts +1 -1
  158. package/vendor/core/dist/capabilities.js +5 -0
  159. package/vendor/core/dist/connector-query-errors.d.ts +6 -0
  160. package/vendor/core/dist/connector-query-errors.js +4 -0
  161. package/vendor/core/dist/contracts/entity-reference.d.ts +3 -0
  162. package/vendor/core/dist/contracts/entity-reference.js +31 -0
  163. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +3 -0
  164. package/vendor/core/dist/contracts/tools/manage-automations.js +4 -1
  165. package/vendor/core/dist/contracts/tools/manage-connections.js +1 -1
  166. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +2 -2
  167. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +117 -34
  168. package/vendor/core/dist/contracts/tools/manage-entity.js +47 -14
  169. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +13 -4
  170. package/vendor/core/dist/contracts/tools/manage-operations.js +19 -7
  171. package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +6 -1
  172. package/vendor/core/dist/contracts/tools/read-knowledge.js +20 -1
  173. package/vendor/core/dist/contracts/tools/view-attach.d.ts +1 -1
  174. package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -0
  175. package/vendor/core/dist/contracts/tools/view-runtime.js +3 -1
  176. package/vendor/core/dist/contracts/worker/device-automation.d.ts +4 -9
  177. package/vendor/core/dist/contracts/worker/device-automation.js +10 -15
  178. package/vendor/core/dist/contracts/worker/protocol.d.ts +20 -0
  179. package/vendor/core/dist/contracts/worker/protocol.js +20 -0
  180. package/vendor/core/dist/errors.d.ts +0 -20
  181. package/vendor/core/dist/errors.js +1 -25
  182. package/vendor/core/dist/otel.js +38 -10
  183. package/vendor/core/dist/reserved.d.ts +6 -3
  184. package/vendor/core/dist/reserved.js +6 -3
  185. package/vendor/core/dist/utils/ajv.js +3 -1
  186. package/vendor/core/dist/worker/auth.d.ts +3 -2
  187. package/vendor/core/package.json +31 -5
  188. package/vendor/postgres/cf/src/query.js +3 -1
  189. package/vendor/postgres/cjs/src/query.js +3 -1
  190. package/vendor/postgres/src/query.js +3 -1
  191. package/vendor/connector-worker/dist/executor/http-status.d.ts +0 -16
  192. package/vendor/connector-worker/dist/executor/http-status.js +0 -21
  193. package/vendor/connector-worker/dist/executor/redact.d.ts +0 -29
  194. /package/vendor/postgres/{.bun-tag-2f292c6554a8475e → .bun-tag-22d644c2873790db} +0 -0
@@ -0,0 +1,488 @@
1
+ // Generic page -> connector-feed transport. The injected connector owns the
2
+ // source API and record format. IndexedDB transactions serialize buffer edits
3
+ // across service-worker eviction and extension pages; no source data lives in
4
+ // a service-worker-only Map.
5
+ const DB_NAME = "lobu.feed-listeners";
6
+ const LIMIT_BYTES = 16 * 1024 * 1024;
7
+ const LIMIT_RECORDS = 10_000;
8
+ const RECORD_BYTES = 128 * 1024;
9
+ const LIMIT_BINDINGS = 64;
10
+ const PREFIX = "lobu-feed-record";
11
+ const CONTEXT_SESSION_KEY = "owletto.feedListenerContext";
12
+ let wake = () => {};
13
+
14
+ function openStore() {
15
+ return new Promise((resolve, reject) => {
16
+ const request = indexedDB.open(DB_NAME, 1);
17
+ request.onupgradeneeded = () => {
18
+ request.result.createObjectStore("bindings", { keyPath: "id" });
19
+ request.result.createObjectStore("buffers", { keyPath: "id" });
20
+ };
21
+ request.onsuccess = () => resolve(request.result);
22
+ request.onerror = () => reject(request.error);
23
+ });
24
+ }
25
+
26
+ async function bindings() {
27
+ const db = await openStore();
28
+ try {
29
+ return await new Promise((resolve, reject) => {
30
+ const tx = db.transaction("bindings", "readonly");
31
+ const request = tx.objectStore("bindings").getAll();
32
+ tx.oncomplete = () => resolve(request.result);
33
+ tx.onerror = () => reject(tx.error);
34
+ });
35
+ } finally {
36
+ db.close();
37
+ }
38
+ }
39
+
40
+ async function mutate(id, update, readOnly = false) {
41
+ const db = await openStore();
42
+ try {
43
+ return await new Promise((resolve, reject) => {
44
+ const tx = db.transaction(["bindings", "buffers"], readOnly ? "readonly" : "readwrite");
45
+ const metaStore = tx.objectStore("bindings");
46
+ const dataStore = tx.objectStore("buffers");
47
+ const meta = metaStore.get(id);
48
+ const data = dataStore.get(id);
49
+ const count = metaStore.count();
50
+ let result;
51
+ let failure;
52
+ count.onsuccess = () => {
53
+ try {
54
+ const state = { meta: meta.result, data: data.result ?? { id, entries: {}, bytes: 0 }, bindingCount: count.result };
55
+ result = update(state);
56
+ if (readOnly) return;
57
+ if (state.meta) {
58
+ metaStore.put(state.meta);
59
+ dataStore.put(state.data);
60
+ } else {
61
+ metaStore.delete(id);
62
+ dataStore.delete(id);
63
+ }
64
+ } catch (error) {
65
+ failure = error;
66
+ tx.abort();
67
+ }
68
+ };
69
+ tx.oncomplete = () => resolve(result);
70
+ tx.onabort = tx.onerror = () => reject(failure ?? tx.error ?? new Error("Feed buffer transaction failed"));
71
+ });
72
+ } finally {
73
+ db.close();
74
+ }
75
+ }
76
+
77
+ function context(runCtx) {
78
+ const value = runCtx?.feedContext;
79
+ if (!value?.device_worker_id || !Number.isSafeInteger(value.feed_id) ||
80
+ !Number.isSafeInteger(value.connection_id) || !value.feed_key) {
81
+ throw new Error("A running connector feed must authorize the page listener");
82
+ }
83
+ return value;
84
+ }
85
+
86
+ function bindingId(ctx) {
87
+ return `${ctx.device_worker_id}:${ctx.feed_id}`;
88
+ }
89
+
90
+ function applyAck(state, ctx) {
91
+ const ack = ctx.ack;
92
+ if (!ack || ack.binding_id !== state.meta.id || ack.epoch !== state.meta.epoch) return;
93
+ for (const item of Array.isArray(ack.records) ? ack.records : []) {
94
+ const key = `source:${item.id}`;
95
+ const stored = state.data.entries[key];
96
+ if (stored?.revision !== item.revision) continue;
97
+ state.data.bytes -= stored.bytes;
98
+ delete state.data.entries[key];
99
+ }
100
+ }
101
+
102
+ // Self-contained ISOLATED-world bridge. It forwards only this binding's
103
+ // messages from the exact main frame origin; the SW validates sender again.
104
+ function pageBridge(binding, origin, prefix) {
105
+ const key = `__lobuFeedBridge:${binding.id}`;
106
+ globalThis[key]?.stop();
107
+ let runtimeListener;
108
+ const listener = (event) => {
109
+ if (event.source !== window || event.origin !== origin ||
110
+ event.data?.type !== prefix || event.data?.token !== binding.token) return;
111
+ chrome.runtime.sendMessage({
112
+ op: prefix, binding_id: binding.id, token: binding.token,
113
+ sequence: event.data.sequence, record: event.data.record,
114
+ }).then((result) => {
115
+ window.postMessage({
116
+ type: `${prefix}:ack`, token: binding.token,
117
+ sequence: event.data.sequence, ok: result?.ok === true,
118
+ }, origin);
119
+ }).catch(() => {
120
+ // Extension reload invalidates this context. The page retains the
121
+ // unacknowledged record and the next sync installs a fresh bridge.
122
+ });
123
+ };
124
+ const stop = () => {
125
+ window.removeEventListener("message", listener);
126
+ if (runtimeListener) chrome.runtime.onMessage.removeListener(runtimeListener);
127
+ };
128
+ const stopSource = () => {
129
+ window.postMessage({ type: `${prefix}:stop`, token: binding.token }, origin);
130
+ stop();
131
+ if (globalThis[key]?.token === binding.token) delete globalThis[key];
132
+ };
133
+ runtimeListener = (message) => {
134
+ if (message?.op !== `${prefix}:stop` || message.binding_id !== binding.id ||
135
+ message.token !== binding.token) return;
136
+ stopSource();
137
+ };
138
+ window.addEventListener("message", listener);
139
+ chrome.runtime.onMessage.addListener(runtimeListener);
140
+ globalThis[key] = { token: binding.token, stop, stopSource };
141
+ return true;
142
+ }
143
+
144
+ function snapshot(state) {
145
+ // Capacity rejects the incoming record, not the accepted backlog. The source
146
+ // retains rejected records until a later bind can retry them after this drains.
147
+ let bytes = 0;
148
+ const records = Object.values(state.data.entries)
149
+ .sort((a, b) => a.revision - b.revision)
150
+ .filter((entry) => { bytes += entry.bytes; return bytes <= 4 * 1024 * 1024; })
151
+ .slice(0, 1000);
152
+ return {
153
+ binding_id: state.meta?.id ?? state.data.id, epoch: state.meta?.epoch ?? "",
154
+ records: records.map(({ revision, payload }) => ({ revision, payload })),
155
+ };
156
+ }
157
+
158
+ function dryRunSnapshot(state) {
159
+ const result = snapshot(state);
160
+ // A first-ever dry run must not create a durable binding, but the parent
161
+ // connector still returns a protocol-validated source_ack in its rolled-back
162
+ // checkpoint. Give that preview a non-persisted epoch instead of the invalid
163
+ // empty string; no later real acknowledgment can observe or consume it.
164
+ if (!result.epoch) result.epoch = crypto.randomUUID();
165
+ return result;
166
+ }
167
+
168
+ export async function listenToFeed(chromeApi, args, runCtx) {
169
+ const ctx = context(runCtx);
170
+ const tab = await chromeApi.tabs.get(args.tab_id);
171
+ const origin = new URL(tab.url).origin;
172
+ if (tab.incognito || !/^https?:/.test(tab.url)) throw new Error("Feed listener requires a regular web tab");
173
+ if (!(await chromeApi.permissions.contains({ origins: [`${origin}/*`] }))) {
174
+ throw new Error("Feed listener requires permission for its page origin");
175
+ }
176
+ const id = bindingId(ctx);
177
+ if (ctx.dry_run) {
178
+ const result = await mutate(id, dryRunSnapshot, true);
179
+ return { ok: true, observation: { ...result, bridge_id: id, listening: false } };
180
+ }
181
+ let previous;
182
+ const binding = await mutate(id, (state) => {
183
+ previous = state.meta ? { ...state.meta } : null;
184
+ if (!state.meta && state.bindingCount >= LIMIT_BINDINGS) throw new Error("Browser feed listener limit reached");
185
+ state.meta ??= {
186
+ id, epoch: crypto.randomUUID(), next_revision: 0,
187
+ feed_id: ctx.feed_id, connection_id: ctx.connection_id, feed_key: ctx.feed_key,
188
+ notification_id: crypto.randomUUID(), changed: false,
189
+ };
190
+ if (state.meta.subscription?.scope_key !== ctx.subscription?.scope_key) {
191
+ // A changed feed configuration cannot keep delivering the old scope.
192
+ state.data = { id, entries: {}, bytes: 0 };
193
+ state.meta.epoch = crypto.randomUUID();
194
+ }
195
+ state.meta.subscription = ctx.subscription ?? null;
196
+ state.meta.needs_rebind = Boolean(ctx.subscription);
197
+ applyAck(state, ctx);
198
+ if (state.meta.overflow) {
199
+ // Retry the source without losing accepted data. A prior checkpoint
200
+ // cannot declare recovery complete: only this epoch's successful sync
201
+ // may clear its wake hint, including when the old backlog is empty.
202
+ state.meta.epoch = crypto.randomUUID();
203
+ state.meta.overflow = false;
204
+ state.meta.changed = true;
205
+ state.meta.notification_id = crypto.randomUUID();
206
+ }
207
+ Object.assign(state.meta, {
208
+ tab_id: tab.id, origin, token: crypto.randomUUID(),
209
+ document_id: null, sequences: {},
210
+ });
211
+ return { ...state.meta };
212
+ });
213
+ if (previous && previous.tab_id !== tab.id) await detachPage(chromeApi, previous);
214
+ const [injection] = await chromeApi.scripting.executeScript({
215
+ target: { tabId: tab.id }, world: "ISOLATED", func: pageBridge,
216
+ args: [binding, origin, PREFIX],
217
+ });
218
+ if (!injection?.documentId) throw new Error("Feed listener could not bind its page document");
219
+ await mutate(id, (state) => {
220
+ if (state.meta?.token !== binding.token) throw new Error("Feed listener changed while binding its document");
221
+ state.meta.document_id = injection.documentId;
222
+ if (state.meta.notification_id === binding.notification_id) state.meta.needs_rebind = false;
223
+ });
224
+ const result = await mutate(id, (state) => {
225
+ if (!state.meta) throw new Error("Feed listener is missing; start it first");
226
+ if (state.meta.token !== binding.token) throw new Error("Feed listener changed while reading its buffer");
227
+ return snapshot(state);
228
+ }, true);
229
+
230
+ return { ok: true, observation: { ...result, bridge_id: id, token: binding.token, listening: true, subscription: binding.subscription } };
231
+ }
232
+
233
+ function referenceBatch(record) {
234
+ const text = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
235
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
236
+ if (!text(record?.id, 1024) || !Array.isArray(record.events) || record.events.length > 500 ||
237
+ Object.keys(record).some((key) => !["id", "events", "checkpoint", "more"].includes(key))) return false;
238
+ if (record.more !== undefined && typeof record.more !== "boolean") return false;
239
+ if (record.checkpoint !== undefined && (!object(record.checkpoint) ||
240
+ Object.keys(record.checkpoint).some((key) => !["previous", "next"].includes(key)) ||
241
+ (record.checkpoint.previous !== null && !object(record.checkpoint.previous)) || !object(record.checkpoint.next))) return false;
242
+ return record.events.every((event) => object(event) && text(event.id, 1024) && text(event.event_type, 100) &&
243
+ text(event.resource_ref, 1024) && (event.resource_type === undefined || text(event.resource_type, 100)) &&
244
+ (event.occurred_at === undefined || (text(event.occurred_at, 64) && Number.isFinite(Date.parse(event.occurred_at)))) &&
245
+ Object.keys(event).every((key) => ["id", "event_type", "resource_ref", "resource_type", "occurred_at"].includes(key)));
246
+ }
247
+
248
+ async function removeBinding(chromeApi, id, expectedNotification, expectedToken) {
249
+ const binding = await mutate(id, (state) => {
250
+ if (expectedNotification && state.meta?.notification_id !== expectedNotification) return;
251
+ if (expectedToken && state.meta?.token !== expectedToken) return;
252
+ const value = state.meta;
253
+ state.meta = null;
254
+ return value;
255
+ });
256
+ if (binding) await detachPage(chromeApi, binding);
257
+ }
258
+
259
+ async function detachPage(chromeApi, binding) {
260
+ // An already-injected extension context remains addressable even after its
261
+ // page host permission is revoked. Let it stop the MAIN-world source observer
262
+ // before falling back to fresh script injection, which may now be forbidden.
263
+ await chromeApi.tabs.sendMessage(binding.tab_id, {
264
+ op: `${PREFIX}:stop`, binding_id: binding.id, token: binding.token,
265
+ }).catch(() => {});
266
+ await chromeApi.scripting.executeScript({
267
+ target: { tabId: binding.tab_id }, world: "ISOLATED",
268
+ func: (id, token) => {
269
+ const key = `__lobuFeedBridge:${id}`;
270
+ const bridge = globalThis[key];
271
+ if (bridge?.token !== token) return;
272
+ if (typeof bridge.stopSource === "function") bridge.stopSource();
273
+ else bridge.stop();
274
+ delete globalThis[key];
275
+ },
276
+ args: [binding.id, binding.token],
277
+ }).catch(() => {}); // The tab may already have closed.
278
+ await chromeApi.scripting.executeScript({
279
+ target: { tabId: binding.tab_id }, world: "MAIN",
280
+ func: (token, prefix) => window.postMessage({ type: `${prefix}:stop`, token }, location.origin),
281
+ args: [binding.token, PREFIX],
282
+ }).catch(() => {});
283
+ }
284
+
285
+ async function receiveRecord(chromeApi, message, sender) {
286
+ if (sender.id !== chromeApi.runtime.id || sender.frameId !== 0 || !sender.tab || sender.tab.incognito) {
287
+ throw new Error("Feed observation requires its bound main frame");
288
+ }
289
+ if (!(await chromeApi.permissions.contains({ origins: [`${new URL(sender.url).origin}/*`] }))) {
290
+ throw new Error("Feed observation page permission was revoked");
291
+ }
292
+ const record = message.record;
293
+ // The id becomes an event origin_id, which the server caps in UTF-8 bytes;
294
+ // a UTF-16 length lets multi-byte ids past that cap and fail the batch.
295
+ if (!record || typeof record.id !== "string" || !record.id ||
296
+ new TextEncoder().encode(record.id).length > 1024 ||
297
+ !Number.isSafeInteger(message.sequence) || message.sequence < 1) throw new Error("Invalid source record");
298
+ const serialized = JSON.stringify(record);
299
+ const size = new TextEncoder().encode(serialized).length;
300
+ // An invalid record must not poison the binding. Its producer receives a
301
+ // negative receipt and remains responsible for splitting or reconciling it.
302
+ if (size > RECORD_BYTES) throw new Error("Feed observation record exceeds the size limit");
303
+ const result = await mutate(message.binding_id, (state) => {
304
+ const meta = state.meta;
305
+ if (!meta || meta.token !== message.token || meta.tab_id !== sender.tab.id ||
306
+ meta.document_id !== sender.documentId || new URL(sender.url).origin !== meta.origin ||
307
+ !meta.document_id) throw new Error("Feed binding is inactive or changed");
308
+ if (meta.subscription) {
309
+ if (typeof record.source_error === "string") {
310
+ meta.needs_rebind = true;
311
+ meta.changed = true;
312
+ meta.notification_id = crypto.randomUUID();
313
+ return { ok: true };
314
+ }
315
+ if (!referenceBatch(record) || record.events.some(event => !meta.subscription.event_types.includes(event.event_type))) {
316
+ throw new Error("Subscription delivery accepts declared reference batches only");
317
+ }
318
+ }
319
+ const key = `source:${record.id}`;
320
+ const old = state.data.entries[key];
321
+ // Keep sequence fences after payload acknowledgment until the binding
322
+ // token rotates. A delayed older record must not resurrect stale content.
323
+ const lastSequence = meta.sequences[key];
324
+ if (lastSequence >= message.sequence) return { ok: true };
325
+ if (meta.subscription && record.more === true) meta.needs_rebind = true;
326
+ // A content-equivalent event is not a new revision (e.g. read receipt).
327
+ if (old && JSON.stringify(old.payload) === serialized) { meta.sequences[key] = message.sequence; return { ok: true }; }
328
+ if (state.data.bytes - (old?.bytes ?? 0) + size > LIMIT_BYTES ||
329
+ (!old && Object.keys(state.data.entries).length >= LIMIT_RECORDS) ||
330
+ (lastSequence == null && Object.keys(meta.sequences).length >= LIMIT_RECORDS)) {
331
+ meta.overflow = true;
332
+ if (meta.subscription) meta.needs_rebind = true;
333
+ meta.changed = true;
334
+ meta.notification_id = crypto.randomUUID();
335
+ return { ok: false, error: "Feed observation buffer overflow" };
336
+ }
337
+ meta.sequences[key] = message.sequence;
338
+ state.data.entries[key] = {
339
+ revision: ++meta.next_revision, payload: record, bytes: size,
340
+ token: message.token, sequence: message.sequence,
341
+ };
342
+ state.data.bytes += size - (old?.bytes ?? 0);
343
+ meta.changed = true;
344
+ meta.notification_id = crypto.randomUUID();
345
+ return { ok: true };
346
+ });
347
+ wake();
348
+ return result;
349
+ }
350
+
351
+ /** Tabs a feed listener is bound to; navigate never reuses them generically. */
352
+ export async function feedListenerTabIds() {
353
+ return new Set((await bindings()).map((row) => row.tab_id).filter((id) => id != null));
354
+ }
355
+
356
+ export async function feedNotifications() {
357
+ const notices = [];
358
+ for (const entry of (await bindings()).slice(0, 64)) {
359
+ const notice = entry.subscription ? await mutate(entry.id, sourceNotification, true) : sourceNotification({ meta: entry });
360
+ if (notice) notices.push(notice);
361
+ }
362
+ return notices;
363
+ }
364
+
365
+ function sourceNotification(state) {
366
+ const entry = state.meta;
367
+ if (!entry) return null;
368
+ const notice = {
369
+ feed_id: entry.feed_id, connection_id: entry.connection_id, feed_key: entry.feed_key,
370
+ notification_id: entry.notification_id, changed: entry.changed,
371
+ };
372
+ if (entry.subscription) {
373
+ let bytes = 0;
374
+ let events = 0;
375
+ const records = [];
376
+ for (const record of Object.values(state.data.entries).sort((a, b) => a.revision - b.revision)) {
377
+ bytes += record.bytes;
378
+ events += record.payload.events.length;
379
+ if (records.length >= 25 || bytes > 192 * 1024 || events > 1000) break;
380
+ records.push({ revision: record.revision, payload: record.payload });
381
+ }
382
+ notice.subscription = { scope_key: entry.subscription.scope_key, binding_id: entry.id,
383
+ epoch: entry.epoch, needs_rebind: entry.needs_rebind === true, records };
384
+ }
385
+ return notice;
386
+ }
387
+
388
+ function applyReceipt(state, receipt) {
389
+ if (!state.meta) return false;
390
+ const wasChanged = state.meta.changed;
391
+ const currentNotification = state.meta.notification_id === receipt.notification_id;
392
+ const before = Object.keys(state.data.entries).length;
393
+ applyAck(state, { ack: receipt.ack });
394
+ const remaining = Object.keys(state.data.entries).length;
395
+ const pending = state.meta.overflow === true || state.meta.needs_rebind === true || remaining > 0;
396
+
397
+ if (pending) {
398
+ // A receipt proves only that scheduling committed. Until a successful feed
399
+ // checkpoint acknowledges every exact revision, keep presenting the wake
400
+ // hint so manual feeds retain their bounded backoff retry as well.
401
+ state.meta.changed = true;
402
+ if (currentNotification && remaining > 0 && remaining < before) {
403
+ state.meta.notification_id = crypto.randomUUID();
404
+ }
405
+ } else if (currentNotification && receipt.ack?.binding_id === state.meta.id &&
406
+ receipt.ack?.epoch === state.meta.epoch) {
407
+ state.meta.changed = false;
408
+ }
409
+
410
+ return !wasChanged && state.meta.changed;
411
+ }
412
+
413
+ export async function acceptFeedReceipts(chromeApi, receipts) {
414
+ let shouldWake = false;
415
+ for (const binding of await bindings()) {
416
+ const receipt = receipts.find((item) => item.feed_id === binding.feed_id &&
417
+ item.connection_id === binding.connection_id && item.feed_key === binding.feed_key);
418
+ if (!receipt) continue;
419
+ if (!receipt.active) {
420
+ if (receipt.notification_id === binding.notification_id) await removeBinding(chromeApi, binding.id, receipt.notification_id);
421
+ continue;
422
+ }
423
+ shouldWake = (await mutate(binding.id, (state) => applyReceipt(state, receipt))) || shouldWake;
424
+ }
425
+ if (shouldWake) wake();
426
+ }
427
+
428
+ async function markBindingsDirtyAfterContextReset(chromeApi, dirty) {
429
+ const stored = await chromeApi.storage.session.get(CONTEXT_SESSION_KEY);
430
+ if (stored[CONTEXT_SESSION_KEY]) return false;
431
+ // storage.session survives ordinary MV3 worker eviction, while an extension
432
+ // reload/update or full browser restart clears it along with the injected
433
+ // page contexts. Only those real context resets need to schedule re-binding.
434
+ await dirty();
435
+ await chromeApi.storage.session.set({ [CONTEXT_SESSION_KEY]: true });
436
+ return true;
437
+ }
438
+
439
+ export function installFeedListenerTransport(chromeApi, onWake) {
440
+ wake = onWake;
441
+ chromeApi.permissions.onRemoved.addListener(() => {
442
+ void bindings().then(async (rows) => {
443
+ for (const row of rows) {
444
+ if (!(await chromeApi.permissions.contains({ origins: [`${row.origin}/*`] }))) {
445
+ // A record already in flight may rotate notification_id after the
446
+ // permission check. The binding token changes only on an authorized
447
+ // re-bind, so it closes that race without deleting a newly re-bound page.
448
+ await removeBinding(chromeApi, row.id, null, row.token);
449
+ }
450
+ }
451
+ }).catch(console.error);
452
+ });
453
+ chromeApi.storage.onChanged.addListener((changes, area) => {
454
+ if (area !== "local") return;
455
+ const worker = changes["owletto.workerId"];
456
+ const token = changes["owletto.accessToken"];
457
+ if ((worker?.oldValue && worker.oldValue !== worker.newValue) || (token?.oldValue && !token.newValue)) {
458
+ void bindings().then((rows) => Promise.all(rows.map((row) => removeBinding(chromeApi, row.id)))).catch(console.error);
459
+ }
460
+ });
461
+ chromeApi.runtime.onMessage.addListener((message, sender, reply) => {
462
+ if (message?.op !== PREFIX) return;
463
+ void receiveRecord(chromeApi, message, sender)
464
+ .then(reply).catch((error) => reply({ ok: false, error: error.message }));
465
+ return true;
466
+ });
467
+ const dirty = async (tabId) => {
468
+ for (const entry of await bindings()) {
469
+ if (tabId != null && entry.tab_id !== tabId) continue;
470
+ await mutate(entry.id, (state) => {
471
+ if (!state.meta) return;
472
+ state.meta.changed = true;
473
+ if (state.meta.subscription) state.meta.needs_rebind = true;
474
+ state.meta.notification_id = crypto.randomUUID();
475
+ });
476
+ }
477
+ wake();
478
+ };
479
+ chromeApi.tabs.onUpdated.addListener((tabId, change) => {
480
+ // A frozen renderer cannot publish source events. Ask normal sync to
481
+ // reconcile from its checkpoint; thaw itself must not schedule a loop.
482
+ if (change.status === "complete" || change.frozen === true) void dirty(tabId).catch(console.error);
483
+ });
484
+ chromeApi.tabs.onRemoved.addListener((tabId) => { void dirty(tabId).catch(console.error); });
485
+ // Ask normal sync to reinstall after a real extension/browser context reset;
486
+ // an ordinary service-worker eviction leaves the injected bridge alive.
487
+ void markBindingsDirtyAfterContextReset(chromeApi, dirty).catch(console.error);
488
+ }
@@ -0,0 +1,48 @@
1
+ export const MAX_STREAM_JSON_BYTES = 3 * 1024 * 1024;
2
+
3
+ export function chunkFeedItems(items, maxBytes = MAX_STREAM_JSON_BYTES) {
4
+ const chunks = [];
5
+ let chunk = [];
6
+ let bytes = 2;
7
+ for (const item of items) {
8
+ const itemBytes =
9
+ new TextEncoder().encode(JSON.stringify(item)).byteLength + 1;
10
+ if (itemBytes > maxBytes)
11
+ throw new Error(
12
+ `Feed item ${item.id ?? "<unknown>"} exceeds the stream byte limit`,
13
+ );
14
+ if (chunk.length > 0 && bytes + itemBytes > maxBytes) {
15
+ chunks.push(chunk);
16
+ chunk = [];
17
+ bytes = 2;
18
+ }
19
+ chunk.push(item);
20
+ bytes += itemBytes;
21
+ }
22
+ if (chunk.length > 0) chunks.push(chunk);
23
+ return chunks;
24
+ }
25
+
26
+ // Deliver a device feed transaction without acknowledging local state until
27
+ // every bounded stream chunk and the exact success completion are confirmed.
28
+ export async function deliverFeedTransaction(
29
+ tx,
30
+ { postBatch, complete, fence, maxBatchBytes = MAX_STREAM_JSON_BYTES },
31
+ ) {
32
+ for (const chunk of chunkFeedItems(tx.items, maxBatchBytes)) {
33
+ fence?.assertActive("batch stream");
34
+ await postBatch(chunk);
35
+ fence?.assertActive("batch stream response");
36
+ }
37
+ fence?.assertActive("success completion");
38
+ const completionConfirmed = await complete({
39
+ status: "success",
40
+ items_collected: tx.items.length,
41
+ checkpoint: tx.checkpoint,
42
+ });
43
+ if (completionConfirmed) {
44
+ if (fence && !fence.isSuccessConfirmed()) return false;
45
+ await tx.commit();
46
+ }
47
+ return completionConfirmed;
48
+ }