cascade-ai 0.79.0 → 0.81.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/index.js CHANGED
@@ -11623,7 +11623,7 @@ function reconcilePrice(model, live) {
11623
11623
  }
11624
11624
 
11625
11625
  // src/constants.ts
11626
- var CASCADE_VERSION = "0.79.0";
11626
+ var CASCADE_VERSION = "0.81.0";
11627
11627
  var CASCADE_CONFIG_DIR = ".cascade";
11628
11628
  var CASCADE_MD_FILE = "CASCADE.md";
11629
11629
  var CASCADE_IGNORE_FILE = ".cascadeignore";
@@ -30861,8 +30861,95 @@ function requiredFieldFor(kind, input) {
30861
30861
  }
30862
30862
  }
30863
30863
 
30864
+ // src/tools/ask-user.ts
30865
+ var MAX_QUESTIONS = 5;
30866
+ var MAX_OPTIONS = 6;
30867
+ var AskUserTool = class extends BaseTool {
30868
+ name = "ask_user";
30869
+ description = "Ask the person a short questionnaire when their request is genuinely ambiguous, instead of guessing. Use it when two readings of the request would produce materially different work \u2014 which account, which date range, whether to include drafts \u2014 and NOT for anything you can settle yourself or from the conversation. Ask everything you need in ONE call: several questions together read as a form, the same questions one per turn read as an interrogation. You may get no answer (nobody is watching, or they did not reply); if so, proceed on your best reading and say which assumption you made.";
30870
+ inputSchema = {
30871
+ type: "object",
30872
+ properties: {
30873
+ questions: {
30874
+ type: "array",
30875
+ minItems: 1,
30876
+ maxItems: MAX_QUESTIONS,
30877
+ description: `The questions to ask together (at most ${MAX_QUESTIONS}).`,
30878
+ items: {
30879
+ type: "object",
30880
+ properties: {
30881
+ prompt: { type: "string", description: "The question, as you would say it to them." },
30882
+ kind: {
30883
+ type: "string",
30884
+ enum: ["choice", "multi", "text"],
30885
+ description: "choice = pick one, multi = pick any that apply, text = free-form answer."
30886
+ },
30887
+ options: {
30888
+ type: "array",
30889
+ items: { type: "string" },
30890
+ description: `The answers to offer, for choice and multi (at most ${MAX_OPTIONS}). Omit for text.`
30891
+ }
30892
+ },
30893
+ required: ["prompt", "kind"]
30894
+ }
30895
+ }
30896
+ },
30897
+ required: ["questions"]
30898
+ };
30899
+ ask;
30900
+ constructor(ask) {
30901
+ super();
30902
+ this.ask = ask;
30903
+ }
30904
+ // Asking a question changes nothing, so it needs no approval gate: a prompt
30905
+ // asking permission to show a prompt is a tax on the behaviour we want.
30906
+ isDangerous() {
30907
+ return false;
30908
+ }
30909
+ async execute(input, options) {
30910
+ const raw = Array.isArray(input["questions"]) ? input["questions"] : [];
30911
+ const questions = [];
30912
+ for (const [i, q] of raw.slice(0, MAX_QUESTIONS).entries()) {
30913
+ const item = q ?? {};
30914
+ const prompt = typeof item["prompt"] === "string" ? item["prompt"].trim() : "";
30915
+ if (!prompt) continue;
30916
+ const kind = item["kind"] === "multi" || item["kind"] === "text" ? item["kind"] : "choice";
30917
+ const options_ = Array.isArray(item["options"]) ? item["options"].filter((o) => typeof o === "string" && o.trim() !== "").slice(0, MAX_OPTIONS) : [];
30918
+ const resolved = kind !== "text" && options_.length < 2 ? "text" : kind;
30919
+ questions.push({
30920
+ // Positional, and assigned HERE. Letting the model supply ids invites
30921
+ // two questions sharing one, and the second answer would overwrite the
30922
+ // first with nothing to say it had.
30923
+ id: `q${i + 1}`,
30924
+ prompt,
30925
+ kind: resolved,
30926
+ ...resolved === "text" ? {} : { options: options_ }
30927
+ });
30928
+ }
30929
+ if (questions.length === 0) {
30930
+ return "Error: ask_user needs at least one question with a prompt.";
30931
+ }
30932
+ const result = await this.ask(questions, options.signal);
30933
+ if (result.outcome !== "answered" || result.answers.length === 0) {
30934
+ const why = result.outcome === "no-listener" ? "There is nobody watching this run to answer" : result.outcome === "aborted" ? "The run was stopped while the question was open" : result.outcome === "answered" ? "They saw the questions and chose not to answer" : "They did not answer in time";
30935
+ return `${why}. Proceed on your best reading of the request, and say plainly which assumption you made.`;
30936
+ }
30937
+ const byId = new Map(result.answers.map((a) => [a.id, a.value]));
30938
+ const lines = questions.map((q) => {
30939
+ const value = byId.get(q.id);
30940
+ const said = Array.isArray(value) ? value.join(", ") : value;
30941
+ return `${q.prompt}
30942
+ \u2192 ${said && said.length > 0 ? said : "(no answer given)"}`;
30943
+ });
30944
+ return `They answered:
30945
+
30946
+ ${lines.join("\n\n")}`;
30947
+ }
30948
+ };
30949
+
30864
30950
  // src/core/cascade.ts
30865
30951
  var ESCALATION_DECISION_TIMEOUT_MS = 5 * 6e4;
30952
+ var CLARIFICATION_TIMEOUT_MS = 2 * 6e4;
30866
30953
  function buildContextualPrompt(prompt, history = []) {
30867
30954
  const recent = history.slice(-6);
30868
30955
  if (recent.length === 0) return prompt;
@@ -31141,6 +31228,112 @@ var Cascade = class _Cascade extends EventEmitter {
31141
31228
  // timeout. Same class of bug as the twelve-failover dead-model race: a wave
31142
31229
  // is concurrent, so per-run singletons are never safe inside it.
31143
31230
  pendingEscalations = /* @__PURE__ */ new Map();
31231
+ /**
31232
+ * Questionnaires waiting on a person, keyed by request id.
31233
+ *
31234
+ * Exactly the shape `pendingEscalations` uses, and for the same reason: the
31235
+ * answer, the timeout and the abort all race, and one settle path guarded by
31236
+ * the map delete is what makes the first of them win.
31237
+ */
31238
+ pendingClarifications = /* @__PURE__ */ new Map();
31239
+ /**
31240
+ * Put a gate's opening question to its listeners, and NOTICE when one fails.
31241
+ *
31242
+ * `emit` cannot do this job. It calls listeners synchronously and discards
31243
+ * what they return, so an `async` listener — the ordinary shape for anything
31244
+ * that has to reach a socket or a UI — does not fail in a way `emit` reports:
31245
+ * it returns a REJECTED PROMISE that nobody is holding. The `try` around the
31246
+ * emit sees nothing, the gate is never told delivery failed, and it parks for
31247
+ * its full timeout while Node raises an unhandled rejection that can take the
31248
+ * process down.
31249
+ *
31250
+ * `onFailed` is called for either shape, and it is safe to call more than
31251
+ * once: both gates route it to `settle`, which is guarded by a map delete, so
31252
+ * the first failure wins and the rest are no-ops.
31253
+ *
31254
+ * PER LISTENER, not around the loop. `emit` stops dispatching at the first
31255
+ * throw, so one broken host used to cost a working one its notification —
31256
+ * the same reason `announceLiveView` delivers its two listeners separately.
31257
+ * A synchronous failure settles the gate once the whole snapshot has been
31258
+ * delivered; an asynchronous one settles it when the rejection arrives, which
31259
+ * is still far better than the window-long park it replaces.
31260
+ *
31261
+ * SETTLED AFTER THE LOOP, not inside it, and that is not tidiness. `onFailed`
31262
+ * settles the gate, and settling emits the gate's CLOSURE — so failing
31263
+ * mid-dispatch announced "this request is over" and then went on handing the
31264
+ * OPENING event to the listeners after it. A host later in the list would
31265
+ * draw a form whose only closure notification had already gone past, and it
31266
+ * would stand there forever. Deliver to everyone, then decide.
31267
+ *
31268
+ * `rawListeners`, NOT `listeners`. Bypassing `emit` means taking on what
31269
+ * `emit` was doing, and `once` is the part that bites: `listeners()` hands
31270
+ * back the UNWRAPPED callback, so calling it never runs the wrapper that
31271
+ * deregisters it. A host that asked to be told once would be told every
31272
+ * time — and told through a transport it had set up for one gate only.
31273
+ * `rawListeners()` returns the wrapper, which removes the registration and
31274
+ * passes the underlying listener's return value straight through, so the
31275
+ * promise below is still the one being observed. Verified against Node.
31276
+ *
31277
+ * `.call(this, …)`, which is the third thing `emit` was doing. EventEmitter
31278
+ * invokes listeners with the emitter as the receiver, so
31279
+ * `function () { this.resolveClarification(...) }` is a legitimate host — and
31280
+ * calling it bare gave it `this === undefined`, which throws, which this
31281
+ * would then have read as the host failing to receive the question and
31282
+ * settled the gate unanswered. A working listener turned into a delivery
31283
+ * failure by the thing delivering it.
31284
+ */
31285
+ deliverGate(event, payload, onFailed) {
31286
+ let delivered = false;
31287
+ let threw = false;
31288
+ const pending = [];
31289
+ for (const listener of this.rawListeners(event)) {
31290
+ try {
31291
+ const out = listener.call(this, payload);
31292
+ if (out && typeof out.then === "function") {
31293
+ pending.push(Promise.resolve(out).then(() => true, () => false));
31294
+ } else {
31295
+ delivered = true;
31296
+ }
31297
+ } catch {
31298
+ threw = true;
31299
+ }
31300
+ }
31301
+ if (delivered) return;
31302
+ if (pending.length === 0) {
31303
+ if (threw) onFailed();
31304
+ return;
31305
+ }
31306
+ void Promise.all(pending).then((results) => {
31307
+ if (!results.some(Boolean)) onFailed();
31308
+ });
31309
+ }
31310
+ /**
31311
+ * Tell listeners something that is over, and let none of them make it worse.
31312
+ *
31313
+ * The closing half of the gate family — `clarification:closed`,
31314
+ * `clarification:timeout`, `escalation:closed`, `escalation:timeout`. Each
31315
+ * was already wrapped in a `try` for the synchronous case, and each had the
31316
+ * same hole `deliverGate` had before last round: `emit` discards what a
31317
+ * listener returns, so an `async` host fails by returning a rejected promise
31318
+ * nobody is holding and Node raises an unhandled rejection.
31319
+ *
31320
+ * There is nothing to settle here — the gate is already closed, which is the
31321
+ * whole message — so unlike `deliverGate` this reports to no one. It exists
31322
+ * so that the four informational emits cannot take the process down, and so
31323
+ * the rule is written once rather than four times.
31324
+ */
31325
+ announceGateClosed(event, payload) {
31326
+ for (const listener of this.rawListeners(event)) {
31327
+ try {
31328
+ const out = listener.call(this, payload);
31329
+ if (out && typeof out.then === "function") {
31330
+ void Promise.resolve(out).catch(() => {
31331
+ });
31332
+ }
31333
+ } catch {
31334
+ }
31335
+ }
31336
+ }
31144
31337
  async requestEscalationDecision(ctx, taskId, signal) {
31145
31338
  if (this.config.autonomy === "auto") return { action: "skip", automatic: true };
31146
31339
  if (this.listenerCount("escalation:decision-required") === 0) return { action: "skip", automatic: true };
@@ -31153,23 +31346,28 @@ var Cascade = class _Cascade extends EventEmitter {
31153
31346
  if (timeout) clearTimeout(timeout);
31154
31347
  signal?.removeEventListener("abort", onAbort);
31155
31348
  resolve2(decision);
31349
+ this.announceGateClosed("escalation:closed", { taskId, requestId, sectionId: ctx.sectionId });
31156
31350
  };
31157
31351
  const onAbort = () => settle({ action: "skip", automatic: true });
31158
31352
  signal?.addEventListener("abort", onAbort, { once: true });
31159
31353
  timeout = setTimeout(() => {
31160
- this.emit("escalation:timeout", { taskId, requestId, sectionId: ctx.sectionId });
31161
31354
  settle({ action: "timeout" });
31355
+ this.announceGateClosed("escalation:timeout", { taskId, requestId, sectionId: ctx.sectionId });
31162
31356
  }, ESCALATION_DECISION_TIMEOUT_MS);
31163
31357
  this.pendingEscalations.set(requestId, settle);
31164
- this.emit("escalation:decision-required", {
31165
- taskId,
31166
- requestId,
31167
- sectionId: ctx.sectionId,
31168
- sectionTitle: ctx.sectionTitle,
31169
- issues: ctx.issues,
31170
- summary: ctx.summary,
31171
- timeoutMs: ESCALATION_DECISION_TIMEOUT_MS
31172
- });
31358
+ this.deliverGate(
31359
+ "escalation:decision-required",
31360
+ {
31361
+ taskId,
31362
+ requestId,
31363
+ sectionId: ctx.sectionId,
31364
+ sectionTitle: ctx.sectionTitle,
31365
+ issues: ctx.issues,
31366
+ summary: ctx.summary,
31367
+ timeoutMs: ESCALATION_DECISION_TIMEOUT_MS
31368
+ },
31369
+ () => settle({ action: "skip", automatic: true })
31370
+ );
31173
31371
  });
31174
31372
  }
