@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,627 @@
1
+ // Console capture primitive for the chrome connector.
2
+ //
3
+ // Exposes three action_keys:
4
+ //
5
+ // console_capture_start({ tab_id?, max_buffer_entries?, max_message_bytes? })
6
+ // Attach the CDP Runtime domain to the tab and start buffering console
7
+ // output (console.log/warn/error/... via Runtime.consoleAPICalled, plus
8
+ // uncaught exceptions via Runtime.exceptionThrown). The first call on a
9
+ // tab adopts the run's scratch tab if `tab_id` is omitted. Returns
10
+ // `{ session_id, tab_id }`. Calling start() again with the same session
11
+ // id is idempotent — useful after a service-worker eviction.
12
+ //
13
+ // console_capture_drain({ session_id })
14
+ // Return all buffered console entries for `session_id` as text (one line
15
+ // per entry). Atomically clears the buffer so subsequent drain() calls
16
+ // see only fresh entries.
17
+ //
18
+ // console_capture_stop({ session_id })
19
+ // Remove the CDP event listener for `session_id` and delete the buffer.
20
+ // Runtime domain stays enabled if other live sessions on the same tab
21
+ // are still listening; otherwise the next withDebugger() on that tab
22
+ // will detach naturally.
23
+ //
24
+ // Wire model: each session = one row in chrome.storage.session under
25
+ // `owletto.console.sessions.<session_id>` with shape
26
+ // { tab_id, buffer: Array<{level, text, args, ts, url}> }.
27
+ // Persisting to chrome.storage.session is the same surface the tab-group
28
+ // store uses — it survives MV3 service-worker eviction,
29
+ // which is critical because a `start` → `drain` round-trip from the
30
+ // gateway may straddle multiple SW wakeups.
31
+ //
32
+ // Concurrency: multiple sessions can coexist on the same tab. The CDP
33
+ // Runtime listener is registered once per session; every console event is
34
+ // appended to each session's buffer independently. Two connectors that
35
+ // both watch the same tab each get an independent copy in their own buffer.
36
+ //
37
+ // Message size: an entry's rendered text bigger than `max_message_bytes`
38
+ // (default 8 KiB) is truncated and flagged `truncated: true`. Each session
39
+ // caps total buffered entries at `max_buffer_entries` (default 200) —
40
+ // oldest entries drop first (FIFO).
41
+ //
42
+ // Security: respects the connector's `allowedOrigins` runCtx exactly the
43
+ // same way as tools.js — the start() call enforces against the tab's
44
+ // current URL, and every entry URL is matched against the same allowlist at
45
+ // capture time (a session can't be coerced into capturing off-allowlist
46
+ // console output by a redirect).
47
+
48
+ const SESSION_KEY_PREFIX = 'owletto.console.sessions.';
49
+
50
+ const DEFAULT_MAX_BUFFER_ENTRIES = 200;
51
+ const DEFAULT_MAX_MESSAGE_BYTES = 8 * 1024;
52
+
53
+ // Shared debugger lease/refcount. Both withDebugger() (action tools) and
54
+ // tool_console_capture_start hold leases on the same tabId;
55
+ // chrome.debugger.attach/detach happen only on 0→1 / 1→0 transitions so a
56
+ // long-lived capture session coexists cleanly with per-call action tools on
57
+ // the same tab. Lives in its own module to avoid a tools.js ↔
58
+ // console-capture.js import cycle.
59
+ import {
60
+ acquireDebuggerLease,
61
+ debuggerDetachGeneration,
62
+ onExternalDebuggerDetach,
63
+ prepareDiscardedTab,
64
+ releaseDebuggerLease,
65
+ } from "./debugger-lease.js";
66
+ import { browserUrlAllowed, assertBrowserSessionGrant } from "./browser-origin-policy.js";
67
+
68
+ // In-memory per-SW-instance: session_id → { tabId, listener }.
69
+ // On SW eviction this is empty on next wake; the persisted session row in
70
+ // chrome.storage.session lets start() re-attach idempotently.
71
+ const LIVE_SESSIONS = new Map();
72
+
73
+ // External detach (user cancels the debugging infobar, DevTools takes the
74
+ // target, tab closes) kills the CDP attachment out from under every live
75
+ // session on that tab. Drop the dead in-memory entries so a same-session
76
+ // start() performs a REAL reattach instead of returning resumed:true on a
77
+ // listener that will never fire again. The persisted row (buffer + policy)
78
+ // is intentionally kept — the resume revives it. No lease release: the lease
79
+ // module hard-resets the tab's refcount on this same event.
80
+ onExternalDebuggerDetach((chromeApi, tabId) => {
81
+ for (const [sessionId, live] of LIVE_SESSIONS) {
82
+ if (live.tabId !== tabId) continue;
83
+ chromeApi.debugger.onEvent.removeListener(live.listener);
84
+ LIVE_SESSIONS.delete(sessionId);
85
+ }
86
+ });
87
+
88
+ // ONE per-session promise chain that serializes the ENTIRE per-session
89
+ // lifecycle. Every operation that touches a session's shared state —
90
+ // start()/stop()/drain() bodies AND each buffered-entry append — runs under
91
+ // withSessionLock(sessionId, fn), so for a given session_id no two of them
92
+ // ever interleave. This is the structural guard for a whole class of races
93
+ // we kept hitting one at a time:
94
+ // - buffer read-modify-write (chrome.storage.session has no CAS: two
95
+ // appends both read → push → write and clobber each other);
96
+ // - session-start (two concurrent idempotent retries of the same
97
+ // session_id each acquiring a lease + installing a listener, then one
98
+ // LIVE_SESSIONS entry overwriting the other → orphaned listener/lease);
99
+ // - stop racing an in-flight append (a late append resurrecting a phantom
100
+ // row after the row was deleted).
101
+ // Keyed by session so unrelated sessions never block each other. Mirrors the
102
+ // idiom of tab-groups.js mutateStore and debugger-lease.js withLeaseLock. A
103
+ // rejection in one link never wedges the chain (the next link runs
104
+ // regardless). NB: never nest withSessionLock inside itself for the same id —
105
+ // that self-waits forever; the lifecycle ops each take the lock exactly once.
106
+ const SESSION_LOCKS = new Map(); // session_id → Promise chain
107
+
108
+ function withSessionLock(sessionId, fn) {
109
+ const prev = SESSION_LOCKS.get(sessionId) ?? Promise.resolve();
110
+ const next = prev.then(fn, fn);
111
+ const tail = next.then(
112
+ () => {},
113
+ () => {},
114
+ );
115
+ SESSION_LOCKS.set(sessionId, tail);
116
+ // Drop the entry once this tail settles, but only if it's still the current
117
+ // tail (a newer call may have chained on and replaced it). session_id is a
118
+ // random UUID, so without this the Map would grow unbounded across the SW's
119
+ // lifetime as stopped sessions leave settled-Promise entries behind.
120
+ tail.then(() => {
121
+ if (SESSION_LOCKS.get(sessionId) === tail) SESSION_LOCKS.delete(sessionId);
122
+ });
123
+ return next;
124
+ }
125
+
126
+ function dbgTarget(tabId) {
127
+ return { tabId };
128
+ }
129
+
130
+ function sessionKey(sessionId) {
131
+ return `${SESSION_KEY_PREFIX}${sessionId}`;
132
+ }
133
+
134
+ async function readSession(chromeApi, sessionId) {
135
+ const key = sessionKey(sessionId);
136
+ const stored = await chromeApi.storage.session.get(key);
137
+ return stored[key] ?? null;
138
+ }
139
+
140
+ async function writeSession(chromeApi, sessionId, row) {
141
+ await chromeApi.storage.session.set({ [sessionKey(sessionId)]: row });
142
+ }
143
+
144
+ async function deleteSession(chromeApi, sessionId) {
145
+ await chromeApi.storage.session.remove(sessionKey(sessionId));
146
+ }
147
+
148
+ function generateSessionId() {
149
+ // crypto.randomUUID is available in MV3 SWs (Chrome 92+); minimum is 120
150
+ // in manifest.json so this is safe.
151
+ return `console-${globalThis.crypto.randomUUID()}`;
152
+ }
153
+
154
+ // Render a CDP RemoteObject (from Runtime.consoleAPICalled args) to a short
155
+ // string. We never deref by objectId — the value/description that CDP ships
156
+ // inline is all we keep, which is enough for a log line and avoids a second
157
+ // round-trip per arg.
158
+ function serializeRemoteObject(obj) {
159
+ if (!obj || typeof obj !== 'object') return String(obj);
160
+ if ('value' in obj && obj.value !== undefined) {
161
+ if (typeof obj.value === 'object') {
162
+ try {
163
+ return JSON.stringify(obj.value);
164
+ } catch {
165
+ return String(obj.value);
166
+ }
167
+ }
168
+ return String(obj.value);
169
+ }
170
+ if (typeof obj.description === 'string') return obj.description;
171
+ if (obj.type === 'undefined') return 'undefined';
172
+ if (obj.subtype === 'null') return 'null';
173
+ return obj.type ?? '';
174
+ }
175
+
176
+ // Render an exception (Runtime.exceptionThrown) to a single string, preferring
177
+ // the thrown value's description over the bare text.
178
+ function serializeException(details) {
179
+ const ex = details?.exception;
180
+ if (ex && typeof ex.description === 'string') return ex.description;
181
+ // Only serialize the thrown value when it's actually present. Many
182
+ // Runtime.exceptionThrown payloads ship no `exception` RemoteObject at all
183
+ // (just `text` + a stackTrace); serializeRemoteObject(undefined) returns the
184
+ // literal string "undefined", so without this guard those would render as
185
+ // "undefined" instead of the real error text.
186
+ if (ex) {
187
+ const value = serializeRemoteObject(ex);
188
+ if (value) return value;
189
+ }
190
+ return details?.text ?? 'Uncaught exception';
191
+ }
192
+
193
+ // ── start ────────────────────────────────────────────────────────────────
194
+ //
195
+ // The whole body runs under withSessionLock(sessionId), so two concurrent
196
+ // starts of the same session_id (e.g. idempotent retries across SW wakeups)
197
+ // serialize: the first installs the lease + listener, the second reuses them
198
+ // after waking the tab if needed. Each live session holds one persistent lease
199
+ // and one listener.
200
+ export async function tool_console_capture_start(chromeApi, args, runCtx) {
201
+ const requestedTabId = args?.tab_id ?? runCtx.scratchTabId;
202
+ if (requestedTabId == null) {
203
+ throw new Error('console_capture_start: no tab (pass tab_id or use after navigate)');
204
+ }
205
+ const sessionId = args?.session_id ?? generateSessionId();
206
+
207
+ return withSessionLock(sessionId, async () => {
208
+ // Idempotent resume: if this session is already live in *this* SW
209
+ // instance, keep its row (including any in-flight buffer), persistent
210
+ // lease and listener. Under the lock this is the authoritative "already started"
211
+ // check, so a concurrent same-session start can't have half-installed.
212
+ // Report the tab the session is ACTUALLY bound to — a retry passing a
213
+ // different tab_id must not misreport where the listener lives.
214
+ //
215
+ // Liveness is gated on the tab's detach generation: an entry whose
216
+ // generation no longer matches the tab's current one was orphaned by an
217
+ // external detach (possibly one that landed after acquireDebuggerLease but
218
+ // before this entry was published, which the eager onDetach sweep can't
219
+ // see). Treat it as dead — remove its listener and fall through to a real
220
+ // reattach — rather than returning a resumed:true no-op on a lease that's
221
+ // already been reset to 0.
222
+ assertBrowserSessionGrant((await readSession(chromeApi, sessionId)) ?? LIVE_SESSIONS.get(sessionId), runCtx);
223
+ const live = LIVE_SESSIONS.get(sessionId);
224
+ if (live) {
225
+ if (debuggerDetachGeneration(live.tabId) === live.detachGen) {
226
+ await prepareDiscardedTab(chromeApi, live.tabId, () =>
227
+ enforceTabUrlAgainstAllowedOrigins(chromeApi, live.tabId, { allowedOrigins: live.allowed_origins }),
228
+ );
229
+ if (debuggerDetachGeneration(live.tabId) === live.detachGen) {
230
+ return {
231
+ ok: true,
232
+ observation: { session_id: sessionId, tab_id: live.tabId, resumed: true },
233
+ };
234
+ }
235
+ }
236
+ chromeApi.debugger.onEvent.removeListener(live.listener);
237
+ LIVE_SESSIONS.delete(sessionId);
238
+ }
239
+
240
+ // An existing persisted row (SW-eviction resume: the row survived in
241
+ // chrome.storage.session but LIVE_SESSIONS was cleared) is AUTHORITATIVE
242
+ // for the session's tab, origin policy, and limits — args/runCtx configure
243
+ // NEW sessions only. Otherwise a retry with a different tab_id or under a
244
+ // different allowlist would silently rebind the session and change its
245
+ // security policy while inheriting a buffer captured under the old one.
246
+ const existing = await readSession(chromeApi, sessionId);
247
+ const tabId = existing?.tab_id ?? requestedTabId;
248
+ const allowedOriginsPolicy = existing
249
+ ? (existing.allowed_origins ?? [])
250
+ : (runCtx.allowedOrigins ?? []);
251
+ const maxBufferEntries = existing
252
+ ? existing.max_buffer_entries
253
+ : clampInt(args?.max_buffer_entries, 1, 2000, DEFAULT_MAX_BUFFER_ENTRIES);
254
+ const maxMessageBytes = existing
255
+ ? existing.max_message_bytes
256
+ : clampInt(args?.max_message_bytes, 256, 1024 * 1024, DEFAULT_MAX_MESSAGE_BYTES);
257
+
258
+ // allowedOrigins enforcement on the *current* tab URL — keeps the
259
+ // primitive symmetric with click_ref / type_ref / evaluate. A connector
260
+ // for linkedin.com can't accidentally start capturing bank.com's console
261
+ // because it passed the wrong tab_id. Checked against the EFFECTIVE
262
+ // tab + policy (stored ones on resume), before any state is committed.
263
+ await enforceTabUrlAgainstAllowedOrigins(chromeApi, tabId, {
264
+ allowedOrigins: allowedOriginsPolicy,
265
+ });
266
+ // Before the row is written: a refusal must not touch a resumed session.
267
+ await prepareDiscardedTab(chromeApi, tabId);
268
+
269
+ // Persist the session row first so a SW eviction between start() and the
270
+ // CDP attach can't leave a dangling listener / phantom buffer. Preserve an
271
+ // existing buffer so re-attaching doesn't drop entries captured before the
272
+ // eviction.
273
+ await writeSession(chromeApi, sessionId, {
274
+ tab_id: tabId,
275
+ allowed_origins: allowedOriginsPolicy,
276
+ max_buffer_entries: maxBufferEntries,
277
+ max_message_bytes: maxMessageBytes,
278
+ buffer: Array.isArray(existing?.buffer) ? existing.buffer : [],
279
+ created_at: existing?.created_at ?? Date.now(),
280
+ });
281
+
282
+ // Take a shared debugger lease (see tools.js). If no one else is attached
283
+ // on this tab, the lease attaches; if a withDebugger() action tool
284
+ // currently holds the tab, the lease just bumps the refcount and we ride
285
+ // the existing attach. We keep the lease for the session's lifetime
286
+ // (intentionally NOT under withDebugger which auto-detaches at end of fn),
287
+ // and release it in tool_console_capture_stop when the last live session
288
+ // on this tab ends. This is what makes a later navigate / evaluate via
289
+ // withDebugger on the same tab safe: it sees a non-zero lease, skips the
290
+ // attach, runs, decrements back. The 1→0 detach is deferred until
291
+ // console_capture_stop.
292
+ let lease;
293
+ try {
294
+ lease = await acquireDebuggerLease(chromeApi, tabId);
295
+ } catch (err) {
296
+ await deleteSession(chromeApi, sessionId);
297
+ throw err;
298
+ }
299
+
300
+ // Authoritative committed top-frame URL, updated in CDP event order on
301
+ // every top-frame navigation and read synchronously by the listener.
302
+ // Starts null and is seeded from the tab URL AFTER the listener is
303
+ // installed (see below), so a navigation racing the seed fetch is never
304
+ // missed; until the seed resolves, allowlisted sessions conservatively
305
+ // drop entries rather than trust a stale URL.
306
+ let topFrameUrl = null;
307
+
308
+ const listener = (source, method, params) => {
309
+ if (source.tabId !== tabId) return;
310
+ // Track the committed top-frame URL synchronously, in delivery order.
311
+ // Only top frames (no parentId) redefine the tab's security origin.
312
+ if (method === 'Page.frameNavigated') {
313
+ const frame = params?.frame;
314
+ if (frame && frame.parentId == null && typeof frame.url === 'string') {
315
+ topFrameUrl = frame.url;
316
+ }
317
+ return;
318
+ }
319
+ if (method === 'Runtime.consoleAPICalled') {
320
+ const level = params?.type ?? 'log';
321
+ const url = firstFrameUrl(params?.stackTrace);
322
+ const text = (params?.args ?? []).map(serializeRemoteObject).join(' ');
323
+ // Fire-and-buffer. We don't await here — listener must return
324
+ // synchronously to keep CDP delivery in order. Snapshot the origin URL
325
+ // NOW (synchronously) so a later navigation can't retroactively
326
+ // authorize this entry.
327
+ void bufferEntry(chromeApi, sessionId, {
328
+ level,
329
+ text,
330
+ url,
331
+ originUrl: topFrameUrl,
332
+ allowedOrigins: allowedOriginsPolicy,
333
+ maxMessageBytes,
334
+ maxBufferEntries,
335
+ });
336
+ return;
337
+ }
338
+ if (method === 'Runtime.exceptionThrown') {
339
+ const details = params?.exceptionDetails;
340
+ const url = details?.url || firstFrameUrl(details?.stackTrace);
341
+ void bufferEntry(chromeApi, sessionId, {
342
+ level: 'error',
343
+ text: serializeException(details),
344
+ url,
345
+ originUrl: topFrameUrl,
346
+ allowedOrigins: allowedOriginsPolicy,
347
+ maxMessageBytes,
348
+ maxBufferEntries,
349
+ });
350
+ }
351
+ };
352
+
353
+ // Install before enabling the domains: Chrome replays the page's buffered
354
+ // console messages in response to Runtime.enable, and events can arrive
355
+ // before the enable promise settles.
356
+ chromeApi.debugger.onEvent.addListener(listener);
357
+
358
+ try {
359
+ await chromeApi.debugger.sendCommand(dbgTarget(tabId), 'Runtime.enable', {});
360
+ // Page domain gives us Page.frameNavigated, the authoritative committed
361
+ // top-frame URL delivered in CDP event order. We track it synchronously
362
+ // (below) so origin enforcement reads the URL that was live *at the
363
+ // moment each console event was delivered* — not an async tabs.get
364
+ // sampled afterward, which an off-allowlist page could beat by logging
365
+ // and immediately navigating to an allowlisted URL before the lookup
366
+ // resolves.
367
+ await chromeApi.debugger.sendCommand(dbgTarget(tabId), 'Page.enable', {});
368
+ } catch (err) {
369
+ // If enabling the CDP domains fails the session is unusable; drop the
370
+ // listener, release the lease we just acquired and clean up the
371
+ // persisted row.
372
+ chromeApi.debugger.onEvent.removeListener(listener);
373
+ await releaseDebuggerLease(chromeApi, lease);
374
+ await deleteSession(chromeApi, sessionId);
375
+ throw err;
376
+ }
377
+
378
+ // Seed the origin from the current tab URL (validated against the
379
+ // allowlist at the top of start()) — but only if no frameNavigated arrived
380
+ // while the fetch was in flight; a navigation observed in event order is
381
+ // always fresher than an async tabs.get sample.
382
+ const seedUrl = await currentTabUrl(chromeApi, tabId);
383
+ if (topFrameUrl == null) topFrameUrl = seedUrl;
384
+ // detachGen comes from the LEASE token (read atomically with acquisition),
385
+ // not a pre-acquire sample — so a detach landing during acquire yields a
386
+ // token whose generation already reflects it, and the entry is correctly
387
+ // live-or-stale with no leaked refcount. Store the lease for stop() to
388
+ // release with the same token.
389
+ LIVE_SESSIONS.set(sessionId, {
390
+ allowed_origins: allowedOriginsPolicy,
391
+ tabId,
392
+ listener,
393
+ lease,
394
+ detachGen: lease.generation,
395
+ });
396
+
397
+ return { ok: true, observation: { session_id: sessionId, tab_id: tabId, resumed: false } };
398
+ });
399
+ }
400
+
401
+ function firstFrameUrl(stackTrace) {
402
+ const frame = stackTrace?.callFrames?.[0];
403
+ return frame?.url ?? '';
404
+ }
405
+
406
+ async function bufferEntry(
407
+ chromeApi,
408
+ sessionId,
409
+ { level, text, url, originUrl, allowedOrigins, maxMessageBytes, maxBufferEntries },
410
+ ) {
411
+ try {
412
+ // Per-entry allowlist enforcement. `originUrl` is the committed top-frame
413
+ // URL snapshotted SYNCHRONOUSLY in the CDP listener at event-delivery time
414
+ // (tracked via Page.frameNavigated in event order) — the browser's
415
+ // authoritative origin, which page JS cannot spoof. We deliberately do NOT
416
+ // authorize by the entry's own stack-frame `url` (forgeable via
417
+ // `//# sourceURL=`), and we do NOT sample chrome.tabs.get after the fact
418
+ // (an off-allowlist page could log and immediately navigate to an
419
+ // allowlisted URL before the async lookup resolves). The entry's `url` is
420
+ // still recorded as untrusted metadata for display/grep.
421
+ if (Array.isArray(allowedOrigins) && allowedOrigins.length > 0) {
422
+ if (!originUrl || !browserUrlAllowed(originUrl, allowedOrigins)) return;
423
+ }
424
+ const capped = truncateToBytes(text ?? '', maxMessageBytes);
425
+ const rendered = capped.text;
426
+ const truncated = capped.truncated;
427
+ // Serialize the read-modify-write under the same per-session lock as
428
+ // start/stop/drain, so concurrent console events can't clobber each
429
+ // other's appends (chrome.storage.session has no CAS) and a late append
430
+ // can't race a stop() that's tearing the session down.
431
+ await withSessionLock(sessionId, async () => {
432
+ const row = await readSession(chromeApi, sessionId);
433
+ if (!row) return; // stopped between event + buffer write
434
+ row.buffer.push({
435
+ level,
436
+ text: rendered,
437
+ url,
438
+ truncated,
439
+ ts: Date.now(),
440
+ });
441
+ // FIFO cap.
442
+ while (row.buffer.length > maxBufferEntries) row.buffer.shift();
443
+ await writeSession(chromeApi, sessionId, row);
444
+ });
445
+ } catch {
446
+ // chrome.storage.session can throw under quota pressure / eviction —
447
+ // swallow so a single lost line never kills the listener. The connector
448
+ // sees one fewer entry, matching the best-effort semantics of the
449
+ // network-intercept path.
450
+ }
451
+ }
452
+
453
+ async function currentTabUrl(chromeApi, tabId) {
454
+ try {
455
+ const tab = await chromeApi.tabs.get(tabId);
456
+ return tab?.url ?? '';
457
+ } catch {
458
+ return '';
459
+ }
460
+ }
461
+
462
+ // ── drain ────────────────────────────────────────────────────────────────
463
+
464
+ export async function tool_console_capture_drain(chromeApi, args, runCtx = {}) {
465
+ const sessionId = args?.session_id;
466
+ if (typeof sessionId !== 'string') {
467
+ throw new Error('console_capture_drain: `session_id` is required');
468
+ }
469
+ // Read-and-clear through the same per-session lock as bufferEntry, so a
470
+ // concurrent append can't slip between the read and the clear-write and get
471
+ // silently dropped: the drain either runs fully before an append or fully
472
+ // after it.
473
+ const entries = await withSessionLock(sessionId, async () => {
474
+ const row = await readSession(chromeApi, sessionId);
475
+ if (!row) return null;
476
+ assertBrowserSessionGrant(row, runCtx);
477
+ const drained = row.buffer ?? [];
478
+ row.buffer = [];
479
+ await writeSession(chromeApi, sessionId, row);
480
+ return drained;
481
+ });
482
+ if (entries == null) {
483
+ return {
484
+ ok: true,
485
+ observation: { session_id: sessionId, text: '', drained: 0, missing: true },
486
+ };
487
+ }
488
+ const text = entries.map(formatEntry).join('\n');
489
+ return {
490
+ ok: true,
491
+ observation: {
492
+ session_id: sessionId,
493
+ text,
494
+ drained: entries.length,
495
+ missing: false,
496
+ },
497
+ };
498
+ }
499
+
500
+ // One console entry → one text line: `[level] message (url)`. Keeps the
501
+ // drain output greppable by connector code without re-parsing structured
502
+ // fields.
503
+ function formatEntry(entry) {
504
+ const level = entry?.level ?? 'log';
505
+ // Collapse embedded CR/LF into spaces so a multiline message or an exception
506
+ // stack trace stays a single output line — drain() joins entries with '\n'
507
+ // and the connector greps line-by-line, so a raw newline inside one entry
508
+ // would masquerade as an entry boundary.
509
+ const text = (entry?.text ?? '').replace(/\r\n|[\r\n]/g, ' ');
510
+ const suffix = entry?.truncated ? ' …[truncated]' : '';
511
+ const origin = entry?.url ? ` (${entry.url})` : '';
512
+ return `[${level}] ${text}${suffix}${origin}`;
513
+ }
514
+
515
+ // ── stop ─────────────────────────────────────────────────────────────────
516
+
517
+ export async function tool_console_capture_stop(chromeApi, args, runCtx = {}) {
518
+ const sessionId = args?.session_id;
519
+ if (typeof sessionId !== 'string') {
520
+ throw new Error('console_capture_stop: `session_id` is required');
521
+ }
522
+ // Under the per-session lock, stop() is ordered after any in-flight append
523
+ // for this session (bufferEntry takes the same lock), so a late append can't
524
+ // resurrect a phantom row after we delete it, and it removes exactly what
525
+ // start() added: one listener + one lease.
526
+ return withSessionLock(sessionId, async () => {
527
+ assertBrowserSessionGrant((await readSession(chromeApi, sessionId)) ?? LIVE_SESSIONS.get(sessionId), runCtx);
528
+ const live = LIVE_SESSIONS.get(sessionId);
529
+ if (live) {
530
+ chromeApi.debugger.onEvent.removeListener(live.listener);
531
+ LIVE_SESSIONS.delete(sessionId);
532
+ }
533
+ await deleteSession(chromeApi, sessionId);
534
+ // Release our debugger lease. The shared refcount in debugger-lease.js
535
+ // handles detach: this only physically detaches when no other session AND
536
+ // no action tool is currently holding the tab. Action tools that
537
+ // overlapped via withDebugger will have already released their lease at
538
+ // the end of their inner fn — so if WE were the last lease holder the
539
+ // detach happens here.
540
+ //
541
+ // Gate on `live` alone, not the storage row: the lease is acquired
542
+ // exactly once when the LIVE_SESSIONS entry is created (start path), so
543
+ // `live` is the authoritative "we hold a lease" signal. Requiring the row
544
+ // too would leak the lease (refcount stuck > 0, blocking future detach)
545
+ // whenever the row was deleted first — e.g. a racing stop or
546
+ // chrome.storage.session eviction.
547
+ if (live) {
548
+ // Release with the stored lease TOKEN so a lease superseded by an
549
+ // external detach (its refcount already reset) is a no-op instead of
550
+ // decrementing a newer lease's count.
551
+ await releaseDebuggerLease(chromeApi, live.lease);
552
+ }
553
+ return {
554
+ ok: true,
555
+ observation: { session_id: sessionId, stopped: true },
556
+ };
557
+ });
558
+ }
559
+
560
+ // ── helpers ──────────────────────────────────────────────────────────────
561
+
562
+ async function enforceTabUrlAgainstAllowedOrigins(chromeApi, tabId, runCtx) {
563
+ if (!runCtx?.allowedOrigins || runCtx.allowedOrigins.length === 0) return;
564
+ const tab = await chromeApi.tabs.get(tabId);
565
+ if (!tab?.url) {
566
+ throw new Error(
567
+ `console_capture: tab ${tabId} has no URL to validate against allowedOrigins`,
568
+ );
569
+ }
570
+ // about:blank is the scratch-tab setup URL used by extension setup. The
571
+ // pattern is: open scratch tab (about:blank) → start the Runtime listener
572
+ // → navigate to the real allowed-origin URL. Rejecting about:blank here
573
+ // would block the only safe ordering for capturing the page's
574
+ // initial-render console output (entries emitted before our listener
575
+ // attaches are lost). The buffered listener itself still enforces the
576
+ // allowlist on every captured entry URL, so this carve-out is just for the
577
+ // bare-tab attach, not for what gets recorded.
578
+ if (tab.url === 'about:blank') return;
579
+ if (!browserUrlAllowed(tab.url, runCtx.allowedOrigins)) {
580
+ throw new Error(
581
+ `console_capture: '${tab.url}' is not in allowedOrigins [${runCtx.allowedOrigins.join(', ')}]`,
582
+ );
583
+ }
584
+ }
585
+
586
+ // Truncate `s` to at most `maxBytes` UTF-8 bytes without splitting a code
587
+ // point. The primitive's `max_message_bytes` contract is a *byte* budget —
588
+ // enforcing it on `.length` (UTF-16 units) undercounts multibyte text (emoji,
589
+ // CJK) by up to 4×, so a single logged emoji-heavy line could blow the budget
590
+ // the connector sized its buffer against. TextEncoder gives real byte counts;
591
+ // we grow the slice code-point by code-point (via the string iterator, which
592
+ // yields whole surrogate pairs) until the next one would overflow.
593
+ function truncateToBytes(s, maxBytes) {
594
+ const encoder = new TextEncoder();
595
+ if (encoder.encode(s).length <= maxBytes) return { text: s, truncated: false };
596
+ let out = '';
597
+ let used = 0;
598
+ for (const ch of s) {
599
+ const chBytes = encoder.encode(ch).length;
600
+ if (used + chBytes > maxBytes) break;
601
+ out += ch;
602
+ used += chBytes;
603
+ }
604
+ return { text: out, truncated: true };
605
+ }
606
+
607
+ function clampInt(value, min, max, fallback) {
608
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback;
609
+ const v = Math.floor(value);
610
+ if (v < min) return min;
611
+ if (v > max) return max;
612
+ return v;
613
+ }
614
+
615
+ // Test-only: lets unit tests reset the in-memory listener + per-session lock
616
+ // maps between cases. Production code never imports this — the SW lifecycle
617
+ // handles it.
618
+ export function __resetLiveSessionsForTests() {
619
+ LIVE_SESSIONS.clear();
620
+ SESSION_LOCKS.clear();
621
+ }
622
+
623
+ export const CONSOLE_CAPTURE_TOOLS = {
624
+ console_capture_start: tool_console_capture_start,
625
+ console_capture_drain: tool_console_capture_drain,
626
+ console_capture_stop: tool_console_capture_stop,
627
+ };