@myrialabs/clopen 0.4.21 → 0.4.22

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 (86) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/engine/README.md +11 -8
  5. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  6. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  7. package/backend/engine/docs/adapter-contract.md +66 -2
  8. package/backend/engine/docs/adding-an-engine.md +46 -7
  9. package/backend/engine/docs/frontend-and-chat.md +80 -17
  10. package/backend/engine/docs/lessons-learned.md +126 -7
  11. package/backend/engine/docs/quick-reference.md +12 -3
  12. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  13. package/backend/engine/docs/websocket-routes.md +54 -15
  14. package/backend/engine/install-runner.ts +4 -4
  15. package/backend/engine/resolve-model.ts +87 -0
  16. package/backend/engine/structured-helpers.test.ts +64 -0
  17. package/backend/engine/structured-helpers.ts +105 -13
  18. package/backend/mcp/README.md +32 -11
  19. package/backend/mcp/internal/config.ts +3 -20
  20. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  24. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  25. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  26. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  27. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  28. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  29. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  30. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  31. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  32. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  33. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  34. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  35. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  36. package/backend/preview/browser/browser-console-manager.ts +310 -156
  37. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  38. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  39. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  40. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  41. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  42. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  43. package/backend/preview/browser/browser-pool.ts +83 -9
  44. package/backend/preview/browser/browser-preview-service.ts +432 -53
  45. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  46. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  47. package/backend/preview/browser/capture-profile.ts +213 -0
  48. package/backend/preview/browser/element-locator.ts +357 -0
  49. package/backend/preview/browser/frame-targeting.ts +92 -0
  50. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  51. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  52. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  53. package/backend/preview/browser/types.ts +397 -37
  54. package/backend/utils/cli.ts +1 -1
  55. package/backend/utils/path-enrich.ts +2 -2
  56. package/backend/ws/README.md +1 -1
  57. package/backend/ws/artifacts/generate.ts +2 -1
  58. package/backend/ws/engine/codex/accounts.ts +1 -1
  59. package/backend/ws/engine/codex/status.ts +1 -1
  60. package/backend/ws/git/branch-name.ts +11 -5
  61. package/backend/ws/git/commit-message.ts +11 -5
  62. package/backend/ws/index.ts +3 -3
  63. package/backend/ws/preview/browser/host.ts +95 -0
  64. package/backend/ws/preview/browser/interact.ts +204 -10
  65. package/backend/ws/preview/browser/native-ui.ts +31 -1
  66. package/backend/ws/preview/browser/tab-info.ts +10 -1
  67. package/backend/ws/preview/browser/tab.ts +43 -0
  68. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  69. package/backend/ws/preview/index.ts +58 -1
  70. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  71. package/backend/ws/stack/index.ts +16 -0
  72. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  73. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  74. package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
  75. package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
  76. package/dist/assets/main-BD3-qPfT.css +1 -0
  77. package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
  78. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  79. package/dist/index.html +2 -2
  80. package/package.json +1 -1
  81. package/shared/types/stores/settings.ts +6 -0
  82. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  83. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  84. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  85. package/backend/ws/system-tools/index.ts +0 -16
  86. package/dist/assets/main-D8I0MfRQ.css +0 -1
@@ -7,6 +7,12 @@
7
7
  *
8
8
  * Audio is encoded with AudioEncoder (Opus codec) and sent via DataChannel
9
9
  * to the WebCodecs peer connection.
10
+ *
11
+ * The tap is a side-chain: the page's own signal path stays untouched and a
12
+ * parallel branch feeds the encoder through a muted sink. `ScriptProcessor`
13
+ * (the only option before AudioWorklet) had to sit *inside* the signal path
14
+ * and re-emit what it received, which both ran the mixdown on the page's main
15
+ * thread and added a buffer of latency to everything the page played.
10
16
  */
11
17
 
12
18
  import type { StreamingConfig } from '../types';
