@lobu/runtime-device 24.1.0 → 24.2.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 (159) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +26 -28
  3. package/npm-shrinkwrap.json +155 -172
  4. package/package.json +1 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +14 -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/apply/render.js +4 -14
  66. package/vendor/cli/dist/commands/_lib/chrome-for-testing.d.ts +13 -0
  67. package/vendor/cli/dist/commands/_lib/chrome-for-testing.js +226 -0
  68. package/vendor/cli/dist/commands/_lib/device-credential.d.ts +34 -0
  69. package/vendor/cli/dist/commands/_lib/device-credential.js +157 -0
  70. package/vendor/cli/dist/commands/_lib/device-wizard.d.ts +17 -0
  71. package/vendor/cli/dist/commands/_lib/device-wizard.js +11 -2
  72. package/vendor/cli/dist/commands/_lib/native-messaging.d.ts +7 -0
  73. package/vendor/cli/dist/commands/_lib/native-messaging.js +40 -0
  74. package/vendor/cli/dist/commands/browser.d.ts +23 -0
  75. package/vendor/cli/dist/commands/browser.js +492 -0
  76. package/vendor/cli/dist/commands/call.d.ts +12 -0
  77. package/vendor/cli/dist/commands/call.js +48 -26
  78. package/vendor/cli/dist/commands/context.d.ts +3 -1
  79. package/vendor/cli/dist/commands/context.js +13 -2
  80. package/vendor/cli/dist/commands/daemon.js +2 -152
  81. package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +4 -1
  82. package/vendor/cli/dist/commands/memory/_lib/errors.js +9 -1
  83. package/vendor/cli/dist/commands/memory/_lib/mcp.d.ts +0 -9
  84. package/vendor/cli/dist/commands/memory/_lib/mcp.js +1 -23
  85. package/vendor/cli/dist/commands/memory/_lib/memory-auth.d.ts +20 -4
  86. package/vendor/cli/dist/commands/memory/_lib/memory-auth.js +21 -17
  87. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +6 -17
  88. package/vendor/cli/dist/commands/memory/run.js +4 -25
  89. package/vendor/cli/dist/connectors/google_gmail.ts +70 -41
  90. package/vendor/cli/dist/connectors/google_gmail_references.ts +406 -0
  91. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +107 -36
  92. package/vendor/cli/dist/connectors/linkedin-inbox.ts +13 -0
  93. package/vendor/cli/dist/connectors/linkedin.ts +1 -1
  94. package/vendor/cli/dist/connectors/postgres.ts +5 -3
  95. package/vendor/cli/dist/connectors/reddit.ts +171 -5
  96. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +147 -61
  97. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +6 -2
  98. package/vendor/cli/dist/connectors/whatsapp_web.ts +48 -17
  99. package/vendor/cli/dist/connectors/x-dm-adapter.js +252 -35
  100. package/vendor/cli/dist/connectors/x.ts +189 -13
  101. package/vendor/cli/dist/index.js +46 -6
  102. package/vendor/cli/dist/internal/device-state.d.ts +2 -0
  103. package/vendor/cli/dist/internal/device-state.js +4 -0
  104. package/vendor/cli/dist/runtime-components.json +4 -4
  105. package/vendor/cli/dist/templates/AGENTS.md.tmpl +3 -1
  106. package/vendor/cli/dist/templates/TESTING.md.tmpl +8 -8
  107. package/vendor/cli/package.json +1 -1
  108. package/vendor/connector-sdk/dist/browser-requirement.js +1 -1
  109. package/vendor/connector-sdk/dist/connector-types.d.ts +5 -1
  110. package/vendor/connector-sdk/package.json +1 -1
  111. package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +9 -0
  112. package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +23 -2
  113. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +14 -6
  114. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +62 -25
  115. package/vendor/connector-worker/dist/agent-turn/media-tools.d.ts +1 -0
  116. package/vendor/connector-worker/dist/agent-turn/media-tools.js +5 -2
  117. package/vendor/connector-worker/dist/bin.js +2 -0
  118. package/vendor/connector-worker/dist/daemon/agent-turn.js +52 -17
  119. package/vendor/connector-worker/dist/daemon/automation.js +2 -12
  120. package/vendor/connector-worker/dist/daemon/client.d.ts +8 -2
  121. package/vendor/connector-worker/dist/daemon/client.js +8 -1
  122. package/vendor/connector-worker/dist/daemon/interactive-session.js +29 -6
  123. package/vendor/connector-worker/dist/daemon/poll-loop.js +23 -1
  124. package/vendor/connector-worker/dist/daemon/terminal-delivery.d.ts +5 -10
  125. package/vendor/connector-worker/dist/daemon/terminal-delivery.js +55 -23
  126. package/vendor/connector-worker/dist/daemon/terminal-failure.js +2 -2
  127. package/vendor/connector-worker/dist/executor/isolate.js +3 -0
  128. package/vendor/connector-worker/package.json +1 -1
  129. package/vendor/core/dist/agent-tooling.d.ts +8 -0
  130. package/vendor/core/dist/agent-tooling.js +9 -1
  131. package/vendor/core/dist/capabilities.d.ts +1 -1
  132. package/vendor/core/dist/capabilities.js +5 -0
  133. package/vendor/core/dist/contracts/entity-reference.d.ts +3 -0
  134. package/vendor/core/dist/contracts/entity-reference.js +31 -0
  135. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +3 -0
  136. package/vendor/core/dist/contracts/tools/manage-automations.js +3 -0
  137. package/vendor/core/dist/contracts/tools/manage-connections.js +1 -1
  138. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +1 -1
  139. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +113 -34
  140. package/vendor/core/dist/contracts/tools/manage-entity.js +41 -14
  141. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +13 -4
  142. package/vendor/core/dist/contracts/tools/manage-operations.js +19 -7
  143. package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +6 -1
  144. package/vendor/core/dist/contracts/tools/read-knowledge.js +20 -1
  145. package/vendor/core/dist/contracts/tools/view-attach.d.ts +1 -1
  146. package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -0
  147. package/vendor/core/dist/contracts/tools/view-runtime.js +3 -1
  148. package/vendor/core/dist/contracts/worker/device-automation.d.ts +4 -9
  149. package/vendor/core/dist/contracts/worker/device-automation.js +10 -15
  150. package/vendor/core/dist/contracts/worker/protocol.d.ts +20 -0
  151. package/vendor/core/dist/contracts/worker/protocol.js +20 -0
  152. package/vendor/core/dist/reserved.d.ts +6 -3
  153. package/vendor/core/dist/reserved.js +6 -3
  154. package/vendor/core/dist/worker/auth.d.ts +3 -2
  155. package/vendor/core/package.json +6 -1
  156. package/vendor/postgres/cf/src/query.js +3 -1
  157. package/vendor/postgres/cjs/src/query.js +3 -1
  158. package/vendor/postgres/src/query.js +3 -1
  159. /package/vendor/postgres/{.bun-tag-2f292c6554a8475e → .bun-tag-22d644c2873790db} +0 -0
