deputy-mcp 0.1.4 → 0.1.6

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/README.md CHANGED
@@ -5,10 +5,16 @@ stdio, and it talks to the Deputy extension in your Chrome. The page never reach
5
5
  agent gets a typed tool for each form and makes one call.
6
6
 
7
7
  ```bash
8
- claude mcp add deputy -- npx -y deputy-mcp # Claude Code
8
+ # Claude Code: the plugin (adds /deputy:setup and a Deputy skill)
9
+ claude plugin marketplace add RazinAI/deputy && claude plugin install deputy@razin
10
+ # or a plain MCP server, for every project
11
+ claude mcp add --scope user deputy -- npx -y deputy-mcp
12
+
9
13
  codex mcp add deputy -- npx -y deputy-mcp # Codex
10
14
  ```
11
15
 
16
+ Every other agent, from Gemini CLI and OpenCode to Cursor and Copilot: [deputy.docs.razin.ai/docs/connecting](https://deputy.docs.razin.ai/docs/connecting).
17
+
12
18
  Any other MCP client: run `npx -y deputy-mcp` as a stdio server.
13
19
 
14
20
  Deputy is free to start: without a key your agent gets 10 tools. [Deputy Pro](https://razin.ai/deputy/)
@@ -16,7 +22,19 @@ adds the other 17 and hosted models; paste its license key on the extension's se
16
22
  open-source version is at [github.com/zraisan/deputy](https://github.com/zraisan/deputy).
17
23
 
18
24
  Several clients can use the same browser at once. The first one to start owns the connection to
19
- the extension on `127.0.0.1:7331`; later ones share it, and take over if it exits. `DEPUTY_PORT`
20
- picks another port.
25
+ the extension on `127.0.0.1:7331`; later ones share it, and take over if it exits. Each one works
26
+ in its own tab. Deputy enabled in more than one Chrome profile is fine too: each call goes to the
27
+ profile that has the tab. `DEPUTY_PORT` picks another port.
28
+
29
+ Your own model: Deputy can use an [OpenRouter](https://openrouter.ai) key of yours for
30
+ `browser_ask` and `delegate_goal`. Every Deputy process plans with its own key, so put it where
31
+ all of them read it, and no restart is needed:
32
+
33
+ ```bash
34
+ mkdir -p ~/.config/deputy && echo 'OPENROUTER_API_KEY=sk-or-...' >> ~/.config/deputy/env
35
+ ```
36
+
37
+ `OPENROUTER_MODEL` there picks the model. The same variables in the environment win over the
38
+ file; `DEPUTY_CONFIG` moves the file.
21
39
 
22
40
  License: [PolyForm Shield 1.0.0](LICENSE).
@@ -68886,6 +68886,43 @@ class Registry {
68886
68886
  }
68887
68887
  }
68888
68888
 
68889
+ // packages/deputyd/src/holds.ts
68890
+ var HOLD_MS = 10 * 60000;
68891
+
68892
+ class Holds {
68893
+ by = new Map;
68894
+ claim(tabId, who, now = Date.now()) {
68895
+ this.by.set(tabId, { who, at: now });
68896
+ }
68897
+ release(tabId) {
68898
+ this.by.delete(tabId);
68899
+ }
68900
+ drop(who) {
68901
+ for (const [tabId, h] of this.by)
68902
+ if (h.who === who)
68903
+ this.by.delete(tabId);
68904
+ }
68905
+ clear() {
68906
+ this.by.clear();
68907
+ }
68908
+ others(who, now = Date.now()) {
68909
+ return [...this.by].filter(([, h]) => h.who !== who && now - h.at < HOLD_MS).map(([tabId, h]) => [tabId, h.at]);
68910
+ }
68911
+ heldElsewhere(tabId, who, now = Date.now()) {
68912
+ const h = this.by.get(tabId);
68913
+ return !!h && h.who !== who && now - h.at < HOLD_MS;
68914
+ }
68915
+ }
68916
+ function defaultTab(tabs, activeTabId, mine, elsewhere) {
68917
+ const own2 = tabs.find((t) => t.tabId === mine);
68918
+ if (own2 && !elsewhere(own2.tabId))
68919
+ return own2;
68920
+ const active = tabs.find((t) => t.tabId === activeTabId);
68921
+ if (active && !elsewhere(active.tabId))
68922
+ return active;
68923
+ return null;
68924
+ }
68925
+
68889
68926
  // packages/deputyd/src/tasks.ts
68890
68927
  var TERMINAL = new Set(["completed", "failed", "canceled"]);
68891
68928
  var INTERRUPTED = new Set(["input_required", "auth_required"]);
@@ -68985,6 +69022,11 @@ class TaskStore {
68985
69022
  }
68986
69023
  }
68987
69024
 
69025
+ // packages/deputyd/src/planner.ts
69026
+ import { readFileSync } from "node:fs";
69027
+ import { homedir } from "node:os";
69028
+ import { join } from "node:path";
69029
+
68988
69030
  // packages/deputyd/src/pro.ts
68989
69031
  var DEFAULT_PRO_URL = "https://deputy.api.razin.ai";
68990
69032
  var PRO_UPGRADE = "browser_look is part of Deputy Pro: a vision model reads the page and answers in text, so your " + "context stays small and it works in clients that cannot display images, such as Codex. Add a " + "license key on Deputy's setup page (the extension's options). Without Pro, use browser_screenshot " + "to see the page yourself, or browser_ask and browser_read for text.";
@@ -69061,6 +69103,7 @@ var STOPWORDS = new Set([
69061
69103
  "with"
69062
69104
  ]);
69063
69105
  var words = (s) => s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOPWORDS.has(w));
69106
+ var BUY_URL = "https://deputy.razin.ai/buy";
69064
69107
 
69065
69108
  class HeuristicPlanner {
69066
69109
  name = "heuristic (no model configured)";
@@ -69087,6 +69130,12 @@ class HeuristicPlanner {
69087
69130
  }
69088
69131
  const props = best.tool.inputSchema?.properties ?? {};
69089
69132
  const keys = Object.keys(props);
69133
+ if (keys.length > 1) {
69134
+ return {
69135
+ kind: "give_up",
69136
+ reason: `"${best.tool.name}" has ${keys.length} fields (${keys.join(", ")}). Turning a goal into several fields takes ` + `a model, and delegate_goal has one with Deputy Pro: ${BUY_URL}`
69137
+ };
69138
+ }
69090
69139
  const args = {};
69091
69140
  if (keys.length === 1)
69092
69141
  args[keys[0]] = goal;
@@ -69095,7 +69144,7 @@ class HeuristicPlanner {
69095
69144
  async answer(_question, _pageText, _page) {
69096
69145
  return {
69097
69146
  answered: false,
69098
- text: "Deputy has no model configured, so it cannot read the page for you. Set OPENROUTER_API_KEY."
69147
+ text: `Deputy has no model here, so it cannot read the page for you. Deputy Pro adds one: ${BUY_URL}`
69099
69148
  };
69100
69149
  }
69101
69150
  }
@@ -69148,7 +69197,7 @@ class OpenRouterPlanner {
69148
69197
  modelUsage.promptTokens += Number(u.prompt_tokens ?? 0);
69149
69198
  modelUsage.completionTokens += Number(u.completion_tokens ?? 0);
69150
69199
  modelUsage.costUsd += Number(u.cost ?? 0);
69151
- console.log(` [deputy model] call #${modelUsage.calls} ` + `${u.prompt_tokens ?? 0} in / ${u.completion_tokens ?? 0} out $${Number(u.cost ?? 0).toFixed(6)}`);
69200
+ console.error(` [deputy model] call #${modelUsage.calls} ` + `${u.prompt_tokens ?? 0} in / ${u.completion_tokens ?? 0} out $${Number(u.cost ?? 0).toFixed(6)}`);
69152
69201
  const text = String(body?.choices?.[0]?.message?.content ?? "").trim();
69153
69202
  if (!text)
69154
69203
  return { ok: false, text: "Deputy's model returned an empty response." };
@@ -69179,7 +69228,7 @@ Question: ${question}`);
69179
69228
  description: t.description,
69180
69229
  inputSchema: t.inputSchema
69181
69230
  }));
69182
- const res = await this.complete("Pick exactly one tool to satisfy the goal and fill its arguments from the goal text. " + `Reply with JSON only: {"tool":"<name>","args":{...}}. Arguments must match the tool's ` + 'inputSchema. If no tool fits, reply {"tool":null,"reason":"<why>"}.', `Page: ${page.title} <${page.url}>
69231
+ const res = await this.complete("Pick exactly one tool to satisfy the goal and fill its arguments from the goal text. " + `Reply with JSON only: {"tool":"<name>","args":{...},"missing":[...]}. Arguments must match the tool's ` + `inputSchema. "missing" lists, in the goal's words, each value the goal gives that no argument can ` + "hold (for example a field the tool lacks); leave it empty when everything fits. " + 'If no tool fits, reply {"tool":null,"reason":"<why>"}.', `Page: ${page.title} <${page.url}>
69183
69232
 
69184
69233
  Tools:
69185
69234
  ${JSON.stringify(catalogue, null, 1)}
@@ -69199,7 +69248,13 @@ Goal: ${goal}`);
69199
69248
  reason: `Deputy's model picked "${parsed.tool}", which this page does not expose. Available: ${tools.map((t) => t.name).join(", ")}.`
69200
69249
  };
69201
69250
  }
69202
- return { kind: "call", tool: String(parsed.tool), args: parsed.args ?? {} };
69251
+ const missing = Array.isArray(parsed.missing) ? parsed.missing.map(String).filter(Boolean) : [];
69252
+ return {
69253
+ kind: "call",
69254
+ tool: String(parsed.tool),
69255
+ args: parsed.args ?? {},
69256
+ ...missing.length ? { missing } : {}
69257
+ };
69203
69258
  }
