cascade-ai 0.77.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.77.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";
@@ -16130,6 +16130,45 @@ var ToolsConfigSchema = zod.z.object({
16130
16130
  shellBlocklist: zod.z.array(zod.z.string()).default(["rm -rf", "sudo rm", "format", "mkfs"]),
16131
16131
  requireApprovalFor: zod.z.array(zod.z.string()).default([]),
16132
16132
  browserEnabled: zod.z.boolean().default(false),
16133
+ /**
16134
+ * Let a run ACT on the page open in the desktop's built-in browser — click,
16135
+ * type, submit — not just read it.
16136
+ *
16137
+ * Distinct from `browserEnabled`, which turns on the headless Playwright
16138
+ * tool. That one drives a throwaway browser with an empty cookie jar; this
16139
+ * one drives the session the user is signed into, which is a different order
16140
+ * of consequence and so gets its own switch rather than riding on that one.
16141
+ *
16142
+ * Off by default. Turning it on does not hand anything over silently: the
16143
+ * tool still goes through the approval chain, and the browser panel carries a
16144
+ * stop control for the run that is acting.
16145
+ */
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(),
16133
16172
  mcpServers: zod.z.array(McpServerConfigSchema).optional(),
16134
16173
  mcpTrusted: zod.z.array(zod.z.string()).optional(),
16135
16174
  /** Web search backends — at least one should be configured for best results */
@@ -20914,6 +20953,23 @@ Now execute your subtask using this context where relevant.`
20914
20953
  this.setStatus("FAILED", finalOutput);
20915
20954
  this.peerBus?.publish(this.id, assignment.subtaskId, finalOutput, "FAILED");
20916
20955
  return this.buildResult("ESCALATED", finalOutput, { checksRun, passed, failed }, issues, correctionAttempts);
20956
+ } finally {
20957
+ this.releaseBrowserControl();
20958
+ }
20959
+ }
20960
+ /**
20961
+ * End this worker's hold on the shared browser.
20962
+ *
20963
+ * Duck-typed rather than imported: `browser_control` is registered only by a
20964
+ * host that HAS a browser (the desktop), so in the CLI and hosted runs there
20965
+ * is no such tool and this is a no-op. Importing the class to instanceof-check
20966
+ * it would couple the worker to a tool that usually is not there.
20967
+ */
20968
+ releaseBrowserControl() {
20969
+ try {
20970
+ const tool = this.toolRegistry.getTool?.("browser_control");
20971
+ tool?.releaseActor?.(this.id);
20972
+ } catch {
20917
20973
  }
20918
20974
  }
20919
20975
  sendToPeer(toId, content) {
@@ -30730,6 +30786,127 @@ var CurrentPageTool = class extends BaseTool {
30730
30786
  }
30731
30787
  };
30732
30788
 
30789
+ // src/tools/browser-control.ts
30790
+ var BrowserControlTool = class extends BaseTool {
30791
+ name = "browser_control";
30792
+ description = "Act on the web page the user has open in the built-in browser: navigate, click an element, type into a field, press a key, or wait for something to appear. This drives the REAL browser the user is signed into and can see, so actions have real consequences \u2014 prefer read_current_page when you only need to look. CSS selectors are matched against the live page; call extract_text first if you need to find one. There is one browser: if another part of this run is using it, this call waits its turn, so a slow reply means queued, not stuck.";
30793
+ inputSchema = {
30794
+ type: "object",
30795
+ properties: {
30796
+ action: {
30797
+ type: "string",
30798
+ enum: ["navigate", "click", "fill", "press", "wait_for", "extract_text"],
30799
+ description: "What to do."
30800
+ },
30801
+ url: { type: "string", description: "For navigate: the http(s) address to open." },
30802
+ selector: {
30803
+ type: "string",
30804
+ description: "CSS selector for click, fill and wait_for. Optional for extract_text (defaults to the whole page)."
30805
+ },
30806
+ value: { type: "string", description: "For fill: the text to type." },
30807
+ key: { type: "string", description: 'For press: a key name such as "Enter", "Tab" or "Escape".' },
30808
+ timeoutMs: { type: "number", description: "For wait_for: how long to wait before giving up (default 10000, max 30000)." }
30809
+ },
30810
+ required: ["action"]
30811
+ };
30812
+ controller;
30813
+ release;
30814
+ /** One-way. See `revoke`. */
30815
+ revoked = false;
30816
+ constructor(controller, release) {
30817
+ super();
30818
+ this.controller = controller;
30819
+ this.release = release;
30820
+ }
30821
+ /**
30822
+ * A worker has finished. Ends its hold on the browser.
30823
+ *
30824
+ * Called from the tier's terminal path rather than by the model, because a
30825
+ * model cannot be relied on to announce that it is done — which is why the
30826
+ * host cannot use idle time as the boundary instead.
30827
+ */
30828
+ releaseActor(actorId) {
30829
+ this.release?.(actorId);
30830
+ }
30831
+ /**
30832
+ * Permanently disable this tool, whatever the registry still holds.
30833
+ *
30834
+ * Registration-time gates cannot express "this run turned out to be
30835
+ * unattended": a host that wires the controller and only then declares the
30836
+ * run unattended has already registered the tool, and a check that ran at
30837
+ * registration has no second chance. Enforcing at EXECUTION time makes the
30838
+ * guarantee independent of call order, which is the whole point of stating
30839
+ * the invariant rather than relying on the scheduler's current sequence.
30840
+ *
30841
+ * One-way on purpose. A safety gate that can be re-opened by a later call is
30842
+ * a gate that a refactor re-opens by accident.
30843
+ */
30844
+ revoke() {
30845
+ this.revoked = true;
30846
+ }
30847
+ // Acting on a session the user is signed into is the highest-consequence
30848
+ // thing in the tool set — higher than shell, arguably, because the blast
30849
+ // radius is someone else's server rather than this machine.
30850
+ isDangerous() {
30851
+ return true;
30852
+ }
30853
+ async execute(input, options) {
30854
+ if (this.revoked) {
30855
+ return "Error: browser control is not available in this run. It requires a person watching who can stop it, and nobody is.";
30856
+ }
30857
+ const kind = input["action"];
30858
+ if (!kind) return "Error: action is required.";
30859
+ if (options?.signal?.aborted) return "Error: the run was cancelled before this action ran.";
30860
+ const missing = requiredFieldFor(kind, input);
30861
+ if (missing) return `Error: "${kind}" needs ${missing}.`;
30862
+ const action = {
30863
+ kind,
30864
+ ...typeof input["url"] === "string" ? { url: input["url"] } : {},
30865
+ ...typeof input["selector"] === "string" ? { selector: input["selector"] } : {},
30866
+ ...typeof input["value"] === "string" ? { value: input["value"] } : {},
30867
+ ...typeof input["key"] === "string" ? { key: input["key"] } : {},
30868
+ ...typeof input["timeoutMs"] === "number" ? { timeoutMs: Math.min(Math.max(input["timeoutMs"], 0), 3e4) } : {}
30869
+ };
30870
+ let outcome;
30871
+ try {
30872
+ outcome = await this.controller(action, {
30873
+ // `sessionId` is the run. The host scopes both revocation and its
30874
+ // single-owner lease on it, so passing it is not telemetry — drop it
30875
+ // and a Stop in one run silently stops every later one.
30876
+ sessionId: options?.sessionId ?? "",
30877
+ actorId: options?.tierId ?? options?.sessionId ?? "",
30878
+ ...options?.signal ? { signal: options.signal } : {}
30879
+ });
30880
+ } catch (err) {
30881
+ return `Error: the browser could not perform "${kind}" \u2014 ${err instanceof Error ? err.message : String(err)}`;
30882
+ }
30883
+ const where = outcome.url ? `
30884
+ Page: ${outcome.title ? `${outcome.title} \u2014 ` : ""}${outcome.url}` : "";
30885
+ return `${outcome.ok ? "" : "Failed: "}${outcome.detail}${where}`;
30886
+ }
30887
+ };
30888
+ function requiredFieldFor(kind, input) {
30889
+ const has = (k) => typeof input[k] === "string" && input[k].length > 0;
30890
+ const given = (k) => typeof input[k] === "string";
30891
+ switch (kind) {
30892
+ case "navigate":
30893
+ return has("url") ? null : "a url";
30894
+ case "click":
30895
+ return has("selector") ? null : "a selector";
30896
+ case "fill":
30897
+ return has("selector") ? given("value") ? null : "a value" : "a selector";
30898
+ case "press":
30899
+ return has("key") ? null : "a key";
30900
+ case "wait_for":
30901
+ return has("selector") ? null : "a selector";
30902
+ // extract_text works with or without a selector.
30903
+ case "extract_text":
30904
+ return null;
30905
+ default:
30906
+ return null;
30907
+ }
30908
+ }
30909
+
30733
30910
  // src/core/cascade.ts
30734
30911
  var ESCALATION_DECISION_TIMEOUT_MS = 5 * 6e4;
30735
30912
  function buildContextualPrompt(prompt, history = []) {
@@ -31222,6 +31399,79 @@ ${input}` }],
31222
31399
  if ((this.config.tools?.disabledTools ?? []).includes("read_current_page")) return;