31175
31373
  /**
@@ -31206,6 +31404,73 @@ var Cascade = class _Cascade extends EventEmitter {
31206
31404
  releasePendingEscalations(action = "skip") {
31207
31405
  for (const settle of Array.from(this.pendingEscalations.values())) settle({ action, automatic: true });
31208
31406
  }
31407
+ // ── Clarification: asking instead of assuming ───────────────────────
31408
+ // The same gate shape as the escalation above, and for the same reasons. The
31409
+ // difference that matters: an unanswered escalation SKIPS a section, while an
31410
+ // unanswered question just means the model proceeds on its own reading — so
31411
+ // every non-answer here is benign, and none of them may park the run.
31412
+ /**
31413
+ * Put a questionnaire to whoever is watching, if anybody is.
31414
+ *
31415
+ * Returns `no-listener` rather than waiting when there is nothing attached to
31416
+ * answer — a scheduled run, an API caller with no socket, an autonomous run
31417
+ * that has already said it wants no prompts. That check is the whole reason
31418
+ * this can be offered to the model at all: a tool that might hang a headless
31419
+ * run forever is a tool that cannot be registered.
31420
+ */
31421
+ async askUser(questions, signal) {
31422
+ const none = (outcome) => ({ outcome, answers: [] });
31423
+ if (this.unattended) return none("no-listener");
31424
+ if (this.config.autonomy === "auto") return none("no-listener");
31425
+ if (this.listenerCount("clarification:required") === 0) return none("no-listener");
31426
+ if (signal?.aborted) return none("aborted");
31427
+ const requestId = randomUUID();
31428
+ return await new Promise((resolve2) => {
31429
+ let timeout;
31430
+ const settle = (result) => {
31431
+ if (!this.pendingClarifications.delete(requestId)) return;
31432
+ if (timeout) clearTimeout(timeout);
31433
+ signal?.removeEventListener("abort", onAbort);
31434
+ resolve2(result);
31435
+ this.announceGateClosed("clarification:closed", { requestId });
31436
+ };
31437
+ const onAbort = () => settle(none("aborted"));
31438
+ signal?.addEventListener("abort", onAbort, { once: true });
31439
+ timeout = setTimeout(() => {
31440
+ settle(none("timeout"));
31441
+ this.announceGateClosed("clarification:timeout", { requestId });
31442
+ }, CLARIFICATION_TIMEOUT_MS);
31443
+ this.pendingClarifications.set(requestId, settle);
31444
+ this.deliverGate(
31445
+ "clarification:required",
31446
+ { requestId, questions, timeoutMs: CLARIFICATION_TIMEOUT_MS },
31447
+ () => settle(none("no-listener"))
31448
+ );
31449
+ });
31450
+ }
31451
+ /**
31452
+ * Answer a questionnaire from a REPL / dashboard / cloud listener.
31453
+ *
31454
+ * `requestId` comes back on the `clarification:required` event and is what
31455
+ * makes an answer land on the question that asked. Optional for a host with
31456
+ * only one in flight, matching `resolveEscalation`: without it the oldest
31457
+ * outstanding request is answered, which is correct whenever there is one.
31458
+ */
31459
+ resolveClarification(answers, requestId) {
31460
+ const result = { outcome: "answered", answers };
31461
+ if (requestId) {
31462
+ this.pendingClarifications.get(requestId)?.(result);
31463
+ return;
31464
+ }
31465
+ const oldest = this.pendingClarifications.keys().next();
31466
+ if (!oldest.done) this.pendingClarifications.get(oldest.value)?.(result);
31467
+ }
31468
+ /** Release every parked questionnaire — run teardown, so none outlive the run. */
31469
+ releasePendingClarifications() {
31470
+ for (const settle of Array.from(this.pendingClarifications.values())) {
31471
+ settle({ outcome: "aborted", answers: [] });
31472
+ }
31473
+ }
31209
31474
  /**
31210
31475
  * Resolve a pending boardroom plan approval from a REPL / dashboard listener.
31211
31476
  * An optional `note` re-plans and re-asks; an optional `editedPlan` is applied
@@ -31230,12 +31495,14 @@ var Cascade = class _Cascade extends EventEmitter {
31230
31495
  const timeout = setTimeout(() => {
31231
31496
  if (this.pendingContextApproval) {
31232
31497
  this.pendingContextApproval = void 0;
31498
+ this.announceGateClosed("context:approval-closed", {});
31233
31499
  resolve2(true);
31234
31500
  }
31235
31501
  }, 12e4);
31236
31502
  this.pendingContextApproval = (approved) => {
31237
31503
  clearTimeout(timeout);
31238
31504
  this.pendingContextApproval = void 0;
31505
+ this.announceGateClosed("context:approval-closed", {});
31239
31506
  resolve2(approved);
31240
31507
  };
31241
31508
  this.emit("context:approval-required", info);
@@ -31426,6 +31693,34 @@ ${input}` }],
31426
31693
  if ((this.config.tools?.disabledTools ?? []).includes("browser_control")) return;
31427
31694
  this.toolRegistry.register(new BrowserControlTool(controller, release));
31428
31695
  }
31696
+ /**
31697
+ * Declare that this host can put a questionnaire to a person and answer it.
31698
+ *
31699
+ * Explicit, and NOT done at construction, because registering a tool is a
31700
+ * promise the host has to keep. A host that registers `ask_user` without
31701
+ * listening for `clarification:required` gives the model a tool that always
31702
+ * answers "there is nobody watching this run" — while a person sits at the
31703
+ * terminal looking at it. That is worse than not offering the tool at all:
31704
+ * it costs a round trip and then tells the model something false.
31705
+ *
31706
+ * Only `cloud/server` bridges the protocol today. The CLI REPL and the
31707
+ * dashboard do not, so they do not call this, and their models are not shown
31708
+ * a capability nobody can serve. Wiring either of them is a matter of
31709
+ * listening for the event and calling `resolveClarification`, then calling
31710
+ * this.
31711
+ *
31712
+ * Still gated on the same conditions as the call itself, and `askUser`
31713
+ * re-checks them: `setUnattended` can land after this, so the tool can be
31714
+ * registered for a run that later turns out to have nobody on it. Then it
31715
+ * answers `no-listener` and the model proceeds on its own reading, which is
31716
+ * the same defence-in-depth `BrowserControlTool.revoke` provides.
31717
+ */
31718
+ enableClarification() {
31719
+ if (this.unattended) return;
31720
+ if (this.config.autonomy === "auto") return;
31721
+ if ((this.config.tools?.disabledTools ?? []).includes("ask_user")) return;
31722
+ this.toolRegistry.register(new AskUserTool((questions, signal) => this.askUser(questions, signal)));
31723
+ }
31429
31724
  registerMediaTools(workspacePath) {
31430
31725
  const denied = new Set(this.config.tools?.disabledTools ?? []);
31431
31726
  const permitted = (name) => !denied.has(name);
@@ -32371,6 +32666,10 @@ ${finalOutput}` : ""
32371
32666
  this.releasePendingEscalations();
32372
32667
  } catch {
32373
32668
  }
32669
+ try {
32670
+ this.releasePendingClarifications();
32671
+ } catch {
32672
+ }
32374
32673
  this.router.restoreTierModels();
32375
32674
  this.router.setRunSignal(void 0);
32376
32675
  if (this.taskAnalyzer) {
@@ -34977,11 +35276,13 @@ async function discoverMcpTools(servers) {
34977
35276
  }
34978
35277
 
34979
35278
  // src/browser/lease.ts
35279
+ var HUMAN_ACTOR = "__human__";
35280
+ var HUMAN_IDLE_MS = 12e4;
34980
35281
  var LEASE_DEADLOCK_CEILING_MS = 3e5;
34981
35282
  var QUEUE_WAIT_MS = 18e4;
34982
35283
  var MAX_QUEUED = 8;
34983
35284
  var ACTION_HANDOFF_MS = 2e3;
34984
- var ACTION_HANDOFF_POLL_MS = 25;
35285
+ var HANDBACK_RETRY_MS = 25;
34985
35286
  var BrowserLease = class {
34986
35287
  actor = null;
34987
35288
  session = null;
@@ -35000,6 +35301,51 @@ var BrowserLease = class {
35000
35301
  * took the slot may release it.
35001
35302
  */
35002
35303
  action = null;
35304
+ /** Whether the current action slot represents activity by its holder. */
35305
+ actionCountsAsHumanActivity = false;
35306
+ /**
35307
+ * The human action that has already consumed its one idle-deadline grace.
35308
+ * A single wedged CDP request must not look like fresh activity every two
35309
+ * minutes forever. The first deadline may yield to an event that began before
35310
+ * it; a second deadline for that SAME event becomes a pending lapse instead.
35311
+ */
35312
+ idleGraceAction = null;
35313
+ /** Release the human hold as soon as this overlong action finally unwinds. */
35314
+ idleLapseAfterAction = null;
35315
+ /**
35316
+ * Everyone waiting for that slot, IN THE ORDER THEY ASKED.
35317
+ *
35318
+ * A queue rather than a poll, and the ordering is the whole reason for it.
35319
+ * `acquireActionSlot` used to spin on a 25ms timer, which decides nothing
35320
+ * about who goes first: each waiter checks on its own phase, so the one that
35321
+ * asked SECOND can find the slot free a full poll ahead of the one that asked
35322
+ * first. The person types one event per keypress — `{ kind: 'text', text }`
35323
+ * carries a single character — so that reordering is not a theoretical
35324
+ * unfairness, it is "passowrd" appearing in the box.
35325
+ *
35326
+ * The slot is handed straight from `endAction` to the head of this line while
35327
+ * still synchronous, so nothing can slip in between the two, and a waiter
35328
+ * that reaches the front never has to be told the slot is already taken.
35329
+ */
35330
+ actionQueue = [];
35331
+ /** Lapses a human hold nobody is using. See `HUMAN_IDLE_MS`. */
35332
+ humanTimer = null;
35333
+ /**
35334
+ * The person ASKED for the hold to end and it could not end yet.
35335
+ *
35336
+ * Kept as a request rather than only a retry timer, because the retry shares
35337
+ * `humanTimer` with the idle deadline: an authorised event settling after the
35338
+ * request would otherwise call `touch()`, re-arm that timer for a full idle
35339
+ * interval, and quietly cancel a handback the person had already asked for.
35340
+ * "Give it back" is not undone by activity that was already under way when
35341
+ * they said it.
35342
+ *
35343
+ * Explicit requests ONLY. An idle expiry must never set this: a deadline that
35344
+ * lands on the person's own in-flight event is evidence they were THERE, and
35345
+ * recording it here made `touch()` bail afterwards, so the hold dropped the
35346
+ * instant a fresh interaction finished. See `lapse()`.
35347
+ */
35348
+ handBackWanted = false;
35003
35349
  isRevoked;
35004
35350
  onChange;
35005
35351
  constructor(options = {}) {
@@ -35010,6 +35356,20 @@ var BrowserLease = class {
35010
35356
  get holderActor() {
35011
35357
  return this.actor;
35012
35358
  }
35359
+ /** Whether a person, rather than the agent, is driving the page right now. */
35360
+ get heldByHuman() {
35361
+ return this.actor === HUMAN_ACTOR;
35362
+ }
35363
+ /**
35364
+ * Whether THIS actor is the one holding the browser right now.
35365
+ *
35366
+ * For asking again after a wait. `acquire` is re-entrant for the holder, so
35367
+ * "I was granted the lease" is a fact about the moment it was granted and
35368
+ * says nothing about the moment the caller finally gets to act.
35369
+ */
35370
+ heldBy(actorId) {
35371
+ return this.actor === actorId;
35372
+ }
35013
35373
  get holderSession() {
35014
35374
  return this.session;
35015
35375
  }
@@ -35036,6 +35396,7 @@ var BrowserLease = class {
35036
35396
  * the same worker coming back for its next step must not queue behind itself.
35037
35397
  */
35038
35398
  async acquire(actorId, sessionId, signal) {
35399
+ if (this.actor === HUMAN_ACTOR && actorId !== HUMAN_ACTOR) return "human";
35039
35400
  if (this.actor === null || this.actor === actorId) {
35040
35401
  this.actor = actorId;
35041
35402
  this.session = sessionId;
@@ -35076,6 +35437,105 @@ var BrowserLease = class {
35076
35437
  if (this.action) return;
35077
35438
  if (this.actor === actorId) this.release();
35078
35439
  }
35440
+ /**
35441
+ * Give the browser to the person watching it.
35442
+ *
35443
+ * Callers must have waited the in-flight action out first — see
35444
+ * `acquireActionSlot`. This does not interrupt one, because it cannot: a
35445
+ * Playwright call already inside the page finishes whatever it started, and
35446
+ * taking the lease off it would only mean the person and a still-running
35447
+ * `fill` were both touching the same form. Waiting is what makes "you have
35448
+ * control" true when the UI says it.
35449
+ *
35450
+ * Every queued worker is turned away rather than left in line, for the same
35451
+ * reason `acquire` refuses: they were planned against a page the person is
35452
+ * about to change.
35453
+ */
35454
+ takeOver(sessionId) {
35455
+ for (let i = this.waiting.length - 1; i >= 0; i--) this.waiting[i].settle("human");
35456
+ this.clearCeiling();
35457
+ this.actor = HUMAN_ACTOR;
35458
+ this.session = sessionId;
35459
+ this.touch();
35460
+ this.onChange();
35461
+ }
35462
+ /**
35463
+ * The person is still there — anything they did counts.
35464
+ *
35465
+ * Called per authorised input rather than on a heartbeat, so the hold is
35466
+ * extended by USE and not merely by a tab being open. A left-open panel on a
35467
+ * forgotten laptop stops holding a billed session two minutes later.
35468
+ */
35469
+ touch() {
35470
+ if (this.actor !== HUMAN_ACTOR) return;
35471
+ if (this.handBackWanted) return;
35472
+ this.armIdle();
35473
+ }
35474
+ /** (Re)start the idle interval. The only place the deadline is set. */
35475
+ armIdle() {
35476
+ this.clearHumanIdle();
35477
+ this.humanTimer = setTimeout(() => {
35478
+ this.lapse();
35479
+ }, HUMAN_IDLE_MS);
35480
+ this.humanTimer.unref?.();
35481
+ }
35482
+ /**
35483
+ * The idle deadline came round.
35484
+ *
35485
+ * Both ways a hold ends obey the same rule — never while one of the person's
35486
+ * own events is still landing — but they resolve that clash in OPPOSITE
35487
+ * directions, and routing the lapse through `handBack()` collapsed them into
35488
+ * one. An event in flight BEGAN before this deadline, which makes it evidence
35489
+ * the person was there; deferring the lapse and then releasing the moment
35490
+ * that event lands ends the hold immediately after a fresh interaction, which
35491
+ * is the precise opposite of what an idle deadline measures. So an
35492
+ * interrupted lapse yields: the interval starts again, and the next silence
35493
+ * decides.
35494
+ *
35495
+ * `handBack()` keeps the deferral instead, because "Give it back" is a
35496
+ * decision and activity already under way when it was made does not withdraw
35497
+ * it. Same rule, different answer, which is why they are different methods.
35498
+ */
35499
+ lapse() {
35500
+ if (this.actor !== HUMAN_ACTOR) return;
35501
+ if (this.action && this.actionCountsAsHumanActivity) {
35502
+ if (this.idleGraceAction !== this.action) {
35503
+ this.idleGraceAction = this.action;
35504
+ this.armIdle();
35505
+ } else {
35506
+ this.idleLapseAfterAction = this.action;
35507
+ this.clearHumanIdle();
35508
+ }
35509
+ return;
35510
+ }
35511
+ this.release();
35512
+ }
35513
+ /**
35514
+ * The person hands the browser back, or their hold lapses.
35515
+ *
35516
+ * Answers whether there was a human hold to end, so a caller can tell a real
35517
+ * handback from a duplicate click or a lapse that already happened.
35518
+ */
35519
+ handBack() {
35520
+ if (this.actor !== HUMAN_ACTOR) return false;
35521
+ if (this.action) {
35522
+ this.handBackWanted = true;
35523
+ this.clearHumanIdle();
35524
+ this.humanTimer = setTimeout(() => {
35525
+ this.handBack();
35526
+ }, HANDBACK_RETRY_MS);
35527
+ this.humanTimer.unref?.();
35528
+ return false;
35529
+ }
35530
+ this.release();
35531
+ return true;
35532
+ }
35533
+ clearHumanIdle() {
35534
+ if (this.humanTimer) {
35535
+ clearTimeout(this.humanTimer);
35536
+ this.humanTimer = null;
35537
+ }
35538
+ }
35079
35539
  /** Drop every queued waiter belonging to a run, and the lease if it holds it. */
35080
35540
  dropRun(sessionId) {
35081
35541
  for (let i = this.waiting.length - 1; i >= 0; i--) {
@@ -35091,6 +35551,10 @@ var BrowserLease = class {
35091
35551
  /** Hand the browser to the next actor in line, if any. */
35092
35552
  release() {
35093
35553
  this.clearCeiling();
35554
+ this.clearHumanIdle();
35555
+ this.handBackWanted = false;
35556
+ this.idleGraceAction = null;
35557
+ this.idleLapseAfterAction = null;
35094
35558
  this.actor = null;
35095
35559
  this.session = null;
35096
35560
  let next = this.waiting.shift();
@@ -35119,33 +35583,111 @@ var BrowserLease = class {
35119
35583
  this.ceilingTimer = null;
35120
35584
  }
35121
35585
  }
35122
- /** Take the per-action slot, or null when one is already running. */
35123
- beginAction() {
35586
+ /**
35587
+ * Take the per-action slot, or null when one is already running.
35588
+ *
35589
+ * PRIVATE, so the queue is the only way in. A caller that could take the slot
35590
+ * without joining the line would be exactly the jump-the-queue the ordering
35591
+ * is there to prevent.
35592
+ */
35593
+ beginAction(countsAsHumanActivity = true) {
35124
35594
  if (this.action) return null;
35125
35595
  const token = /* @__PURE__ */ Symbol("browser-action");
35126
35596
  this.action = token;
35597
+ this.actionCountsAsHumanActivity = countsAsHumanActivity;
35127
35598
  return token;
35128
35599
  }
35129
- /** Release the slot, but only for the action that took it. */
35600
+ /**
35601
+ * Release the slot, but only for the action that took it.
35602
+ *
35603
+ * Hands it to the head of the line rather than merely clearing it, and does
35604
+ * so SYNCHRONOUSLY: the waiter's `beginAction` runs before this call returns,
35605
+ * so there is no window in which the slot is free and somebody who asked
35606
+ * later can take it.
35607
+ */
35130
35608
  endAction(token) {
35131
35609
  if (this.action !== token) return false;
35610
+ const lapseNow = this.actor === HUMAN_ACTOR && this.idleLapseAfterAction === token;
35132
35611
  this.action = null;
35612
+ this.actionCountsAsHumanActivity = false;
35613
+ if (this.idleGraceAction === token) this.idleGraceAction = null;
35614
+ if (this.idleLapseAfterAction === token) this.idleLapseAfterAction = null;
35615
+ if (lapseNow) this.release();
35616
+ this.actionQueue.shift()?.();
35133
35617
  return true;
35134
35618
  }
35135
35619
  /**
35136
- * Wait, briefly, for an outgoing action to unwind.
35620
+ * Take the slot only if it is free RIGHT NOW, never joining the line.
35621
+ *
35622
+ * For input that is a SAMPLE rather than a decision — pointer movement. A
35623
+ * click or a keystroke is a thing the person meant to do and has to happen,
35624
+ * so it waits its turn; a pointer position is one of many on the way
35625
+ * somewhere, and one that cannot be applied now is worth less than the one
35626
+ * behind it. Queueing them is actively harmful: on an endpoint slower than
35627
+ * the client's sampling interval the backlog grows, and the click behind it
35628
+ * can age out against `acquireActionSlot`'s bound and be refused — movement
35629
+ * costing the person the action they actually intended.
35630
+ *
35631
+ * The queue length is checked as well as the slot, so a sample cannot step
35632
+ * over a click that is already waiting.
35633
+ */
35634
+ tryActionSlot() {
35635
+ if (this.action || this.actionQueue.length > 0) return null;
35636
+ return this.beginAction();
35637
+ }
35638
+ /**
35639
+ * Take the per-action slot, waiting in line for it if somebody has it.
35137
35640
  *
35138
35641
  * A release can hand the browser on while the previous holder's abort is
35139
35642
  * still propagating through an awaited navigation. That is a handoff, not a
35140
- * conflict, so it is waited out rather than refused — but bounded, because a
35141
- * wedged action must not pin the queue.
35142
- */
35143
- async awaitActionSlot() {
35144
- for (let waited = 0; waited < ACTION_HANDOFF_MS; waited += ACTION_HANDOFF_POLL_MS) {
35145
- if (!this.action) return true;
35146
- await new Promise((r) => setTimeout(r, ACTION_HANDOFF_POLL_MS));
35147
- }
35148
- return this.action === null;
35643
+ * conflict, so it is normally bounded: a wedged action must not pin an agent
35644
+ * or a takeover forever. Human discrete input is the exception and passes
35645
+ * `null`: once a click, key or committed text has been accepted into this
35646
+ * ordered queue, expiring it merely because earlier accepted input took more
35647
+ * than two seconds silently truncates what the person typed.
35648
+ *
35649
+ * Waiting and TAKING are one step, which they deliberately were not before:
35650
+ * the wait used to answer "the slot looks free" and leave the caller to call
35651
+ * `beginAction` afterwards. Two callers woken by the same release both saw it
35652
+ * free, and the loser was told "another action is already running" — a
35653
+ * refusal for having asked first. Granting it here means whoever reaches the
35654
+ * front of the line gets it, and everybody else is still waiting rather than
35655
+ * refused.
35656
+ *
35657
+ * `null` as a RESULT means a bounded wait ran out OR a caller-supplied queue
35658
+ * cap refused a new waiter. `null` as `withinMs` means an ACCEPTED operation
35659
+ * is intentionally unbounded by time and will leave the queue only when its
35660
+ * turn arrives; it does not require accepting infinitely many operations.
35661
+ * `countsAsHumanActivity=false` is for
35662
+ * lifecycle barriers: they still serialize, but an idle deadline must not
35663
+ * mistake framework cleanup for evidence that the person is present.
35664
+ */
35665
+ async acquireActionSlot(withinMs = ACTION_HANDOFF_MS, countsAsHumanActivity = true, maxQueued = null) {
35666
+ if (!this.action && this.actionQueue.length === 0) {
35667
+ return this.beginAction(countsAsHumanActivity);
35668
+ }
35669
+ if (maxQueued !== null && this.actionQueue.length >= maxQueued) return null;
35670
+ return await new Promise((resolve2) => {
35671
+ let done = false;
35672
+ let timer;
35673
+ const wake = () => {
35674
+ if (done) return;
35675
+ done = true;
35676
+ if (timer) clearTimeout(timer);
35677
+ resolve2(this.beginAction(countsAsHumanActivity));
35678
+ };
35679
+ if (withinMs !== null) {
35680
+ timer = setTimeout(() => {
35681
+ if (done) return;
35682
+ done = true;
35683
+ const i = this.actionQueue.indexOf(wake);
35684
+ if (i >= 0) this.actionQueue.splice(i, 1);
35685
+ resolve2(null);
35686
+ }, withinMs);
35687
+ timer.unref?.();
35688
+ }
35689
+ this.actionQueue.push(wake);
35690
+ });
35149
35691
  }
35150
35692
  /**
35151
35693
  * Queue one actor, resolving when it gets the browser or is turned away.
@@ -35180,7 +35722,35 @@ var BrowserLease = class {
35180
35722
  };
35181
35723
 
35182
35724
  // src/browser/remote/controller.ts
35725
+ var KEYS = {
35726
+ Enter: { code: 13, text: "\r" },
35727
+ Tab: { code: 9 },
35728
+ Backspace: { code: 8 },
35729
+ Delete: { code: 46 },
35730
+ Escape: { code: 27 },
35731
+ ArrowUp: { code: 38 },
35732
+ ArrowDown: { code: 40 },
35733
+ ArrowLeft: { code: 37 },
35734
+ ArrowRight: { code: 39 },
35735
+ Home: { code: 36 },
35736
+ End: { code: 35 },
35737
+ PageUp: { code: 33 },
35738
+ PageDown: { code: 34 }
35739
+ };
35740
+ var BUTTONS = { left: 1, middle: 4, right: 2 };
35741
+ var SCREENCAST = { format: "jpeg", quality: 60, maxWidth: 1280, maxHeight: 800 };
35183
35742
  var ACTION_TIMEOUT_MS = 3e4;
35743
+ var RESTORE_FRAME_MS = 2e3;
35744
+ var MAX_HUMAN_INPUT_QUEUE = 64;
35745
+ var MAX_CAPTURE_TRANSITION_QUEUE = 16;
35746
+ var MAX_WATCH_LIFECYCLE_QUEUE = 16;
35747
+ function notify(deliver) {
35748
+ try {
35749
+ void Promise.resolve(deliver()).catch(() => {
35750
+ });
35751
+ } catch {
35752
+ }
35753
+ }
35184
35754
  var RemoteBrowserController = class {
35185
35755
  provider;
35186
35756
  maxSessions;
@@ -35193,8 +35763,49 @@ var RemoteBrowserController = class {
35193
35763
  * bearer capability for a browser somebody else is driving.
35194
35764
  */
35195
35765
  liveViewListeners = /* @__PURE__ */ new Map();
35766
+ /**
35767
+ * Told when a run's browser changes hands, or stops being pictured.
35768
+ *
35769
+ * Needed because a takeover can end without anybody asking. The hold lapses
35770
+ * on its own after `HUMAN_IDLE_MS`, and a client left believing it still has
35771
+ * control would keep sending input into a lease it no longer holds — every
35772
+ * event refused, with nothing on screen saying why.
35773
+ */
35774
+ controlListeners = /* @__PURE__ */ new Map();
35775
+ /** What each run's listener was last told, so unchanged states stay quiet. */
35776
+ controlAnnounced = /* @__PURE__ */ new Map();
35196
35777
  /** An embedder that wants every run's live view, told which run each is. */
35197
35778
  onLiveViewAll;
35779
+ /** Told when a provider session could not be handed back. See `disposeRun`. */
35780
+ onReleaseFailed;
35781
+ /**
35782
+ * Tell the observer a session leaked, without letting it become the leak.
35783
+ *
35784
+ * Guarded, because this runs inside a `.catch` on the release: an observer
35785
+ * that throws — a logging or telemetry sink that is momentarily unavailable
35786
+ * is the ordinary case — would turn its own failure into a fresh rejection
35787
+ * from `disposeRun`, so `endRun` would reject before `forgetRun` and the
35788
+ * fire-and-forget `stopRun` path would raise an unhandled rejection.
35789
+ *
35790
+ * That is precisely the guarantee this whole change claims to preserve: a
35791
+ * release that fails must never fail the run. Reporting it cannot be the
35792
+ * thing that breaks it.
35793
+ *
35794
+ * TWO WAYS TO FAIL, not one. The `try` catches a synchronous throw; an
35795
+ * `async` sink — which is what a telemetry or logging callback usually is —
35796
+ * fails by returning a REJECTED PROMISE, which no `try` around a call that is
35797
+ * never awaited can see. Node then raises an unhandled rejection and can take
35798
+ * the process down: the observer would not merely have failed to report the
35799
+ * leak, it would have killed the run, which is the one outcome this function
35800
+ * exists to prevent, reached through the door the guard did not cover.
35801
+ *
35802
+ * Not awaited, though. The caller is a `.catch` on the release and is not
35803
+ * going to wait for a telemetry round trip; attaching a handler is what makes
35804
+ * the rejection observed, which is the whole requirement.
35805
+ */
35806
+ reportReleaseFailure(runId, sessionId, err, expiresInMs) {
35807
+ notify(() => this.onReleaseFailed?.(runId, sessionId, err, expiresInMs));
35808
+ }
35198
35809
  runs = /* @__PURE__ */ new Map();
35199
35810
  /**
35200
35811
  * Runs that have a pool slot but no browser yet.
@@ -35202,7 +35813,7 @@ var RemoteBrowserController = class {
35202
35813
  * Counted alongside `runs` against the cap. Without it the limit was a
35203
35814
  * check-then-act across four awaits, and simultaneous first uses both won.
35204
35815
  */
35205
- opening = /* @__PURE__ */ new Set();
35816
+ opening = /* @__PURE__ */ new Map();
35206
35817
  /**
35207
35818
  * A run's stop signal, created when its slot is reserved.
35208
35819
  *
@@ -35235,7 +35846,7 @@ var RemoteBrowserController = class {
35235
35846
  * own teardown settles, so a later, genuine re-open of the same run id
35236
35847
  * never collides with one still in flight.
35237
35848
  */
35238
- closing = /* @__PURE__ */ new Set();
35849
+ closing = /* @__PURE__ */ new Map();
35239
35850
  /** Runs the user has stopped, by run id — same meaning as on the desktop. */
35240
35851
  revoked = /* @__PURE__ */ new Set();
35241
35852
  /**
@@ -35253,11 +35864,39 @@ var RemoteBrowserController = class {
35253
35864
  const asked = Math.max(1, options.maxSessions ?? 1);
35254
35865
  this.maxSessions = options.provider.isolatesSessions ? asked : 1;
35255
35866
  this.onLiveViewAll = options.onLiveView;
35867
+ this.onReleaseFailed = options.onReleaseFailed;
35868
+ this.ready = options.ready;
35256
35869
  }
35870
+ /**
35871
+ * The predecessor's teardown, until it has been waited for once.
35872
+ *
35873
+ * Cleared as soon as it settles so the wait is not re-entered on every open
35874
+ * — and so the promise itself is not retained for the life of the process.
35875
+ */
35876
+ ready;
35877
+ /**
35878
+ * This controller has been retired and will never open anything again.
35879
+ *
35880
+ * Stronger than "its runs were ended", and it has to be. A caller parked on
35881
+ * the `ready` gate above is invisible to `dispose()` — it holds no run and
35882
+ * has reserved no slot, because it has not got that far — so a SECOND
35883
+ * settings change, arriving while the first retirement is still settling,
35884
+ * found nothing to wait for and let the newest controller start immediately.
35885
+ * The parked caller then woke up on a controller nobody holds a reference to
35886
+ * and allocated a session against the superseded configuration, with the
35887
+ * newest controller free to allocate its own.
35888
+ *
35889
+ * Set synchronously at the top of `dispose`, so anything already waiting is
35890
+ * excluded the moment retirement begins rather than when it finishes.
35891
+ */
35892
+ retired = false;
35257
35893
  leaseFor(runId) {
35258
35894
  let lease = this.leases.get(runId);
35259
35895
  if (!lease) {
35260
- lease = new BrowserLease({ isRevoked: (id) => this.revoked.has(id) });
35896
+ lease = new BrowserLease({
35897
+ isRevoked: (id) => this.revoked.has(id),
35898
+ onChange: () => this.announceControl(runId)
35899
+ });
35261
35900
  lease.setLifecycleReleaseWired(true);
35262
35901
  this.leases.set(runId, lease);
35263
35902
  }
@@ -35274,6 +35913,44 @@ var RemoteBrowserController = class {
35274
35913
  offLiveViewFor(runKey) {
35275
35914
  this.liveViewListeners.delete(runKey);
35276
35915
  }
35916
+ onControlFor(runKey, listener) {
35917
+ this.controlListeners.set(runKey, listener);
35918
+ }
35919
+ offControlFor(runKey) {
35920
+ this.controlListeners.delete(runKey);
35921
+ this.controlAnnounced.delete(runKey);
35922
+ }
35923
+ /**
35924
+ * Say who has the browser, but only when the answer has changed.
35925
+ *
35926
+ * The lease reports every ownership change, and during ordinary work that is
35927
+ * one per action as workers take it and give it back. None of those are
35928
+ * interesting to a viewer — the agent had it before and has it now — and
35929
+ * emitting them would put a socket message on every click the agent makes.
35930
+ */
35931
+ announceControl(runId, force = false) {
35932
+ const listener = this.controlListeners.get(runId);
35933
+ if (!listener) return;
35934
+ const held = this.runs.get(runId);
35935
+ const state = {
35936
+ human: this.leases.get(runId)?.heldByHuman === true,
35937
+ capturing: held?.capturing === true,
35938
+ // A receipt vouches for a VIEW, so it stops meaning anything the moment
35939
+ // there is no view. `stopWatching` clears the session without bumping the
35940
+ // watch — deliberately, since replacing the consumer is what a new watch
35941
+ // is about — so the receipt stayed matched across the whole detach and
35942
+ // re-attach, which `beginWatching` performs on every reconnect and every
35943
+ // return to a conversation. Announced `confirmed` through that window,
35944
+ // the client mounted and FOCUSED the blind keyboard surface over a page
35945
+ // no session was serving: keystrokes meant for the composer went to a
35946
+ // remote page that could only refuse them.
35947
+ confirmed: held?.screencast !== void 0 && held.watchGen !== void 0 && held.seenGen === held.watchGen
35948
+ };
35949
+ const key = `${state.human}:${state.capturing}:${state.confirmed}`;
35950
+ if (!force && this.controlAnnounced.get(runId) === key) return;
35951
+ this.controlAnnounced.set(runId, key);
35952
+ notify(() => listener(state));
35953
+ }
35277
35954
  /**
35278
35955
  * Tell a run's listener what its browser situation is.
35279
35956
  *
@@ -35283,9 +35960,32 @@ var RemoteBrowserController = class {
35283
35960
  * apart — and would drop the Stop control for the first as if it were the
35284
35961
  * second.
35285
35962
  */
35963
+ /*
35964
+ * Guarded HERE rather than at the call sites, which is the point.
35965
+ *
35966
+ * This is the fifth place in this changeset where a notification could take
35967
+ * down the thing it was notifying about — after the release observer,
35968
+ * `clarification:closed`, `clarification:timeout` and `escalation:timeout`.
35969
+ * The first four were fixed one door at a time, which is how a fifth door
35970
+ * came to exist: the announcement added on the reuse path propagated out of
35971
+ * `open()`, `act()` caught it as an action failure, and every later action
35972
+ * against a perfectly healthy browser was skipped.
35973
+ *
35974
+ * Putting the guard at the source closes all four call sites at once and
35975
+ * leaves no door for a sixth. The worst of them is not the reported one:
35976
+ * `disposeRun` announces `active: false` as its FIRST statement, so a
35977
+ * throwing listener aborted teardown before the screencast was stopped, the
35978
+ * context closed, or the session handed back — leaking the provider session
35979
+ * and never reaching `reportReleaseFailure`. The leak report would have been
35980
+ * skipped by exactly the failure it exists to report.
35981
+ *
35982
+ * Two separate guards, not one around both: these are different listeners —
35983
+ * the per-run panel and the global observer — and one failing must not cost
35984
+ * the other its notification.
35985
+ */
35286
35986
  announceLiveView(runId, liveViewUrl, active) {
35287
- this.liveViewListeners.get(runId)?.({ active, ...liveViewUrl ? { liveViewUrl } : {} });
35288
- this.onLiveViewAll?.(runId, liveViewUrl);
35987
+ notify(() => this.liveViewListeners.get(runId)?.({ active, ...liveViewUrl ? { liveViewUrl } : {} }));
35988
+ notify(() => this.onLiveViewAll?.(runId, liveViewUrl));
35289
35989
  }
35290
35990
  /**
35291
35991
  * Hand back a session the run turned out not to want.
@@ -35294,22 +35994,682 @@ var RemoteBrowserController = class {
35294
35994
  * allocated and billed until the whole run ended, for a run that has just
35295
35995
  * been stopped.
35296
35996
  */
35297
- async releaseIfIdle(runId) {
35997
+ async releaseIfIdle(runId, releaseSlot) {
35298
35998
  const held = this.runs.get(runId);
35299
- if (!held) return;
35999
+ if (!held) {
36000
+ releaseSlot?.();
36001
+ return;
36002
+ }
35300
36003
  this.runs.delete(runId);
35301
- this.closing.add(runId);
35302
- await this.teardown(runId, held);
36004
+ const teardown = this.teardown(runId, held);
36005
+ releaseSlot?.();
36006
+ await teardown;
35303
36007
  }
35304
36008
  /** Release every run's session. For when the deployment's config changes. */
35305
36009
  async dispose() {
35306
- const ids = /* @__PURE__ */ new Set([...this.runs.keys(), ...this.opening]);
36010
+ this.retired = true;
36011
+ const opening = [...this.opening.values()];
36012
+ const ids = /* @__PURE__ */ new Set([...this.runs.keys(), ...this.opening.keys()]);
35307
36013
  await Promise.all([...ids].map((runId) => this.endRun(runId)));
36014
+ await Promise.all(opening.map((open) => open.catch(() => {
36015
+ })));
36016
+ await Promise.all([...this.closing.values()].map((done) => done.catch(() => {
36017
+ })));
35308
36018
  }
35309
36019
  /** A worker finished; it will never ask for the browser again. */
35310
36020
  actorEnded(actorId) {
35311
36021
  for (const lease of this.leases.values()) lease.actorEnded(actorId);
35312
36022
  }
36023
+ /**
36024
+ * Start streaming this run's page to whoever is watching it.
36025
+ *
36026
+ * Nothing streams until someone asks. That is the whole reason this is a
36027
+ * method rather than something `open()` does: an unwatched run would
36028
+ * otherwise pay to encode frames nobody sees, on every run, forever — and on
36029
+ * a metered provider it would pay for the bandwidth too.
36030
+ *
36031
+ * Frames are ACKED after they are handed on, never before. Chrome sends the
36032
+ * next frame only once the previous is acknowledged, so this bounds it to one
36033
+ * outstanding frame against OUR OWN handling. It does not reach further than
36034
+ * that, and an earlier version of this comment claimed it did: `onFrame` ends
36035
+ * at a socket emit, which hands the JPEG to a transport rather than to a
36036
+ * viewer, so the ack says nothing about what the person actually received.
36037
+ * Bounding the rest of the path is the transport's job — see `emitFrame`,
36038
+ * where frames go out lossy so a slow connection drops pictures instead of
36039
+ * banking stale ones. Dropping the ack stops the stream dead, which is why it
36040
+ * is best-effort but unconditional.
36041
+ *
36042
+ * Returns false when there is nothing to watch — the run has no browser, or
36043
+ * it is already being watched. Callers use that to avoid promising a viewer
36044
+ * a stream that will never arrive.
36045
+ */
36046
+ async startWatching(runId, onFrame) {
36047
+ const held = this.runs.get(runId);
36048
+ if (!held) return false;
36049
+ return await this.queueWatch(held, async () => {
36050
+ held.onFrame = onFrame;
36051
+ held.watchGen = (held.watchGen ?? 0) + 1;
36052
+ if (held.screencast) {
36053
+ this.announceControl(runId);
36054
+ return true;
36055
+ }
36056
+ const attached = await this.attachScreencast(runId, held, onFrame);
36057
+ if (!attached && held.onFrame === onFrame) held.onFrame = void 0;
36058
+ return attached !== null;
36059
+ });
36060
+ }
36061
+ /**
36062
+ * Run one watch or unwatch after every one already asked for.
36063
+ *
36064
+ * The chain is kept non-rejecting on purpose: a failed attach must not poison
36065
+ * every later request for this run, which is what a bare `.then` chain would
36066
+ * do. The caller still sees its own failure, because that is the promise
36067
+ * returned rather than the one stored.
36068
+ */
36069
+ queueWatch(held, op) {
36070
+ const depth = held.watchQueueDepth ?? 0;
36071
+ if (held.watchCollapsedPromise || depth >= MAX_WATCH_LIFECYCLE_QUEUE) {
36072
+ held.watchCollapsed = op;
36073
+ if (!held.watchCollapsedPromise) {
36074
+ const drain = async () => {
36075
+ let result;
36076
+ while (held.watchCollapsed) {
36077
+ const latest = held.watchCollapsed;
36078
+ held.watchCollapsed = void 0;
36079
+ try {
36080
+ result = await latest();
36081
+ } catch {
36082
+ }
36083
+ }
36084
+ return result;
36085
+ };
36086
+ const tail = (held.watchQueue ?? Promise.resolve()).then(drain, drain);
36087
+ let tracked;
36088
+ tracked = tail.finally(() => {
36089
+ if (held.watchCollapsedPromise === tracked) {
36090
+ held.watchCollapsedPromise = void 0;
36091
+ held.watchCollapsed = void 0;
36092
+ }
36093
+ });
36094
+ held.watchCollapsedPromise = tracked;
36095
+ held.watchQueue = tracked.catch(() => {
36096
+ });
36097
+ }
36098
+ return held.watchCollapsedPromise;
36099
+ }
36100
+ held.watchQueueDepth = depth + 1;
36101
+ const mine = (held.watchQueue ?? Promise.resolve()).then(op, op);
36102
+ const counted = mine.finally(() => {
36103
+ held.watchQueueDepth = Math.max(0, (held.watchQueueDepth ?? 1) - 1);
36104
+ });
36105
+ held.watchQueue = counted.catch(() => {
36106
+ });
36107
+ return counted;
36108
+ }
36109
+ /**
36110
+ * Attach at most one physical CDP screencast session at a time.
36111
+ *
36112
+ * `startWatching()` already serializes watcher lifecycle through `watchQueue`,
36113
+ * but the agent's detached-hidden restore cannot join that queue: it holds the
36114
+ * action slot, while an earlier unwatch may be waiting for exactly that slot.
36115
+ * Sharing only the physical attach closes the two-session race without making
36116
+ * watcher teardown and agent mutation wait on each other in a cycle.
36117
+ *
36118
+ * A real watcher claims `onFrame` immediately, before it waits for an attach
36119
+ * already started by the agent. The lower-level attach never writes the sink,
36120
+ * so finishing an older temporary attempt cannot overwrite a newer viewer.
36121
+ */
36122
+ async attachScreencast(runId, held, onFrame, popupDetachGen) {
36123
+ const consumerIntent = onFrame && popupDetachGen !== void 0 ? popupDetachGen : void 0;
36124
+ if (onFrame) held.onFrame = onFrame;
36125
+ if (held.screencast && held.screencastPage === held.page) return held.screencast;
36126
+ const targetPage = held.page;
36127
+ const existing = held.attaching;
36128
+ if (existing) {
36129
+ const existingPage = held.attachingPage;
36130
+ await existing.catch(() => null);
36131
+ if (held.page !== targetPage || existingPage !== targetPage) {
36132
+ return this.attachScreencast(runId, held, onFrame, popupDetachGen);
36133
+ }
36134
+ const cdp = held.screencastPage === targetPage ? held.screencast ?? null : null;
36135
+ if (consumerIntent !== void 0 && (held.watchDetachGen ?? 0) !== consumerIntent) return null;
36136
+ if (cdp && onFrame) held.onFrame = onFrame;
36137
+ return cdp;
36138
+ }
36139
+ if (held.screencast && held.screencastPage !== targetPage) {
36140
+ const stale = held.screencast;
36141
+ held.screencast = void 0;
36142
+ held.screencastPage = void 0;
36143
+ await stale.send("Page.stopScreencast").catch(() => {
36144
+ });
36145
+ await stale.detach().catch(() => {
36146
+ });
36147
+ }
36148
+ const attempt = this.attachScreencastFresh(runId, held, targetPage, consumerIntent);
36149
+ held.attaching = attempt;
36150
+ held.attachingPage = targetPage;
36151
+ try {
36152
+ const cdp = await attempt;
36153
+ if (consumerIntent !== void 0 && (held.watchDetachGen ?? 0) !== consumerIntent) return null;
36154
+ if (cdp && onFrame) held.onFrame = onFrame;
36155
+ return cdp;
36156
+ } finally {
36157
+ if (held.attaching === attempt) {
36158
+ held.attaching = void 0;
36159
+ held.attachingPage = void 0;
36160
+ }
36161
+ }
36162
+ }
36163
+ /** Open one new CDP session and start the stream when it is safe to do so. */
36164
+ async attachScreencastFresh(runId, held, targetPage, consumerIntent) {
36165
+ const safetyGate = held.hiddenByHolder === true || held.visibilityUnconfirmed === true;
36166
+ let cdp;
36167
+ try {
36168
+ cdp = await targetPage.context().newCDPSession(targetPage);
36169
+ } catch {
36170
+ if (!safetyGate) {
36171
+ held.visibilityUnconfirmed = false;
36172
+ held.capturing = true;
36173
+ this.announceControl(runId);
36174
+ }
36175
+ return null;
36176
+ }
36177
+ if (held.page !== targetPage) {
36178
+ await cdp.detach().catch(() => {
36179
+ });
36180
+ return null;
36181
+ }
36182
+ cdp.on("Page.screencastFrame", ((e) => {
36183
+ if (held.page === targetPage && typeof e?.data === "string") {
36184
+ const width = e.metadata?.deviceWidth ?? 0;
36185
+ const height = e.metadata?.deviceHeight ?? 0;
36186
+ held.metricsStale = true;
36187
+ if (held.visibilityUnconfirmed) {
36188
+ held.visibilityUnconfirmed = false;
36189
+ if (held.capturing !== true) {
36190
+ held.capturing = true;
36191
+ this.announceControl(runId);
36192
+ }
36193
+ }
36194
+ const ping = held.framePing;
36195
+ held.framePing = void 0;
36196
+ ping?.();
36197
+ const deliver = held.onFrame;
36198
+ if (deliver) {
36199
+ const frame = { data: e.data, width, height, generation: held.watchGen ?? 0 };
36200
+ notify(() => deliver(frame));
36201
+ }
36202
+ }
36203
+ void cdp.send("Page.screencastFrameAck", { sessionId: e?.sessionId }).catch(() => {
36204
+ });
36205
+ }));
36206
+ const paused = held.hiddenByHolder === true;
36207
+ if (!paused) {
36208
+ try {
36209
+ await cdp.send("Page.startScreencast", { ...SCREENCAST });
36210
+ } catch {
36211
+ if (!safetyGate) {
36212
+ held.visibilityUnconfirmed = false;
36213
+ held.capturing = true;
36214
+ this.announceControl(runId);
36215
+ } else {
36216
+ held.capturing = false;
36217
+ this.announceControl(runId);
36218
+ }
36219
+ await cdp.detach().catch(() => {
36220
+ });
36221
+ return null;
36222
+ }
36223
+ }
36224
+ if (held.page !== targetPage) {
36225
+ if (!paused) await cdp.send("Page.stopScreencast").catch(() => {
36226
+ });
36227
+ await cdp.detach().catch(() => {
36228
+ });
36229
+ return null;
36230
+ }
36231
+ if (consumerIntent !== void 0 && (held.watchDetachGen ?? 0) !== consumerIntent) {
36232
+ if (!paused) await cdp.send("Page.stopScreencast").catch(() => {
36233
+ });
36234
+ await cdp.detach().catch(() => {
36235
+ });
36236
+ return null;
36237
+ }
36238
+ held.screencast = cdp;
36239
+ held.screencastPage = targetPage;
36240
+ held.capturing = !paused;
36241
+ held.hiddenByHolder = paused;
36242
+ this.announceControl(runId);
36243
+ return cdp;
36244
+ }
36245
+ /** Nobody is watching any more: stop paying to render frames. */
36246
+ async stopWatching(runId) {
36247
+ const held = this.runs.get(runId);
36248
+ if (!held) return;
36249
+ held.watchDetachGen = (held.watchDetachGen ?? 0) + 1;
36250
+ held.onFrame = void 0;
36251
+ await this.queueWatch(held, async () => {
36252
+ const cdp = held.screencast;
36253
+ held.onFrame = void 0;
36254
+ if (!cdp) return;
36255
+ held.screencast = void 0;
36256
+ held.screencastPage = void 0;
36257
+ held.capturing = false;
36258
+ this.announceControl(runId);
36259
+ const lease = this.leases.get(runId);
36260
+ const token = lease ? await lease.acquireActionSlot(null, false) : null;
36261
+ if (lease && !token) return;
36262
+ try {
36263
+ await cdp.send("Page.stopScreencast").catch(() => {
36264
+ });
36265
+ await cdp.detach().catch(() => {
36266
+ });
36267
+ } finally {
36268
+ if (token && lease) lease.endAction(token);
36269
+ }
36270
+ });
36271
+ }
36272
+ /**
36273
+ * Suspend or resume the picture without giving up control.
36274
+ *
36275
+ * The credential case, and the only reason this is separate from watching. A
36276
+ * person who has taken the page over to sign in is about to type a password
36277
+ * into a field whose contents are echoed as dots — but a password manager's
36278
+ * dropdown, a "show password" toggle, a one-time code in plain text and the
36279
+ * confirmation page afterwards are not, and all of them would otherwise be
36280
+ * encoded into frames and sent across the network.
36281
+ *
36282
+ * What this does NOT do is hide anything from the agent: it stops the
36283
+ * picture, not the page. Nothing about a suspended capture would stop a
36284
+ * `extract_text` from reading the same screen — it is the lease that stops
36285
+ * that, by refusing the agent for as long as the person holds it.
36286
+ *
36287
+ * Answers whether frames are flowing afterwards, which is what a UI needs to
36288
+ * show and is not always what was asked for: a run with nobody watching has
36289
+ * no session to suspend.
36290
+ */
36291
+ async setCapture(runId, on) {
36292
+ const held = this.runs.get(runId);
36293
+ const cdp = held?.screencast;
36294
+ const watch = held?.watchGen;
36295
+ if (!held || !cdp) return false;
36296
+ const lease = this.leaseFor(runId);
36297
+ if (!on && !lease.heldByHuman) return held.capturing === true;
36298
+ if (!on && (watch === void 0 || held.seenGen !== watch)) {
36299
+ return held.capturing === true;
36300
+ }
36301
+ if (held.capturing === on) {
36302
+ if (lease.heldByHuman) lease.touch();
36303
+ return on;
36304
+ }
36305
+ const token = await lease.acquireActionSlot(null, true, MAX_CAPTURE_TRANSITION_QUEUE);
36306
+ if (!token) return held.capturing === true;
36307
+ try {
36308
+ if (!on && !lease.heldByHuman) return held.capturing === true;
36309
+ if (!on && (held.screencast !== cdp || held.watchGen !== watch)) {
36310
+ return held.capturing === true;
36311
+ }
36312
+ if (!on && (watch === void 0 || held.seenGen !== watch)) {
36313
+ return held.capturing === true;
36314
+ }
36315
+ const target = on ? held.screencast : cdp;
36316
+ if (!target) {
36317
+ if (on) {
36318
+ held.hiddenByHolder = false;
36319
+ if (lease.heldByHuman) lease.touch();
36320
+ }
36321
+ return held.capturing === true;
36322
+ }
36323
+ const now = await this.applyCapture(runId, held, target, on);
36324
+ if (lease.heldByHuman) lease.touch();
36325
+ return now;
36326
+ } finally {
36327
+ lease.endAction(token);
36328
+ }
36329
+ }
36330
+ /**
36331
+ * The capture transition itself, with no lease bookkeeping.
36332
+ *
36333
+ * Separate because the agent's restore in `act()` already holds the action
36334
+ * slot — taking it again there would deadlock against itself, and the whole
36335
+ * point of that call site is that it happens INSIDE the agent's turn.
36336
+ *
36337
+ * `confirmWithFrame` is used only by the agent's visibility gate. There, a
36338
+ * successful CDP command is not enough: the externally visible state remains
36339
+ * paused until a frame arrives, and the frame handler is the only code that
36340
+ * promotes it to capturing. This makes a restore timeout sticky rather than
36341
+ * a one-action refusal.
36342
+ */
36343
+ async applyCapture(runId, held, cdp, on, confirmWithFrame = false) {
36344
+ if (held.capturing === on && !(on && confirmWithFrame && held.visibilityUnconfirmed)) return on;
36345
+ const wasUnconfirmed = held.visibilityUnconfirmed === true;
36346
+ const wasCapturing = held.capturing === true;
36347
+ if (on) held.visibilityUnconfirmed = true;
36348
+ try {
36349
+ if (on) await cdp.send("Page.startScreencast", { ...SCREENCAST });
36350
+ else await cdp.send("Page.stopScreencast");
36351
+ if (on) {
36352
+ if (!confirmWithFrame) held.capturing = true;
36353
+ } else {
36354
+ held.visibilityUnconfirmed = false;
36355
+ held.capturing = false;
36356
+ }
36357
+ held.hiddenByHolder = !on;
36358
+ this.announceControl(runId);
36359
+ } catch {
36360
+ if (on) {
36361
+ held.visibilityUnconfirmed = wasUnconfirmed;
36362
+ held.capturing = wasCapturing;
36363
+ this.announceControl(runId);
36364
+ }
36365
+ return held.capturing === true && !held.visibilityUnconfirmed;
36366
+ }
36367
+ return on;
36368
+ }
36369
+ /**
36370
+ * Wait, briefly, for Chrome to produce a frame.
36371
+ *
36372
+ * `Page.startScreencast` resolves when the command is accepted, which is not
36373
+ * when a picture exists. The agent's visibility gate — "the page must be
36374
+ * VISIBLE before anything changes it" — was therefore satisfied by a request
36375
+ * rather than by a repaint, and the agent could click while the panel was
36376
+ * still showing the page from before it was hidden, or nothing at all.
36377
+ *
36378
+ * A frame rather than a client receipt, deliberately. A receipt would prove
36379
+ * somebody SAW it, which is stronger — and would make the agent's progress
36380
+ * depend on a viewer that may not exist: this path runs after a handback or a
36381
+ * lapse, when there may be nobody watching at all, and an agent that stalls
36382
+ * because a tab was closed is a worse failure than the one being fixed. What
36383
+ * this does guarantee is ours to guarantee: the stream is producing again.
36384
+ *
36385
+ * Bounded, and the bound rests on the property rounds 14 and 15 already rely
36386
+ * on — a screencast that has just been started emits its first frame at once,
36387
+ * whatever the page is doing. If one does not arrive, the picture genuinely
36388
+ * has not come back, and the caller refuses on the same trade it already
36389
+ * makes when the restore itself fails.
36390
+ */
36391
+ nextFrame(held, withinMs = RESTORE_FRAME_MS) {
36392
+ return new Promise((resolve2) => {
36393
+ const timer = setTimeout(() => {
36394
+ if (held.framePing === ping) held.framePing = void 0;
36395
+ resolve2(false);
36396
+ }, withinMs);
36397
+ timer.unref?.();
36398
+ const ping = () => {
36399
+ clearTimeout(timer);
36400
+ resolve2(true);
36401
+ };
36402
+ held.framePing = ping;
36403
+ });
36404
+ }
36405
+ /** Whether a person is driving this run's browser right now. */
36406
+ humanHolds(runId) {
36407
+ return this.leases.get(runId)?.heldByHuman === true;
36408
+ }
36409
+ /**
36410
+ * Hand this run's browser to the person watching it.
36411
+ *
36412
+ * The wait is the substance. An agent action already inside Playwright cannot
36413
+ * be interrupted — `click` waits for its element to become actionable and
36414
+ * then clicks, whatever anyone decided in the meantime — so a takeover that
36415
+ * returned immediately would put the person on a page an action was still
36416
+ * about to change. Bounded by the action ceiling, because that is the longest
36417
+ * an action can legitimately take; past it something is wedged, and saying so
36418
+ * is better than a spinner that never resolves.
36419
+ *
36420
+ * Idempotent for someone who already holds it: a second click of Take control
36421
+ * just says they are still there.
36422
+ */
36423
+ async takeOver(runId) {
36424
+ if (this.revoked.has(runId)) {
36425
+ return { ok: false, detail: "Browser control was stopped for this run." };
36426
+ }
36427
+ const requested = this.runs.get(runId);
36428
+ if (!requested) {
36429
+ return { ok: false, detail: "This run has no browser open." };
36430
+ }
36431
+ const requestedCdp = requested.screencast;
36432
+ const requestedWatch = requested.watchGen;
36433
+ if (!requestedCdp || requestedWatch === void 0 || !requested.onFrame) {
36434
+ return { ok: false, detail: "This browser is not being watched right now." };
36435
+ }
36436
+ const lease = this.leaseFor(runId);
36437
+ if (lease.heldByHuman) {
36438
+ lease.touch();
36439
+ this.announceControl(runId, true);
36440
+ return { ok: true };
36441
+ }
36442
+ const token = await lease.acquireActionSlot(ACTION_TIMEOUT_MS);
36443
+ if (!token) {
36444
+ return {
36445
+ ok: false,
36446
+ detail: "The agent is still finishing an action on this page. Try again in a moment."
36447
+ };
36448
+ }
36449
+ try {
36450
+ const held = this.runs.get(runId);
36451
+ if (this.revoked.has(runId)) {
36452
+ return { ok: false, detail: "Browser control was stopped for this run." };
36453
+ }
36454
+ if (!held || held.page.isClosed()) {
36455
+ return { ok: false, detail: "That browser closed while you were waiting for it." };
36456
+ }
36457
+ if (held.screencast !== requestedCdp || held.watchGen !== requestedWatch || !held.onFrame) {
36458
+ return { ok: false, detail: "The browser view changed while you were waiting. Take control again from the current view." };
36459
+ }
36460
+ lease.takeOver(runId);
36461
+ } finally {
36462
+ lease.endAction(token);
36463
+ }
36464
+ return { ok: true };
36465
+ }
36466
+ /** The person is done. Answers whether they were holding it at all. */
36467
+ /**
36468
+ * The viewer confirms it received a picture of this run's page.
36469
+ *
36470
+ * Reliable, one per watch, and the only thing that opens Hide. Checked
36471
+ * against the CURRENT watch: a receipt that names an older one is from a
36472
+ * viewer that has since been replaced, and vouching for its successor is the
36473
+ * reconnect hole this counter exists to close.
36474
+ */
36475
+ frameSeen(runId, generation) {
36476
+ const held = this.runs.get(runId);
36477
+ if (!held) return;
36478
+ if (typeof generation !== "number" || !Number.isFinite(generation)) return;
36479
+ if (held.watchGen === void 0 || generation !== held.watchGen) return;
36480
+ if (held.seenGen === generation) return;
36481
+ held.seenGen = generation;
36482
+ this.announceControl(runId);
36483
+ }
36484
+ handBack(runId) {
36485
+ return this.leases.get(runId)?.handBack() === true;
36486
+ }
36487
+ /**
36488
+ * One thing the person did to the page.
36489
+ *
36490
+ * Authorised per event, not per session. A takeover is not a channel that
36491
+ * stays open once opened: between two clicks the run can be stopped, the hold
36492
+ * can lapse, the page can close, and each of those has to stop the NEXT
36493
+ * event rather than be noticed at the end. So every event re-checks that this
36494
+ * run is live and that the lease is still the person's, and every accepted
36495
+ * event says so by extending the hold.
36496
+ */
36497
+ async input(runId, event) {
36498
+ const held = this.runs.get(runId);
36499
+ const cdp = held?.screencast;
36500
+ const watch = held?.watchGen;
36501
+ if (!held || held.page.isClosed()) return { ok: false, detail: "This run has no browser open." };
36502
+ const page2 = held.page;
36503
+ const pageGeneration = held.generation;
36504
+ if (!cdp) return { ok: false, detail: "Nothing is streaming this browser, so it cannot be driven." };
36505
+ const lease = this.leaseFor(runId);
36506
+ if (!lease.heldByHuman) {
36507
+ return { ok: false, detail: "You do not have control of this browser. Take control first." };
36508
+ }
36509
+ if (held.capturing !== true && (held.watchGen === void 0 || held.seenGen !== held.watchGen)) {
36510
+ return { ok: false, detail: "Show the page before typing into it \u2014 this view has not seen it yet." };
36511
+ }
36512
+ const sampled = event.kind === "move";
36513
+ const token = sampled ? lease.tryActionSlot() : await lease.acquireActionSlot(null, true, MAX_HUMAN_INPUT_QUEUE);
36514
+ if (!token) {
36515
+ if (sampled) return { ok: true };
36516
+ return { ok: false, detail: "Too many browser inputs are already waiting. Let the page catch up, then try again." };
36517
+ }
36518
+ try {
36519
+ if (!lease.heldByHuman) {
36520
+ return { ok: false, detail: "Your control of this browser ended while that was waiting." };
36521
+ }
36522
+ if (held.page !== page2 || held.generation !== pageGeneration) {
36523
+ return { ok: false, detail: "The page changed while that input was waiting, so it did not land." };
36524
+ }
36525
+ if (held.screencast !== cdp || held.watchGen !== watch) {
36526
+ return { ok: false, detail: "The view you were driving is gone, so that did not land." };
36527
+ }
36528
+ const pagesBefore = new Set(held.page.context().pages());
36529
+ await this.dispatch(cdp, held, event);
36530
+ await this.followOpenedPage(runId, held, pagesBefore);
36531
+ } catch (err) {
36532
+ return { ok: false, detail: err instanceof Error ? err.message : String(err) };
36533
+ } finally {
36534
+ lease.endAction(token);
36535
+ }
36536
+ lease.touch();
36537
+ return { ok: true };
36538
+ }
36539
+ /**
36540
+ * The page's own coordinate space, measured rather than inferred.
36541
+ *
36542
+ * Cached, because a click should not cost a round trip, and invalidated by
36543
+ * the frame metadata changing shape — which arrives free with every frame. A
36544
+ * failed measurement falls back to the last good one rather than to a guess:
36545
+ * a stale viewport is off by a resize, an invented one is off by anything.
36546
+ */
36547
+ async pageViewport(held, cdp) {
36548
+ if (held.viewport && !held.metricsStale) return held.viewport;
36549
+ try {
36550
+ const metrics = await cdp.send("Page.getLayoutMetrics");
36551
+ const width = metrics?.cssVisualViewport?.clientWidth;
36552
+ const height = metrics?.cssVisualViewport?.clientHeight;
36553
+ if (typeof width === "number" && typeof height === "number" && width > 0 && height > 0) {
36554
+ held.viewport = { width, height };
36555
+ held.metricsStale = false;
36556
+ return held.viewport;
36557
+ }
36558
+ } catch {
36559
+ }
36560
+ return null;
36561
+ }
36562
+ /**
36563
+ * Turn one authorised event into CDP calls. Coordinates arrive normalised.
36564
+ *
36565
+ * A switch with a default that REFUSES, rather than a chain of ifs ending in
36566
+ * the click branch. This is a mutation boundary reached from a socket, so the
36567
+ * question is not what a well-formed event does but what a malformed one
36568
+ * does: the chain answered "clicks", which meant a version-skewed client
36569
+ * sending `{ kind: 'drag', x, y }` pressed the mouse on a real page, and a
36570
+ * kind with no coordinates at all clamped to 0 and clicked the top-left
36571
+ * corner. Unknown input has to fail closed.
36572
+ *
36573
+ * The `never` in the default is the other half: adding a member to
36574
+ * `BrowserInput` without handling it here stops compiling, so the next kind
36575
+ * cannot silently inherit whatever the last branch happened to be.
36576
+ */
36577
+ async dispatch(cdp, held, event) {
36578
+ switch (event.kind) {
36579
+ case "text": {
36580
+ if (typeof event.text !== "string") {
36581
+ throw new Error("That is not text that can be typed into the page.");
36582
+ }
36583
+ const text = event.text.slice(0, 4e3);
36584
+ if (!text) return;
36585
+ await cdp.send("Input.insertText", { text });
36586
+ return;
36587
+ }
36588
+ case "key": {
36589
+ const modifiers = event.modifiers;
36590
+ if (modifiers !== void 0) {
36591
+ if (!Array.isArray(modifiers) || modifiers.some((m) => m !== "Control" && m !== "Meta" && m !== "Shift") || new Set(modifiers).size !== modifiers.length) {
36592
+ throw new Error("That editing shortcut has invalid modifiers.");
36593
+ }
36594
+ const primary = modifiers.filter((m) => m === "Control" || m === "Meta");
36595
+ const shifted = modifiers.includes("Shift");
36596
+ if (primary.length !== 1) {
36597
+ throw new Error("That editing shortcut cannot be sent to the page.");
36598
+ }
36599
+ const key = typeof event.key === "string" ? event.key : "";
36600
+ const lower = key.toLowerCase();
36601
+ const shortcut = lower === "a" && !shifted ? { key: "a", code: "KeyA", vk: 65 } : lower === "z" ? { key: "z", code: "KeyZ", vk: 90 } : lower === "y" && !shifted ? { key: "y", code: "KeyY", vk: 89 } : key === "Backspace" && !shifted ? { key: "Backspace", code: "Backspace", vk: 8 } : key === "Delete" && !shifted ? { key: "Delete", code: "Delete", vk: 46 } : void 0;
36602
+ if (!shortcut) {
36603
+ throw new Error(`That editing shortcut is not supported for the remote page: ${key}`);
36604
+ }
36605
+ const modifierBits = (primary[0] === "Control" ? 2 : 4) | (shifted ? 8 : 0);
36606
+ const base2 = {
36607
+ key: shortcut.key,
36608
+ code: shortcut.code,
36609
+ windowsVirtualKeyCode: shortcut.vk,
36610
+ nativeVirtualKeyCode: shortcut.vk,
36611
+ modifiers: modifierBits
36612
+ };
36613
+ await cdp.send("Input.dispatchKeyEvent", { ...base2, type: "rawKeyDown" });
36614
+ await cdp.send("Input.dispatchKeyEvent", { ...base2, type: "keyUp" });
36615
+ return;
36616
+ }
36617
+ const spec = typeof event.key === "string" && Object.hasOwn(KEYS, event.key) ? KEYS[event.key] : void 0;
36618
+ if (!spec) throw new Error(`That key cannot be sent to the page: ${String(event.key)}`);
36619
+ const base = {
36620
+ key: event.key,
36621
+ code: event.key,
36622
+ windowsVirtualKeyCode: spec.code,
36623
+ nativeVirtualKeyCode: spec.code,
36624
+ ...spec.text ? { text: spec.text } : {}
36625
+ };
36626
+ await cdp.send("Input.dispatchKeyEvent", { ...base, type: spec.text ? "keyDown" : "rawKeyDown" });
36627
+ await cdp.send("Input.dispatchKeyEvent", { ...base, type: "keyUp" });
36628
+ return;
36629
+ }
36630
+ case "move":
36631
+ case "scroll":
36632
+ case "click": {
36633
+ const view = await this.pageViewport(held, cdp);
36634
+ if (!view) throw new Error("The page has not been measured yet, so a click cannot be placed on it.");
36635
+ const x = coordinate(event.x, "horizontal position") * view.width;
36636
+ const y = coordinate(event.y, "vertical position") * view.height;
36637
+ if (event.kind === "move") {
36638
+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none", buttons: 0 });
36639
+ return;
36640
+ }
36641
+ if (event.kind === "scroll") {
36642
+ await cdp.send("Input.dispatchMouseEvent", {
36643
+ type: "mouseWheel",
36644
+ x,
36645
+ y,
36646
+ button: "none",
36647
+ buttons: 0,
36648
+ deltaX: 0,
36649
+ deltaY: scrollDelta(event.deltaY)
36650
+ });
36651
+ return;
36652
+ }
36653
+ if (event.button !== void 0 && !Object.hasOwn(BUTTONS, event.button)) {
36654
+ throw new Error(`That is not a mouse button: ${String(event.button)}`);
36655
+ }
36656
+ const button = event.button ?? "left";
36657
+ const buttons = BUTTONS[button];
36658
+ if (event.clicks !== void 0 && (typeof event.clicks !== "number" || !Number.isFinite(event.clicks))) {
36659
+ throw new Error("That is not a number of clicks.");
36660
+ }
36661
+ const clickCount = Math.min(Math.max(Math.trunc(event.clicks ?? 1), 1), 3);
36662
+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none", buttons: 0 });
36663
+ await cdp.send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button, buttons, clickCount });
36664
+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button, buttons: 0, clickCount });
36665
+ return;
36666
+ }
36667
+ default: {
36668
+ const unknown = event;
36669
+ throw new Error(`That is not something that can be done to the page: ${unknown?.kind ?? "an event with no kind"}`);
36670
+ }
36671
+ }
36672
+ }
35313
36673
  /** The user stopped this run. Refuses further actions and clears its queue. */
35314
36674
  stopRun(runId) {
35315
36675
  this.revoked.add(runId);
@@ -35318,7 +36678,6 @@ var RemoteBrowserController = class {
35318
36678
  const held = this.runs.get(runId);
35319
36679
  if (!held) return;
35320
36680
  this.runs.delete(runId);
35321
- this.closing.add(runId);
35322
36681
  void this.teardown(runId, held);
35323
36682
  }
35324
36683
  /** A run ended: release its browser rather than pay for an idle session. */
@@ -35331,7 +36690,6 @@ var RemoteBrowserController = class {
35331
36690
  return;
35332
36691
  }
35333
36692
  this.runs.delete(runId);
35334
- this.closing.add(runId);
35335
36693
  await this.teardown(runId, held);
35336
36694
  this.forgetRun(runId);
35337
36695
  }
@@ -35341,6 +36699,7 @@ var RemoteBrowserController = class {
35341
36699
  this.leases.delete(runId);
35342
36700
  this.aborts.delete(runId);
35343
36701
  this.liveViewListeners.delete(runId);
36702
+ this.offControlFor(runId);
35344
36703
  }
35345
36704
  /**
35346
36705
  * Let go of one run's browser.
@@ -35352,12 +36711,22 @@ var RemoteBrowserController = class {
35352
36711
  async disposeRun(runId, held) {
35353
36712
  held.abort.abort();
35354
36713
  this.announceLiveView(runId, void 0, false);
36714
+ await held.watchQueue?.catch(() => {
36715
+ });
36716
+ const watching = held.screencast;
36717
+ held.screencast = void 0;
36718
+ held.screencastPage = void 0;
36719
+ if (watching) {
36720
+ await watching.send("Page.stopScreencast").catch(() => {
36721
+ });
36722
+ await watching.detach().catch(() => {
36723
+ });
36724
+ }
35355
36725
  await held.ownedContext?.close().catch(() => {
35356
36726
  });
35357
36727
  await held.browser.close().catch(() => {
35358
36728
  });
35359
- await this.provider.endSession(held.session.id).catch(() => {
35360
- });
36729
+ await this.provider.endSession(held.session.id).catch((err) => this.reportReleaseFailure(runId, held.session.id, err, held.session.expiresInMs));
35361
36730
  }
35362
36731
  /**
35363
36732
  * Run `disposeRun`, with the run id counted in `closing` until it settles.
@@ -35367,12 +36736,12 @@ var RemoteBrowserController = class {
35367
36736
  * guarantees the removal happens, success or failure, so a disposal that
35368
36737
  * throws cannot leave the slot counted against the pool forever.
35369
36738
  */
35370
- async teardown(runId, held) {
35371
- try {
35372
- await this.disposeRun(runId, held);
35373
- } finally {
36739
+ teardown(runId, held) {
36740
+ const done = this.disposeRun(runId, held).finally(() => {
35374
36741
  this.closing.delete(runId);
35375
- }
36742
+ });
36743
+ this.closing.set(runId, done);
36744
+ return done;
35376
36745
  }
35377
36746
  async act(action, context) {
35378
36747
  const runId = context.sessionId;
@@ -35386,7 +36755,9 @@ var RemoteBrowserController = class {
35386
36755
  if (context.signal?.aborted) {
35387
36756
  return { ok: false, detail: "The run was cancelled." };
35388
36757
  }
35389
- const planned = this.runs.get(runId)?.generation ?? 0;
36758
+ const plannedRun = this.runs.get(runId);
36759
+ const planned = plannedRun?.generation ?? 0;
36760
+ const recoveringClosedPage = plannedRun?.page.isClosed() === true;
35390
36761
  const lease_ = this.leaseFor(runId);
35391
36762
  const lease = await lease_.acquire(actor, runId, context.signal);
35392
36763
  if (lease !== "granted") {
@@ -35400,28 +36771,96 @@ var RemoteBrowserController = class {
35400
36771
  lease_.releaseIfHeldBy(actor);
35401
36772
  return { ok: false, detail: "The run was cancelled." };
35402
36773
  }
35403
- if (!await lease_.awaitActionSlot()) {
36774
+ const token = await lease_.acquireActionSlot();
36775
+ if (!token) {
35404
36776
  lease_.releaseIfHeldBy(actor);
35405
36777
  return { ok: false, detail: "Another browser action is still finishing. Try again." };
35406
36778
  }
35407
- const token = lease_.beginAction();
35408
- if (!token) {
35409
- return { ok: false, detail: "Another browser action is already running. Wait for it to finish." };
36779
+ if (!lease_.heldBy(actor)) {
36780
+ lease_.endAction(token);
36781
+ return { ok: false, detail: refusal(lease_.heldByHuman ? "human" : "off") };
35410
36782
  }
36783
+ let temporaryCapture;
35411
36784
  try {
35412
36785
  const held = await this.open(runId, context.signal);
35413
36786
  if (this.revoked.has(runId)) {
35414
- await this.releaseIfIdle(runId);
36787
+ await this.releaseIfIdle(runId, () => lease_.endAction(token));
35415
36788
  return { ok: false, detail: "The user stopped browser control for this run." };
35416
36789
  }
35417
36790
  if (context.signal?.aborted || held.abort.signal.aborted) {
35418
- await this.releaseIfIdle(runId);
36791
+ await this.releaseIfIdle(runId, () => lease_.endAction(token));
35419
36792
  return { ok: false, detail: "The run was cancelled." };
35420
36793
  }
35421
- return await this.perform(held, action, planned);
36794
+ if ((held.hiddenByHolder === true || held.visibilityUnconfirmed === true) && !held.screencast) {
36795
+ const watchGen = held.watchGen;
36796
+ let cdp = null;
36797
+ try {
36798
+ cdp = await this.attachScreencast(runId, held);
36799
+ } catch {
36800
+ }
36801
+ if (!cdp) {
36802
+ return {
36803
+ ok: false,
36804
+ detail: "The page could not be shown again, so nothing was done to it."
36805
+ };
36806
+ }
36807
+ if (held.onFrame === void 0 && held.watchGen === watchGen) {
36808
+ temporaryCapture = { held, cdp, watchGen };
36809
+ }
36810
+ }
36811
+ if (held.screencast && (held.capturing === false || held.visibilityUnconfirmed === true)) {
36812
+ const cdp = held.screencast;
36813
+ if (held.capturing === true) {
36814
+ await cdp.send("Page.stopScreencast").catch(() => {
36815
+ });
36816
+ held.capturing = false;
36817
+ this.announceControl(runId);
36818
+ }
36819
+ const drawn = this.nextFrame(held);
36820
+ if (!await this.applyCapture(runId, held, cdp, true, true)) {
36821
+ return {
36822
+ ok: false,
36823
+ detail: "The page could not be shown again, so nothing was done to it."
36824
+ };
36825
+ }
36826
+ if (!await drawn) {
36827
+ held.visibilityUnconfirmed = true;
36828
+ held.capturing = false;
36829
+ await cdp.send("Page.stopScreencast").catch(() => {
36830
+ });
36831
+ this.announceControl(runId);
36832
+ return {
36833
+ ok: false,
36834
+ detail: "The page did not come back on screen, so nothing was done to it."
36835
+ };
36836
+ }
36837
+ if (this.revoked.has(runId)) {
36838
+ await this.releaseIfIdle(runId, () => lease_.endAction(token));
36839
+ return { ok: false, detail: "The user stopped browser control for this run." };
36840
+ }
36841
+ if (context.signal?.aborted || held.abort.signal.aborted) {
36842
+ await this.releaseIfIdle(runId, () => lease_.endAction(token));
36843
+ return { ok: false, detail: "The run was cancelled." };
36844
+ }
36845
+ }
36846
+ return await this.perform(runId, held, action, recoveringClosedPage ? held.generation : planned);
35422
36847
  } catch (err) {
35423
36848
  return { ok: false, detail: err instanceof Error ? err.message : String(err) };
35424
36849
  } finally {
36850
+ if (temporaryCapture) {
36851
+ const { held, cdp, watchGen } = temporaryCapture;
36852
+ if (held.screencast === cdp && held.onFrame === void 0 && held.watchGen === watchGen && held.hiddenByHolder === false && held.visibilityUnconfirmed === false && held.capturing === true) {
36853
+ held.onFrame = void 0;
36854
+ held.screencast = void 0;
36855
+ held.screencastPage = void 0;
36856
+ held.capturing = true;
36857
+ this.announceControl(runId);
36858
+ await cdp.send("Page.stopScreencast").catch(() => {
36859
+ });
36860
+ await cdp.detach().catch(() => {
36861
+ });
36862
+ }
36863
+ }
35425
36864
  lease_.endAction(token);
35426
36865
  if (context.signal?.aborted || this.revoked.has(runId)) lease_.releaseIfHeldBy(actor);
35427
36866
  }
@@ -35437,22 +36876,46 @@ var RemoteBrowserController = class {
35437
36876
  * it out changed no test. Two copies of a cap invite them to disagree.
35438
36877
  */
35439
36878
  async open(runId, signal) {
36879
+ if (this.ready) {
36880
+ const settling = this.ready;
36881
+ try {
36882
+ await settling;
36883
+ } catch {
36884
+ }
36885
+ if (this.ready === settling) this.ready = void 0;
36886
+ }
35440
36887
  const existing = this.runs.get(runId);
35441
- if (existing && !existing.page.isClosed()) return existing;
36888
+ if (existing && !existing.page.isClosed()) {
36889
+ this.announceLiveView(runId, existing.session.liveViewUrl, true);
36890
+ return existing;
36891
+ }
36892
+ if (existing && existing.page.isClosed()) {
36893
+ const fallback = existing.page.context().pages().filter((p) => !p.isClosed()).at(-1);
36894
+ if (fallback) {
36895
+ await this.adoptPage(runId, existing, fallback);
36896
+ if (this.runs.get(runId) === existing && !existing.abort.signal.aborted) {
36897
+ this.announceLiveView(runId, existing.session.liveViewUrl, true);
36898
+ }
36899
+ return existing;
36900
+ }
36901
+ }
35442
36902
  if (existing) {
35443
36903
  this.runs.delete(runId);
35444
- this.closing.add(runId);
35445
36904
  await this.teardown(runId, existing);
35446
36905
  }
36906
+ if (this.retired) {
36907
+ throw new Error("The browser settings changed while this action was waiting. Try again.");
36908
+ }
35447
36909
  if (this.runs.size + this.opening.size + this.closing.size >= this.maxSessions) {
35448
36910
  throw new Error(
35449
36911
  `All ${this.maxSessions} browser session${this.maxSessions === 1 ? "" : "s"} are in use by other runs. Try again when one finishes, or raise the session limit in settings.`
35450
36912
  );
35451
36913
  }
35452
- this.opening.add(runId);
35453
36914
  if (!this.aborts.has(runId)) this.aborts.set(runId, new AbortController());
36915
+ const opening = this.openReserved(runId, signal);
36916
+ this.opening.set(runId, opening);
35454
36917
  try {
35455
- return await this.openReserved(runId, signal);
36918
+ return await opening;
35456
36919
  } finally {
35457
36920
  this.opening.delete(runId);
35458
36921
  }
@@ -35463,9 +36926,9 @@ var RemoteBrowserController = class {
35463
36926
  const abort = this.aborts.get(runId)?.signal;
35464
36927
  const creationSignal = signal && abort ? AbortSignal.any([signal, abort]) : signal ?? abort;
35465
36928
  const session = await this.provider.createSession(creationSignal);
35466
- this.announceLiveView(runId, session.liveViewUrl, true);
35467
36929
  let browser;
35468
36930
  let owned;
36931
+ let held;
35469
36932
  try {
35470
36933
  browser = await playwright.chromium.connectOverCDP(session.cdpUrl);
35471
36934
  owned = this.provider.isolatesSessions ? void 0 : await browser.newContext();
@@ -35473,25 +36936,85 @@ var RemoteBrowserController = class {
35473
36936
  const page2 = owned ? await owned.newPage() : context.pages()[0] ?? await context.newPage();
35474
36937
  const abort2 = this.aborts.get(runId);
35475
36938
  if (!abort2) throw new Error("The run ended while its browser was still opening.");
35476
- const held = { session, browser, page: page2, generation: 0, abort: abort2, ...owned ? { ownedContext: owned } : {} };
35477
- page2.on("framenavigated", ((frame) => {
35478
- if (frame !== page2.mainFrame()) return;
35479
- held.generation += 1;
35480
- }));
36939
+ held = { session, browser, page: page2, generation: 0, abort: abort2, ...owned ? { ownedContext: owned } : {} };
36940
+ this.trackPageNavigation(runId, held, page2);
35481
36941
  this.runs.set(runId, held);
35482
- return held;
35483
36942
  } catch (err) {
35484
- this.announceLiveView(runId, void 0, false);
35485
36943
  await owned?.close().catch(() => {
35486
36944
  });
35487
36945
  await browser?.close().catch(() => {
35488
36946
  });
35489
- await this.provider.endSession(session.id).catch(() => {
35490
- });
36947
+ await this.provider.endSession(session.id).catch((releaseErr) => this.reportReleaseFailure(runId, session.id, releaseErr, session.expiresInMs));
35491
36948
  throw err;
35492
36949
  }
36950
+ this.announceLiveView(runId, session.liveViewUrl, true);
36951
+ return held;
36952
+ }
36953
+ /** Count main-frame navigation only while this page is the run's active page. */
36954
+ trackPageNavigation(runId, held, page2) {
36955
+ page2.on("framenavigated", ((frame) => {
36956
+ if (held.page !== page2 || frame !== page2.mainFrame()) return;
36957
+ held.generation += 1;
36958
+ if (held.onFrame && held.watchGen !== void 0) {
36959
+ held.watchGen += 1;
36960
+ this.announceControl(runId);
36961
+ }
36962
+ }));
35493
36963
  }
35494
- async perform(held, action, planned) {
36964
+ /**
36965
+ * Follow a page opened by the action that just finished.
36966
+ *
36967
+ * A popup/new tab is part of the same user gesture (OAuth is the common
36968
+ * example). Keeping `held.page` and the screencast on its opener makes the
36969
+ * new page both invisible and impossible to drive. This runs while the SAME
36970
+ * action slot is still held, after the opening click/key has fully landed, so
36971
+ * no later human/agent event can slip between detecting the popup and moving
36972
+ * the view to it.
36973
+ */
36974
+ async followOpenedPage(runId, held, before) {
36975
+ if (this.runs.get(runId) !== held || held.abort.signal.aborted) return;
36976
+ const candidates = held.page.context().pages().filter((p) => !p.isClosed() && !before.has(p));
36977
+ const next = candidates.at(-1);
36978
+ if (!next || next === held.page) return;
36979
+ await this.adoptPage(runId, held, next);
36980
+ }
36981
+ /**
36982
+ * Make one live page the run's controlled/viewed page. Used in both
36983
+ * directions: into a popup opened by an action, and back to another surviving
36984
+ * page when that popup closes itself after OAuth/login completion.
36985
+ */
36986
+ async adoptPage(runId, held, next) {
36987
+ if (next === held.page || next.isClosed()) return;
36988
+ held.page = next;
36989
+ held.generation += 1;
36990
+ held.viewport = void 0;
36991
+ held.metricsStale = true;
36992
+ this.trackPageNavigation(runId, held, next);
36993
+ const deliver = held.onFrame;
36994
+ if (deliver) {
36995
+ held.watchGen = (held.watchGen ?? 0) + 1;
36996
+ held.visibilityUnconfirmed = true;
36997
+ held.capturing = false;
36998
+ this.announceControl(runId);
36999
+ await this.attachScreencast(runId, held, deliver, held.watchDetachGen ?? 0);
37000
+ return;
37001
+ }
37002
+ const pending = held.attaching;
37003
+ if (pending) await pending.catch(() => null);
37004
+ if (held.screencast && held.screencastPage !== next) {
37005
+ const stale = held.screencast;
37006
+ held.screencast = void 0;
37007
+ held.screencastPage = void 0;
37008
+ await stale.send("Page.stopScreencast").catch(() => {
37009
+ });
37010
+ await stale.detach().catch(() => {
37011
+ });
37012
+ }
37013
+ held.visibilityUnconfirmed = false;
37014
+ held.capturing = held.hiddenByHolder !== true;
37015
+ this.announceControl(runId);
37016
+ }
37017
+ async perform(runId, held, action, planned) {
35495
37018
  const { page: page2 } = held;
35496
37019
  const stoppable = async (work) => {
35497
37020
  if (held.abort.signal.aborted) throw new Error("The user stopped browser control for this run.");
@@ -35513,10 +37036,10 @@ var RemoteBrowserController = class {
35513
37036
  }
35514
37037
  };
35515
37038
  const timeout = Math.min(action.timeoutMs ?? 1e4, ACTION_TIMEOUT_MS);
35516
- const where = async () => ({
35517
- url: page2.url(),
35518
- title: await page2.title().catch(() => "")
35519
- });
37039
+ const where = async () => {
37040
+ const current = held.page;
37041
+ return { url: current.url(), title: await current.title().catch(() => "") };
37042
+ };
35520
37043
  if (action.kind !== "navigate" && held.generation !== planned) {
35521
37044
  return {
35522
37045
  ok: false,
@@ -35533,15 +37056,20 @@ var RemoteBrowserController = class {
35533
37056
  await stoppable(page2.goto(target, { timeout: ACTION_TIMEOUT_MS, waitUntil: "domcontentloaded" }));
35534
37057
  return { ok: true, detail: `Opened ${target}`, ...await where() };
35535
37058
  }
35536
- case "click":
37059
+ case "click": {
37060
+ const pagesBefore = new Set(page2.context().pages());
35537
37061
  await stoppable(page2.click(action.selector, { timeout }));
37062
+ await this.followOpenedPage(runId, held, pagesBefore);
35538
37063
  return { ok: true, detail: `Clicked ${action.selector}`, ...await where() };
37064
+ }
35539
37065
  case "fill":
35540
37066
  await stoppable(page2.fill(action.selector, action.value ?? "", { timeout }));
35541
37067
  return { ok: true, detail: `Filled ${action.selector}`, ...await where() };
35542
37068
  case "press": {
37069
+ const pagesBefore = new Set(page2.context().pages());
35543
37070
  if (action.selector) await stoppable(page2.press(action.selector, action.key, { timeout }));
35544
37071
  else await stoppable(page2.keyboard.press(action.key));
37072
+ await this.followOpenedPage(runId, held, pagesBefore);
35545
37073
  return { ok: true, detail: `Pressed ${action.key}`, ...await where() };
35546
37074
  }
35547
37075
  case "wait_for":
@@ -35557,10 +37085,25 @@ var RemoteBrowserController = class {
35557
37085
  }
35558
37086
  };
35559
37087
  function refusal(result) {
37088
+ if (result === "human") {
37089
+ return "The user has taken control of this browser. Stop using it and tell them what you were about to do.";
37090
+ }
35560
37091
  if (result === "off") return "Browser control was turned off while this action waited for the browser.";
35561
37092
  if (result === "cancelled") return "The run was cancelled while waiting for the browser.";
35562
37093
  return "The browser is in use by another part of this run and did not come free in time. Try again, or do something else first.";
35563
37094
  }
37095
+ function coordinate(n, what) {
37096
+ if (typeof n !== "number" || !Number.isFinite(n)) {
37097
+ throw new Error(`That ${what} is not a position on the page.`);
37098
+ }
37099
+ return Math.min(Math.max(n, 0), 1);
37100
+ }
37101
+ function scrollDelta(n) {
37102
+ if (typeof n !== "number" || !Number.isFinite(n)) {
37103
+ throw new Error("That scroll has no distance to travel.");
37104
+ }
37105
+ return Math.min(Math.max(n, -2e3), 2e3);
37106
+ }
35564
37107
  async function loadPlaywright() {
35565
37108
  try {
35566
37109
  return await import('playwright');
@@ -35611,6 +37154,139 @@ function isCdpEndpoint(url) {
35611
37154
 
35612
37155
  // src/browser/remote/steel.ts
35613
37156
  var DEFAULT_BASE = "https://api.steel.dev";
37157
+ function isHostedSteel(url) {
37158
+ if (!url) return true;
37159
+ try {
37160
+ return hostKey(new URL(url).hostname) === hostKey(new URL(DEFAULT_BASE).hostname);
37161
+ } catch {
37162
+ return false;
37163
+ }
37164
+ }
37165
+ function isUsableSteelBase(url) {
37166
+ try {
37167
+ const u = new URL(url);
37168
+ if (u.protocol !== "http:" && u.protocol !== "https:") return false;
37169
+ if (u.username !== "" || u.password !== "") return false;
37170
+ const built = new URL(withoutTrailingSlashes(url) + PROBE_PATH);
37171
+ if (FETCH_BLOCKED_PORTS.has(built.port)) return false;
37172
+ if (built.search !== "" || built.hash !== "") return false;
37173
+ if (!built.pathname.endsWith(PROBE_PATH)) return false;
37174
+ if (isHostedSteel(url)) {
37175
+ if (built.pathname !== PROBE_PATH) return false;
37176
+ if (u.protocol !== "https:") return false;
37177
+ if (built.port !== "") return false;
37178
+ }
37179
+ return true;
37180
+ } catch {
37181
+ return false;
37182
+ }
37183
+ }
37184
+ function isUsableSteelKey(apiKey) {
37185
+ for (const ch of apiKey) {
37186
+ const c = ch.codePointAt(0) ?? 0;
37187
+ if (c === 9) continue;
37188
+ if (c >= 32 && c <= 126) continue;
37189
+ if (c >= 128 && c <= 255) continue;
37190
+ return false;
37191
+ }
37192
+ return true;
37193
+ }
37194
+ var API_KEY_HEADER = "steel-api-key";
37195
+ var FETCH_BLOCKED_PORTS = /* @__PURE__ */ new Set([
37196
+ "1",
37197
+ "7",
37198
+ "9",
37199
+ "11",
37200
+ "13",
37201
+ "15",
37202
+ "17",
37203
+ "19",
37204
+ "20",
37205
+ "21",
37206
+ "22",
37207
+ "23",
37208
+ "25",
37209
+ "37",
37210
+ "42",
37211
+ "43",
37212
+ "53",
37213
+ "69",
37214
+ "77",
37215
+ "79",
37216
+ "87",
37217
+ "95",
37218
+ "101",
37219
+ "102",
37220
+ "103",
37221
+ "104",
37222
+ "109",
37223
+ "110",
37224
+ "111",
37225
+ "113",
37226
+ "115",
37227
+ "117",
37228
+ "119",
37229
+ "123",
37230
+ "135",
37231
+ "137",
37232
+ "139",
37233
+ "143",
37234
+ "161",
37235
+ "179",
37236
+ "389",
37237
+ "427",
37238
+ "465",
37239
+ "512",
37240
+ "513",
37241
+ "514",
37242
+ "515",
37243
+ "526",
37244
+ "530",
37245
+ "531",
37246
+ "532",
37247
+ "540",
37248
+ "548",
37249
+ "554",
37250
+ "556",
37251
+ "563",
37252
+ "587",
37253
+ "601",
37254
+ "636",
37255
+ "989",
37256
+ "990",
37257
+ "993",
37258
+ "995",
37259
+ "1719",
37260
+ "1720",
37261
+ "1723",
37262
+ "2049",
37263
+ "3659",
37264
+ "4045",
37265
+ "4190",
37266
+ "5060",
37267
+ "5061",
37268
+ "6000",
37269
+ "6566",
37270
+ "6665",
37271
+ "6666",
37272
+ "6667",
37273
+ "6668",
37274
+ "6669",
37275
+ "6679",
37276
+ "6697",
37277
+ "10080"
37278
+ ]);
37279
+ var PROBE_PATH = "/v1/sessions";
37280
+ function withoutTrailingSlashes(value) {
37281
+ let out = value;
37282
+ while (out.endsWith("/")) out = out.slice(0, -1);
37283
+ return out;
37284
+ }
37285
+ function hostKey(hostname) {
37286
+ let host = hostname.toLowerCase();
37287
+ while (host.endsWith(".")) host = host.slice(0, -1);
37288
+ return host;
37289
+ }
35614
37290
  var CREATE_TIMEOUT_MS = 6e4;
35615
37291
  var SteelProvider = class {
35616
37292
  name = "Steel";
@@ -35620,9 +37296,7 @@ var SteelProvider = class {
35620
37296
  base;
35621
37297
  apiKey;
35622
37298
  constructor(opts = {}) {
35623
- let base = opts.url || DEFAULT_BASE;
35624
- while (base.endsWith("/")) base = base.slice(0, -1);
35625
- this.base = base;
37299
+ this.base = withoutTrailingSlashes(opts.url || DEFAULT_BASE);
35626
37300
  this.apiKey = opts.apiKey;
35627
37301
  }
35628
37302
  async createSession(signal) {
@@ -35633,14 +37307,15 @@ var SteelProvider = class {
35633
37307
  return {
35634
37308
  id: details.id,
35635
37309
  cdpUrl: details.websocketUrl,
35636
- ...details.debugUrl ? { liveViewUrl: details.debugUrl } : {}
37310
+ ...details.debugUrl ? { liveViewUrl: details.debugUrl } : {},
37311
+ // Carried through because it explains an otherwise mysterious death. A
37312
+ // session nobody released dies at exactly this number, and without it a
37313
+ // leak looks identical to an orderly shutdown.
37314
+ ...typeof details.timeout === "number" ? { expiresInMs: details.timeout } : {}
35637
37315
  };
35638
37316
  }
35639
37317
  async endSession(id) {
35640
- try {
35641
- await this.call("POST", `/v1/sessions/${encodeURIComponent(id)}/release`, void 0, {});
35642
- } catch {
35643
- }
37318
+ await this.call("POST", `/v1/sessions/${encodeURIComponent(id)}/release`, void 0, {});
35644
37319
  }
35645
37320
  async call(method, path30, signal, body) {
35646
37321
  const timeout = AbortSignal.timeout(CREATE_TIMEOUT_MS);
@@ -35651,7 +37326,7 @@ var SteelProvider = class {
35651
37326
  "content-type": "application/json",
35652
37327
  // Sent only when configured — the self-hosted API takes no key, and an
35653
37328
  // empty header is worse than none.
35654
- ...this.apiKey ? { "steel-api-key": this.apiKey } : {}
37329
+ ...this.apiKey ? { [API_KEY_HEADER]: this.apiKey } : {}
35655
37330
  },
35656
37331
  body: JSON.stringify(body),
35657
37332
  signal: composed
@@ -36315,6 +37990,6 @@ function applySyncBundle(bundle, config, cleanup) {
36315
37990
  return next;
36316
37991
  }
36317
37992
 
36318
- export { AZURE_BASE_MODELS, AZURE_BASE_URL_TEMPLATE, AuditLogger, BrowserControlTool, BrowserLease, CASCADE_AUDIT_FILE, CASCADE_CONFIG_DIR, CASCADE_CONFIG_FILE, CASCADE_DASHBOARD_SECRET_FILE, CASCADE_DB_FILE, CASCADE_IGNORE_FILE, CASCADE_KEYSTORE_FILE, CASCADE_MD_FILE, CASCADE_VERSION, CHARS_PER_TOKEN2 as CHARS_PER_TOKEN, COMPLEXITY_T2_COUNT, Cascade, CascadeCancelledError, CascadeConfigSchema, CascadeIgnore, CascadeRouter, CascadeToolError, CloudClient, CodeSearchTool, ConfigManager, CurrentPageTool, DEFAULT_API_PORT, DEFAULT_APPROVAL_REQUIRED, DEFAULT_AUTO_SUMMARIZE_AT, DEFAULT_CLOUD_URL, DEFAULT_CONTEXT_LIMIT, DEFAULT_DASHBOARD_PORT, DEFAULT_MAX_SESSION_MESSAGES, DEFAULT_RETENTION_DAYS, DEFAULT_THEME, DOCUMENT_MIME, DashboardServer, DependencyScheduler, FileMcpOAuthStore, GLOBAL_CONFIG_DIR, GLOBAL_CREDENTIALS_FILE, GLOBAL_DB_FILE, GLOBAL_KEYSTORE_FILE, GLOBAL_RUNTIME_DB_FILE, GenerateDocumentTool, GenericCdpProvider, GraphRetriever, GraphSearchTool, HooksRunner, Keystore, LLMReranker, LM_STUDIO_BASE_URL, MAX_PAGE_TEXT_CHARS, MCP_TOOL_PREFIX, MODELS, McpClient, McpOAuthProvider, MemoryStore, OLLAMA_BASE_URL, OpenAICompatibleEmbedder, PROVIDER_DISPLAY_NAMES, RESUME_SCHEMA_VERSION, RemoteBrowserController, ResumeStore, Retriever, SqliteVectorStore, SteelProvider, T1Administrator, T1_MODEL_PRIORITY, T2Manager, T2_MODEL_PRIORITY, T3Worker, T3_MODEL_PRIORITY, THEME_NAMES, TOOL_NAMES, TaskGraphValidationError, TaskScheduler, Telemetry, ToolRegistry, VISION_MODEL_PRIORITY, WorkspaceIndex, applyEndpointEdit, applyProviderApiKey, applyProviderCredential, applySettingsCredentials, applySettingsPayload, applySyncBundle, azureModelForDeployment, beginMcpOAuth, buildDocumentTools, buildManifest, buildSessionTranscript, bytesToBase64, cagCharBudget, chartKind, chartToTableRows, chatCompleterFromProviders, chunkCode, chunkText2 as chunkText, commitSettings, compileSectionGraph, compileSubtaskGraph, compileTaskGraph, completeMcpOAuth, connectMcpWithLoopbackOAuth, createCascade, credentialDispositionForEdit, credentialEndpointIdentity, decryptJSON as decryptSyncBlob, diffManifest, disambiguateMcpServerNames, discoverMcpAuthServer, discoverMcpTools, distillSessionFacts, embedderFromProviders, encryptJSON as encryptSyncBlob, endpointFromSettingsPayload, evaluateAcceptance, explainRefusal, extractCharts, failures, fileExt, fileOAuthProvider, gatherSyncBundle, hasDefaultEndpoint, hasProviderCredential, hasUsableProvider, hashContent, heuristicCodeChunker, inferAzureBaseModel, inlineRuns, isCdpEndpoint, isDocumentFormat, isMcpToolName, matchImageLine, mcpServerPrefix, mcpToolName, nodeHttpFetch, normalizeEndpoint, parseBlocks, parseChartSpec, parseDelimited, parseRankOrder, parseSlide, planRetrieval, preferIpv4Host, priorAzureRow, reciprocalRankFusion, refreshMcpToken, removeMcpServerDenials, renderDocument, renderDocx, renderPptx, renderXlsx, runCascade, sameAzureEndpoint, sameCredentialEndpoint, sameEndpoint, sessionWorthRemembering, settingsSnapshot, sniffImage, splitSlides, streamCascade, stripInline, summarizeCompleted, undecided, uniqueMcpServerName };
37993
+ export { AZURE_BASE_MODELS, AZURE_BASE_URL_TEMPLATE, AskUserTool, AuditLogger, BrowserControlTool, BrowserLease, CASCADE_AUDIT_FILE, CASCADE_CONFIG_DIR, CASCADE_CONFIG_FILE, CASCADE_DASHBOARD_SECRET_FILE, CASCADE_DB_FILE, CASCADE_IGNORE_FILE, CASCADE_KEYSTORE_FILE, CASCADE_MD_FILE, CASCADE_VERSION, CHARS_PER_TOKEN2 as CHARS_PER_TOKEN, COMPLEXITY_T2_COUNT, Cascade, CascadeCancelledError, CascadeConfigSchema, CascadeIgnore, CascadeRouter, CascadeToolError, CloudClient, CodeSearchTool, ConfigManager, CurrentPageTool, DEFAULT_API_PORT, DEFAULT_APPROVAL_REQUIRED, DEFAULT_AUTO_SUMMARIZE_AT, DEFAULT_CLOUD_URL, DEFAULT_CONTEXT_LIMIT, DEFAULT_DASHBOARD_PORT, DEFAULT_MAX_SESSION_MESSAGES, DEFAULT_RETENTION_DAYS, DEFAULT_THEME, DOCUMENT_MIME, DashboardServer, DependencyScheduler, FileMcpOAuthStore, GLOBAL_CONFIG_DIR, GLOBAL_CREDENTIALS_FILE, GLOBAL_DB_FILE, GLOBAL_KEYSTORE_FILE, GLOBAL_RUNTIME_DB_FILE, GenerateDocumentTool, GenericCdpProvider, GraphRetriever, GraphSearchTool, HooksRunner, Keystore, LLMReranker, LM_STUDIO_BASE_URL, MAX_PAGE_TEXT_CHARS, MCP_TOOL_PREFIX, MODELS, McpClient, McpOAuthProvider, MemoryStore, OLLAMA_BASE_URL, OpenAICompatibleEmbedder, PROVIDER_DISPLAY_NAMES, RESUME_SCHEMA_VERSION, RemoteBrowserController, ResumeStore, Retriever, SqliteVectorStore, SteelProvider, T1Administrator, T1_MODEL_PRIORITY, T2Manager, T2_MODEL_PRIORITY, T3Worker, T3_MODEL_PRIORITY, THEME_NAMES, TOOL_NAMES, TaskGraphValidationError, TaskScheduler, Telemetry, ToolRegistry, VISION_MODEL_PRIORITY, WorkspaceIndex, applyEndpointEdit, applyProviderApiKey, applyProviderCredential, applySettingsCredentials, applySettingsPayload, applySyncBundle, azureModelForDeployment, beginMcpOAuth, buildDocumentTools, buildManifest, buildSessionTranscript, bytesToBase64, cagCharBudget, chartKind, chartToTableRows, chatCompleterFromProviders, chunkCode, chunkText2 as chunkText, commitSettings, compileSectionGraph, compileSubtaskGraph, compileTaskGraph, completeMcpOAuth, connectMcpWithLoopbackOAuth, createCascade, credentialDispositionForEdit, credentialEndpointIdentity, decryptJSON as decryptSyncBlob, diffManifest, disambiguateMcpServerNames, discoverMcpAuthServer, discoverMcpTools, distillSessionFacts, embedderFromProviders, encryptJSON as encryptSyncBlob, endpointFromSettingsPayload, evaluateAcceptance, explainRefusal, extractCharts, failures, fileExt, fileOAuthProvider, gatherSyncBundle, hasDefaultEndpoint, hasProviderCredential, hasUsableProvider, hashContent, heuristicCodeChunker, inferAzureBaseModel, inlineRuns, isCdpEndpoint, isDocumentFormat, isHostedSteel, isMcpToolName, isUsableSteelBase, isUsableSteelKey, matchImageLine, mcpServerPrefix, mcpToolName, nodeHttpFetch, normalizeEndpoint, parseBlocks, parseChartSpec, parseDelimited, parseRankOrder, parseSlide, planRetrieval, preferIpv4Host, priorAzureRow, reciprocalRankFusion, refreshMcpToken, removeMcpServerDenials, renderDocument, renderDocx, renderPptx, renderXlsx, runCascade, sameAzureEndpoint, sameCredentialEndpoint, sameEndpoint, sessionWorthRemembering, settingsSnapshot, sniffImage, splitSlides, streamCascade, stripInline, summarizeCompleted, undecided, uniqueMcpServerName };
36319
37994
  //# sourceMappingURL=index.js.map
36320
37995
  //# sourceMappingURL=index.js.map