69204
69259
  }
69205
69260
  function ownKeyFailure(status) {
@@ -69225,11 +69280,41 @@ function parseJsonish(text) {
69225
69280
  }
69226
69281
  return null;
69227
69282
  }
69228
- function makePlanner() {
69229
- const apiKey = process.env.OPENROUTER_API_KEY;
69283
+ function makePlanner(env = process.env) {
69284
+ const apiKey = env.OPENROUTER_API_KEY;
69230
69285
  if (!apiKey)
69231
69286
  return new HeuristicPlanner;
69232
- return new OpenRouterPlanner({ apiKey, model: process.env.OPENROUTER_MODEL || "qwen/qwen3.7-flash" });
69287
+ return new OpenRouterPlanner({ apiKey, model: env.OPENROUTER_MODEL || "qwen/qwen3.7-flash" });
69288
+ }
69289
+ var configPath = () => process.env.DEPUTY_CONFIG || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "deputy", "env");
69290
+ function readSettings(path = configPath()) {
69291
+ let body;
69292
+ try {
69293
+ body = readFileSync(path, "utf8");
69294
+ } catch {
69295
+ return {};
69296
+ }
69297
+ const out = {};
69298
+ for (const line of body.split(/\r?\n/)) {
69299
+ const m = line.match(/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$/i);
69300
+ if (m)
69301
+ out[m[1]] = m[2].replace(/^(['"])(.*)\1$/, "$2");
69302
+ }
69303
+ return out;
69304
+ }
69305
+ var settings = null;
69306
+ var own2 = null;
69307
+ function ownPlanner() {
69308
+ if (!settings || Date.now() - settings.at > 2000)
69309
+ settings = { at: Date.now(), values: readSettings() };
69310
+ const env = {
69311
+ OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY || settings.values.OPENROUTER_API_KEY,
69312
+ OPENROUTER_MODEL: process.env.OPENROUTER_MODEL || settings.values.OPENROUTER_MODEL
69313
+ };
69314
+ const id = `${env.OPENROUTER_API_KEY ?? ""}|${env.OPENROUTER_MODEL ?? ""}`;
69315
+ if (own2?.id !== id)
69316
+ own2 = { id, planner: makePlanner(env) };
69317
+ return own2.planner;
69233
69318
  }
69234
69319
 
69235
69320
  // packages/deputyd/src/excerpt.ts
@@ -69372,6 +69457,10 @@ async function needBrowser() {
69372
69457
  throw new Error(why);
69373
69458
  }
69374
69459
  function setLink(next) {
69460
+ if (next !== current) {
69461
+ mine = null;
69462
+ opened.clear();
69463
+ }
69375
69464
  current = next;
69376
69465
  accessChanged();
69377
69466
  }
@@ -69416,22 +69505,23 @@ var link = {
69416
69505
  return false;
69417
69506
  }
69418
69507
  };
69419
- var planner = makePlanner();
69508
+ var planner = () => ownPlanner();
69420
69509
  var proCache = null;
69421
69510
  async function proConfig() {
69422
69511
  if (proCache && Date.now() - proCache.at < 30000)
69423
69512
  return proCache.cfg;
69424
- const settings = await link.call({ op: "settings" }).catch(() => null);
69425
- proCache = { at: Date.now(), cfg: resolveProConfig(settings) };
69513
+ const settings2 = await link.call({ op: "settings" }).catch(() => null);
69514
+ proCache = { at: Date.now(), cfg: resolveProConfig(settings2) };
69426
69515
  return proCache.cfg;
69427
69516
  }
69428
69517
  var proPlanners = new Map;
69429
69518
  async function activePlanner() {
69430
- if (!(planner instanceof HeuristicPlanner))
69431
- return planner;
69519
+ const own3 = planner();
69520
+ if (!(own3 instanceof HeuristicPlanner))
69521
+ return own3;
69432
69522
  const pro = await proConfig();
69433
69523
  if (!pro.licenseKey || !pro.url || onFreeTier())
69434
- return planner;
69524
+ return own3;
69435
69525
  const id = `${pro.url}|${pro.licenseKey}`;
69436
69526
  if (!proPlanners.has(id)) {
69437
69527
  proPlanners.set(id, new OpenRouterPlanner({ apiKey: pro.licenseKey, model: "anthropic/claude-haiku-5.5", baseUrl: `${pro.url}/v1/chat` }));
@@ -69440,9 +69530,42 @@ async function activePlanner() {
69440
69530
  }
69441
69531
  var tasks = new TaskStore;
69442
69532
  var sleep2 = (ms2) => new Promise((r2) => setTimeout(r2, ms2));
69533
+ var mine = null;
69534
+ var opened = new Set;
69535
+ var elsewhere = (tabId) => current?.heldElsewhere?.(tabId) ?? false;
69536
+ function claim2(tab) {
69537
+ if (elsewhere(tab.tabId))
69538
+ return tab;
69539
+ mine = tab.tabId;
69540
+ current?.claim?.(tab.tabId);
69541
+ return tab;
69542
+ }
69543
+ var defaultTab2 = () => defaultTab(link.registry.tabs(), link.registry.activeTab()?.tabId ?? null, mine, elsewhere);
69544
+ function tabFor(tabId) {
69545
+ if (tabId != null)
69546
+ return claim2(link.registry.resolve(tabId));
69547
+ const tab = defaultTab2();
69548
+ if (tab)
69549
+ return claim2(tab);
69550
+ const busy = link.registry.activeTab() ?? (link.registry.tabs().length === 1 ? link.registry.tabs()[0] : null);
69551
+ if (busy && elsewhere(busy.tabId)) {
69552
+ throw new Error(`Another agent is working in the active tab (${busy.title}). Open a page of your own with browser_navigate ` + "(it opens a new tab), or pass the tabId of a tab you opened.");
69553
+ }
69554
+ return claim2(link.registry.resolve());
69555
+ }
69556
+ function findTool(name, tabId) {
69557
+ if (tabId != null)
69558
+ return link.registry.findTool(name, tabId);
69559
+ for (const tab of [defaultTab2(), ...link.registry.tabs().filter((t2) => !elsewhere(t2.tabId))]) {
69560
+ const tool = tab?.tools.find((t2) => t2.name === name);
69561
+ if (tool)
69562
+ return { tab, tool };
69563
+ }
69564
+ return null;
69565
+ }
69443
69566
  async function page(tabId, call, args = {}) {
69444
69567
  await needBrowser();
69445
- const tab = link.registry.resolve(tabId);
69568
+ const tab = tabFor(tabId);
69446
69569
  return link.call({ op: "page", tabId: tab.tabId, call, args });
69447
69570
  }
69448
69571
  var MIME = {
@@ -69621,20 +69744,25 @@ ${String(text2).trim()}`;
69621
69744
  async function pageText(tab) {
69622
69745
  const looksPdf = /\.pdf($|[?#])/i.test(tab.url);
69623
69746
  if (!looksPdf) {
69624
- try {
69625
- const t2 = String(await link.call({ op: "read", tabId: tab.tabId }) ?? "");
69626
- if (t2)
69627
- return t2;
69628
- } catch (err) {
69629
- if (!/Receiving end|Could not establish/i.test(String(err)))
69630
- throw err;
69747
+ for (let attempt = 0;attempt < 6; attempt++) {
69748
+ try {
69749
+ const t2 = String(await link.call({ op: "read", tabId: tab.tabId }) ?? "");
69750
+ if (t2)
69751
+ return t2;
69752
+ break;
69753
+ } catch (err) {
69754
+ if (!/Receiving end|Could not establish/i.test(String(err)))
69755
+ throw err;
69756
+ await sleep2(500);
69757
+ }
69631
69758
  }
69632
69759
  }
69633
69760
  if (!/^https?:|^file:/.test(tab.url))
69634
69761
  throw new Error(`Deputy cannot read ${tab.url}.`);
69635
69762
  const got = await link.call({ op: "fetch", tabId: tab.tabId, url: tab.url });
69636
- if (!looksPdf && !/pdf/i.test(got.contentType))
69637
- throw new Error(`Deputy cannot read ${tab.url} (no content script, and it is not a PDF).`);
69763
+ if (!looksPdf && !/pdf/i.test(got.contentType)) {
69764
+ throw new Error(`Deputy cannot read ${tab.url} yet: the page has not loaded Deputy. Try again in a moment; if it keeps failing, reload the tab.`);
69765
+ }
69638
69766
  return pdfText(Buffer.from(got.data, "base64"));
69639
69767
  }
69640
69768
  async function pagePixels(t2) {
@@ -69703,11 +69831,11 @@ var SEARCH_HINTS = {
69703
69831
  browser_capabilities: "page forms tools actions refs what can I do",
69704
69832
  browser_downloads: "download downloaded file saved export csv pdf report"
69705
69833
  };
69706
- var INSTRUCTIONS = "Deputy drives the user's real browser. Start with browser_navigate: its result lists the page's forms as typed tools with JSON Schemas, plus clickable actions with refs. Fill a whole form with ONE " + "browser_invoke call — those page tools are not MCP tools, never search for them. For anything else use " + "browser_act with a ref; every action result says what changed on the page, so you rarely need to check. Read with browser_ask/browser_read/browser_extract; use browser_screenshot only when you must see pixels. Without Deputy Pro only the free tools are listed: act with browser_click/browser_fill. If the user needs one that is missing (screenshots, tabs, scrolling, console, network and more), Deputy Pro adds it: https://deputy.razin.ai/buy.";
69834
+ var INSTRUCTIONS = "Deputy drives the user's real browser. Start with browser_navigate: its result lists the page's forms as typed tools with JSON Schemas, plus clickable actions with refs. Fill a whole form with ONE " + "browser_invoke call — those page tools are not MCP tools, never search for them. For anything else use " + "browser_act with a ref; every action result says what changed on the page, so you rarely need to check. Read with browser_ask/browser_read/browser_extract; use browser_screenshot only when you must see pixels. Without Deputy Pro only the free tools are listed: act with browser_click/browser_fill. If the user needs one that is missing (acting by visible text, screenshots, tabs, scrolling, console, network and more), Deputy Pro adds it: https://deputy.razin.ai/buy.";
69707
69835
  var json = (v2) => text(JSON.stringify(v2, null, 2));
69708
69836
  async function runGoal(taskId, goal, tabId) {
69709
69837
  await needBrowser();
69710
- const tab = link.registry.resolve(tabId);
69838
+ const tab = tabFor(tabId);
69711
69839
  tasks.progress(taskId, `looking at ${tab.title} (${tab.url})`);
69712
69840
  if (tab.tools.length === 0) {
69713
69841
  tasks.fail(taskId, `${tab.url} exposes no tools, even after grafting. It may have no forms.`);
@@ -69722,10 +69850,22 @@ async function runGoal(taskId, goal, tabId) {
69722
69850
  tasks.needsInput(taskId, decision.question);
69723
69851
  return;
69724
69852
  }
69853
+ const fields = Object.keys(tab.tools.find((t2) => t2.name === decision.tool)?.inputSchema?.properties ?? {});
69854
+ if (fields.length && !Object.keys(decision.args).length) {
69855
+ tasks.fail(taskId, `Nothing in the goal fills "${decision.tool}" (fields: ${fields.join(", ")}). Fill it yourself with browser_invoke.`);
69856
+ return;
69857
+ }
69725
69858
  tasks.progress(taskId, `calling ${decision.tool} with ${JSON.stringify(decision.args)}`);
69726
69859
  try {
69727
69860
  const result = await link.call({ op: "invoke", tabId: tab.tabId, tool: decision.tool, args: decision.args });
69728
- tasks.complete(taskId, { tool: decision.tool, args: decision.args, result });
69861
+ tasks.complete(taskId, {
69862
+ tool: decision.tool,
69863
+ args: decision.args,
69864
+ result,
69865
+ ...decision.missing?.length ? {
69866
+ notDone: `The form has no field for: ${decision.missing.join("; ")}. Deputy did not set ${decision.missing.length === 1 ? "it" : "them"}. Look for the control in browser_capabilities actions and set it with browser_fill or browser_click.`
69867
+ } : {}
69868
+ });
69729
69869
  } catch (err) {
69730
69870
  tasks.fail(taskId, String(err instanceof Error ? err.message : err));
69731
69871
  }
@@ -69780,7 +69920,7 @@ function describeResult(result) {
69780
69920
  return summary.length > 160 ? `${summary.slice(0, 157)}…` : summary;
69781
69921
  }
69782
69922
  async function reported(tool, args, run) {
69783
- const tabOf = () => typeof args?.tabId === "number" ? args.tabId : link.registry.activeTab()?.tabId;
69923
+ const tabOf = () => typeof args?.tabId === "number" ? args.tabId : defaultTab2()?.tabId;
69784
69924
  const tell = (tabId, entry2) => {
69785
69925
  if (tabId == null || !current)
69786
69926
  return;
@@ -69803,7 +69943,7 @@ async function reported(tool, args, run) {
69803
69943
  }
69804
69944
  }
69805
69945
  function buildServer() {
69806
- const server = new McpServer({ name: "deputy", version: "0.1.4" }, { instructions: INSTRUCTIONS });
69946
+ const server = new McpServer({ name: "deputy", version: "0.1.6" }, { instructions: INSTRUCTIONS });
69807
69947
  const register2 = server.registerTool.bind(server);
69808
69948
  const tools = new Map;
69809
69949
  server.registerTool = (name, config2, handler) => {
@@ -69840,6 +69980,7 @@ function buildServer() {
69840
69980
  title: t2.title,
69841
69981
  url: t2.url,
69842
69982
  active: t2.tabId === link.registry.activeTab()?.tabId,
69983
+ ...elsewhere(t2.tabId) ? { anotherAgent: true } : {},
69843
69984
  tools: t2.tools.map((x2) => ({
69844
69985
  name: x2.name,
69845
69986
  description: x2.description,
@@ -69868,11 +70009,11 @@ function buildServer() {
69868
70009
  return consent;
69869
70010
  return text(await decideApproval(resumed, consent === "granted" ? "submit" : "cancel"));
69870
70011
  }
69871
- let found = link.registry.findTool(tool, tabId);
70012
+ let found = findTool(tool, tabId);
69872
70013
  if (!found) {
69873
70014
  const tab = (() => {
69874
70015
  try {
69875
- return link.registry.resolve(tabId);
70016
+ return tabFor(tabId);
69876
70017
  } catch {
69877
70018
  return null;
69878
70019
  }
@@ -69880,12 +70021,13 @@ function buildServer() {
69880
70021
  const fresh = tab ? await link.call({ op: "annotate", tabId: tab.tabId }).catch(() => null) : null;
69881
70022
  if (fresh?.tabId != null && Array.isArray(fresh.tools))
69882
70023
  link.registry.upsert(fresh);
69883
- found = link.registry.findTool(tool, tabId);
70024
+ found = findTool(tool, tabId);
69884
70025
  }
69885
70026
  if (!found) {
69886
70027
  const available = link.registry.tabs().flatMap((t2) => t2.tools.map((x2) => x2.name));
69887
70028
  return text(`No tool "${tool}" in the browser. Available: ${available.join(", ") || "none"}.`);
69888
70029
  }
70030
+ claim2(found.tab);
69889
70031
  const call = { op: "invoke", tabId: found.tab.tabId, tool: found.tool.frameTool ?? tool, frameId: found.tool.frameId, args: args ?? {} };
69890
70032
  if (found.tool.consequential) {
69891
70033
  const elicit = canElicit(ctx, server);
@@ -69934,7 +70076,7 @@ ${now ? await pageSummary(now) : "It returned no value."}`);
69934
70076
  })
69935
70077
  }, async ({ ref, value, tabId }) => {
69936
70078
  await needBrowser();
69937
- const tab = link.registry.resolve(tabId);
70079
+ const tab = tabFor(tabId);
69938
70080
  return text(String(await link.call({ op: "fill", tabId: tab.tabId, ref, value })));
69939
70081
  });