@@ -39,6 +45,64 @@ export function audioCaptureScript(config: StreamingConfig['audio']) {
39
45
  const interceptedContexts = new WeakSet();
40
46
  const captureNodes = new Map();
41
47
 
48
+ // ── Cross-frame delivery ────────────────────────────────────────────────
49
+ //
50
+ // The DataChannel lives on `__webCodecsPeer`, which only exists in the top
51
+ // frame. This script runs in every frame (it is injected on new document),
52
+ // so audio produced inside an iframe — embedded players, ad frames, anything
53
+ // on a CDN origin — encoded fine and was then dropped for want of a channel.
54
+ // Same-origin frames can reach the peer directly; cross-origin ones hand the
55
+ // encoded chunk to the top frame over postMessage.
56
+ const RELAY_KEY = '__clopenAudioChunk';
57
+ const isTopFrame = window === window.top;
58
+
59
+ /** The peer, if this frame can legally reach it. */
60
+ function resolvePeer(): any | null {
61
+ const local = (window as any).__webCodecsPeer;
62
+ if (local) return local;
63
+
64
+ try {
65
+ // Throws for cross-origin parents, which is the signal to relay.
66
+ const top = (window.top as any)?.__webCodecsPeer;
67
+ return top ?? null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ function deliverChunk(timestamp: number, data: Uint8Array) {
74
+ const peer = resolvePeer();
75
+ if (peer) {
76
+ if (!peer.isActive()) return;
77
+ peer.sendAudioChunk(timestamp, data);
78
+ return;
79
+ }
80
+
81
+ if (isTopFrame) return;
82
+
83
+ try {
84
+ // Copy into a fresh buffer: the encoder's view may be reused, and the
85
+ // transfer would neuter it out from under the next chunk.
86
+ const copy = new Uint8Array(data);
87
+ window.top?.postMessage({ [RELAY_KEY]: { timestamp, data: copy } }, '*', [copy.buffer]);
88
+ } catch {
89
+ // Frame is detached or the post was refused — drop the chunk; audio
90
+ // gaps are handled by the client's playback scheduler.
91
+ }
92
+ }
93
+
94
+ // Top frame: accept chunks relayed up from cross-origin children.
95
+ if (isTopFrame) {
96
+ window.addEventListener('message', (event: MessageEvent) => {
97
+ const relayed = (event.data as Record<string, any> | null)?.[RELAY_KEY];
98
+ if (!relayed) return;
99
+
100
+ const peer = (window as any).__webCodecsPeer;
101
+ if (!peer || !peer.isActive()) return;
102
+ peer.sendAudioChunk(relayed.timestamp, new Uint8Array(relayed.data));
103
+ });
104
+ }
105
+
42
106
  // Initialize audio encoder
43
107
  async function initAudioEncoder() {
44
108
  if (audioEncoder && audioEncoder.state === 'configured') {
@@ -48,17 +112,12 @@ export function audioCaptureScript(config: StreamingConfig['audio']) {
48
112
  try {
49
113
  audioEncoder = new AudioEncoder({
50
114
  output: (chunk: EncodedAudioChunk) => {
51
- // Send audio chunk directly via __webCodecsPeer DataChannel
52
- const peer = (window as any).__webCodecsPeer;
53
- if (!peer || !peer.isActive()) {
54
- return;
55
- }
56
-
57
115
  const data = new Uint8Array(chunk.byteLength);
58
116
  chunk.copyTo(data);
59
117
 
60
- // Send via the same DataChannel used for video
61
- peer.sendAudioChunk(chunk.timestamp, data);
118
+ // Reaches the DataChannel directly in the top frame, or via the
119
+ // relay when this encoder is running inside an iframe.
120
+ deliverChunk(chunk.timestamp, data);
62
121
  },
63
122
  error: (e: Error) => {}
64
123
  });
@@ -75,76 +134,195 @@ export function audioCaptureScript(config: StreamingConfig['audio']) {
75
134
  }
76
135
  }
77
136
 
78
- // Create capture nodes for an AudioContext
79
- function setupCaptureForContext(ctx: AudioContext) {
80
- if (captureNodes.has(ctx)) return captureNodes.get(ctx);
137
+ /**
138
+ * Encode one interleaved-by-channel block.
139
+ * `left`/`right` are separate planes; AudioData wants them concatenated
140
+ * for the planar format.
141
+ */
142
+ function encodeBlock(left: Float32Array, right: Float32Array, sampleRate: number) {
143
+ if (!isCapturing || !audioEncoder || audioEncoder.state !== 'configured') return;
144
+
145
+ // Skip digital silence — most pages are silent most of the time, and an
146
+ // Opus frame of silence still costs an encode, a packet and a decode.
147
+ let hasAudio = false;
148
+ for (let i = 0; i < left.length; i += 64) {
149
+ if (Math.abs(left[i]) > 0.0001 || Math.abs(right[i]) > 0.0001) {
150
+ hasAudio = true;
151
+ break;
152
+ }
153
+ }
154
+ if (!hasAudio) return;
81
155
 
82
156
  try {
83
- // Create a script processor to capture audio
84
- const processor = ctx.createScriptProcessor(config.bufferSize, config.numberOfChannels, config.numberOfChannels);
157
+ const planar = new Float32Array(left.length * config.numberOfChannels);
158
+ planar.set(left, 0);
159
+ if (config.numberOfChannels > 1) {
160
+ planar.set(right, left.length);
161
+ }
85
162
 
86
- processor.onaudioprocess = (event: AudioProcessingEvent) => {
87
- if (!isCapturing || !audioEncoder || audioEncoder.state !== 'configured') {
88
- // Pass through audio unchanged
89
- for (let ch = 0; ch < event.outputBuffer.numberOfChannels; ch++) {
90
- const input = event.inputBuffer.getChannelData(ch);
91
- const output = event.outputBuffer.getChannelData(ch);
92
- output.set(input);
93
- }
94
- return;
95
- }
163
+ // Use performance.now() directly (same as video) for proper AV sync
164
+ const audioData = new AudioData({
165
+ format: 'f32-planar',
166
+ sampleRate,
167
+ numberOfFrames: left.length,
168
+ numberOfChannels: config.numberOfChannels,
169
+ timestamp: performance.now() * 1000, // microseconds
170
+ data: planar
171
+ });
96
172
 
97
- try {
98
- const left = event.inputBuffer.getChannelData(0);
99
- const right = event.inputBuffer.numberOfChannels > 1
100
- ? event.inputBuffer.getChannelData(1)
101
- : left;
173
+ audioEncoder.encode(audioData);
174
+ audioData.close();
102
175
 
103
- // Pass through to output
104
- event.outputBuffer.getChannelData(0).set(left);
105
- if (event.outputBuffer.numberOfChannels > 1) {
106
- event.outputBuffer.getChannelData(1).set(right);
107
- }
176
+ sampleCount += left.length;
177
+ } catch (error) {
178
+ // Silent fail to not interrupt audio
179
+ }
180
+ }
108
181
 
109
- // Check if there's any audio (not silence)
110
- let hasAudio = false;
111
- for (let i = 0; i < left.length; i += 64) {
112
- if (Math.abs(left[i]) > 0.0001 || Math.abs(right[i]) > 0.0001) {
113
- hasAudio = true;
114
- break;
115
- }
182
+ /**
183
+ * AudioWorklet tap. Runs on the audio rendering thread, so the page's main
184
+ * thread (which is also running the video encoder) never sees it.
185
+ */
186
+ const workletSource = `
187
+ class ClopenTapProcessor extends AudioWorkletProcessor {
188
+ constructor(options) {
189
+ super();
190
+ this.blockSize = (options.processorOptions && options.processorOptions.blockSize) || 2048;
191
+ this.left = new Float32Array(this.blockSize);
192
+ this.right = new Float32Array(this.blockSize);
193
+ this.filled = 0;
194
+ }
195
+ process(inputs) {
196
+ const input = inputs[0];
197
+ if (!input || input.length === 0) return true;
198
+ const l = input[0];
199
+ const r = input.length > 1 ? input[1] : input[0];
200
+ if (!l) return true;
201
+ for (let i = 0; i < l.length; i++) {
202
+ this.left[this.filled] = l[i];
203
+ this.right[this.filled] = r[i];
204
+ this.filled++;
205
+ if (this.filled === this.blockSize) {
206
+ this.port.postMessage(
207
+ { left: this.left, right: this.right },
208
+ [this.left.buffer, this.right.buffer]
209
+ );
210
+ this.left = new Float32Array(this.blockSize);
211
+ this.right = new Float32Array(this.blockSize);
212
+ this.filled = 0;
116
213
  }
214
+ }
215
+ return true;
216
+ }
217
+ }
218
+ registerProcessor('clopen-tap', ClopenTapProcessor);
219
+ `;
220
+
221
+ let workletModuleUrl: string | null = null;
222
+
223
+ function getWorkletUrl(): string | null {
224
+ if (workletModuleUrl) return workletModuleUrl;
225
+ try {
226
+ workletModuleUrl = URL.createObjectURL(new Blob([workletSource], { type: 'text/javascript' }));
227
+ return workletModuleUrl;
228
+ } catch (e) {
229
+ return null;
230
+ }
231
+ }
117
232
 
118
- if (!hasAudio) return;
233
+ /**
234
+ * Attach a capture tap to a context.
235
+ *
236
+ * Returns the node the page's audio should be routed *into*. The tap itself
237
+ * terminates in a muted gain node so it never contributes to what the page
238
+ * plays — the audible path is a separate direct connection.
239
+ */
240
+ function setupCaptureForContext(ctx: AudioContext, destination: AudioNode) {
241
+ if (captureNodes.has(ctx)) return captureNodes.get(ctx);
119
242
 
120
- // Use performance.now() directly (same as video) for proper AV sync
121
- // Both video and audio now use the same timestamp origin
122
- const timestamp = performance.now() * 1000; // microseconds
243
+ let sink: GainNode;
244
+ try {
245
+ // Muted terminator: nodes only pull audio while connected to a
246
+ // destination, but this branch must stay inaudible.
247
+ sink = ctx.createGain();
248
+ sink.gain.value = 0;
249
+ sink.connect(destination);
250
+ } catch (e) {
251
+ return null;
252
+ }
123
253
 
124
- // Create AudioData with planar format
125
- const audioData = new AudioData({
126
- format: 'f32-planar',
127
- sampleRate: ctx.sampleRate,
128
- numberOfFrames: left.length,
129
- numberOfChannels: config.numberOfChannels,
130
- timestamp: timestamp,
131
- data: new Float32Array([...left, ...right])
254
+ const captureInfo: { input: AudioNode | null; sink: GainNode } = { input: null, sink };
255
+ captureNodes.set(ctx, captureInfo);
256
+
257
+ const url = getWorkletUrl();
258
+ if (url && ctx.audioWorklet) {
259
+ ctx.audioWorklet
260
+ .addModule(url)
261
+ .then(() => {
262
+ const node = new AudioWorkletNode(ctx, 'clopen-tap', {
263
+ numberOfInputs: 1,
264
+ numberOfOutputs: 1,
265
+ outputChannelCount: [config.numberOfChannels],
266
+ processorOptions: { blockSize: config.bufferSize }
132
267
  });
268
+ node.port.onmessage = (event) => {
269
+ encodeBlock(event.data.left, event.data.right, ctx.sampleRate);
270
+ };
271
+ node.connect(sink);
272
+ captureInfo.input = node;
273
+ })
274
+ .catch(() => {
275
+ // Blob worklets are blocked by strict CSP on some pages —
276
+ // fall back to the legacy tap rather than losing audio.
277
+ captureInfo.input = createScriptProcessorTap(ctx, sink);
278
+ });
279
+ } else {
280
+ captureInfo.input = createScriptProcessorTap(ctx, sink);
281
+ }
133
282
 
134
- audioEncoder!.encode(audioData);
135
- audioData.close();
283
+ return captureInfo;
284
+ }
136
285
 
137
- sampleCount += left.length;
138
- } catch (error) {
139
- // Silent fail to not interrupt audio
140
- }
141
- };
286
+ /**
287
+ * Run `connect` once the tap node exists. Bounded: if the worklet module
288
+ * never loads and the fallback also failed, give up instead of polling for
289
+ * the lifetime of the page.
290
+ */
291
+ function whenTapReady(
292
+ captureInfo: { input: AudioNode | null },
293
+ connect: (input: AudioNode) => void,
294
+ attempt = 0
295
+ ) {
296
+ if (captureInfo.input) {
297
+ try {
298
+ connect(captureInfo.input);
299
+ } catch (e) {}
300
+ return;
301
+ }
302
+ if (attempt >= 40) return; // ~2s
303
+ setTimeout(() => whenTapReady(captureInfo, connect, attempt + 1), 50);
304
+ }
142
305
 
143
- const captureInfo = { processor };
144
- captureNodes.set(ctx, captureInfo);
306
+ function createScriptProcessorTap(ctx: AudioContext, sink: GainNode): AudioNode | null {
307
+ try {
308
+ const processor = ctx.createScriptProcessor(
309
+ config.bufferSize,
310
+ config.numberOfChannels,
311
+ config.numberOfChannels
312
+ );
145
313
 
146
- return captureInfo;
147
- } catch (error) {
314
+ processor.onaudioprocess = (event: AudioProcessingEvent) => {
315
+ if (!isCapturing) return;
316
+ const left = event.inputBuffer.getChannelData(0);
317
+ const right =
318
+ event.inputBuffer.numberOfChannels > 1 ? event.inputBuffer.getChannelData(1) : left;
319
+ // Copy: the event buffers are reused by the audio thread.
320
+ encodeBlock(new Float32Array(left), new Float32Array(right), ctx.sampleRate);
321
+ };
322
+
323
+ processor.connect(sink);
324
+ return processor;
325
+ } catch (e) {
148
326
  return null;
149
327
  }
150
328
  }
@@ -154,13 +332,14 @@ export function audioCaptureScript(config: StreamingConfig['audio']) {
154
332
  interceptedContexts.add(ctx);
155
333
 
156
334
  // Resume AudioContext immediately — in headless Chrome without a user gesture,
157
- // AudioContext starts in 'suspended' state and onaudioprocess never fires.
335
+ // AudioContext starts in 'suspended' state and rendering never runs.
158
336
  if (ctx.state === 'suspended') {
159
337
  ctx.resume().catch(() => {});
160
338
  }
161
339
 
162
340
  // Store original destination
163
341
  const originalDestination = ctx.destination;
342
+ (ctx as any).__originalDestination = originalDestination;
164
343
 
165
344
  // Create a capture gain node that sits before the destination
166
345
  let captureGain: GainNode | null = null;
@@ -168,20 +347,22 @@ export function audioCaptureScript(config: StreamingConfig['audio']) {
168
347
  captureGain = ctx.createGain();
169
348
  captureGain.gain.value = 1.0;
170
349
 
171
- // Setup capture processor connected to this gain
172
- const captureInfo = setupCaptureForContext(ctx);
350
+ // Audible path — unchanged, full gain, no added latency.
351
+ captureGain.connect(originalDestination);
352
+
353
+ // Side-chain tap for the encoder.
354
+ const captureInfo = setupCaptureForContext(ctx, originalDestination);
173
355
  if (captureInfo) {
174
- captureGain.connect(captureInfo.processor);
175
- captureInfo.processor.connect(originalDestination);
356
+ // The tap node may appear asynchronously (worklet module load).
357
+ const gain = captureGain;
358
+ whenTapReady(captureInfo, (input) => gain.connect(input));
176
359
  }
177
- captureGain.connect(originalDestination);
178
360
  } catch (e) {
179
361
  return;
180
362
  }
181
363
 
182
364
  // Store references
183
365
  (ctx as any).__captureDestination = captureGain;
184
- (ctx as any).__originalDestination = originalDestination;
185
366
 
186
367
  // Override the destination getter to return our capture node
187
368
  try {
@@ -221,8 +402,8 @@ export function audioCaptureScript(config: StreamingConfig['audio']) {
221
402
 
222
403
  try {
223
404
  // We need an AudioContext to capture from media element
224
- const OriginalAudioContext = (window as any).__OriginalAudioContext || window.AudioContext;
225
- const ctx = new OriginalAudioContext();
405
+ const OriginalCtor = (window as any).__OriginalAudioContext || window.AudioContext;
406
+ const ctx = new OriginalCtor();
226
407
 
227
408
  // Resume context immediately — headless Chrome requires explicit resume
228
409
  if (ctx.state === 'suspended') {
@@ -232,13 +413,12 @@ export function audioCaptureScript(config: StreamingConfig['audio']) {
232
413
  // Create media element source
233
414
  const source = ctx.createMediaElementSource(element);
234
415
 
235
- // Create capture chain
236
- const captureInfo = setupCaptureForContext(ctx);
416
+ // Audible path first so playback never depends on the tap.
417
+ source.connect(ctx.destination);
418
+
419
+ const captureInfo = setupCaptureForContext(ctx, ctx.destination);
237
420
  if (captureInfo) {
238
- source.connect(captureInfo.processor);
239
- captureInfo.processor.connect(ctx.destination);
240
- } else {
241
- source.connect(ctx.destination);
421
+ whenTapReady(captureInfo, (input) => source.connect(input));
242
422
  }
243
423
 
244
424
  mediaElementSources.set(element, { ctx, source });