@@ -0,0 +1,120 @@
1
+ import { getGatewayUrl } from "./config.js";
2
+ import { normalizePageUrl } from "./page-url.js";
3
+ import { agentLabelFor } from "./tab-labels.js";
4
+
5
+ // Hints cached under the old key were normalized lossily; a new key drops them.
6
+ export const PAGE_ACTIVATIONS_KEY = "owletto.page_activations.exact";
7
+ const inFlightRuns = new Set();
8
+
9
+ export function sanitizePageActivations(value) {
10
+ if (!Array.isArray(value)) return [];
11
+ return value
12
+ .map((item) => {
13
+ const runId = Number(item?.run_id);
14
+ const urls = Array.isArray(item?.urls)
15
+ ? [...new Set(item.urls.map(normalizePageUrl).filter(Boolean))]
16
+ : [];
17
+ return Number.isSafeInteger(runId) && runId > 0 && urls.length > 0
18
+ ? { run_id: runId, urls }
19
+ : null;
20
+ })
21
+ .filter(Boolean)
22
+ .slice(0, 100);
23
+ }
24
+
25
+ async function paintBadge(chromeApi, activations) {
26
+ const count = activations.length;
27
+ await chromeApi.action.setBadgeText({ text: count ? String(Math.min(count, 99)) : "" });
28
+ if (count) {
29
+ await chromeApi.action.setBadgeBackgroundColor({ color: "#2563eb" });
30
+ await chromeApi.action.setTitle({
31
+ title: `${count} Lobu ${count === 1 ? "item" : "items"} ready on matching pages`,
32
+ });
33
+ } else {
34
+ await chromeApi.action.setTitle({ title: "Lobu" });
35
+ }
36
+ }
37
+
38
+ async function readActivations(chromeApi) {
39
+ const stored = await chromeApi.storage.local.get(PAGE_ACTIVATIONS_KEY);
40
+ return sanitizePageActivations(stored[PAGE_ACTIVATIONS_KEY]);
41
+ }
42
+
43
+ async function removeActivation(chromeApi, runId) {
44
+ const remaining = (await readActivations(chromeApi)).filter(
45
+ (item) => item.run_id !== runId,
46
+ );
47
+ await chromeApi.storage.local.set({ [PAGE_ACTIVATIONS_KEY]: remaining });
48
+ await paintBadge(chromeApi, remaining);
49
+ }
50
+
51
+ export async function activateMatchingPage(chromeApi, tab, fetchFn = fetch) {
52
+ if (!tab?.active || !Number.isSafeInteger(tab.id) || !tab.url) return false;
53
+ // Agent tabs never activate a page; only the user's own visit does.
54
+ if (await agentLabelFor(chromeApi, tab.id)) return false;
55
+ const normalized = normalizePageUrl(tab.url);
56
+ if (!normalized) return false;
57
+ const match = (await readActivations(chromeApi)).find((item) =>
58
+ item.urls.includes(normalized),
59
+ );
60
+ if (!match || inFlightRuns.has(match.run_id)) return false;
61
+
62
+ const stored = await chromeApi.storage.local.get([
63
+ "owletto.workerId",
64
+ "owletto.accessToken",
65
+ ]);
66
+ const workerId = stored["owletto.workerId"];
67
+ const token = stored["owletto.accessToken"];
68
+ const gatewayUrl = await getGatewayUrl();
69
+ if (!gatewayUrl || !workerId || !token) return false;
70
+
71
+ inFlightRuns.add(match.run_id);
72
+ try {
73
+ const response = await fetchFn(`${gatewayUrl}/api/workers/activate-page`, {
74
+ method: "POST",
75
+ headers: {
76
+ "content-type": "application/json",
77
+ authorization: `Bearer ${token}`,
78
+ },
79
+ body: JSON.stringify({
80
+ worker_id: workerId,
81
+ run_id: match.run_id,
82
+ tab_id: tab.id,
83
+ url: tab.url,
84
+ }),
85
+ });
86
+ if (!response.ok) return false;
87
+ const result = await response.json().catch(() => null);
88
+ if (result?.status !== "activated" && result?.status !== "unavailable") {
89
+ return false;
90
+ }
91
+ await removeActivation(chromeApi, match.run_id);
92
+ return result.status === "activated";
93
+ } finally {
94
+ inFlightRuns.delete(match.run_id);
95
+ }
96
+ }
97
+
98
+ async function activateCurrentPage(chromeApi) {
99
+ const tabs = await chromeApi.tabs.query({ active: true, lastFocusedWindow: true });
100
+ if (tabs[0]) await activateMatchingPage(chromeApi, tabs[0]);
101
+ }
102
+
103
+ export async function replacePageActivations(chromeApi, value) {
104
+ const activations = sanitizePageActivations(value);
105
+ await chromeApi.storage.local.set({ [PAGE_ACTIVATIONS_KEY]: activations });
106
+ await paintBadge(chromeApi, activations);
107
+ await activateCurrentPage(chromeApi);
108
+ }
109
+
110
+ export function installPageActivationListeners(chromeApi) {
111
+ chromeApi.tabs.onActivated.addListener(({ tabId }) => {
112
+ void chromeApi.tabs.get(tabId).then((tab) => activateMatchingPage(chromeApi, tab));
113
+ });
114
+ chromeApi.tabs.onUpdated.addListener((_tabId, changeInfo, tab) => {
115
+ if (tab.active && (changeInfo.status === "complete" || changeInfo.url)) {
116
+ void activateMatchingPage(chromeApi, tab);
117
+ }
118
+ });
119
+ void readActivations(chromeApi).then((items) => paintBadge(chromeApi, items));
120
+ }
@@ -0,0 +1,125 @@
1
+ // JS dialogs (alert / confirm / prompt / beforeunload) on tabs we debug.
2
+ //
3
+ // With the debugger attached and the Page domain enabled, Chrome hands a
4
+ // dialog to the debugger instead of showing it, and the page's event loop
5
+ // blocks until someone answers. Answering on the agent's behalf hid real
6
+ // decisions ("Delete this item?" silently became "no"), so nothing here
7
+ // answers: a dialog is recorded per tab, the action it interrupted reports
8
+ // it, later actions on that tab refuse until it is answered, and
9
+ // handle_dialog answers it by id.
10
+ //
11
+ // The record is in memory. An attached debugger keeps the MV3 service worker
12
+ // alive, and Chrome forgets the dialog (shows it natively) once we detach, so
13
+ // the record lives exactly as long as the attachment that can answer it.
14
+
15
+ const OPEN_DIALOGS = new Map(); // tabId → dialog record
16
+ const OPEN_WAITERS = new Map(); // tabId → Set<(dialog) => void>
17
+ const CLOSE_WAITERS = new Map(); // tabId → Set<(closed) => void>
18
+ // Called as (chromeApi, tabId, dialog) whenever a dialog opens; debugger-lease
19
+ // uses it to hand a dialog nobody answers back to the user.
20
+ const OPEN_SUBSCRIBERS = new Set();
21
+
22
+ export function onDialogOpened(callback) {
23
+ OPEN_SUBSCRIBERS.add(callback);
24
+ }
25
+
26
+ function notify(waiters, tabId, value) {
27
+ const set = waiters.get(tabId);
28
+ if (!set) return;
29
+ waiters.delete(tabId);
30
+ for (const resolve of set) resolve(value);
31
+ }
32
+
33
+ function addWaiter(waiters, tabId, resolve) {
34
+ let set = waiters.get(tabId);
35
+ if (!set) {
36
+ set = new Set();
37
+ waiters.set(tabId, set);
38
+ }
39
+ set.add(resolve);
40
+ return () => {
41
+ set.delete(resolve);
42
+ if (set.size === 0 && waiters.get(tabId) === set) waiters.delete(tabId);
43
+ };
44
+ }
45
+
46
+ // Registered from background.js at SW top level (MV3 listeners must be).
47
+ export function registerDialogHandler(chromeApi) {
48
+ chromeApi.debugger.onEvent.addListener((source, method, params) => {
49
+ const tabId = source?.tabId;
50
+ if (tabId == null) return;
51
+ if (method === "Page.javascriptDialogOpening") {
52
+ const dialog = {
53
+ dialog_id: crypto.randomUUID(),
54
+ type: params?.type ?? "alert",
55
+ message: typeof params?.message === "string" ? params.message.slice(0, 2000) : "",
56
+ url: typeof params?.url === "string" ? params.url : null,
57
+ opened_at: Date.now(),
58
+ };
59
+ if (dialog.type === "prompt" && typeof params?.defaultPrompt === "string") {
60
+ dialog.default_prompt = params.defaultPrompt.slice(0, 2000);
61
+ }
62
+ OPEN_DIALOGS.set(tabId, dialog);
63
+ notify(OPEN_WAITERS, tabId, dialog);
64
+ for (const callback of OPEN_SUBSCRIBERS) {
65
+ try {
66
+ callback(chromeApi, tabId, dialog);
67
+ } catch {
68
+ // A subscriber's failure must not lose the dialog record.
69
+ }
70
+ }
71
+ return;
72
+ }
73
+ if (method === "Page.javascriptDialogClosed") {
74
+ OPEN_DIALOGS.delete(tabId);
75
+ notify(CLOSE_WAITERS, tabId, { accepted: params?.result === true });
76
+ }
77
+ });
78
+ }
79
+
80
+ export function openDialog(tabId) {
81
+ return OPEN_DIALOGS.get(tabId) ?? null;
82
+ }
83
+
84
+ // Our attachment to the tab is gone: Chrome shows any pending dialog itself
85
+ // now, and no handle_dialog could reach it.
86
+ export function forgetDialog(tabId) {
87
+ OPEN_DIALOGS.delete(tabId);
88
+ notify(CLOSE_WAITERS, tabId, null);
89
+ }
90
+
91
+ // Resolves with the dialog record when one opens on `tabId`.
92
+ export function whenDialogOpens(tabId) {
93
+ let cancel = () => {};
94
+ const promise = new Promise((resolve) => {
95
+ cancel = addWaiter(OPEN_WAITERS, tabId, resolve);
96
+ });
97
+ return { promise, cancel };
98
+ }
99
+
100
+ // Resolves with { accepted } when the tab's dialog closes, or null when our
101
+ // attachment went away first.
102
+ export function whenDialogCloses(tabId) {
103
+ let cancel = () => {};
104
+ const promise = new Promise((resolve) => {
105
+ cancel = addWaiter(CLOSE_WAITERS, tabId, resolve);
106
+ });
107
+ return { promise, cancel };
108
+ }
109
+
110
+ // The result an action returns when a dialog blocks the page: the action
111
+ // may have run (it may be what opened the dialog), but nothing after it can
112
+ // be observed until the dialog is answered.
113
+ export function dialogInterruption(tabId, dialog) {
114
+ return {
115
+ ok: false,
116
+ error: `a ${dialog.type} dialog is open on tab ${tabId} ("${dialog.message.slice(0, 200)}"); answer it with handle_dialog (dialog_id ${dialog.dialog_id}) before acting on this tab again`,
117
+ observation: { tab_id: tabId, dialog, outcome: "unverifiable" },
118
+ };
119
+ }
120
+
121
+ export function __resetDialogsForTests() {
122
+ OPEN_DIALOGS.clear();
123
+ OPEN_WAITERS.clear();
124
+ CLOSE_WAITERS.clear();
125
+ }
@@ -0,0 +1,11 @@
1
+ // Keep resource identity intact; URL canonicalizes host case and default ports.
2
+ export function normalizePageUrl(value) {
3
+ try {
4
+ const url = new URL(value);
5
+ return url.protocol === "http:" || url.protocol === "https:"
6
+ ? url.toString()
7
+ : null;
8
+ } catch {
9
+ return null;
10
+ }
11
+ }
@@ -0,0 +1,184 @@
1
+ // The side panel's sign-in credential, kept apart from the device token.
2
+ //
3
+ // The gateway only turns a credential into a web session when it already
4
+ // carries full access (mcp:admin). A desktop-app pairing hands Chrome a
5
+ // device-only child PAT for the worker, plus a separate browser session for the
6
+ // panel. The panel signs in with that session; OAuth and local pairings store a
7
+ // full-access token and sign in with it directly.
8
+
9
+ export const PANEL_SESSION_KEY = "owletto.panelSessionToken";
10
+
11
+ // Native-messaging host installed by the Lobu Mac app. When present, it
12
+ // short-circuits the OAuth dance by minting a child device token through
13
+ // POST /api/me/devices/mint-child-token using the Mac app's bearer.
14
+ export const NATIVE_HOST = "ai.lobu.bridge";
15
+ export const NATIVE_HANDSHAKE_TIMEOUT_MS = 2500;
16
+
17
+ export function panelSignInToken(stored, accessTokenKey) {
18
+ return stored[PANEL_SESSION_KEY] || stored[accessTokenKey] || null;
19
+ }
20
+
21
+ // Single-shot native-messaging handshake against the desktop bridge. Resolves
22
+ // to the bridge response or null when the host isn't installed, reachable or
23
+ // responsive within `timeoutMs`. Disconnects the port either way. Never
24
+ // rejects: the pair flow treats every failure as "no desktop bridge".
25
+ //
26
+ // The worker id is read BEFORE the port opens and the listeners attach in the
27
+ // same tick as connectNative. With no host installed Chrome tears the port down
28
+ // asynchronously; an await between connecting and attaching both misses that
29
+ // disconnect and leaves a port whose members throw "Extension context
30
+ // invalidated" — which rejected the whole pair flow and blanked the panel.
31
+ export async function nativeBridgeHandshake({
32
+ connectNative,
33
+ readWorkerId,
34
+ timeoutMs,
35
+ onReply,
36
+ }) {
37
+ // Forward this browser's existing worker_id (if any) so the bridge can pass
38
+ // it to /api/me/devices/mint-child-token, which reuses the device identity
39
+ // instead of minting a fresh uuid across native re-pairs.
40
+ let existingWorkerId;
41
+ try {
42
+ existingWorkerId = await readWorkerId();
43
+ } catch {
44
+ existingWorkerId = undefined;
45
+ }
46
+ return new Promise((resolve) => {
47
+ let port = null;
48
+ let timer = null;
49
+ let settled = false;
50
+ const settle = (value) => {
51
+ if (settled) return;
52
+ settled = true;
53
+ clearTimeout(timer);
54
+ try {
55
+ port?.disconnect();
56
+ } catch {}
57
+ resolve(value);
58
+ };
59
+ try {
60
+ port = connectNative();
61
+ port.onMessage.addListener((msg) => {
62
+ onReply?.();
63
+ settle(msg);
64
+ });
65
+ port.onDisconnect.addListener(() => settle(null));
66
+ timer = setTimeout(() => settle(null), timeoutMs);
67
+ port.postMessage({
68
+ op: "pair",
69
+ platform: "chrome-extension",
70
+ ...(existingWorkerId ? { worker_id: existingWorkerId } : {}),
71
+ });
72
+ } catch {
73
+ settle(null);
74
+ }
75
+ });
76
+ }
77
+
78
+ // Validate a desktop-bridge pair response. Returns null unless it carries the
79
+ // fields a pairing needs.
80
+ export function readNativePairResponse(response) {
81
+ if (
82
+ !response ||
83
+ typeof response !== "object" ||
84
+ !response.gateway_url ||
85
+ !response.worker_id ||
86
+ !response.access_token
87
+ ) {
88
+ return null;
89
+ }
90
+ return {
91
+ gatewayUrl: response.gateway_url,
92
+ workerId: response.worker_id,
93
+ accessToken: response.access_token,
94
+ sessionToken:
95
+ typeof response.session_token === "string" && response.session_token
96
+ ? response.session_token
97
+ : null,
98
+ };
99
+ }
100
+
101
+ // Set by every new pairing, never by a token refresh or re-approval. The next
102
+ // panel mount opens Settings once as the welcome, even when the pairing
103
+ // happened in the background before the panel was ever opened.
104
+ export const WELCOME_PENDING_KEY = "lobu.welcomePending";
105
+
106
+ // Storage writes for a desktop-bridge pairing. The panel and the background
107
+ // both pair this way, so the shape lives in one place. The server allows the
108
+ // extension's own origin, so no site permission is needed to reach it.
109
+ export function nativePairStorage({
110
+ pair,
111
+ gatewayBase,
112
+ keys,
113
+ gatewayKey,
114
+ now = Date.now,
115
+ }) {
116
+ return {
117
+ [gatewayKey]: gatewayBase,
118
+ [keys.workerId]: pair.workerId,
119
+ [keys.accessToken]: pair.accessToken,
120
+ [PANEL_SESSION_KEY]: pair.sessionToken,
121
+ [keys.refreshToken]: null,
122
+ [GRANTED_SCOPE_KEY]: null,
123
+ [keys.clientId]: null,
124
+ [keys.clientSecret]: null,
125
+ [keys.pairedAt]: now(),
126
+ [WELCOME_PENDING_KEY]: true,
127
+ };
128
+ }
129
+
130
+ // After the gateway rejects the panel's sign-in, ask the desktop app for a
131
+ // fresh pairing once. Only applies to a desktop pairing (no OAuth refresh
132
+ // token) on the same gateway, and only when the app returns a session; anything
133
+ // else leaves the bootstrap page's Re-pair action to the user. Returns true
134
+ // when a new pairing was stored.
135
+ export async function refreshDesktopPanelSession({
136
+ storage,
137
+ keys,
138
+ gatewayBase,
139
+ handshake,
140
+ normalizeGatewayBase,
141
+ now = Date.now,
142
+ }) {
143
+ const stored = await storage.get([keys.refreshToken, keys.workerId]);
144
+ if (stored[keys.refreshToken]) return false;
145
+ const pair = readNativePairResponse(await handshake());
146
+ if (!pair) return false;
147
+ if (normalizeGatewayBase(pair.gatewayUrl) !== gatewayBase) return false;
148
+ if (!pair.sessionToken) {
149
+ // Minting a device token revokes the one it replaces, so a reply without
150
+ // a session can still carry this device's only working token. Keep it so
151
+ // polling survives; the panel still needs the user's Re-pair to sign in.
152
+ if (pair.workerId === stored[keys.workerId]) {
153
+ await storage.set({ [keys.accessToken]: pair.accessToken });
154
+ }
155
+ return false;
156
+ }
157
+ await storage.set({
158
+ [keys.workerId]: pair.workerId,
159
+ [keys.accessToken]: pair.accessToken,
160
+ [PANEL_SESSION_KEY]: pair.sessionToken,
161
+ // A new pairedAt makes the panel re-run the bootstrap with the new session.
162
+ [keys.pairedAt]: now(),
163
+ });
164
+ return true;
165
+ }
166
+
167
+ // The scope the gateway granted an OAuth pairing, from its token responses.
168
+ // Pairings made before the panel asked for mcp:admin hold a read-only grant
169
+ // that the gateway will stop accepting for sign-in; refreshing never widens a
170
+ // grant, so only a fresh approval can upgrade it.
171
+ export const GRANTED_SCOPE_KEY = "owletto.grantedScope";
172
+
173
+ export function grantedScopeUpdate(tokens) {
174
+ return typeof tokens?.scope === "string" && tokens.scope.trim()
175
+ ? { [GRANTED_SCOPE_KEY]: tokens.scope.trim() }
176
+ : {};
177
+ }
178
+
179
+ export function needsAccessReapproval(stored, refreshTokenKey) {
180
+ const scope = stored[GRANTED_SCOPE_KEY];
181
+ if (!stored[refreshTokenKey] || typeof scope !== "string") return false;
182
+ // RFC 6749 §3.3: scope is a space-delimited list.
183
+ return !scope.split(" ").includes("mcp:admin");
184
+ }
@@ -0,0 +1,85 @@
1
+ export const LOST_AUTH_STORAGE_KEYS = Object.freeze([
2
+ "owletto.accessToken",
3
+ "owletto.panelSessionToken",
4
+ "owletto.refreshToken",
5
+ "owletto.grantedScope",
6
+ "owletto.lastRefreshAt",
7
+ "owletto.reconnectingSince",
8
+ ]);
9
+
10
+ function withTerminalPunctuation(message) {
11
+ return /[.!?]$/.test(message) ? message : `${message}.`;
12
+ }
13
+
14
+ export async function clearLostPairing({
15
+ host,
16
+ message = "Sign-in expired. Re-pair to reconnect this browser.",
17
+ setHealth,
18
+ removeStorage,
19
+ stopPolling,
20
+ }) {
21
+ // Invalidate the active loop immediately. Removing accessToken also triggers
22
+ // the storage listener's stop, but an explicit stop prevents this in-flight
23
+ // poll from re-arming before that asynchronous event arrives.
24
+ stopPolling();
25
+ await setHealth({
26
+ connected: false,
27
+ reason: "auth-lost",
28
+ host,
29
+ message,
30
+ });
31
+ // Keep owletto.workerId: it is the stable identity forwarded on re-pair so
32
+ // the server reuses the same device_workers row instead of minting a new one.
33
+ await removeStorage(LOST_AUTH_STORAGE_KEYS);
34
+ return { claimed: false, keepGoing: false };
35
+ }
36
+
37
+ export async function handlePollAuthorizationFailure(
38
+ response,
39
+ { host, setHealth, removeStorage, stopPolling },
40
+ ) {
41
+ if (response.status !== 403) return null;
42
+
43
+ const body = await response.json().catch(() => ({}));
44
+ const detail = [body?.error_description, body?.error].find(
45
+ (value) => typeof value === "string" && value.trim().length > 0,
46
+ );
47
+ const message = detail
48
+ ? `${withTerminalPunctuation(detail.trim())} Re-pair to reconnect this browser.`
49
+ : `${host} denied access on poll. Re-pair to reconnect this browser.`;
50
+
51
+ return clearLostPairing({
52
+ host,
53
+ message,
54
+ setHealth,
55
+ removeStorage,
56
+ stopPolling,
57
+ });
58
+ }
59
+
60
+ // How often a below-floor extension asks again. Chrome installs the store
61
+ // update and restarts the extension on its own; this only re-checks in case the
62
+ // gateway lowers its floor in the meantime.
63
+ export const UPGRADE_RECHECK_MS = 15 * 60_000;
64
+
65
+ // The gateway answers a poll from a client below its version floor with
66
+ // 409 upgrade_required (MIN_CLIENT_VERSION). Show that as an update prompt
67
+ // rather than a generic poll failure, keep the pairing, and back off.
68
+ export async function handlePollUpgradeRequired(response, { host, setHealth }) {
69
+ if (response.status !== 409) return null;
70
+ const body = await response.json().catch(() => ({}));
71
+ if (body?.error !== "upgrade_required") return null;
72
+ const detail =
73
+ typeof body.error_description === "string"
74
+ ? body.error_description.trim()
75
+ : "";
76
+ await setHealth({
77
+ connected: false,
78
+ reason: "update-required",
79
+ host,
80
+ message: detail
81
+ ? withTerminalPunctuation(detail)
82
+ : "This version of Lobu for Chrome is no longer supported. Update it to reconnect.",
83
+ });
84
+ return { claimed: false, keepGoing: true, nextDelayMs: UPGRADE_RECHECK_MS };
85
+ }
@@ -0,0 +1,22 @@
1
+ // Retry backoff for a FAILING poll.
2
+ //
3
+ // The idle-cadence backoff this module used to carry is gone: the gateway now
4
+ // holds an idle poll open (`wait_seconds`), so an idle worker costs one parked
5
+ // request instead of a tick every few seconds, and it learns about work the
6
+ // moment the gateway does. Pacing a healthy poll is the server's job — it
7
+ // answers `next_poll_seconds` with whatever hold budget went unspent.
8
+ //
9
+ // What the server cannot pace is a poll that never reached it. A gateway
10
+ // outage, a dropped network, a 5xx: those still need the client to back off on
11
+ // its own rather than retry every few seconds for the length of the incident.
12
+ export const POLL_RETRY_BASE_MS = 5_000;
13
+ export const POLL_RETRY_MAX_MS = 30_000;
14
+
15
+ /** Delay before retrying after `streak` consecutive failed polls (1-based). */
16
+ export function pollFailureBackoffMs(
17
+ streak,
18
+ { base = POLL_RETRY_BASE_MS, max = POLL_RETRY_MAX_MS } = {},
19
+ ) {
20
+ if (streak <= 1) return base;
21
+ return Math.min(max, base * 2 ** (streak - 1));
22
+ }
@@ -0,0 +1,117 @@
1
+ export class RunFence {
2
+ constructor({
3
+ timeoutMs,
4
+ now = Date.now,
5
+ setTimer = setTimeout,
6
+ clearTimer = clearTimeout,
7
+ onTimeout,
8
+ }) {
9
+ this.controller = new AbortController();
10
+ this.now = now;
11
+ this.deadline = now() + timeoutMs;
12
+ this.state = "active";
13
+ this.completionIntent = null;
14
+ this.completionConfirmed = null;
15
+ this.timeoutPromise = null;
16
+ this.timer = setTimer(() => {
17
+ if (this.timeout()) void onTimeout?.();
18
+ }, timeoutMs);
19
+ // Native browser timers reject the RunFence instance as their receiver.
20
+ this.clearTimer = (timer) => clearTimer(timer);
21
+ }
22
+
23
+ get signal() {
24
+ return this.controller.signal;
25
+ }
26
+
27
+ remainingMs() {
28
+ return Math.max(0, this.deadline - this.now());
29
+ }
30
+
31
+ assertActive(phase = "work") {
32
+ if (this.state !== "active" || this.signal.aborted) {
33
+ throw new DOMException(
34
+ `Run is ${this.state}; ${phase} is fenced`,
35
+ "AbortError",
36
+ );
37
+ }
38
+ }
39
+
40
+ timeout() {
41
+ if (
42
+ this.state !== "active" &&
43
+ this.state !== "completing_success" &&
44
+ this.state !== "completing_failure"
45
+ )
46
+ return false;
47
+ this.state = "timed_out";
48
+ this.controller.abort(new DOMException("Run timed out", "TimeoutError"));
49
+ return true;
50
+ }
51
+
52
+ beginCompletion(intent) {
53
+ if (intent === "success") {
54
+ if (this.state !== "active") return null;
55
+ this.state = "completing_success";
56
+ } else if (this.state === "active") {
57
+ this.state = "completing_failure";
58
+ this.controller.abort(new DOMException("Run failed", "AbortError"));
59
+ } else if (this.state === "timed_out") {
60
+ this.state = "completing_timeout";
61
+ } else {
62
+ return null;
63
+ }
64
+ this.completionIntent = intent;
65
+ this.completionToken = Symbol(intent);
66
+ return this.completionToken;
67
+ }
68
+
69
+ confirmCompletion(token, intent) {
70
+ if (token !== this.completionToken || this.completionIntent !== intent)
71
+ return false;
72
+ const expected =
73
+ intent === "success"
74
+ ? "completing_success"
75
+ : intent === "timeout"
76
+ ? "completing_timeout"
77
+ : "completing_failure";
78
+ if (this.state !== expected) return false;
79
+ this.state =
80
+ intent === "success"
81
+ ? "succeeded"
82
+ : intent === "timeout"
83
+ ? "timed_out"
84
+ : "failed";
85
+ this.completionConfirmed = intent;
86
+ this.clearTimer(this.timer);
87
+ return true;
88
+ }
89
+
90
+ failCompletion(token, intent) {
91
+ if (token !== this.completionToken || this.completionIntent !== intent)
92
+ return;
93
+ if (intent === "success" && this.state === "completing_success") {
94
+ this.state = "completion_ambiguous";
95
+ this.controller.abort(
96
+ new DOMException("Success completion was not confirmed", "AbortError"),
97
+ );
98
+ } else if (this.state.startsWith("completing_")) {
99
+ this.state = intent === "timeout" ? "timed_out" : "failed";
100
+ }
101
+ this.clearTimer(this.timer);
102
+ }
103
+
104
+ isSuccessConfirmed() {
105
+ return this.state === "succeeded" && this.completionConfirmed === "success";
106
+ }
107
+
108
+ dispose() {
109
+ this.clearTimer(this.timer);
110
+ }
111
+ }
112
+
113
+ export function throwIfAborted(signal, phase) {
114
+ if (signal?.aborted) {
115
+ throw signal.reason ?? new DOMException(`${phase} aborted`, "AbortError");
116
+ }
117
+ }