69940
70082
  server.registerTool("browser_click", {
@@ -69947,20 +70089,20 @@ ${now ? await pageSummary(now) : "It returned no value."}`);
69947
70089
  }, async ({ ref, tabId }) => {
69948
70090
  const r2 = String(await page(tabId, "act", { ref, action: "click" }));
69949
70091
  await sleep2(300);
69950
- const tab = link.registry.resolve(tabId);
70092
+ const tab = tabFor(tabId);
69951
70093
  return text(`${r2}${tab.url ? `
69952
70094
  The tab is on ${tab.title} <${tab.url}>.` : ""}`);
69953
70095
  });
69954
70096
  server.registerTool("browser_read", {
69955
70097
  title: "Read a page as text",
69956
- description: "Return the page as plain text for you to read yourself. Use browser_ask instead when you only need one fact: with a model (Deputy Pro or OPENROUTER_API_KEY) Deputy reads the page and answers in a sentence. Use this when you genuinely need the content to reason over.",
70098
+ description: "Return the page as plain text for you to read yourself. Use browser_ask instead when you only need one fact: with Deputy Pro, Deputy reads the page and answers in a sentence. Use this when you genuinely need the content to reason over.",
69957
70099
  inputSchema: object({
69958
70100
  tabId: number2().optional(),
69959
70101
  maxChars: number2().optional().describe("Cap the returned text (default 6000).")
69960
70102
  })
69961
70103
  }, async ({ tabId, maxChars }) => {
69962
70104
  await needBrowser();
69963
- const tab = link.registry.resolve(tabId);
70105
+ const tab = tabFor(tabId);
69964
70106
  const full = await pageText(tab);
69965
70107
  const cap = Math.max(200, Math.min(maxChars ?? 6000, 40000));
69966
70108
  const body = full.slice(0, cap);
@@ -69973,7 +70115,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
69973
70115
  });
69974
70116
  server.registerTool("browser_navigate", {
69975
70117
  title: "Open a URL, or go back, forward or reload",
69976
- description: 'Point a tab at a URL and wait for it to load, or move through its history with action "back" / "forward", or "reload" it. Deputy re-reads what the new page can do, so call browser_capabilities afterwards to see the tools that appeared.',
70118
+ description: `Point a tab at a URL and wait for it to load, or move through its history with action "back" / "forward", or "reload" it. Deputy re-reads what the new page can do, so call browser_capabilities afterwards to see the tools that appeared. Without a tabId, the first URL opens a tab of your own and later calls stay in it, so the user's page and other agents' tabs are left alone; other tools act on that tab too. To work on the page the user has open, pass its tabId (browser_capabilities marks it active).`,
69977
70119
  inputSchema: object({
69978
70120
  url: string2().optional().describe("Absolute URL to open."),
69979
70121
  action: _enum(["back", "forward", "reload"]).optional().describe("Instead of a URL: move through history, or reload."),
@@ -69982,14 +70124,20 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
69982
70124
  }, async ({ url: url2, action, tabId }) => {
69983
70125
  await needBrowser();
69984
70126
  const describe2 = (after) => {
69985
- if (after?.tabId != null && Array.isArray(after.tools))
70127
+ if (after?.tabId != null && Array.isArray(after.tools)) {
69986
70128
  link.registry.upsert(after, true);
70129
+ claim2(after);
70130
+ }
69987
70131
  return pageSummary(after);
69988
70132
  };
69989
- if (url2 && !action && tabId == null && !link.registry.activeTab()) {
69990
- return text(await describe2(await link.call({ op: "tabs", action: "open", url: url2 })));
69991
- }
69992
- const tab = link.registry.resolve(tabId);
70133
+ const own3 = defaultTab2();
70134
+ if (url2 && !action && tabId == null && !(own3 && opened.has(own3.tabId))) {
70135
+ const fresh = await link.call({ op: "tabs", action: "open", url: url2 });
70136
+ if (fresh?.tabId != null)
70137
+ opened.add(fresh.tabId);
70138
+ return text(await describe2(fresh));
70139
+ }
70140
+ const tab = tabFor(tabId);
69993
70141
  if (action) {
69994
70142
  const res = await link.call({ op: "history", tabId: tab.tabId, action });
69995
70143
  if (!res?.moved)
@@ -70010,6 +70158,19 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70010
70158
  })
70011
70159
  }, async ({ action, url: url2, tabId }) => {
70012
70160
  const r2 = await link.call({ op: "tabs", action, url: url2, tabId });
70161
+ if (action === "open" && r2?.tabId != null) {
70162
+ opened.add(r2.tabId);
70163
+ claim2(r2);
70164
+ }
70165
+ if (action === "select" && tabId != null) {
70166
+ const t2 = link.registry.tabs().find((x2) => x2.tabId === tabId);
70167
+ if (t2)
70168
+ claim2(t2);
70169
+ }
70170
+ if (action === "close" && tabId === mine)
70171
+ mine = null;
70172
+ if (action === "list" && Array.isArray(r2))
70173
+ return json(r2.map((t2) => elsewhere(t2.tabId) ? { ...t2, anotherAgent: true } : t2));
70013
70174
  return text(action === "open" && r2?.tools ? await pageSummary(r2, "Opened") : JSON.stringify(r2, null, 2));
70014
70175
  });
70015
70176
  server.registerTool("browser_wait", {
@@ -70024,7 +70185,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70024
70185
  })
70025
70186
  }, async ({ text: t2, textGone, selector, timeoutMs, tabId }) => {
70026
70187
  await needBrowser();
70027
- const tab = link.registry.resolve(tabId);
70188
+ const tab = tabFor(tabId);
70028
70189
  return text(String(await link.call({ op: "wait", tabId: tab.tabId, text: t2, textGone, selector, timeoutMs })));
70029
70190
  });
70030
70191
  server.registerTool("browser_screenshot", {
@@ -70040,7 +70201,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70040
70201
  })
70041
70202
  }, async ({ fullPage, ref, selector, format, maxDimension, tabId }) => {
70042
70203
  await needBrowser();
70043
- const tab = link.registry.resolve(tabId);
70204
+ const tab = tabFor(tabId);
70044
70205
  const shot = await link.call({ op: "screenshot", tabId: tab.tabId, fullPage, ref, selector, format, maxDimension });
70045
70206
  return {
70046
70207
  content: [
@@ -70070,9 +70231,10 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70070
70231
  }, async ({ tabId, ...args }) => json(await page(tabId, "find", args)));
70071
70232
  server.registerTool("browser_act", {
70072
70233
  title: "Act on an element",
70073
- description: 'Do one thing to an element: click, double_click, right_click, hover, focus, type (value; replaces unless append), press (keys like "Enter", "Tab", "Escape", "ArrowDown", "Control+a"; without a target, presses on the focused element), check, uncheck, select (value = option label or value, native or custom dropdown), clear, scroll_into_view. Typing is sent key by key so autocompletes react. The result reports any dialog or error the action caused. For whole forms, prefer browser_invoke with the typed tool.',
70234
+ description: `Do one thing to an element: click, double_click, right_click, hover, focus, type (value; replaces unless append), press (keys like "Enter", "Tab", "Escape", "ArrowDown", "Control+a"; without a target, presses on the focused element), check, uncheck, select (value = option label or value, native or custom dropdown), clear, scroll_into_view. Typing is sent key by key so autocompletes react. The result reports any dialog or error the action caused. For whole forms, prefer browser_invoke with the typed tool. With no ref, text names the element as the page shows it (a button's words, a field's label): browser_act({ text: "Save", action: "click" }).`,
70074
70235
  inputSchema: object({
70075
70236
  ...target,
70237
+ text: string2().optional().describe("Visible text or label of the element, if you have no ref."),
70076
70238
  action: _enum(["click", "double_click", "right_click", "hover", "focus", "type", "press", "check", "uncheck", "select", "clear", "scroll_into_view"]).optional(),
70077
70239
  value: string2().optional().describe("Text to type, or the option to select."),
70078
70240
  keys: string2().optional().describe('For press: e.g. "Enter" or "Shift+Tab".'),
@@ -70082,6 +70244,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70082
70244
  steps: array(object({
70083
70245
  ref: string2().optional(),
70084
70246
  selector: string2().optional(),
70247
+ text: string2().optional(),
70085
70248
  action: _enum(["click", "double_click", "right_click", "hover", "focus", "type", "press", "check", "uncheck", "select", "clear", "scroll_into_view"]),
70086
70249
  value: string2().optional(),
70087
70250
  keys: string2().optional(),
@@ -70191,7 +70354,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70191
70354
  if (!reset && width == null && height == null)
70192
70355
  return text("Pass width and height (CSS pixels), or reset: true to restore the window.");
70193
70356
  await needBrowser();
70194
- const tab = link.registry.resolve(tabId);
70357
+ const tab = tabFor(tabId);
70195
70358
  const r2 = await link.call({ op: "resize", tabId: tab.tabId, width, height, reset });
70196
70359
  if (reset) {
70197
70360
  if (r2.restored === false)
@@ -70210,7 +70373,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70210
70373
  inputSchema: object({ code: string2(), world: _enum(["main", "isolated"]).optional(), tabId: number2().optional() })
70211
70374
  }, async ({ code, world, tabId }) => {
70212
70375
  await needBrowser();
70213
- const tab = link.registry.resolve(tabId);
70376
+ const tab = tabFor(tabId);
70214
70377
  return json(await link.call({ op: "eval", tabId: tab.tabId, code, world }));
70215
70378
  });
70216
70379
  server.registerTool("browser_downloads", {
@@ -70238,7 +70401,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70238
70401
  inputSchema: object({ question: string2().optional(), tabId: number2().optional() })
70239
70402
  }, async ({ question, tabId }) => {
70240
70403
  await needBrowser();
70241
- const tab = link.registry.resolve(tabId);
70404
+ const tab = tabFor(tabId);
70242
70405
  const pro = await proConfig();
70243
70406
  if (!pro.licenseKey)
70244
70407
  return text(PRO_UPGRADE);
@@ -70258,7 +70421,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70258
70421
  })
70259
70422
  }, async ({ question, tabId }) => {
70260
70423
  await needBrowser();
70261
- const tab = link.registry.resolve(tabId);
70424
+ const tab = tabFor(tabId);
70262
70425
  const content = await pageText(tab).catch(() => "");
70263
70426
  const notes = [
70264
70427
  isVisualQuestion(question) ? `This asks how the page looks, which its text can't show: ${onFreeTier() ? "Deputy Pro's browser_screenshot does (https://deputy.razin.ai/buy)" : "browser_screenshot does"}.` : "",
@@ -70271,7 +70434,7 @@ The tab is on ${tab.title} <${tab.url}>.` : ""}`);
70271
70434
  const active = await activePlanner();
70272
70435
  let lead;
70273
70436
  if (active instanceof HeuristicPlanner) {
70274
- lead = "Deputy has no model configured, so here is the page text most relevant to your question";
70437
+ lead = "No answer: Deputy has no model here, so here instead is the page text most relevant to your question";
70275
70438
  } else {
70276
70439
  const answer = await active.answer(question, content, { title: tab.title, url: tab.url });
70277
70440
  if (answer.answered)
@@ -70283,7 +70446,7 @@ Meanwhile, here is the page text most relevant to your question`;
70283
70446
  const excerpt = relevantText(question, content, EXCERPT_BUDGET);
70284
70447
  const whole = excerpt.length >= content.length;
70285
70448
  return text(`${notes ? `${notes}
70286
- ` : ""}${lead} (${whole ? `all ${content.length}` : `${excerpt.length} of ${content.length}`} characters, in page order).` + (active instanceof HeuristicPlanner ? " With Deputy Pro (or OPENROUTER_API_KEY), browser_ask answers in a sentence instead." : "") + `
70449
+ ` : ""}${lead} (${whole ? `all ${content.length}` : `${excerpt.length} of ${content.length}`} characters, in page order).` + (active instanceof HeuristicPlanner ? ` With Deputy Pro, browser_ask answers in a sentence instead: ${BUY_URL}` : "") + `
70287
70450
 
70288
70451
  ${excerpt}` + (whole ? "" : `
70289
70452
 
@@ -70723,12 +70886,29 @@ var originHost = (origin) => {
70723
70886
  };
70724
70887
  async function startHub() {
70725
70888
  const registry2 = new Registry;
70726
- let ext = null;
70727
- const peers = new Set;
70889
+ const exts = new Map;
70890
+ let focus = null;
70891
+ const peers = new Map;
70892
+ const holds = new Holds;
70728
70893
  const pending = new Map;
70894
+ const primary = () => focus ?? [...exts.values()].at(-1) ?? null;
70895
+ const ownerOf = (tabId) => focus?.tabs.has(tabId) ? focus : [...exts.values()].find((e2) => e2.tabs.has(tabId)) ?? null;
70896
+ function rebuild() {
70897
+ const all = new Map;
70898
+ for (const e2 of exts.values())
70899
+ if (e2 !== focus)
70900
+ for (const [id, t2] of e2.tabs)
70901
+ all.set(id, t2);
70902
+ if (focus)
70903
+ for (const [id, t2] of focus.tabs)
70904
+ all.set(id, t2);
70905
+ registry2.reconcile([...all.values()], focus?.active ?? null);
70906
+ }
70729
70907
  function callExtension(msg) {
70730
70908
  return new Promise((resolve, reject) => {
70731
- if (!ext) {
70909
+ const tabId = msg.tabId;
70910
+ const target = (tabId != null ? ownerOf(tabId) : null) ?? primary();
70911
+ if (!target) {
70732
70912
  reject(new Error("Deputy can't reach the browser: the Deputy extension isn't connected. Make sure Chrome is open with the Deputy extension installed and enabled (https://razin.ai/deputy)."));
70733
70913
  return;
70734
70914
  }
@@ -70746,9 +70926,10 @@ async function startHub() {
70746
70926
  clearTimeout(timer);
70747
70927
  reject(e2);
70748
70928
  },
70749
- tabId: msg.op === "tabs" ? undefined : msg.tabId
70929
+ tabId: msg.op === "tabs" ? undefined : tabId,
70930
+ ws: target.ws
70750
70931
  });
70751
- ext.send(JSON.stringify({ id, ...msg }));
70932
+ target.ws.send(JSON.stringify({ id, ...msg }));
70752
70933
  });
70753
70934
  }
70754
70935
  function failCallsForTab(tabId) {
@@ -70759,12 +70940,8 @@ async function startHub() {
70759
70940
  }
70760
70941
  }
70761
70942
  }
70762
- let tabsReported = false;
70763
- let locked = null;
70764
- let free = null;
70765
- let off = [];
70766
70943
  const readyWaiters = new Set;
70767
- const isReady = () => ext !== null && tabsReported;
70944
+ const isReady = () => [...exts.values()].some((e2) => e2.reported);
70768
70945
  const wakeReady = () => {
70769
70946
  if (isReady()) {
70770
70947
  for (const w2 of readyWaiters)
@@ -70787,23 +70964,26 @@ async function startHub() {
70787
70964
  readyWaiters.add(done);
70788
70965
  });
70789
70966
  }
70967
+ const locked = () => primary()?.locked ?? null;
70968
+ const free = () => primary()?.free ?? null;
70969
+ const off = () => primary()?.off ?? [];
70790
70970
  const handler = createMcpHandler(buildServer);
70791
70971
  const serveMcp = toNodeHandler(handler);
70792
- const snapshot = () => JSON.stringify({
70972
+ const snapshot = (who) => JSON.stringify({
70793
70973
  t: "snapshot",
70794
70974
  tabs: registry2.tabs(),
70795
70975
  activeTabId: registry2.activeTab()?.tabId ?? null,
70796
- extension: ext !== null,
70797
- locked,
70798
- free,
70799
- off
70976
+ extension: exts.size > 0,
70977
+ locked: locked(),
70978
+ free: free(),
70979
+ off: off(),
70980
+ others: holds.others(who)
70800
70981
  });
70801
70982
  let notifyTimer;
70802
70983
  let lastVersion = registry2.version();
70803
70984
  const changed = () => {
70804
- const snap = snapshot();
70805
- for (const p2 of peers)
70806
- p2.send(snap);
70985
+ for (const [p2, who] of peers)
70986
+ p2.send(snapshot(who));
70807
70987
  clearTimeout(notifyTimer);
70808
70988
  notifyTimer = setTimeout(() => {
70809
70989
  const now = registry2.version();
@@ -70820,11 +71000,12 @@ async function startHub() {
70820
71000
  res.end(JSON.stringify({
70821
71001
  ok: true,
70822
71002
  deputy: true,
70823
- extensionConnected: ext !== null,
71003
+ extensionConnected: exts.size > 0,
71004
+ browsers: exts.size,
70824
71005
  peers: peers.size,
70825
71006
  tabs: registry2.tabs().length,
70826
71007
  tools: registry2.toolCount(),
70827
- planner: planner.name,
71008
+ planner: planner().name,
70828
71009
  deputyModelUsage: { ...modelUsage }
70829
71010
  }));
70830
71011
  return;
@@ -70845,7 +71026,8 @@ async function startHub() {
70845
71026
  server.on("upgrade", (req, socket, head) => {
70846
71027
  const { pathname } = new URL(req.url ?? "/", "http://127.0.0.1");
70847
71028
  const origin = req.headers.origin;
70848
- const allowed = pathname === "/ext" && (!origin || origin.startsWith("chrome-extension://")) || pathname === "/peer" && !origin;
71029
+ const only = process.env.DEPUTY_EXT_ID;
71030
+ const allowed = pathname === "/ext" && (only ? origin === `chrome-extension://${only}` : !origin || origin.startsWith("chrome-extension://")) || pathname === "/peer" && !origin;
70849
71031
  if (!allowed) {
70850
71032
  socket.write(`HTTP/1.1 403 Forbidden\r
70851
71033
  \r
@@ -70856,23 +71038,30 @@ async function startHub() {
70856
71038
  wss.handleUpgrade(req, socket, head, (ws2) => pathname === "/ext" ? onExtension(ws2) : onPeer(ws2));
70857
71039
  });
70858
71040
  function onExtension(ws2) {
70859
- ext = ws2;
70860
- log("extension connected");
71041
+ const me2 = { ws: ws2, tabs: new Map, active: null, reported: false, locked: null, free: null, off: [] };
71042
+ exts.set(ws2, me2);
71043
+ log(`extension connected (${exts.size} browser profile${exts.size === 1 ? "" : "s"})`);
70861
71044
  changed();
71045
+ const focusHere = () => {
71046
+ if (focus !== me2) {
71047
+ focus = me2;
71048
+ accessChanged();
71049
+ }
71050
+ };
70862
71051
  ws2.on("close", () => {
70863
- if (ext !== ws2)
70864
- return;
70865
- ext = null;
70866
- tabsReported = false;
70867
- locked = null;
70868
- free = null;
70869
- off = [];
70870
- accessChanged();
71052
+ exts.delete(ws2);
71053
+ if (focus === me2)
71054
+ focus = [...exts.values()].at(-1) ?? null;
70871
71055
  for (const [id, p2] of pending) {
70872
- p2.reject(new Error("The browser disconnected."));
70873
- pending.delete(id);
71056
+ if (p2.ws === ws2) {
71057
+ p2.reject(new Error("The browser disconnected."));
71058
+ pending.delete(id);
71059
+ }
70874
71060
  }
70875
- registry2.reconcile([], null);
71061
+ for (const tabId of me2.tabs.keys())
71062
+ holds.release(tabId);
71063
+ accessChanged();
71064
+ rebuild();
70876
71065
  changed();
70877
71066
  log("extension disconnected");
70878
71067
  });
@@ -70887,27 +71076,42 @@ async function startHub() {
70887
71076
  case "ping":
70888
71077
  return;
70889
71078
  case "tabs":
70890
- registry2.reconcile(msg.tabs, msg.activeTabId);
70891
- tabsReported = true;
71079
+ me2.tabs = new Map(msg.tabs.map((t2) => [t2.tabId, t2]));
71080
+ me2.active = msg.activeTabId != null && me2.tabs.has(msg.activeTabId) ? msg.activeTabId : null;
71081
+ me2.reported = true;
71082
+ if (!focus)
71083
+ focusHere();
71084
+ rebuild();
70892
71085
  wakeReady();
70893
71086
  break;
70894
71087
  case "tab":
70895
- registry2.upsert(msg.tab, msg.active);
71088
+ me2.tabs.set(msg.tab.tabId, msg.tab);
71089
+ if (msg.active) {
71090
+ me2.active = msg.tab.tabId;
71091
+ focusHere();
71092
+ }
71093
+ rebuild();
70896
71094
  break;
70897
71095
  case "tabGone":
70898
71096
  failCallsForTab(msg.tabId);
70899
- registry2.remove(msg.tabId);
71097
+ me2.tabs.delete(msg.tabId);
71098
+ if (me2.active === msg.tabId)
71099
+ me2.active = null;
71100
+ holds.release(msg.tabId);
71101
+ rebuild();
70900
71102
  break;
70901
71103
  case "activeTab":
70902
- registry2.setActive(msg.tabId);
71104
+ me2.active = me2.tabs.has(msg.tabId) ? msg.tabId : null;
71105
+ focusHere();
71106
+ rebuild();
70903
71107
  break;
70904
71108
  case "license":
70905
- locked = msg.ok ? null : msg.message ?? "Deputy needs a Deputy Pro license key.";
70906
- free = msg.ok && msg.pro === false ? msg.message ?? "" : null;
71109
+ me2.locked = msg.ok ? null : msg.message ?? "Deputy needs a Deputy Pro license key.";
71110
+ me2.free = msg.ok && msg.pro === false ? msg.message ?? "" : null;
70907
71111
  accessChanged();
70908
71112
  break;
70909
71113
  case "access":
70910
- off = parseOff(msg.off);
71114
+ me2.off = parseOff(msg.off);
70911
71115
  accessChanged();
70912
71116
  break;
70913
71117
  case "reply": {
@@ -70923,9 +71127,14 @@ async function startHub() {
70923
71127
  });
70924
71128
  }
70925
71129
  function onPeer(ws2) {
70926
- peers.add(ws2);
70927
- ws2.send(snapshot());
70928
- ws2.on("close", () => peers.delete(ws2));
71130
+ const who = randomUUID2();
71131
+ peers.set(ws2, who);
71132
+ ws2.send(snapshot(who));
71133
+ ws2.on("close", () => {
71134
+ peers.delete(ws2);
71135
+ holds.drop(who);
71136
+ changed();
71137
+ });
70929
71138
  ws2.on("message", (raw) => {
70930
71139
  let msg;
70931
71140
  try {
@@ -70933,6 +71142,11 @@ async function startHub() {
70933
71142
  } catch {
70934
71143
  return;
70935
71144
  }
71145
+ if (msg.t === "claim") {
71146
+ holds.claim(msg.tabId, who);
71147
+ changed();
71148
+ return;
71149
+ }
70936
71150
  if (msg.t !== "call")
70937
71151
  return;
70938
71152
  const reply = (r2) => {
@@ -70953,11 +71167,24 @@ async function startHub() {
70953
71167
  if (!bound)
70954
71168
  return null;
70955
71169
  return {
70956
- link: { registry: registry2, call: callExtension, ready, locked: () => locked, free: () => free, off: () => off },
71170
+ link: {
71171
+ registry: registry2,
71172
+ call: callExtension,
71173
+ ready,
71174
+ locked,
71175
+ free,
71176
+ off,
71177
+ claim: (tabId) => {
71178
+ holds.claim(tabId, "hub");
71179
+ changed();
71180
+ },
71181
+ heldElsewhere: (tabId) => holds.heldElsewhere(tabId, "hub")
71182
+ },
70957
71183
  close: () => new Promise((r2) => {
70958
- for (const p2 of peers)
71184
+ for (const p2 of peers.keys())
70959
71185
  p2.terminate();
70960
- ext?.terminate();
71186
+ for (const e2 of exts.keys())
71187
+ e2.terminate();
70961
71188
  wss.close();
70962
71189
  server.closeAllConnections();
70963
71190
  server.close(() => r2());
@@ -70972,16 +71199,18 @@ function joinHub() {
70972
71199
  const ws2 = new wrapper_default(`ws://127.0.0.1:${PORT}/peer`);
70973
71200
  const registry2 = new Registry;
70974
71201
  const pending = new Map;
70975
- let opened = false;
71202
+ let opened2 = false;
70976
71203
  let extension2 = false;
70977
71204
  let locked = null;
70978
71205
  let free = null;
70979
71206
  let off = [];
71207
+ let others = new Map;
71208
+ const claimed = new Map;
70980
71209
  const waiters = new Set;
70981
71210
  let closeHub;
70982
71211
  const closed = new Promise((r2) => closeHub = r2);
70983
71212
  ws2.on("open", () => {
70984
- opened = true;
71213
+ opened2 = true;
70985
71214
  resolve({
70986
71215
  closed,
70987
71216
  link: {
@@ -70989,6 +71218,15 @@ function joinHub() {
70989
71218
  locked: () => locked,
70990
71219
  free: () => free,
70991
71220
  off: () => off,
71221
+ claim(tabId) {
71222
+ claimed.set(tabId, Date.now());
71223
+ if (ws2.readyState === ws2.OPEN)
71224
+ ws2.send(JSON.stringify({ t: "claim", tabId }));
71225
+ },
71226
+ heldElsewhere(tabId) {
71227
+ const at2 = others.get(tabId);
71228
+ return at2 != null && Date.now() - at2 < HOLD_MS && (claimed.get(tabId) ?? 0) < at2;
71229
+ },
70992
71230
  ready(timeoutMs) {
70993
71231
  if (extension2)
70994
71232
  return Promise.resolve(true);
@@ -71037,6 +71275,7 @@ function joinHub() {
71037
71275
  if (msg.t === "snapshot") {
71038
71276
  registry2.reconcile(msg.tabs, msg.activeTabId);
71039
71277
  extension2 = msg.extension;
71278
+ others = new Map(msg.others ?? []);
71040
71279
  locked = msg.locked ?? null;
71041
71280
  const nextFree = msg.free ?? null;
71042
71281
  const nextOff = msg.off ?? [];
@@ -71059,7 +71298,7 @@ function joinHub() {
71059
71298
  msg.ok ? p2.resolve(msg.result) : p2.reject(new Error(msg.error));
71060
71299
  });
71061
71300
  ws2.on("error", () => {
71062
- if (!opened)
71301
+ if (!opened2)
71063
71302
  resolve(null);
71064
71303
  });
71065
71304
  ws2.on("close", () => {
@@ -71081,7 +71320,7 @@ async function stayAttached() {
71081
71320
  const hub = await startHub();
71082
71321
  if (hub) {
71083
71322
  setLink(hub.link);
71084
- log(`hub on 127.0.0.1:${PORT} · planner: ${planner.name}`);
71323
+ log(`hub on 127.0.0.1:${PORT} · planner: ${planner().name}`);
71085
71324
  return new Promise(() => {});
71086
71325
  }
71087
71326
  const peer = await joinHub();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deputy-mcp",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "mcpName": "io.github.zraisan/deputy",
5
5
  "description": "Deputy's MCP bridge: Claude Code, Codex, Cursor and any MCP client use the pages in your browser as typed tools. Needs the Deputy Chrome extension; free to start, Deputy Pro adds 17 tools and hosted models.",
6
6
  "type": "module",