31223
31400
  this.toolRegistry.register(new CurrentPageTool(provider));
31224
31401
  }
31402
+ /**
31403
+ * True when nobody is watching this run — a scheduled/cron task, which
31404
+ * auto-approves every tool because there is no one to ask.
31405
+ *
31406
+ * That auto-approval is fine for ordinary tools and disqualifying for this
31407
+ * one: `browser_control` drives the signed-in browser, and "every run asks
31408
+ * first" is the promise the Settings copy makes. The property used to hold
31409
+ * only because `runScheduledTask` happens not to call `setBrowserController`
31410
+ * — a guarantee resting on an ABSENT call, which is exactly what a later
31411
+ * refactor adds without noticing. Stated and enforced instead.
31412
+ */
31413
+ unattended = false;
31414
+ /**
31415
+ * Declare that no human is watching this run, so capabilities that depend on
31416
+ * a person being able to see and stop them are refused outright.
31417
+ */
31418
+ setUnattended(on) {
31419
+ this.unattended = on;
31420
+ if (!on) return;
31421
+ const tool = this.toolRegistry.getTool("browser_control");
31422
+ tool?.revoke?.();
31423
+ }
31424
+ /**
31425
+ * Wire the host's browser so a run can ACT on the open page, not just read it.
31426
+ *
31427
+ * Two gates before this registers anything, and both matter:
31428
+ *
31429
+ * - `tools.agentBrowserControl` must be on. Unlike read_current_page, which
31430
+ * reaches nothing the user has not already opened themselves, this drives
31431
+ * the session they are signed into. That is opt-in, not a default.
31432
+ * - `disabledTools` still removes it, the same as every other tool.
31433
+ * - The run must not be UNATTENDED. See `setUnattended`.
31434
+ *
31435
+ * Host-supplied like the page provider: the tool exists only where there is a
31436
+ * real browser to drive, so it never has to be refused in the CLI or a hosted
31437
+ * run — it is simply not there.
31438
+ */
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) {
31470
+ if (this.unattended) return;
31471
+ if (!enabled) return;
31472
+ if ((this.config.tools?.disabledTools ?? []).includes("browser_control")) return;
31473
+ this.toolRegistry.register(new BrowserControlTool(controller, release));
31474
+ }
31225
31475
  registerMediaTools(workspacePath) {
31226
31476
  const denied = new Set(this.config.tools?.disabledTools ?? []);
31227
31477
  const permitted = (name) => !denied.has(name);
@@ -31827,6 +32077,7 @@ ${prompt}` : prompt;
31827
32077
  this.router.setRunSignal(options.signal);
31828
32078
  const startMs = Date.now();
31829
32079
  const taskId = crypto.randomUUID();
32080
+ this.emit("run:started", { taskId });
31830
32081
  this.decisionLog = [];
31831
32082
  this.currentRunCompleted = [];
31832
32083
  this.wroteCheckpointThisRun = false;
@@ -32562,6 +32813,20 @@ function applySettingsPayload(config, data) {
32562
32813
  if (data.webSearch.tavilyApiKey) next.tavilyApiKey = data.webSearch.tavilyApiKey;
32563
32814
  config.tools.webSearch = next;
32564
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
+ }
32565
32830
  if (data.advanced && typeof data.advanced === "object") {
32566
32831
  const a = data.advanced;
32567
32832
  const num = (v, min, max) => {
@@ -32592,6 +32857,7 @@ function applySettingsPayload(config, data) {
32592
32857
  if (["auto", "T1", "T2", "T3"].includes(a["forceTier"])) config.routing = { ...config.routing ?? {}, forceTier: a["forceTier"] };
32593
32858
  if (typeof a["benchmarksLive"] === "boolean") config.benchmarks = { ...config.benchmarks ?? {}, live: a["benchmarksLive"] };
32594
32859
  if (["isolate", "worker", "auto"].includes(a["dynamicToolSandbox"])) config.tools = { ...config.tools ?? {}, dynamicToolSandbox: a["dynamicToolSandbox"] };
32860
+ if (typeof a["agentBrowserControl"] === "boolean") config.tools = { ...config.tools ?? {}, agentBrowserControl: a["agentBrowserControl"] };
32595
32861
  if (typeof a["factsExtraction"] === "boolean") config.knowledge = { ...config.knowledge ?? {}, factsExtraction: a["factsExtraction"] };
32596
32862
  if (typeof a["rememberSessions"] === "boolean") config.memory = { ...config.memory ?? {}, rememberSessions: a["rememberSessions"] };
32597
32863
  if (typeof a["enableToolCreation"] === "boolean") config.enableToolCreation = a["enableToolCreation"];
@@ -32607,6 +32873,7 @@ function settingsSnapshot(config) {
32607
32873
  if (p?.type && p?.baseUrl && p.type !== "azure") endpoints[p.type] = p.baseUrl;
32608
32874
  }
32609
32875
  const ws = config.tools?.webSearch ?? {};
32876
+ const rb = config.tools?.remoteBrowser ?? {};
32610
32877
  return {
32611
32878
  models: config.models ?? {},
32612
32879
  budget: {
@@ -32636,6 +32903,15 @@ function settingsSnapshot(config) {
32636
32903
  hasBraveKey: typeof ws.braveApiKey === "string" && ws.braveApiKey.length > 0,
32637
32904
  hasTavilyKey: typeof ws.tavilyApiKey === "string" && ws.tavilyApiKey.length > 0
32638
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
+ },
32639
32915
  advanced: {
32640
32916
  autonomy: config.autonomy,
32641
32917
  planApproval: config.planApproval,
@@ -32649,6 +32925,7 @@ function settingsSnapshot(config) {
32649
32925
  forceTier: config.routing?.forceTier,
32650
32926
  benchmarksLive: config.benchmarks?.live,
32651
32927
  dynamicToolSandbox: config.tools?.dynamicToolSandbox,
32928
+ agentBrowserControl: config.tools?.agentBrowserControl,
32652
32929
  factsExtraction: config.knowledge?.factsExtraction,
32653
32930
  rememberSessions: config.memory?.rememberSessions,
32654
32931
  enableToolCreation: config.enableToolCreation,
@@ -33153,6 +33430,14 @@ var DashboardServer = class {
33153
33430
  * always failing.
33154
33431
  */
33155
33432
  currentPageProvider;
33433
+ /**
33434
+ * Supplied by the desktop shell so a run can ACT on that page — click, type,
33435
+ * submit — not just read it. Same reasoning as the provider above: absent in
33436
+ * the CLI, so the tool is not registered rather than present and failing.
33437
+ * Cascade applies the `tools.agentBrowserControl` gate on top of this.
33438
+ */
33439
+ browserController;
33440
+ browserActorRelease;
33156
33441
  activeControllers = /* @__PURE__ */ new Map();
33157
33442
  /**
33158
33443
  * Run taskIds per chat session — file snapshots are keyed by the run's
@@ -33214,6 +33499,7 @@ var DashboardServer = class {
33214
33499
  });
33215
33500
  this.socket.onConfigUpdate(async (data) => {
33216
33501
  const result = await commitSettings(this.config, data, (committed) => this.persistConfig(committed));
33502
+ if (result.ok) this.settingsChangeHook?.(this.config);
33217
33503
  const refused = result.refused.map((r) => ({
33218
33504
  type: r.type,
33219
33505
  reason: r.reason,
@@ -33237,6 +33523,7 @@ var DashboardServer = class {
33237
33523
  const cascade = new Cascade(cfg, this.workspacePath, this.store);
33238
33524
  this.activeSessions.set(sessionId, cascade);
33239
33525
  if (this.currentPageProvider) cascade.setCurrentPageProvider(this.currentPageProvider);
33526
+ if (this.browserController) cascade.setBrowserController(this.browserController, this.browserActorRelease);
33240
33527
  cascade.on("stream:token", (e) => {
33241
33528
  this.emitToSessionClients(socketId, sessionId, "stream:token", { sessionId, tierId: e.tierId, text: e.text, primary: e.primary });
33242
33529
  });
@@ -33260,13 +33547,16 @@ var DashboardServer = class {
33260
33547
  if (ev.requestId) this.clearPendingEscalation(ev.requestId);
33261
33548
  this.emitToSessionClients(socketId, sessionId, "escalation:timeout", { sessionId, ...e });
33262
33549
  });
33550
+ cascade.on("run:started", (e) => {
33551
+ const id = e.taskId;
33552
+ if (id) this.recordSessionTask(sessionId, id);
33553
+ });
33263
33554
  try {
33264
33555
  const result = await cascade.run({
33265
33556
  prompt: runPrompt,
33266
33557
  signal: abortController.signal,
33267
33558
  approvalCallback: this.makeApprovalCallback(sessionId)
33268
33559
  });
33269
- this.recordSessionTask(sessionId, result.taskId);
33270
33560
  this.persistRunEnd(sessionId, title, prompt, result.output, "COMPLETED", result);
33271
33561
  this.captureWhy(sessionId, cascade, result);
33272
33562
  this.emitToSessionClients(socketId, sessionId, "session:complete", { sessionId, result });
@@ -33332,6 +33622,49 @@ var DashboardServer = class {
33332
33622
  setCurrentPageProvider(provider) {
33333
33623
  this.currentPageProvider = provider;
33334
33624
  }
33625
+ /** Let runs act on that view, not just read it (desktop only). */
33626
+ setBrowserController(controller, release) {
33627
+ this.browserController = controller;
33628
+ this.browserActorRelease = release;
33629
+ }
33630
+ /**
33631
+ * Told whenever settings are committed through THIS server.
33632
+ *
33633
+ * Settings reach the live config by two routes — the desktop's Electron IPC
33634
+ * handler and this server's `config:update` socket — and both run the same
33635
+ * `commitSettings`. The desktop mirrors `tools.agentBrowserControl` into its
33636
+ * browser module after its own route, but had no way to learn about the
33637
+ * other, so a socket write left the module's copy stale: an enable the module
33638
+ * still refused, or worse a disable the module still honoured for a run
33639
+ * already holding the tool. This is the same sibling-writer drift
33640
+ * `settings-payload.ts` exists to prevent, one layer up.
33641
+ */
33642
+ settingsChangeHook;
33643
+ onSettingsChanged(hook) {
33644
+ this.settingsChangeHook = hook;
33645
+ }
33646
+ /**
33647
+ * Told when a run ends, so a host holding run-scoped state can release it.
33648
+ *
33649
+ * The desktop uses this to retire a run's browser Stop control: that has to
33650
+ * outlive each individual action (the gap between two actions is when the
33651
+ * user most wants it) but must not outlive the run.
33652
+ */
33653
+ /**
33654
+ * Fired when a run ends, carrying BOTH identifiers explicitly.
33655
+ *
33656
+ * They are different things and conflating them was a live bug: a chat
33657
+ * `sessionId` can contain many runs (hence `sessionTaskIds`), while
33658
+ * `Cascade.run()` mints a fresh random `taskId` per run — and it is the
33659
+ * taskId that tools see as `ToolExecuteOptions.sessionId`. Passing only the
33660
+ * chat id meant browser cleanup keyed on the task id matched nothing, so a
33661
+ * finished run kept its Stop banner armed and held its browser lease until
33662
+ * the deadlock ceiling.
33663
+ */
33664
+ runEndedHook;
33665
+ onRunEnded(hook) {
33666
+ this.runEndedHook = hook;
33667
+ }
33335
33668
  async start() {
33336
33669
  const isLoopback = this.host === "127.0.0.1" || this.host === "::1" || this.host === "localhost";
33337
33670
  if (!isLoopback) {
@@ -33522,6 +33855,8 @@ var DashboardServer = class {
33522
33855
  }
33523
33856
  /** Record run end: the assistant reply (when there is one) and the runtime row's final status. */
33524
33857
  persistRunEnd(sessionId, title, latestPrompt, reply, status, result) {
33858
+ const endedTaskId = result?.taskId ?? this.sessionTaskIds.get(sessionId)?.at(-1);
33859
+ this.runEndedHook?.({ sessionId, ...endedTaskId ? { taskId: endedTaskId } : {} });
33525
33860
  try {
33526
33861
  if (reply && reply.trim()) {
33527
33862
  this.store.addMessage({ id: crypto.randomUUID(), sessionId, role: "assistant", content: reply, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
@@ -33615,6 +33950,7 @@ var DashboardServer = class {
33615
33950
  const prompt = task.prompt;
33616
33951
  const title = this.persistRunStart(sessionId, `[${task.name}] ${prompt}`);
33617
33952
  const cascade = new Cascade(this.config, task.workspacePath ?? this.workspacePath, this.store);
33953
+ cascade.setUnattended(true);
33618
33954
  this.activeSessions.set(sessionId, cascade);
33619
33955
  cascade.on("tier:status", (e) => {
33620
33956
  this.socket.broadcast("tier:status", { sessionId, ...e });
@@ -33622,13 +33958,16 @@ var DashboardServer = class {
33622
33958
  cascade.on("peer:message", (e) => {
33623
33959
  this.socket.emitPeerMessage(e);
33624
33960
  });
33961
+ cascade.on("run:started", (e) => {
33962
+ const id = e.taskId;
33963
+ if (id) this.recordSessionTask(sessionId, id);
33964
+ });
33625
33965
  try {
33626
33966
  const result = await cascade.run({
33627
33967
  prompt,
33628
33968
  identityId: task.identityId,
33629
33969
  approvalCallback: async () => ({ approved: true, always: false })
33630
33970
  });
33631
- this.recordSessionTask(sessionId, result.taskId);
33632
33971
  this.persistRunEnd(sessionId, title, prompt, result.output, "COMPLETED", result);
33633
33972
  this.captureWhy(sessionId, cascade, result);
33634
33973
  this.socket.broadcast("session:complete", { sessionId, result });
@@ -34261,6 +34600,7 @@ ${prompt}`;
34261
34600
  const cascade = new Cascade(this.config, this.workspacePath, this.store);
34262
34601
  this.activeSessions.set(sessionId, cascade);
34263
34602
  if (this.currentPageProvider) cascade.setCurrentPageProvider(this.currentPageProvider);
34603
+ if (this.browserController) cascade.setBrowserController(this.browserController, this.browserActorRelease);
34264
34604
  cascade.on("stream:token", (e) => {
34265
34605
  this.socket.broadcastToRoom(`session:${sessionId}`, "stream:token", { sessionId, tierId: e.tierId, text: e.text, primary: e.primary });
34266
34606
  });
@@ -34284,13 +34624,16 @@ ${prompt}`;
34284
34624
  if (ev.requestId) this.clearPendingEscalation(ev.requestId);
34285
34625
  this.socket.broadcastToRoom(`session:${sessionId}`, "escalation:timeout", { sessionId, ...e });
34286
34626
  });
34627
+ cascade.on("run:started", (e) => {
34628
+ const id = e.taskId;
34629
+ if (id) this.recordSessionTask(sessionId, id);
34630
+ });
34287
34631
  try {
34288
34632
  const result = await cascade.run({
34289
34633
  prompt: runPrompt,
34290
34634
  identityId: body.identityId,
34291
34635
  approvalCallback: this.makeApprovalCallback(sessionId)
34292
34636
  });
34293
- this.recordSessionTask(sessionId, result.taskId);
34294
34637
  this.persistRunEnd(sessionId, title, prompt, result.output, "COMPLETED", result);
34295
34638
  this.captureWhy(sessionId, cascade, result);
34296
34639
  this.socket.broadcast("cost:update", {
@@ -34679,6 +35022,694 @@ async function discoverMcpTools(servers) {
34679
35022
  return results;
34680
35023
  }
34681
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
+
34682
35713
  // src/retrieval/chunk.ts
34683
35714
  var DEFAULTS2 = { targetChars: 2e3, overlapChars: 200, minChars: 80 };
34684
35715
  function splitLongBlock(block, max) {
@@ -35333,6 +36364,8 @@ function applySyncBundle(bundle, config, cleanup) {
35333
36364
  exports.AZURE_BASE_MODELS = AZURE_BASE_MODELS;
35334
36365
  exports.AZURE_BASE_URL_TEMPLATE = AZURE_BASE_URL_TEMPLATE;
35335
36366
  exports.AuditLogger = AuditLogger;
36367
+ exports.BrowserControlTool = BrowserControlTool;
36368
+ exports.BrowserLease = BrowserLease;
35336
36369
  exports.CASCADE_AUDIT_FILE = CASCADE_AUDIT_FILE;
35337
36370
  exports.CASCADE_CONFIG_DIR = CASCADE_CONFIG_DIR;
35338
36371
  exports.CASCADE_CONFIG_FILE = CASCADE_CONFIG_FILE;
@@ -35373,6 +36406,7 @@ exports.GLOBAL_DB_FILE = GLOBAL_DB_FILE;
35373
36406
  exports.GLOBAL_KEYSTORE_FILE = GLOBAL_KEYSTORE_FILE;
35374
36407
  exports.GLOBAL_RUNTIME_DB_FILE = GLOBAL_RUNTIME_DB_FILE;
35375
36408
  exports.GenerateDocumentTool = GenerateDocumentTool;
36409
+ exports.GenericCdpProvider = GenericCdpProvider;
35376
36410
  exports.GraphRetriever = GraphRetriever;
35377
36411
  exports.GraphSearchTool = GraphSearchTool;
35378
36412
  exports.HooksRunner = HooksRunner;
@@ -35389,9 +36423,11 @@ exports.OLLAMA_BASE_URL = OLLAMA_BASE_URL;
35389
36423
  exports.OpenAICompatibleEmbedder = OpenAICompatibleEmbedder;
35390
36424
  exports.PROVIDER_DISPLAY_NAMES = PROVIDER_DISPLAY_NAMES;
35391
36425
  exports.RESUME_SCHEMA_VERSION = RESUME_SCHEMA_VERSION;
36426
+ exports.RemoteBrowserController = RemoteBrowserController;
35392
36427
  exports.ResumeStore = ResumeStore;
35393
36428
  exports.Retriever = Retriever;
35394
36429
  exports.SqliteVectorStore = SqliteVectorStore;
36430
+ exports.SteelProvider = SteelProvider;
35395
36431
  exports.T1Administrator = T1Administrator;
35396
36432
  exports.T1_MODEL_PRIORITY = T1_MODEL_PRIORITY;
35397
36433
  exports.T2Manager = T2Manager;
@@ -35456,6 +36492,7 @@ exports.hashContent = hashContent;
35456
36492
  exports.heuristicCodeChunker = heuristicCodeChunker;
35457
36493
  exports.inferAzureBaseModel = inferAzureBaseModel;
35458
36494
  exports.inlineRuns = inlineRuns;
36495
+ exports.isCdpEndpoint = isCdpEndpoint;
35459
36496
  exports.isDocumentFormat = isDocumentFormat;
35460
36497
  exports.isMcpToolName = isMcpToolName;
35461
36498
  exports.matchImageLine = matchImageLine;