cascade-ai 0.78.0 → 0.79.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.cjs CHANGED
@@ -11669,7 +11669,7 @@ function reconcilePrice(model, live) {
11669
11669
  }
11670
11670
 
11671
11671
  // src/constants.ts
11672
- var CASCADE_VERSION = "0.78.0";
11672
+ var CASCADE_VERSION = "0.79.0";
11673
11673
  var CASCADE_CONFIG_DIR = ".cascade";
11674
11674
  var CASCADE_MD_FILE = "CASCADE.md";
11675
11675
  var CASCADE_IGNORE_FILE = ".cascadeignore";
@@ -16144,6 +16144,31 @@ var ToolsConfigSchema = zod.z.object({
16144
16144
  * stop control for the run that is acting.
16145
16145
  */
16146
16146
  agentBrowserControl: zod.z.boolean().default(false),
16147
+ /**
16148
+ * Where a HOSTED run gets a browser, since it has none of its own.
16149
+ *
16150
+ * The desktop drives the Chromium the user is signed into and can watch. A
16151
+ * server has neither, and running one inside the container is wrong twice
16152
+ * over — page JavaScript issues requests no URL check ever sees, from inside
16153
+ * the trust boundary, and a session costs 200-400 MB. So this points at a
16154
+ * browser somebody else runs.
16155
+ *
16156
+ * Absent by default: no provider, no capability. There is nothing to turn
16157
+ * off because nothing is registered until an endpoint is supplied.
16158
+ */
16159
+ remoteBrowser: zod.z.object({
16160
+ /** `cdp` for an endpoint you run; `steel` for a Steel deployment. */
16161
+ provider: zod.z.enum(["cdp", "steel"]).optional(),
16162
+ /** The websocket endpoint for `cdp`, or the API base for `steel`. */
16163
+ url: zod.z.string().optional(),
16164
+ apiKey: zod.z.string().optional(),
16165
+ /**
16166
+ * Concurrent sessions. One by default and deliberately so: every session
16167
+ * is billed, and a wave of workers each opening their own is a cost the
16168
+ * user did not choose. Raising it is a decision, not a default.
16169
+ */
16170
+ maxSessions: zod.z.number().int().min(1).max(16).default(1)
16171
+ }).optional(),
16147
16172
  mcpServers: zod.z.array(McpServerConfigSchema).optional(),
16148
16173
  mcpTrusted: zod.z.array(zod.z.string()).optional(),
16149
16174
  /** Web search backends — at least one should be configured for best results */
@@ -31412,8 +31437,38 @@ ${input}` }],
31412
31437
  * run — it is simply not there.
31413
31438
  */
31414
31439
  setBrowserController(controller, release) {
31440
+ this.registerBrowserControl(controller, release, this.config.tools?.agentBrowserControl === true);
31441
+ }
31442
+ /**
31443
+ * Wire a REMOTE browser — one the host connects to rather than one the user
31444
+ * is signed into.
31445
+ *
31446
+ * A separate entry point because the enablement is a different question, and
31447
+ * conflating them made the hosted capability dead on arrival: this went out
31448
+ * calling `setBrowserController`, which gates on `agentBrowserControl`, and
31449
+ * that flag means "drive the browser I am signed into on this machine". It
31450
+ * defaults to false and has no meaning on a server, so the hosted tool was
31451
+ * never registered at all — the feature looked shipped and did nothing.
31452
+ *
31453
+ * Configuring a provider IS the opt-in here. It takes a deliberate act with
31454
+ * an endpoint and usually a paid account, and the browser it reaches is a
31455
+ * throwaway signed into nothing — a smaller consent than handing over the
31456
+ * session the user is already authenticated in, and one the desktop flag
31457
+ * cannot stand in for.
31458
+ */
31459
+ setRemoteBrowserController(controller, release) {
31460
+ this.registerBrowserControl(controller, release, Boolean(this.config.tools?.remoteBrowser?.provider));
31461
+ }
31462
+ /**
31463
+ * The gates every surface shares, with only enablement differing.
31464
+ *
31465
+ * One place, because the two callers above are exactly the sibling-writer
31466
+ * shape that has already drifted twice in this feature: a rule added to one
31467
+ * and not the other is silent on the surface that missed it.
31468
+ */
31469
+ registerBrowserControl(controller, release, enabled) {
31415
31470
  if (this.unattended) return;
31416
- if (!this.config.tools?.agentBrowserControl) return;
31471
+ if (!enabled) return;
31417
31472
  if ((this.config.tools?.disabledTools ?? []).includes("browser_control")) return;
31418
31473
  this.toolRegistry.register(new BrowserControlTool(controller, release));
31419
31474
  }
@@ -32758,6 +32813,20 @@ function applySettingsPayload(config, data) {
32758
32813
  if (data.webSearch.tavilyApiKey) next.tavilyApiKey = data.webSearch.tavilyApiKey;
32759
32814
  config.tools.webSearch = next;
32760
32815
  }
32816
+ if (data.remoteBrowser && typeof data.remoteBrowser === "object") {
32817
+ const prior = config.tools.remoteBrowser ?? {};
32818
+ const next = { ...prior };
32819
+ if (data.remoteBrowser.provider === "cdp" || data.remoteBrowser.provider === "steel") {
32820
+ next.provider = data.remoteBrowser.provider;
32821
+ }
32822
+ if (typeof data.remoteBrowser.url === "string") next.url = data.remoteBrowser.url.trim() || void 0;
32823
+ if (data.remoteBrowser.apiKey) next.apiKey = data.remoteBrowser.apiKey;
32824
+ const n = data.remoteBrowser.maxSessions;
32825
+ if (typeof n === "number" && Number.isFinite(n)) {
32826
+ next.maxSessions = Math.min(Math.max(Math.floor(n), 1), 16);
32827
+ }
32828
+ config.tools.remoteBrowser = next;
32829
+ }
32761
32830
  if (data.advanced && typeof data.advanced === "object") {
32762
32831
  const a = data.advanced;
32763
32832
  const num = (v, min, max) => {
@@ -32804,6 +32873,7 @@ function settingsSnapshot(config) {
32804
32873
  if (p?.type && p?.baseUrl && p.type !== "azure") endpoints[p.type] = p.baseUrl;
32805
32874
  }
32806
32875
  const ws = config.tools?.webSearch ?? {};
32876
+ const rb = config.tools?.remoteBrowser ?? {};
32807
32877
  return {
32808
32878
  models: config.models ?? {},
32809
32879
  budget: {
@@ -32833,6 +32903,15 @@ function settingsSnapshot(config) {
32833
32903
  hasBraveKey: typeof ws.braveApiKey === "string" && ws.braveApiKey.length > 0,
32834
32904
  hasTavilyKey: typeof ws.tavilyApiKey === "string" && ws.tavilyApiKey.length > 0
32835
32905
  },
32906
+ // `hasApiKey`, never the key. The panel needs to show whether one is set;
32907
+ // sending the value back would put a live credential in every settings
32908
+ // response, where it reaches any client that can read them.
32909
+ remoteBrowser: {
32910
+ provider: rb.provider,
32911
+ url: rb.url,
32912
+ hasApiKey: typeof rb.apiKey === "string" && rb.apiKey.length > 0,
32913
+ maxSessions: rb.maxSessions
32914
+ },
32836
32915
  advanced: {
32837
32916
  autonomy: config.autonomy,
32838
32917
  planApproval: config.planApproval,
@@ -34943,6 +35022,694 @@ async function discoverMcpTools(servers) {
34943
35022
  return results;
34944
35023
  }
34945
35024
 
35025
+ // src/browser/lease.ts
35026
+ var LEASE_DEADLOCK_CEILING_MS = 3e5;
35027
+ var QUEUE_WAIT_MS = 18e4;
35028
+ var MAX_QUEUED = 8;
35029
+ var ACTION_HANDOFF_MS = 2e3;
35030
+ var ACTION_HANDOFF_POLL_MS = 25;
35031
+ var BrowserLease = class {
35032
+ actor = null;
35033
+ session = null;
35034
+ ceilingTimer = null;
35035
+ waiting = [];
35036
+ lifecycleWired = false;
35037
+ /**
35038
+ * The action holding the browser, if any.
35039
+ *
35040
+ * Needed alongside the lease for a reason the lease cannot cover: the lease
35041
+ * is RE-ENTRANT for its holder — that is what makes a sequence a sequence —
35042
+ * so nothing in it stops ONE actor running two actions at once. A retry
35043
+ * racing the call it retried is exactly that shape.
35044
+ *
35045
+ * A symbol because it identifies the individual call: only the action that
35046
+ * took the slot may release it.
35047
+ */
35048
+ action = null;
35049
+ isRevoked;
35050
+ onChange;
35051
+ constructor(options = {}) {
35052
+ this.isRevoked = options.isRevoked ?? (() => false);
35053
+ this.onChange = options.onChange ?? (() => {
35054
+ });
35055
+ }
35056
+ get holderActor() {
35057
+ return this.actor;
35058
+ }
35059
+ get holderSession() {
35060
+ return this.session;
35061
+ }
35062
+ get queueDepth() {
35063
+ return this.waiting.length;
35064
+ }
35065
+ get actionInFlight() {
35066
+ return this.action !== null;
35067
+ }
35068
+ /**
35069
+ * Declare that this host reports worker terminal states.
35070
+ *
35071
+ * When it does, timers stop being ownership boundaries entirely. When it does
35072
+ * not — an embedder that wired a controller but not the release — the
35073
+ * fallbacks stay, because something has to break a deadlock.
35074
+ */
35075
+ setLifecycleReleaseWired(on) {
35076
+ this.lifecycleWired = on;
35077
+ }
35078
+ /**
35079
+ * Take the browser for this actor, waiting in line if someone else holds it.
35080
+ *
35081
+ * Re-entrant for the actor that already holds it: that is the sequence case —
35082
+ * the same worker coming back for its next step must not queue behind itself.
35083
+ */
35084
+ async acquire(actorId, sessionId, signal) {
35085
+ if (this.actor === null || this.actor === actorId) {
35086
+ this.actor = actorId;
35087
+ this.session = sessionId;
35088
+ this.armCeiling();
35089
+ return "granted";
35090
+ }
35091
+ if (this.waiting.length >= MAX_QUEUED) return "busy";
35092
+ return this.enqueue(actorId, sessionId, signal);
35093
+ }
35094
+ /**
35095
+ * One worker has finished its whole sequence, so its hold ends.
35096
+ *
35097
+ * THIS is the semantic release. It comes from the worker's own terminal path,
35098
+ * so it means "this actor will never ask again" — which a timer can never
35099
+ * mean about a worker that is merely thinking.
35100
+ *
35101
+ * Idempotent, and safe for an actor that never touched the browser.
35102
+ */
35103
+ actorEnded(actorId) {
35104
+ if (!actorId) return;
35105
+ for (let i = this.waiting.length - 1; i >= 0; i--) {
35106
+ const w = this.waiting[i];
35107
+ if (w.actorId === actorId) w.settle("cancelled");
35108
+ }
35109
+ this.releaseIfHeldBy(actorId);
35110
+ this.onChange();
35111
+ }
35112
+ /**
35113
+ * Give the browser up when about to return without using it.
35114
+ *
35115
+ * Two guards, both load-bearing. Never while an action is in flight, because
35116
+ * the lease is RE-ENTRANT: the action still running may be this same actor's
35117
+ * previous step, and taking the lease off it hands the page to a queued
35118
+ * worker mid-sequence. And only while still the holder, because by the time a
35119
+ * refusal path runs a Stop may already have handed the lease on.
35120
+ */
35121
+ releaseIfHeldBy(actorId) {
35122
+ if (this.action) return;
35123
+ if (this.actor === actorId) this.release();
35124
+ }
35125
+ /** Drop every queued waiter belonging to a run, and the lease if it holds it. */
35126
+ dropRun(sessionId) {
35127
+ for (let i = this.waiting.length - 1; i >= 0; i--) {
35128
+ const w = this.waiting[i];
35129
+ if (w.sessionId === sessionId) w.settle("cancelled");
35130
+ }
35131
+ if (this.session === sessionId) this.release();
35132
+ }
35133
+ /** Turn everyone away — the capability itself has gone. */
35134
+ dropAll() {
35135
+ for (let i = this.waiting.length - 1; i >= 0; i--) this.waiting[i].settle("off");
35136
+ }
35137
+ /** Hand the browser to the next actor in line, if any. */
35138
+ release() {
35139
+ this.clearCeiling();
35140
+ this.actor = null;
35141
+ this.session = null;
35142
+ let next = this.waiting.shift();
35143
+ while (next && this.isRevoked(next.sessionId)) {
35144
+ next.settle("cancelled");
35145
+ next = this.waiting.shift();
35146
+ }
35147
+ if (next) {
35148
+ this.actor = next.actorId;
35149
+ this.session = next.sessionId;
35150
+ this.armCeiling();
35151
+ next.settle("granted");
35152
+ }
35153
+ this.onChange();
35154
+ }
35155
+ /** Arm the deadlock ceiling. Not a release schedule — see the constant. */
35156
+ armCeiling() {
35157
+ this.clearCeiling();
35158
+ if (this.lifecycleWired) return;
35159
+ this.ceilingTimer = setTimeout(() => this.release(), LEASE_DEADLOCK_CEILING_MS);
35160
+ this.ceilingTimer.unref?.();
35161
+ }
35162
+ clearCeiling() {
35163
+ if (this.ceilingTimer) {
35164
+ clearTimeout(this.ceilingTimer);
35165
+ this.ceilingTimer = null;
35166
+ }
35167
+ }
35168
+ /** Take the per-action slot, or null when one is already running. */
35169
+ beginAction() {
35170
+ if (this.action) return null;
35171
+ const token = /* @__PURE__ */ Symbol("browser-action");
35172
+ this.action = token;
35173
+ return token;
35174
+ }
35175
+ /** Release the slot, but only for the action that took it. */
35176
+ endAction(token) {
35177
+ if (this.action !== token) return false;
35178
+ this.action = null;
35179
+ return true;
35180
+ }
35181
+ /**
35182
+ * Wait, briefly, for an outgoing action to unwind.
35183
+ *
35184
+ * A release can hand the browser on while the previous holder's abort is
35185
+ * still propagating through an awaited navigation. That is a handoff, not a
35186
+ * conflict, so it is waited out rather than refused — but bounded, because a
35187
+ * wedged action must not pin the queue.
35188
+ */
35189
+ async awaitActionSlot() {
35190
+ for (let waited = 0; waited < ACTION_HANDOFF_MS; waited += ACTION_HANDOFF_POLL_MS) {
35191
+ if (!this.action) return true;
35192
+ await new Promise((r) => setTimeout(r, ACTION_HANDOFF_POLL_MS));
35193
+ }
35194
+ return this.action === null;
35195
+ }
35196
+ /**
35197
+ * Queue one actor, resolving when it gets the browser or is turned away.
35198
+ *
35199
+ * `settle` is wrapped so it runs at most once and always takes the waiter out
35200
+ * of the line: the timeout, an abort and a handoff all race, and settling
35201
+ * twice would silently leave a dead entry holding a queue slot.
35202
+ */
35203
+ enqueue(actorId, sessionId, signal) {
35204
+ return new Promise((resolve2) => {
35205
+ let done = false;
35206
+ const waiter = {
35207
+ actorId,
35208
+ sessionId,
35209
+ settle: (result) => {
35210
+ if (done) return;
35211
+ done = true;
35212
+ clearTimeout(timer);
35213
+ signal?.removeEventListener("abort", giveUp);
35214
+ const i = this.waiting.indexOf(waiter);
35215
+ if (i >= 0) this.waiting.splice(i, 1);
35216
+ resolve2(result);
35217
+ }
35218
+ };
35219
+ const timer = this.lifecycleWired ? void 0 : setTimeout(() => waiter.settle("busy"), QUEUE_WAIT_MS);
35220
+ timer?.unref?.();
35221
+ const giveUp = () => waiter.settle("cancelled");
35222
+ signal?.addEventListener("abort", giveUp, { once: true });
35223
+ this.waiting.push(waiter);
35224
+ });
35225
+ }
35226
+ };
35227
+
35228
+ // src/browser/remote/controller.ts
35229
+ var ACTION_TIMEOUT_MS = 3e4;
35230
+ var RemoteBrowserController = class {
35231
+ provider;
35232
+ maxSessions;
35233
+ /**
35234
+ * Live-view listeners, one per run.
35235
+ *
35236
+ * A single callback was fine while each run had its own controller. Now the
35237
+ * controller is shared across a deployment, so one callback would send run
35238
+ * A's live-view URL to whichever run registered last — and that URL is a
35239
+ * bearer capability for a browser somebody else is driving.
35240
+ */
35241
+ liveViewListeners = /* @__PURE__ */ new Map();
35242
+ /** An embedder that wants every run's live view, told which run each is. */
35243
+ onLiveViewAll;
35244
+ runs = /* @__PURE__ */ new Map();
35245
+ /**
35246
+ * Runs that have a pool slot but no browser yet.
35247
+ *
35248
+ * Counted alongside `runs` against the cap. Without it the limit was a
35249
+ * check-then-act across four awaits, and simultaneous first uses both won.
35250
+ */
35251
+ opening = /* @__PURE__ */ new Set();
35252
+ /**
35253
+ * A run's stop signal, created when its slot is reserved.
35254
+ *
35255
+ * Before this, Stop looked only in `runs` — so during the first `open()`,
35256
+ * while the run existed only in `opening` and four awaits were in flight, it
35257
+ * found nothing and returned. The open then completed, built a FRESH
35258
+ * unaborted controller, and the click the user had stopped went ahead. The
35259
+ * signal has to exist before the browser does.
35260
+ */
35261
+ aborts = /* @__PURE__ */ new Map();
35262
+ /**
35263
+ * Runs whose provider session is being released right now.
35264
+ *
35265
+ * `stopRun`, `endRun`, `releaseIfIdle`, and the stale-page branch of `open`
35266
+ * all delete a run from `runs` synchronously and only THEN await
35267
+ * `disposeRun` settling — the browser disconnect, and `provider.endSession`,
35268
+ * which for Steel is a real HTTP `/release` call. Between that delete and
35269
+ * the call actually finishing, the admission check in `open()` — which
35270
+ * counts only `runs` and `opening` — saw the slot as free, so a second run
35271
+ * could pass admission and call `createSession` before the first run's
35272
+ * session was truly released. At `maxSessions: 1` that is two live, BILLED
35273
+ * provider sessions at once, exactly what the pool exists to prevent.
35274
+ * Counting this set alongside the other two closes the window.
35275
+ *
35276
+ * Keyed by run id, not a counter: every one of those four call sites checks
35277
+ * the run is still IN `runs` before deleting it and starting teardown, and
35278
+ * that delete is synchronous, so at most one teardown can ever be in flight
35279
+ * for a given run id at a time — a second caller finds the entry already
35280
+ * gone and never starts a competing one. The entry is removed only once its
35281
+ * own teardown settles, so a later, genuine re-open of the same run id
35282
+ * never collides with one still in flight.
35283
+ */
35284
+ closing = /* @__PURE__ */ new Set();
35285
+ /** Runs the user has stopped, by run id — same meaning as on the desktop. */
35286
+ revoked = /* @__PURE__ */ new Set();
35287
+ /**
35288
+ * One lease PER RUN, because there is one browser per run.
35289
+ *
35290
+ * The desktop has a single lease because it has a single browser. Here each
35291
+ * run gets its own session, so a global lease would make run B queue behind
35292
+ * run A for a browser it was never going to use — and with no queue timeout,
35293
+ * queue for as long as A lasts. What limits runs against each other is the
35294
+ * session POOL, not the lease.
35295
+ */
35296
+ leases = /* @__PURE__ */ new Map();
35297
+ constructor(options) {
35298
+ this.provider = options.provider;
35299
+ const asked = Math.max(1, options.maxSessions ?? 1);
35300
+ this.maxSessions = options.provider.isolatesSessions ? asked : 1;
35301
+ this.onLiveViewAll = options.onLiveView;
35302
+ }
35303
+ leaseFor(runId) {
35304
+ let lease = this.leases.get(runId);
35305
+ if (!lease) {
35306
+ lease = new BrowserLease({ isRevoked: (id) => this.revoked.has(id) });
35307
+ lease.setLifecycleReleaseWired(true);
35308
+ this.leases.set(runId, lease);
35309
+ }
35310
+ return lease;
35311
+ }
35312
+ /** The controller to hand to `Cascade.setBrowserController`. */
35313
+ get controller() {
35314
+ return (action, context) => this.act(action, context);
35315
+ }
35316
+ /** Watch one run's browser. The URL never goes to any other run's listener. */
35317
+ onLiveViewFor(runKey, listener) {
35318
+ this.liveViewListeners.set(runKey, listener);
35319
+ }
35320
+ offLiveViewFor(runKey) {
35321
+ this.liveViewListeners.delete(runKey);
35322
+ }
35323
+ /**
35324
+ * Tell a run's listener what its browser situation is.
35325
+ *
35326
+ * `active` is separate from the URL and both are needed: a provider with no
35327
+ * live view is attached-but-unwatchable, and a finished run is not attached
35328
+ * at all. Both have no URL, so a listener given only the URL cannot tell them
35329
+ * apart — and would drop the Stop control for the first as if it were the
35330
+ * second.
35331
+ */
35332
+ announceLiveView(runId, liveViewUrl, active) {
35333
+ this.liveViewListeners.get(runId)?.({ active, ...liveViewUrl ? { liveViewUrl } : {} });
35334
+ this.onLiveViewAll?.(runId, liveViewUrl);
35335
+ }
35336
+ /**
35337
+ * Hand back a session the run turned out not to want.
35338
+ *
35339
+ * A browser opened for an action that is then refused would otherwise stay
35340
+ * allocated and billed until the whole run ended, for a run that has just
35341
+ * been stopped.
35342
+ */
35343
+ async releaseIfIdle(runId) {
35344
+ const held = this.runs.get(runId);
35345
+ if (!held) return;
35346
+ this.runs.delete(runId);
35347
+ this.closing.add(runId);
35348
+ await this.teardown(runId, held);
35349
+ }
35350
+ /** Release every run's session. For when the deployment's config changes. */
35351
+ async dispose() {
35352
+ const ids = /* @__PURE__ */ new Set([...this.runs.keys(), ...this.opening]);
35353
+ await Promise.all([...ids].map((runId) => this.endRun(runId)));
35354
+ }
35355
+ /** A worker finished; it will never ask for the browser again. */
35356
+ actorEnded(actorId) {
35357
+ for (const lease of this.leases.values()) lease.actorEnded(actorId);
35358
+ }
35359
+ /** The user stopped this run. Refuses further actions and clears its queue. */
35360
+ stopRun(runId) {
35361
+ this.revoked.add(runId);
35362
+ this.leases.get(runId)?.dropRun(runId);
35363
+ this.aborts.get(runId)?.abort();
35364
+ const held = this.runs.get(runId);
35365
+ if (!held) return;
35366
+ this.runs.delete(runId);
35367
+ this.closing.add(runId);
35368
+ void this.teardown(runId, held);
35369
+ }
35370
+ /** A run ended: release its browser rather than pay for an idle session. */
35371
+ async endRun(runId) {
35372
+ this.leases.get(runId)?.dropRun(runId);
35373
+ this.aborts.get(runId)?.abort();
35374
+ const held = this.runs.get(runId);
35375
+ if (!held) {
35376
+ this.forgetRun(runId);
35377
+ return;
35378
+ }
35379
+ this.runs.delete(runId);
35380
+ this.closing.add(runId);
35381
+ await this.teardown(runId, held);
35382
+ this.forgetRun(runId);
35383
+ }
35384
+ /** Forget a finished run entirely, so nothing accumulates per run. */
35385
+ forgetRun(runId) {
35386
+ this.revoked.delete(runId);
35387
+ this.leases.delete(runId);
35388
+ this.aborts.delete(runId);
35389
+ this.liveViewListeners.delete(runId);
35390
+ }
35391
+ /**
35392
+ * Let go of one run's browser.
35393
+ *
35394
+ * Best-effort throughout: a run is already over by the time this runs, and a
35395
+ * provider that is briefly unreachable must not turn that into a failure the
35396
+ * user sees. The provider's own idle timeout collects anything left.
35397
+ */
35398
+ async disposeRun(runId, held) {
35399
+ held.abort.abort();
35400
+ this.announceLiveView(runId, void 0, false);
35401
+ await held.ownedContext?.close().catch(() => {
35402
+ });
35403
+ await held.browser.close().catch(() => {
35404
+ });
35405
+ await this.provider.endSession(held.session.id).catch(() => {
35406
+ });
35407
+ }
35408
+ /**
35409
+ * Run `disposeRun`, with the run id counted in `closing` until it settles.
35410
+ *
35411
+ * The caller adds the id to `closing` itself, synchronously, in the same
35412
+ * breath as deleting the run from `runs` — see the field comment. This just
35413
+ * guarantees the removal happens, success or failure, so a disposal that
35414
+ * throws cannot leave the slot counted against the pool forever.
35415
+ */
35416
+ async teardown(runId, held) {
35417
+ try {
35418
+ await this.disposeRun(runId, held);
35419
+ } finally {
35420
+ this.closing.delete(runId);
35421
+ }
35422
+ }
35423
+ async act(action, context) {
35424
+ const runId = context.sessionId;
35425
+ if (!runId) {
35426
+ return { ok: false, detail: "This browser action arrived without a run identity, so it was not run." };
35427
+ }
35428
+ const actor = context.actorId || runId;
35429
+ if (this.revoked.has(runId)) {
35430
+ return { ok: false, detail: "The user stopped browser control for this run." };
35431
+ }
35432
+ if (context.signal?.aborted) {
35433
+ return { ok: false, detail: "The run was cancelled." };
35434
+ }
35435
+ const planned = this.runs.get(runId)?.generation ?? 0;
35436
+ const lease_ = this.leaseFor(runId);
35437
+ const lease = await lease_.acquire(actor, runId, context.signal);
35438
+ if (lease !== "granted") {
35439
+ return { ok: false, detail: refusal(lease) };
35440
+ }
35441
+ if (this.revoked.has(runId)) {
35442
+ lease_.releaseIfHeldBy(actor);
35443
+ return { ok: false, detail: "The user stopped browser control for this run." };
35444
+ }
35445
+ if (context.signal?.aborted) {
35446
+ lease_.releaseIfHeldBy(actor);
35447
+ return { ok: false, detail: "The run was cancelled." };
35448
+ }
35449
+ if (!await lease_.awaitActionSlot()) {
35450
+ lease_.releaseIfHeldBy(actor);
35451
+ return { ok: false, detail: "Another browser action is still finishing. Try again." };
35452
+ }
35453
+ const token = lease_.beginAction();
35454
+ if (!token) {
35455
+ return { ok: false, detail: "Another browser action is already running. Wait for it to finish." };
35456
+ }
35457
+ try {
35458
+ const held = await this.open(runId, context.signal);
35459
+ if (this.revoked.has(runId)) {
35460
+ await this.releaseIfIdle(runId);
35461
+ return { ok: false, detail: "The user stopped browser control for this run." };
35462
+ }
35463
+ if (context.signal?.aborted || held.abort.signal.aborted) {
35464
+ await this.releaseIfIdle(runId);
35465
+ return { ok: false, detail: "The run was cancelled." };
35466
+ }
35467
+ return await this.perform(held, action, planned);
35468
+ } catch (err) {
35469
+ return { ok: false, detail: err instanceof Error ? err.message : String(err) };
35470
+ } finally {
35471
+ lease_.endAction(token);
35472
+ if (context.signal?.aborted || this.revoked.has(runId)) lease_.releaseIfHeldBy(actor);
35473
+ }
35474
+ }
35475
+ /**
35476
+ * The run's browser, opened on first use.
35477
+ *
35478
+ * The ONE place the session cap is enforced. An earlier version also checked
35479
+ * it before taking the lease, on the reasoning that a run which cannot get a
35480
+ * session would otherwise queue forever — true when every run shared one
35481
+ * lease, and false once each run got its own, because a second run no longer
35482
+ * queues behind the first at all. Its own revert-check proved it dead: taking
35483
+ * it out changed no test. Two copies of a cap invite them to disagree.
35484
+ */
35485
+ async open(runId, signal) {
35486
+ const existing = this.runs.get(runId);
35487
+ if (existing && !existing.page.isClosed()) return existing;
35488
+ if (existing) {
35489
+ this.runs.delete(runId);
35490
+ this.closing.add(runId);
35491
+ await this.teardown(runId, existing);
35492
+ }
35493
+ if (this.runs.size + this.opening.size + this.closing.size >= this.maxSessions) {
35494
+ throw new Error(
35495
+ `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.`
35496
+ );
35497
+ }
35498
+ this.opening.add(runId);
35499
+ if (!this.aborts.has(runId)) this.aborts.set(runId, new AbortController());
35500
+ try {
35501
+ return await this.openReserved(runId, signal);
35502
+ } finally {
35503
+ this.opening.delete(runId);
35504
+ }
35505
+ }
35506
+ /** The part that may fail, with the pool slot already reserved. */
35507
+ async openReserved(runId, signal) {
35508
+ const playwright = await loadPlaywright();
35509
+ const abort = this.aborts.get(runId)?.signal;
35510
+ const creationSignal = signal && abort ? AbortSignal.any([signal, abort]) : signal ?? abort;
35511
+ const session = await this.provider.createSession(creationSignal);
35512
+ this.announceLiveView(runId, session.liveViewUrl, true);
35513
+ let browser;
35514
+ let owned;
35515
+ try {
35516
+ browser = await playwright.chromium.connectOverCDP(session.cdpUrl);
35517
+ owned = this.provider.isolatesSessions ? void 0 : await browser.newContext();
35518
+ const context = owned ?? browser.contexts()[0] ?? await browser.newContext();
35519
+ const page2 = owned ? await owned.newPage() : context.pages()[0] ?? await context.newPage();
35520
+ const abort2 = this.aborts.get(runId);
35521
+ if (!abort2) throw new Error("The run ended while its browser was still opening.");
35522
+ const held = { session, browser, page: page2, generation: 0, abort: abort2, ...owned ? { ownedContext: owned } : {} };
35523
+ page2.on("framenavigated", ((frame) => {
35524
+ if (frame !== page2.mainFrame()) return;
35525
+ held.generation += 1;
35526
+ }));
35527
+ this.runs.set(runId, held);
35528
+ return held;
35529
+ } catch (err) {
35530
+ this.announceLiveView(runId, void 0, false);
35531
+ await owned?.close().catch(() => {
35532
+ });
35533
+ await browser?.close().catch(() => {
35534
+ });
35535
+ await this.provider.endSession(session.id).catch(() => {
35536
+ });
35537
+ throw err;
35538
+ }
35539
+ }
35540
+ async perform(held, action, planned) {
35541
+ const { page: page2 } = held;
35542
+ const stoppable = async (work) => {
35543
+ if (held.abort.signal.aborted) throw new Error("The user stopped browser control for this run.");
35544
+ let onAbort;
35545
+ try {
35546
+ return await Promise.race([
35547
+ work,
35548
+ new Promise((_, reject) => {
35549
+ onAbort = () => {
35550
+ void page2.close().catch(() => {
35551
+ });
35552
+ reject(new Error("The user stopped browser control for this run."));
35553
+ };
35554
+ held.abort.signal.addEventListener("abort", onAbort, { once: true });
35555
+ })
35556
+ ]);
35557
+ } finally {
35558
+ held.abort.signal.removeEventListener("abort", onAbort);
35559
+ }
35560
+ };
35561
+ const timeout = Math.min(action.timeoutMs ?? 1e4, ACTION_TIMEOUT_MS);
35562
+ const where = async () => ({
35563
+ url: page2.url(),
35564
+ title: await page2.title().catch(() => "")
35565
+ });
35566
+ if (action.kind !== "navigate" && held.generation !== planned) {
35567
+ return {
35568
+ ok: false,
35569
+ detail: "The page changed while this action was waiting for the browser, so it was not run. Look at the page again before retrying.",
35570
+ ...await where()
35571
+ };
35572
+ }
35573
+ switch (action.kind) {
35574
+ case "navigate": {
35575
+ const target = action.url ?? "";
35576
+ if (!/^https?:\/\//i.test(target)) {
35577
+ return { ok: false, detail: "Only http and https addresses can be opened." };
35578
+ }
35579
+ await stoppable(page2.goto(target, { timeout: ACTION_TIMEOUT_MS, waitUntil: "domcontentloaded" }));
35580
+ return { ok: true, detail: `Opened ${target}`, ...await where() };
35581
+ }
35582
+ case "click":
35583
+ await stoppable(page2.click(action.selector, { timeout }));
35584
+ return { ok: true, detail: `Clicked ${action.selector}`, ...await where() };
35585
+ case "fill":
35586
+ await stoppable(page2.fill(action.selector, action.value ?? "", { timeout }));
35587
+ return { ok: true, detail: `Filled ${action.selector}`, ...await where() };
35588
+ case "press": {
35589
+ if (action.selector) await stoppable(page2.press(action.selector, action.key, { timeout }));
35590
+ else await stoppable(page2.keyboard.press(action.key));
35591
+ return { ok: true, detail: `Pressed ${action.key}`, ...await where() };
35592
+ }
35593
+ case "wait_for":
35594
+ await stoppable(page2.waitForSelector(action.selector, { timeout }));
35595
+ return { ok: true, detail: `${action.selector} appeared`, ...await where() };
35596
+ case "extract_text": {
35597
+ const text = await stoppable(page2.innerText(action.selector ?? "body", { timeout }));
35598
+ return { ok: true, detail: text.slice(0, 2e5), ...await where() };
35599
+ }
35600
+ default:
35601
+ return { ok: false, detail: `Unsupported action: ${String(action.kind)}` };
35602
+ }
35603
+ }
35604
+ };
35605
+ function refusal(result) {
35606
+ if (result === "off") return "Browser control was turned off while this action waited for the browser.";
35607
+ if (result === "cancelled") return "The run was cancelled while waiting for the browser.";
35608
+ 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.";
35609
+ }
35610
+ async function loadPlaywright() {
35611
+ try {
35612
+ return await import('playwright');
35613
+ } catch {
35614
+ throw new Error("Playwright is not installed. Run: npm install playwright (no browser download is needed \u2014 this connects to a remote browser).");
35615
+ }
35616
+ }
35617
+
35618
+ // src/browser/remote/generic-cdp.ts
35619
+ var GenericCdpProvider = class {
35620
+ name = "CDP endpoint";
35621
+ // The endpoint is a single browser. There is no session to allocate, so two
35622
+ // runs against it share a page — see the seam.
35623
+ isolatesSessions = false;
35624
+ endpoint;
35625
+ constructor(endpoint) {
35626
+ this.endpoint = endpoint;
35627
+ }
35628
+ /**
35629
+ * There is no session to create — the endpoint is the session.
35630
+ *
35631
+ * `id` is a constant rather than a generated one because there is nothing to
35632
+ * look up later: `endSession` has nothing to call. Inventing a unique id
35633
+ * would imply a lifecycle this provider does not have.
35634
+ */
35635
+ async createSession() {
35636
+ return { id: "cdp", cdpUrl: this.endpoint };
35637
+ }
35638
+ /**
35639
+ * Deliberately nothing.
35640
+ *
35641
+ * The endpoint belongs to whoever runs it and outlives any single run, so
35642
+ * "ending" it is not ours to do — closing it would take the browser away from
35643
+ * every other user of a shared endpoint. The driver still closes its own
35644
+ * connection and its pages; this is only about the browser's lifetime.
35645
+ */
35646
+ async endSession() {
35647
+ }
35648
+ };
35649
+ function isCdpEndpoint(url) {
35650
+ try {
35651
+ const u = new URL(url);
35652
+ return u.protocol === "ws:" || u.protocol === "wss:";
35653
+ } catch {
35654
+ return false;
35655
+ }
35656
+ }
35657
+
35658
+ // src/browser/remote/steel.ts
35659
+ var DEFAULT_BASE = "https://api.steel.dev";
35660
+ var CREATE_TIMEOUT_MS = 6e4;
35661
+ var SteelProvider = class {
35662
+ name = "Steel";
35663
+ // POST /v1/sessions allocates a browser per call, so concurrent runs are
35664
+ // genuinely separate.
35665
+ isolatesSessions = true;
35666
+ base;
35667
+ apiKey;
35668
+ constructor(opts = {}) {
35669
+ let base = opts.url || DEFAULT_BASE;
35670
+ while (base.endsWith("/")) base = base.slice(0, -1);
35671
+ this.base = base;
35672
+ this.apiKey = opts.apiKey;
35673
+ }
35674
+ async createSession(signal) {
35675
+ const details = await this.call("POST", "/v1/sessions", signal, {});
35676
+ if (!details.id || !details.websocketUrl) {
35677
+ throw new Error("Steel returned a session with no id or websocket URL.");
35678
+ }
35679
+ return {
35680
+ id: details.id,
35681
+ cdpUrl: details.websocketUrl,
35682
+ ...details.debugUrl ? { liveViewUrl: details.debugUrl } : {}
35683
+ };
35684
+ }
35685
+ async endSession(id) {
35686
+ try {
35687
+ await this.call("POST", `/v1/sessions/${encodeURIComponent(id)}/release`, void 0, {});
35688
+ } catch {
35689
+ }
35690
+ }
35691
+ async call(method, path30, signal, body) {
35692
+ const timeout = AbortSignal.timeout(CREATE_TIMEOUT_MS);
35693
+ const composed = signal ? AbortSignal.any([signal, timeout]) : timeout;
35694
+ const res = await fetch(`${this.base}${path30}`, {
35695
+ method,
35696
+ headers: {
35697
+ "content-type": "application/json",
35698
+ // Sent only when configured — the self-hosted API takes no key, and an
35699
+ // empty header is worse than none.
35700
+ ...this.apiKey ? { "steel-api-key": this.apiKey } : {}
35701
+ },
35702
+ body: JSON.stringify(body),
35703
+ signal: composed
35704
+ });
35705
+ if (!res.ok) {
35706
+ const detail = await res.text().then((t) => t.slice(0, 300)).catch(() => "");
35707
+ throw new Error(`Steel ${method} ${path30} failed: ${res.status}${detail ? ` \u2014 ${detail}` : ""}`);
35708
+ }
35709
+ return await res.json();
35710
+ }
35711
+ };
35712
+
34946
35713
  // src/retrieval/chunk.ts
34947
35714
  var DEFAULTS2 = { targetChars: 2e3, overlapChars: 200, minChars: 80 };
34948
35715
  function splitLongBlock(block, max) {
@@ -35598,6 +36365,7 @@ exports.AZURE_BASE_MODELS = AZURE_BASE_MODELS;
35598
36365
  exports.AZURE_BASE_URL_TEMPLATE = AZURE_BASE_URL_TEMPLATE;
35599
36366
  exports.AuditLogger = AuditLogger;
35600
36367
  exports.BrowserControlTool = BrowserControlTool;
36368
+ exports.BrowserLease = BrowserLease;
35601
36369
  exports.CASCADE_AUDIT_FILE = CASCADE_AUDIT_FILE;
35602
36370
  exports.CASCADE_CONFIG_DIR = CASCADE_CONFIG_DIR;
35603
36371
  exports.CASCADE_CONFIG_FILE = CASCADE_CONFIG_FILE;
@@ -35638,6 +36406,7 @@ exports.GLOBAL_DB_FILE = GLOBAL_DB_FILE;
35638
36406
  exports.GLOBAL_KEYSTORE_FILE = GLOBAL_KEYSTORE_FILE;
35639
36407
  exports.GLOBAL_RUNTIME_DB_FILE = GLOBAL_RUNTIME_DB_FILE;
35640
36408
  exports.GenerateDocumentTool = GenerateDocumentTool;
36409
+ exports.GenericCdpProvider = GenericCdpProvider;
35641
36410
  exports.GraphRetriever = GraphRetriever;
35642
36411
  exports.GraphSearchTool = GraphSearchTool;
35643
36412
  exports.HooksRunner = HooksRunner;
@@ -35654,9 +36423,11 @@ exports.OLLAMA_BASE_URL = OLLAMA_BASE_URL;
35654
36423
  exports.OpenAICompatibleEmbedder = OpenAICompatibleEmbedder;
35655
36424
  exports.PROVIDER_DISPLAY_NAMES = PROVIDER_DISPLAY_NAMES;
35656
36425
  exports.RESUME_SCHEMA_VERSION = RESUME_SCHEMA_VERSION;
36426
+ exports.RemoteBrowserController = RemoteBrowserController;
35657
36427
  exports.ResumeStore = ResumeStore;
35658
36428
  exports.Retriever = Retriever;
35659
36429
  exports.SqliteVectorStore = SqliteVectorStore;
36430
+ exports.SteelProvider = SteelProvider;
35660
36431
  exports.T1Administrator = T1Administrator;
35661
36432
  exports.T1_MODEL_PRIORITY = T1_MODEL_PRIORITY;
35662
36433
  exports.T2Manager = T2Manager;
@@ -35721,6 +36492,7 @@ exports.hashContent = hashContent;
35721
36492
  exports.heuristicCodeChunker = heuristicCodeChunker;
35722
36493
  exports.inferAzureBaseModel = inferAzureBaseModel;
35723
36494
  exports.inlineRuns = inlineRuns;
36495
+ exports.isCdpEndpoint = isCdpEndpoint;
35724
36496
  exports.isDocumentFormat = isDocumentFormat;
35725
36497
  exports.isMcpToolName = isMcpToolName;
35726
36498
  exports.matchImageLine = matchImageLine;