@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.
- package/dist/component.json +1 -1
- package/dist/dependencies.bun.lock +26 -28
- package/npm-shrinkwrap.json +155 -172
- package/package.json +1 -1
- package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +14 -5
- package/vendor/cli/dist/chrome-extension/accessibility-tree.js +834 -0
- package/vendor/cli/dist/chrome-extension/ambient-context.js +53 -0
- package/vendor/cli/dist/chrome-extension/auth-refresh.js +167 -0
- package/vendor/cli/dist/chrome-extension/automation-run.js +13 -0
- package/vendor/cli/dist/chrome-extension/background.js +1155 -0
- package/vendor/cli/dist/chrome-extension/bridge.js +140 -0
- package/vendor/cli/dist/chrome-extension/browser-origin-policy.js +62 -0
- package/vendor/cli/dist/chrome-extension/browser-recovery.js +260 -0
- package/vendor/cli/dist/chrome-extension/browser-url-sanitizer.js +284 -0
- package/vendor/cli/dist/chrome-extension/completion-response.js +12 -0
- package/vendor/cli/dist/chrome-extension/config.js +144 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome.json +1516 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_bookmarks.json +84 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_downloads.json +86 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_history.json +78 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests.js +1767 -0
- package/vendor/cli/dist/chrome-extension/console-capture.js +627 -0
- package/vendor/cli/dist/chrome-extension/control-activity.js +70 -0
- package/vendor/cli/dist/chrome-extension/debugger-lease.js +439 -0
- package/vendor/cli/dist/chrome-extension/feed-listener.js +488 -0
- package/vendor/cli/dist/chrome-extension/feed-transaction.js +48 -0
- package/vendor/cli/dist/chrome-extension/feeds.js +632 -0
- package/vendor/cli/dist/chrome-extension/focus-tab.js +25 -0
- package/vendor/cli/dist/chrome-extension/fonts/dm-mono-latin-500-normal.woff2 +0 -0
- package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-400-normal.woff2 +0 -0
- package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-600-normal.woff2 +0 -0
- package/vendor/cli/dist/chrome-extension/heartbeat.js +140 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-128-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-128.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-16-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-16.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-32-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-32.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-48-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-48.png +0 -0
- package/vendor/cli/dist/chrome-extension/lens-page.js +135 -0
- package/vendor/cli/dist/chrome-extension/lens-target.js +20 -0
- package/vendor/cli/dist/chrome-extension/manifest.json +76 -0
- package/vendor/cli/dist/chrome-extension/network-intercept.js +657 -0
- package/vendor/cli/dist/chrome-extension/page-activation.js +120 -0
- package/vendor/cli/dist/chrome-extension/page-dialogs.js +125 -0
- package/vendor/cli/dist/chrome-extension/page-url.js +11 -0
- package/vendor/cli/dist/chrome-extension/panel-session.js +184 -0
- package/vendor/cli/dist/chrome-extension/poll-auth.js +85 -0
- package/vendor/cli/dist/chrome-extension/poll-backoff.js +22 -0
- package/vendor/cli/dist/chrome-extension/run-fence.js +117 -0
- package/vendor/cli/dist/chrome-extension/setup-status.js +71 -0
- package/vendor/cli/dist/chrome-extension/side-panel-action-click.js +65 -0
- package/vendor/cli/dist/chrome-extension/sidepanel-context.js +50 -0
- package/vendor/cli/dist/chrome-extension/sidepanel.html +680 -0
- package/vendor/cli/dist/chrome-extension/sidepanel.js +1643 -0
- package/vendor/cli/dist/chrome-extension/tab-labels.js +233 -0
- package/vendor/cli/dist/chrome-extension/tools.js +3354 -0
- package/vendor/cli/dist/chrome-extension/watch-observer.js +354 -0
- package/vendor/cli/dist/chrome-extension/watch-redact.js +96 -0
- package/vendor/cli/dist/chrome-extension/watch.js +348 -0
- package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +6 -4
- package/vendor/cli/dist/commands/_lib/apply/desired-state.js +5 -3
- package/vendor/cli/dist/commands/_lib/apply/diff.js +4 -3
- package/vendor/cli/dist/commands/_lib/apply/render.js +4 -14
- package/vendor/cli/dist/commands/_lib/chrome-for-testing.d.ts +13 -0
- package/vendor/cli/dist/commands/_lib/chrome-for-testing.js +226 -0
- package/vendor/cli/dist/commands/_lib/device-credential.d.ts +34 -0
- package/vendor/cli/dist/commands/_lib/device-credential.js +157 -0
- package/vendor/cli/dist/commands/_lib/device-wizard.d.ts +17 -0
- package/vendor/cli/dist/commands/_lib/device-wizard.js +11 -2
- package/vendor/cli/dist/commands/_lib/native-messaging.d.ts +7 -0
- package/vendor/cli/dist/commands/_lib/native-messaging.js +40 -0
- package/vendor/cli/dist/commands/browser.d.ts +23 -0
- package/vendor/cli/dist/commands/browser.js +492 -0
- package/vendor/cli/dist/commands/call.d.ts +12 -0
- package/vendor/cli/dist/commands/call.js +48 -26
- package/vendor/cli/dist/commands/context.d.ts +3 -1
- package/vendor/cli/dist/commands/context.js +13 -2
- package/vendor/cli/dist/commands/daemon.js +2 -152
- package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +4 -1
- package/vendor/cli/dist/commands/memory/_lib/errors.js +9 -1
- package/vendor/cli/dist/commands/memory/_lib/mcp.d.ts +0 -9
- package/vendor/cli/dist/commands/memory/_lib/mcp.js +1 -23
- package/vendor/cli/dist/commands/memory/_lib/memory-auth.d.ts +20 -4
- package/vendor/cli/dist/commands/memory/_lib/memory-auth.js +21 -17
- package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +6 -17
- package/vendor/cli/dist/commands/memory/run.js +4 -25
- package/vendor/cli/dist/connectors/google_gmail.ts +70 -41
- package/vendor/cli/dist/connectors/google_gmail_references.ts +406 -0
- package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +107 -36
- package/vendor/cli/dist/connectors/linkedin-inbox.ts +13 -0
- package/vendor/cli/dist/connectors/linkedin.ts +1 -1
- package/vendor/cli/dist/connectors/postgres.ts +5 -3
- package/vendor/cli/dist/connectors/reddit.ts +171 -5
- package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +147 -61
- package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +6 -2
- package/vendor/cli/dist/connectors/whatsapp_web.ts +48 -17
- package/vendor/cli/dist/connectors/x-dm-adapter.js +252 -35
- package/vendor/cli/dist/connectors/x.ts +189 -13
- package/vendor/cli/dist/index.js +46 -6
- package/vendor/cli/dist/internal/device-state.d.ts +2 -0
- package/vendor/cli/dist/internal/device-state.js +4 -0
- package/vendor/cli/dist/runtime-components.json +4 -4
- package/vendor/cli/dist/templates/AGENTS.md.tmpl +3 -1
- package/vendor/cli/dist/templates/TESTING.md.tmpl +8 -8
- package/vendor/cli/package.json +1 -1
- package/vendor/connector-sdk/dist/browser-requirement.js +1 -1
- package/vendor/connector-sdk/dist/connector-types.d.ts +5 -1
- package/vendor/connector-sdk/package.json +1 -1
- package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +9 -0
- package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +23 -2
- package/vendor/connector-worker/dist/agent-turn/guest-entry.js +14 -6
- package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +62 -25
- package/vendor/connector-worker/dist/agent-turn/media-tools.d.ts +1 -0
- package/vendor/connector-worker/dist/agent-turn/media-tools.js +5 -2
- package/vendor/connector-worker/dist/bin.js +2 -0
- package/vendor/connector-worker/dist/daemon/agent-turn.js +52 -17
- package/vendor/connector-worker/dist/daemon/automation.js +2 -12
- package/vendor/connector-worker/dist/daemon/client.d.ts +8 -2
- package/vendor/connector-worker/dist/daemon/client.js +8 -1
- package/vendor/connector-worker/dist/daemon/interactive-session.js +29 -6
- package/vendor/connector-worker/dist/daemon/poll-loop.js +23 -1
- package/vendor/connector-worker/dist/daemon/terminal-delivery.d.ts +5 -10
- package/vendor/connector-worker/dist/daemon/terminal-delivery.js +55 -23
- package/vendor/connector-worker/dist/daemon/terminal-failure.js +2 -2
- package/vendor/connector-worker/dist/executor/isolate.js +3 -0
- package/vendor/connector-worker/package.json +1 -1
- package/vendor/core/dist/agent-tooling.d.ts +8 -0
- package/vendor/core/dist/agent-tooling.js +9 -1
- package/vendor/core/dist/capabilities.d.ts +1 -1
- package/vendor/core/dist/capabilities.js +5 -0
- package/vendor/core/dist/contracts/entity-reference.d.ts +3 -0
- package/vendor/core/dist/contracts/entity-reference.js +31 -0
- package/vendor/core/dist/contracts/tools/manage-automations.d.ts +3 -0
- package/vendor/core/dist/contracts/tools/manage-automations.js +3 -0
- package/vendor/core/dist/contracts/tools/manage-connections.js +1 -1
- package/vendor/core/dist/contracts/tools/manage-entity-schema.js +1 -1
- package/vendor/core/dist/contracts/tools/manage-entity.d.ts +113 -34
- package/vendor/core/dist/contracts/tools/manage-entity.js +41 -14
- package/vendor/core/dist/contracts/tools/manage-operations.d.ts +13 -4
- package/vendor/core/dist/contracts/tools/manage-operations.js +19 -7
- package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +6 -1
- package/vendor/core/dist/contracts/tools/read-knowledge.js +20 -1
- package/vendor/core/dist/contracts/tools/view-attach.d.ts +1 -1
- package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -0
- package/vendor/core/dist/contracts/tools/view-runtime.js +3 -1
- package/vendor/core/dist/contracts/worker/device-automation.d.ts +4 -9
- package/vendor/core/dist/contracts/worker/device-automation.js +10 -15
- package/vendor/core/dist/contracts/worker/protocol.d.ts +20 -0
- package/vendor/core/dist/contracts/worker/protocol.js +20 -0
- package/vendor/core/dist/reserved.d.ts +6 -3
- package/vendor/core/dist/reserved.js +6 -3
- package/vendor/core/dist/worker/auth.d.ts +3 -2
- package/vendor/core/package.json +6 -1
- package/vendor/postgres/cf/src/query.js +3 -1
- package/vendor/postgres/cjs/src/query.js +3 -1
- package/vendor/postgres/src/query.js +3 -1
- /package/vendor/postgres/{.bun-tag-2f292c6554a8475e → .bun-tag-22d644c2873790db} +0 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export const CONTROL_ACTIVITY_KEY = "lobu.controlActivity";
|
|
2
|
+
|
|
3
|
+
function label(value) {
|
|
4
|
+
return typeof value === "string"
|
|
5
|
+
? value.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 160)
|
|
6
|
+
: "";
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Same source fields as Lobu activity cards; task titles never supply identity. */
|
|
10
|
+
export function controlSource(source) {
|
|
11
|
+
const agent = label(source?.agent_name) || label(source?.agent_id);
|
|
12
|
+
const client = label(source?.client_name) || label(source?.client_id);
|
|
13
|
+
const actor = agent || client || null;
|
|
14
|
+
const origin = agent ? `Managed agent: ${agent}` : client ? `MCP client: ${client}` : "Unknown requester";
|
|
15
|
+
const automation = label(source?.automation_name);
|
|
16
|
+
const device = label(source?.device_label) || label(source?.device_worker_id);
|
|
17
|
+
return {
|
|
18
|
+
actor,
|
|
19
|
+
origin,
|
|
20
|
+
detail: [origin, agent && client ? `via ${client}` : null,
|
|
21
|
+
automation ? `Automation: ${automation}` : null,
|
|
22
|
+
device ? `Executing on ${device}` : null].filter(Boolean).join(" · "),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createControlActivity(chromeApi) {
|
|
27
|
+
const active = new Map();
|
|
28
|
+
let publishing = Promise.resolve();
|
|
29
|
+
function publish() {
|
|
30
|
+
publishing = publishing.catch(() => {}).then(async () => {
|
|
31
|
+
const values = [...active.values()];
|
|
32
|
+
// A presentation failure must not turn an executed action into a
|
|
33
|
+
// failure that callers might retry. Update both surfaces independently.
|
|
34
|
+
const results = await Promise.allSettled([
|
|
35
|
+
chromeApi.storage.session.set({ [CONTROL_ACTIVITY_KEY]: values }),
|
|
36
|
+
chromeApi.action.setTitle({
|
|
37
|
+
title: values.length ? `Lobu — ${values.map((v) => v.detail).join("\n")}` : "Lobu",
|
|
38
|
+
}),
|
|
39
|
+
]);
|
|
40
|
+
for (const result of results) {
|
|
41
|
+
if (result.status === "rejected") console.warn("[lobu] activity display update failed", result.reason);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
return publishing;
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
// An evicted service worker cannot still own a live JS tool invocation.
|
|
48
|
+
// Clear its presentation on startup instead of restoring a stale actor.
|
|
49
|
+
refresh: publish,
|
|
50
|
+
start(run, gatewayUrl) {
|
|
51
|
+
const source = controlSource(run.source_attribution);
|
|
52
|
+
let url = null;
|
|
53
|
+
try {
|
|
54
|
+
const parsed = new URL(run.source_url);
|
|
55
|
+
if (parsed.origin === new URL(gatewayUrl).origin && ["https:", "http:"].includes(parsed.protocol)) url = parsed.href;
|
|
56
|
+
} catch { /* Older gateways have no source link. */ }
|
|
57
|
+
active.set(run.run_id, {
|
|
58
|
+
runId: run.run_id,
|
|
59
|
+
...source,
|
|
60
|
+
operation: label(run.action_key).replaceAll("_", " ") || "Browser operation",
|
|
61
|
+
url,
|
|
62
|
+
});
|
|
63
|
+
return publish();
|
|
64
|
+
},
|
|
65
|
+
finish(runId) {
|
|
66
|
+
active.delete(runId);
|
|
67
|
+
return publish();
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
// Shared debugger lease/refcount for the chrome connector tools.
|
|
2
|
+
//
|
|
3
|
+
// Both action tools (apps/chrome/tools.js withDebugger) and the long-lived
|
|
4
|
+
// network-intercept primitive (apps/chrome/network-intercept.js) hold
|
|
5
|
+
// leases on the same chrome.debugger session per tab. The physical
|
|
6
|
+
// chrome.debugger.attach happens on the 0→1 transition; the physical
|
|
7
|
+
// detach on 1→0. This lets a navigate / evaluate via withDebugger run
|
|
8
|
+
// while a network-intercept session is alive on the same tab without
|
|
9
|
+
// racing the attach state ("Another debugger is already attached" error).
|
|
10
|
+
//
|
|
11
|
+
// Lives in its own module to avoid a tools.js ↔ network-intercept.js
|
|
12
|
+
// import cycle (tools.js exports NETWORK_INTERCEPT_TOOLS via a bottom-of-
|
|
13
|
+
// file import from network-intercept.js; if network-intercept.js then
|
|
14
|
+
// imported from tools.js at the top, the lease const would be in the
|
|
15
|
+
// temporal dead zone when network-intercept.js evaluated).
|
|
16
|
+
|
|
17
|
+
// tabId → { generation, count }. The count is STAMPED with the detach
|
|
18
|
+
// generation it belongs to. An external detach only bumps the generation (see
|
|
19
|
+
// DETACH_GENERATIONS below); it never touches this map. So a count left over
|
|
20
|
+
// from a superseded generation is simply read as 0 by the next acquire/release
|
|
21
|
+
// — no out-of-band reset, and thus no window in which a reset queued behind
|
|
22
|
+
// the lock could clobber a count a concurrent acquire just set. Every mutation
|
|
23
|
+
// here happens under withLeaseLock.
|
|
24
|
+
import { TABS_MANAGE_SCOPE, isActionGrantEnabled } from "./config.js";
|
|
25
|
+
import { forgetDialog, onDialogOpened, openDialog } from "./page-dialogs.js";
|
|
26
|
+
import { agentLabelFor } from "./tab-labels.js";
|
|
27
|
+
|
|
28
|
+
const ATTACHED_TAB_LEASES = new Map();
|
|
29
|
+
|
|
30
|
+
// An action run is one tool call, and an agent's next call on the same tab
|
|
31
|
+
// usually follows within seconds. Detaching at every 1→0 made Chrome raise and
|
|
32
|
+
// drop its "started debugging this browser" bar around each call: the bar
|
|
33
|
+
// resizes the page (shifting what the last snapshot measured), and each fresh
|
|
34
|
+
// attach is another point where the user can cancel it mid-action. So an
|
|
35
|
+
// action's release keeps the attachment for a short idle window and the next
|
|
36
|
+
// acquire reuses it; the physical detach happens only once the tab goes idle.
|
|
37
|
+
// The idle attachment is stamped with its generation like a count, so an
|
|
38
|
+
// external detach during the window simply makes it stale.
|
|
39
|
+
export const DEBUGGER_IDLE_DETACH_MS = 15_000;
|
|
40
|
+
|
|
41
|
+
// A JS dialog lives only as long as our attachment: once we detach, Chrome
|
|
42
|
+
// shows it to the user and handle_dialog can no longer answer it. So the
|
|
43
|
+
// attachment stays while a dialog waits (the idle timer keeps re-arming), for
|
|
44
|
+
// up to this long after the dialog opened. Then the dialog goes to the user:
|
|
45
|
+
// we detach as if Chrome had taken the debugger away, which also fails the
|
|
46
|
+
// action frozen behind the dialog and frees its tab lock.
|
|
47
|
+
export const DIALOG_HOLD_MS = 120_000;
|
|
48
|
+
|
|
49
|
+
onDialogOpened((chromeApi, tabId, dialog) => {
|
|
50
|
+
setTimeout(() => {
|
|
51
|
+
if (openDialog(tabId)?.dialog_id === dialog.dialog_id) {
|
|
52
|
+
void handDialogToUser(chromeApi, tabId);
|
|
53
|
+
}
|
|
54
|
+
}, DIALOG_HOLD_MS);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
function handDialogToUser(chromeApi, tabId) {
|
|
58
|
+
return withLeaseLock(tabId, async () => {
|
|
59
|
+
if (!openDialog(tabId)) return;
|
|
60
|
+
clearIdleTimer(ATTACHED_TAB_LEASES.get(tabId));
|
|
61
|
+
ATTACHED_TAB_LEASES.delete(tabId);
|
|
62
|
+
invalidateAttachment(chromeApi, tabId, "dialog_handed_to_user");
|
|
63
|
+
try {
|
|
64
|
+
await chromeApi.debugger.detach(dbgTarget(tabId));
|
|
65
|
+
} catch {
|
|
66
|
+
// already gone
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The live count for `tabId` at the CURRENT generation. A stored entry stamped
|
|
72
|
+
// with an older generation was orphaned by an external detach and counts as 0.
|
|
73
|
+
function currentLeaseCount(tabId) {
|
|
74
|
+
const entry = currentEntry(tabId);
|
|
75
|
+
return entry ? entry.count : 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function currentEntry(tabId) {
|
|
79
|
+
const entry = ATTACHED_TAB_LEASES.get(tabId);
|
|
80
|
+
return entry && entry.generation === debuggerDetachGeneration(tabId)
|
|
81
|
+
? entry
|
|
82
|
+
: null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function clearIdleTimer(entry) {
|
|
86
|
+
if (entry?.idleTimer != null) clearTimeout(entry.idleTimer);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Per-tab promise chain that serializes the read-modify-write of the refcount
|
|
90
|
+
// AND the physical attach/detach it gates. Without this, two concurrent
|
|
91
|
+
// acquireDebuggerLease() calls on the same tab both read refcount 0, both
|
|
92
|
+
// await debugger.attach, then both set the count to 1 — losing a reference.
|
|
93
|
+
// A later release then hits 0 and detaches while the other lease is still
|
|
94
|
+
// live, breaking that session (and it can cross modules: console-capture and
|
|
95
|
+
// network-intercept share this one refcount, so an unserialized transition
|
|
96
|
+
// races the detach across both). Chaining makes each 0→1 attach and 1→0
|
|
97
|
+
// detach atomic per tab. Keyed by tab so unrelated tabs never block each
|
|
98
|
+
// other. Mirrors tab-groups.js mutateStore.
|
|
99
|
+
const LEASE_TRANSITIONS = new Map(); // tabId → Promise chain
|
|
100
|
+
|
|
101
|
+
function dbgTarget(tabId) {
|
|
102
|
+
return { tabId };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Serialize a refcount transition for `tabId`. `fn` runs with exclusive
|
|
106
|
+
// access to that tab's slot; concurrent callers queue behind it. A rejection
|
|
107
|
+
// in one link never wedges the chain (the next link runs regardless).
|
|
108
|
+
function withLeaseLock(tabId, fn) {
|
|
109
|
+
const prev = LEASE_TRANSITIONS.get(tabId) ?? Promise.resolve();
|
|
110
|
+
const next = prev.then(fn, fn);
|
|
111
|
+
const tail = next.then(
|
|
112
|
+
() => {},
|
|
113
|
+
() => {},
|
|
114
|
+
);
|
|
115
|
+
LEASE_TRANSITIONS.set(tabId, tail);
|
|
116
|
+
// Drop the entry once settled if it's still the current tail, so the Map
|
|
117
|
+
// doesn't retain a settled-Promise entry for every tab ever debugged.
|
|
118
|
+
tail.then(() => {
|
|
119
|
+
if (LEASE_TRANSITIONS.get(tabId) === tail) LEASE_TRANSITIONS.delete(tabId);
|
|
120
|
+
});
|
|
121
|
+
return next;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Acquire is best-effort with respect to attach errors: if another
|
|
125
|
+
// extension or DevTools is already attached when our refcount transitions
|
|
126
|
+
// 0→1, we still record the lease so the matching release decrements
|
|
127
|
+
// correctly. Per-call sendCommand failures will surface later as plain
|
|
128
|
+
// errors. This matches the prior semantics where network-intercept caught
|
|
129
|
+
// "already attached" and proceeded.
|
|
130
|
+
//
|
|
131
|
+
// Returns a LEASE TOKEN { tabId, generation } that MUST be handed back to
|
|
132
|
+
// releaseDebuggerLease. Because the count is generation-stamped (see
|
|
133
|
+
// ATTACHED_TAB_LEASES) a detach never touches the count out of band — it only
|
|
134
|
+
// bumps the generation — so there is no queued reset that could clobber a count
|
|
135
|
+
// this acquire sets. The one remaining hazard is a detach landing DURING our
|
|
136
|
+
// own debugger.attach await: the physical attachment we just made is already
|
|
137
|
+
// gone, so we must NOT count it. We detect that by comparing the generation
|
|
138
|
+
// across the await and, if it moved, retry in a fresh lock turn (which observes
|
|
139
|
+
// the bumped generation and re-attaches cleanly). The `current === 0` path is
|
|
140
|
+
// the only one that awaits; riding an existing lease is fully synchronous, so
|
|
141
|
+
// no detach can interleave it.
|
|
142
|
+
const MAX_ACQUIRE_RETRIES = 8;
|
|
143
|
+
const RETRY = Symbol("retry");
|
|
144
|
+
|
|
145
|
+
// Chrome freezes or discards background tabs, the user's and agents'
|
|
146
|
+
// alike. A discarded tab still accepts debugger.attach, but every CDP command
|
|
147
|
+
// after it waits for a renderer that never starts. Frozen pages retain their
|
|
148
|
+
// renderer but stop asynchronous work. Callers run this before their commands:
|
|
149
|
+
// it resumes frozen pages or reloads discarded ones only for an agent-owned
|
|
150
|
+
// tab or with "Manage open tabs".
|
|
151
|
+
//
|
|
152
|
+
// Waking can let a navigation finish, invalidating checks on the old page
|
|
153
|
+
// (allowed origins, its label, page activation). `authorize` re-runs those
|
|
154
|
+
// checks; without one, a changed URL is refused so a retry checks from scratch.
|
|
155
|
+
const WAKE_TIMEOUT_MS = 30_000;
|
|
156
|
+
export async function prepareDiscardedTab(chromeApi, tabId, authorize = null) {
|
|
157
|
+
// A missing tab is debugger.attach's error to report.
|
|
158
|
+
const tab = await chromeApi.tabs.get(tabId).catch(() => null);
|
|
159
|
+
// Session restore leaves background tabs "unloaded" without marking them
|
|
160
|
+
// discarded; they have no renderer either.
|
|
161
|
+
if (!tab?.discarded && tab?.status !== "unloaded" && !tab?.frozen) return;
|
|
162
|
+
const authorizeWake = async () => {
|
|
163
|
+
if (authorize) await authorize();
|
|
164
|
+
if (
|
|
165
|
+
!(await agentLabelFor(chromeApi, tabId)) &&
|
|
166
|
+
!(await isActionGrantEnabled(chromeApi, TABS_MANAGE_SCOPE))
|
|
167
|
+
) {
|
|
168
|
+
throw new Error(tab.frozen
|
|
169
|
+
? `tab ${tabId} is frozen by Chrome. It resumes when the user opens it; agents can resume their own tabs, or any tab with "Manage open tabs".`
|
|
170
|
+
: `tab ${tabId} is not loaded (Chrome discarded it to save memory, or has not restored it since a restart), so it has no page to read. It loads when the user opens it; agents can reload their own tabs, or any tab with "Manage open tabs".`);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
await authorizeWake();
|
|
174
|
+
const validatedUrl = tab.url;
|
|
175
|
+
// Frozen pages retain their renderer and state, but timers and asynchronous
|
|
176
|
+
// source reads stop progressing. Resume through the shared debugger lease;
|
|
177
|
+
// reloading or activating the tab would lose state or steal the user's focus.
|
|
178
|
+
if (tab.frozen && !tab.discarded && tab.status !== "unloaded") {
|
|
179
|
+
const lease = await acquireDebuggerLease(chromeApi, tabId);
|
|
180
|
+
let timer;
|
|
181
|
+
let resumed = false;
|
|
182
|
+
try {
|
|
183
|
+
await Promise.race([
|
|
184
|
+
chromeApi.debugger.sendCommand(dbgTarget(tabId), "Page.setWebLifecycleState", { state: "active" }),
|
|
185
|
+
new Promise((_, reject) => {
|
|
186
|
+
timer = setTimeout(() => reject(new Error(`tab ${tabId} stayed frozen for ${WAKE_TIMEOUT_MS}ms`)), WAKE_TIMEOUT_MS);
|
|
187
|
+
}),
|
|
188
|
+
]);
|
|
189
|
+
await authorizeWake();
|
|
190
|
+
if (!authorize && (await chromeApi.tabs.get(tabId)).url !== validatedUrl) {
|
|
191
|
+
throw new Error(`tab ${tabId} resumed on a different page; retry to act on the page it shows now`);
|
|
192
|
+
}
|
|
193
|
+
resumed = true;
|
|
194
|
+
} finally {
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
await releaseDebuggerLease(chromeApi, lease, { idleDetachMs: resumed ? DEBUGGER_IDLE_DETACH_MS : 0 });
|
|
197
|
+
}
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
await chromeApi.tabs.reload(tabId);
|
|
201
|
+
const deadline = Date.now() + WAKE_TIMEOUT_MS;
|
|
202
|
+
for (;;) {
|
|
203
|
+
const live = await chromeApi.tabs.get(tabId);
|
|
204
|
+
if (!live.discarded && live.status === "complete") {
|
|
205
|
+
if (authorize) {
|
|
206
|
+
await authorize();
|
|
207
|
+
} else if (live.url !== validatedUrl) {
|
|
208
|
+
throw new Error(
|
|
209
|
+
`tab ${tabId} was not loaded and its reload landed on a different page; retry to act on the page it shows now`,
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (Date.now() > deadline) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
`tab ${tabId} was not loaded and did not finish loading within ${WAKE_TIMEOUT_MS}ms`,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export async function acquireDebuggerLease(chromeApi, tabId) {
|
|
224
|
+
for (let attempt = 0; ; attempt++) {
|
|
225
|
+
const token = await withLeaseLock(tabId, async () => {
|
|
226
|
+
const genBefore = debuggerDetachGeneration(tabId);
|
|
227
|
+
const current = currentLeaseCount(tabId);
|
|
228
|
+
const idle = currentEntry(tabId);
|
|
229
|
+
const reuseIdle = current === 0 && idle?.idleTimer != null;
|
|
230
|
+
if (reuseIdle) {
|
|
231
|
+
// Still attached from the previous action: no attach, no infobar churn.
|
|
232
|
+
clearIdleTimer(idle);
|
|
233
|
+
} else if (current === 0) {
|
|
234
|
+
try {
|
|
235
|
+
await chromeApi.debugger.attach(dbgTarget(tabId), "1.3");
|
|
236
|
+
} catch (err) {
|
|
237
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
238
|
+
if (!/already attached|Another debugger/i.test(msg)) {
|
|
239
|
+
throw err;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// A detach raced our attach (generation moved during the await). The
|
|
243
|
+
// attachment we just made is gone; counting it would mint a phantom
|
|
244
|
+
// live lease. Retry in a fresh lock turn against the bumped generation.
|
|
245
|
+
if (debuggerDetachGeneration(tabId) !== genBefore) {
|
|
246
|
+
return RETRY;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// Stamp the count with the (post-await, unchanged) generation.
|
|
250
|
+
ATTACHED_TAB_LEASES.set(tabId, {
|
|
251
|
+
generation: genBefore,
|
|
252
|
+
count: current + 1,
|
|
253
|
+
idleTimer: null,
|
|
254
|
+
});
|
|
255
|
+
return { tabId, generation: genBefore };
|
|
256
|
+
});
|
|
257
|
+
if (token !== RETRY) return token;
|
|
258
|
+
// Bound the loop: a detach landing on every one of MAX_ACQUIRE_RETRIES
|
|
259
|
+
// consecutive attempts is a pathological detach storm — throw a retryable
|
|
260
|
+
// error rather than spin or mint a phantom lease. The caller's start()
|
|
261
|
+
// cleans up its persisted row and surfaces the failure.
|
|
262
|
+
if (attempt >= MAX_ACQUIRE_RETRIES) {
|
|
263
|
+
throw new Error(
|
|
264
|
+
`debugger lease: external detach raced ${MAX_ACQUIRE_RETRIES + 1} consecutive attaches on tab ${tabId}`,
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Release a lease acquired above. Pass the token acquireDebuggerLease returned.
|
|
271
|
+
// If the token's generation is older than the tab's current one, an external
|
|
272
|
+
// detach superseded this lease — the physical attach it counted against is
|
|
273
|
+
// gone and a newer lease may now own a fresh attach. Decrementing here would
|
|
274
|
+
// corrupt that newer lease's count (and could physically detach it at 1→0), so
|
|
275
|
+
// a superseded token is a no-op.
|
|
276
|
+
//
|
|
277
|
+
// `idleDetachMs` > 0 keeps the attachment for that long after the last lease
|
|
278
|
+
// goes, for the next action to reuse (see DEBUGGER_IDLE_DETACH_MS).
|
|
279
|
+
export function releaseDebuggerLease(chromeApi, lease, { idleDetachMs = 0 } = {}) {
|
|
280
|
+
const { tabId, generation: leaseGeneration } = lease;
|
|
281
|
+
return withLeaseLock(tabId, async () => {
|
|
282
|
+
if (leaseGeneration !== debuggerDetachGeneration(tabId)) {
|
|
283
|
+
return; // superseded by an external detach — leave the current lease alone
|
|
284
|
+
}
|
|
285
|
+
const current = currentLeaseCount(tabId);
|
|
286
|
+
if (current <= 0) {
|
|
287
|
+
// Unmatched release — be defensive (eviction-induced state loss,
|
|
288
|
+
// racing detach from elsewhere): drop the (empty) entry, don't
|
|
289
|
+
// negative-count. An idle attachment keeps its own detach timer.
|
|
290
|
+
if (currentEntry(tabId)?.idleTimer == null) ATTACHED_TAB_LEASES.delete(tabId);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const next = current - 1;
|
|
294
|
+
if (next === 0 && idleDetachMs > 0) {
|
|
295
|
+
const idleTimer = setTimeout(() => {
|
|
296
|
+
void detachIfStillIdle(chromeApi, tabId, leaseGeneration, idleTimer);
|
|
297
|
+
}, idleDetachMs);
|
|
298
|
+
ATTACHED_TAB_LEASES.set(tabId, {
|
|
299
|
+
generation: leaseGeneration,
|
|
300
|
+
count: 0,
|
|
301
|
+
idleTimer,
|
|
302
|
+
});
|
|
303
|
+
} else if (next === 0) {
|
|
304
|
+
ATTACHED_TAB_LEASES.delete(tabId);
|
|
305
|
+
await detachQuietly(chromeApi, tabId);
|
|
306
|
+
} else {
|
|
307
|
+
ATTACHED_TAB_LEASES.set(tabId, {
|
|
308
|
+
generation: leaseGeneration,
|
|
309
|
+
count: next,
|
|
310
|
+
idleTimer: null,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function detachQuietly(chromeApi, tabId) {
|
|
317
|
+
forgetDialog(tabId);
|
|
318
|
+
try {
|
|
319
|
+
await chromeApi.debugger.detach(dbgTarget(tabId));
|
|
320
|
+
} catch {
|
|
321
|
+
// already detached (DevTools opened, tab closed, another tool just
|
|
322
|
+
// released it) — fine
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// The idle window ran out. Detach only if nothing reacquired the attachment
|
|
327
|
+
// and no external detach replaced it in the meantime (then the attachment this
|
|
328
|
+
// timer was guarding is gone, and a newer one belongs to someone else).
|
|
329
|
+
function detachIfStillIdle(chromeApi, tabId, generation, idleTimer) {
|
|
330
|
+
return withLeaseLock(tabId, async () => {
|
|
331
|
+
const entry = ATTACHED_TAB_LEASES.get(tabId);
|
|
332
|
+
if (
|
|
333
|
+
!entry ||
|
|
334
|
+
entry.idleTimer !== idleTimer ||
|
|
335
|
+
entry.generation !== generation ||
|
|
336
|
+
generation !== debuggerDetachGeneration(tabId)
|
|
337
|
+
) {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if (openDialog(tabId)) {
|
|
341
|
+
// Detaching would hand the waiting dialog to the user early; the
|
|
342
|
+
// dialog's own hold timer decides when that happens.
|
|
343
|
+
const nextTimer = setTimeout(() => {
|
|
344
|
+
void detachIfStillIdle(chromeApi, tabId, generation, nextTimer);
|
|
345
|
+
}, DEBUGGER_IDLE_DETACH_MS);
|
|
346
|
+
entry.idleTimer = nextTimer;
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
ATTACHED_TAB_LEASES.delete(tabId);
|
|
350
|
+
await detachQuietly(chromeApi, tabId);
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ── external detach ──────────────────────────────────────────────────────
|
|
355
|
+
//
|
|
356
|
+
// chrome.debugger.onDetach fires only for detaches WE did not initiate: the
|
|
357
|
+
// user clicks "cancel" on the debugging infobar, DevTools takes the target,
|
|
358
|
+
// or the tab goes away. Our own chrome.debugger.detach() never echoes back.
|
|
359
|
+
// When it fires, the attachment is gone no matter what our refcount says —
|
|
360
|
+
// leases held by live capture sessions are dead, and without invalidation a
|
|
361
|
+
// same-session start() would return resumed:true on a listener that will
|
|
362
|
+
// never see another event.
|
|
363
|
+
|
|
364
|
+
// Long-lived-lease consumers (console-capture, network-intercept) register a
|
|
365
|
+
// callback here at module-import time; called as (chromeApi, tabId, reason).
|
|
366
|
+
// Intentionally NOT cleared by the test reset below — registration happens
|
|
367
|
+
// once per module load, so wiping it between test cases would permanently
|
|
368
|
+
// unsubscribe the consumers.
|
|
369
|
+
const EXTERNAL_DETACH_SUBSCRIBERS = new Set();
|
|
370
|
+
|
|
371
|
+
export function onExternalDebuggerDetach(callback) {
|
|
372
|
+
EXTERNAL_DETACH_SUBSCRIBERS.add(callback);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Per-tab detach generation, bumped SYNCHRONOUSLY the instant onDetach fires.
|
|
376
|
+
// This single scalar is the authoritative liveness signal for the whole
|
|
377
|
+
// module: the refcount is stamped with it (currentLeaseCount reads a
|
|
378
|
+
// stale-generation count as 0), lease tokens carry it (a superseded token
|
|
379
|
+
// releases as a no-op), and consumers store it on their live sessions (a
|
|
380
|
+
// mismatch means "reattach"). Because invalidation is a synchronous generation
|
|
381
|
+
// bump rather than an out-of-band refcount mutation, there is no window in
|
|
382
|
+
// which a queued reset could clobber a count a concurrent acquire just set.
|
|
383
|
+
const DETACH_GENERATIONS = new Map(); // tabId → integer
|
|
384
|
+
// Why Chrome last detached us from a tab (onDetach's reason, e.g.
|
|
385
|
+
// "canceled_by_user" when the user dismissed the debugging bar).
|
|
386
|
+
const DETACH_REASONS = new Map(); // tabId → string
|
|
387
|
+
|
|
388
|
+
export function debuggerDetachGeneration(tabId) {
|
|
389
|
+
return DETACH_GENERATIONS.get(tabId) ?? 0;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function debuggerDetachReason(tabId) {
|
|
393
|
+
return DETACH_REASONS.get(tabId) ?? null;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// Wire chrome.debugger.onDetach → generation bump + subscriber fan-out. Called
|
|
397
|
+
// from background.js at SW top level (MV3 event listeners must be registered on
|
|
398
|
+
// every SW wakeup); tests call it with their chrome stub. We do NOT touch the
|
|
399
|
+
// refcount here — bumping the generation invalidates the stamped count under
|
|
400
|
+
// the lock's own reads, which avoids the reset-vs-acquire race entirely.
|
|
401
|
+
export function registerExternalDetachHandler(chromeApi) {
|
|
402
|
+
chromeApi.debugger.onDetach.addListener((source, reason) => {
|
|
403
|
+
const tabId = source?.tabId;
|
|
404
|
+
if (tabId == null) return;
|
|
405
|
+
clearIdleTimer(ATTACHED_TAB_LEASES.get(tabId));
|
|
406
|
+
invalidateAttachment(chromeApi, tabId, typeof reason === "string" ? reason : "unknown");
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// The attachment is gone (or about to be, when we hand a dialog to the user):
|
|
411
|
+
// every lease and capture session on it is dead.
|
|
412
|
+
function invalidateAttachment(chromeApi, tabId, reason) {
|
|
413
|
+
DETACH_GENERATIONS.set(tabId, (DETACH_GENERATIONS.get(tabId) ?? 0) + 1);
|
|
414
|
+
DETACH_REASONS.set(tabId, reason);
|
|
415
|
+
forgetDialog(tabId);
|
|
416
|
+
for (const cb of EXTERNAL_DETACH_SUBSCRIBERS) {
|
|
417
|
+
try {
|
|
418
|
+
cb(chromeApi, tabId, reason);
|
|
419
|
+
} catch {
|
|
420
|
+
// One consumer's cleanup failure must not starve the others.
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Test-only: reset the lease map between cases. Production code never
|
|
426
|
+
// imports this — SW lifecycle handles eviction.
|
|
427
|
+
export function __resetDebuggerLeasesForTests() {
|
|
428
|
+
for (const entry of ATTACHED_TAB_LEASES.values()) clearIdleTimer(entry);
|
|
429
|
+
ATTACHED_TAB_LEASES.clear();
|
|
430
|
+
DETACH_REASONS.clear();
|
|
431
|
+
LEASE_TRANSITIONS.clear();
|
|
432
|
+
DETACH_GENERATIONS.clear();
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Test-only: inspect the live refcount (at the current generation) for
|
|
436
|
+
// assertions. A count stamped with a superseded generation reads as 0.
|
|
437
|
+
export function __debuggerLeaseCountForTests(tabId) {
|
|
438
|
+
return currentLeaseCount(tabId);
|
|
439
|
+
}
|