taskwindow 0.2.19 → 0.2.21

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
@@ -87,6 +87,15 @@ too. Loaded unpacked before the store listing existed? Remove that copy in
87
87
  taking the daemon connection from each other. For another MCP client, connect to `http://127.0.0.1:9377/mcp` with
88
88
  `Authorization: Bearer <token>`; the token is stored in `~/.taskwindow/token`.
89
89
 
90
+ A local broker such as Ateam can keep that bearer on the browser host and use
91
+ `/mcp/session/<uuid>` for a single approved session. Choose a fresh UUID for
92
+ each grant and stop forwarding when it ends. The scoped endpoint lists single
93
+ tab operations and binds every call to the session’s own Chrome group, even
94
+ when **All tabs** is enabled. Check `scopedSessions` on `/health` to confirm
95
+ both the daemon and the connected extension support it. Bind consent to that
96
+ Chrome connection by retaining its `scopedConnectionId` and sending it as
97
+ `X-TaskWindow-Connection` on each call. A changed connection requires new consent.
98
+
90
99
  ## What the agent gets
91
100
 
92
101
  | Area | Tools |
@@ -98,6 +107,72 @@ taking the daemon connection from each other. For another MCP client, connect to
98
107
  | Debug | `read_console_messages`, `read_network_requests` |
99
108
  | Efficiency | `browser_batch` (multi-step in one call), `gif_record`, `set_viewport` (responsive view), `shortcuts_*` |
100
109
 
110
+ The page tools (`read_page`, `find`, `get_page_text`, `form_input`,
111
+ `file_upload`, `upload_image` and clicks by ref) read same-origin iframes as
112
+ part of the page, so an app that shows its pages inside its own shell frame
113
+ works like any other. A cross-origin iframe stays a single `iframe` line.
114
+
115
+ ## Flows: a script instead of twenty turns
116
+
117
+ A job an agent repeats, such as filling the same long form every day, does not
118
+ need a model turn per field. The agent works the page out once, writes a
119
+ script, and from then on runs the script: one turn, the same steps every time.
120
+ TaskWindow needs nothing extra for this, because a script can call the same
121
+ tools the agent does. Each call is one HTTP request to the daemon, with no
122
+ handshake before it.
123
+
124
+ ```js
125
+ // node flow.mjs <sessionToken> values.json [photo.jpg]
126
+ import { readFileSync } from "node:fs";
127
+ import { homedir } from "node:os";
128
+ import { basename } from "node:path";
129
+
130
+ const [sessionToken, valuesFile, photo] = process.argv.slice(2);
131
+ const token = process.env.TASKWINDOW_TOKEN || readFileSync(`${homedir()}/.taskwindow/token`, "utf8").trim();
132
+
133
+ async function tool(name, args = {}) {
134
+ const res = await fetch(`http://127.0.0.1:${process.env.TASKWINDOW_PORT || 9377}/mcp`, {
135
+ method: "POST",
136
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
137
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: { sessionToken, ...args } } }),
138
+ });
139
+ const { result, error } = await res.json();
140
+ const text = (result?.content || []).filter((c) => c.type === "text").map((c) => c.text).join("\n");
141
+ if (error || result?.isError) throw new Error(error?.message || text);
142
+ return text;
143
+ }
144
+
145
+ // The page side, written once. It runs in the page; the values arrive as data, never as code.
146
+ function fill(values) {
147
+ const now = {};
148
+ for (const [selector, value] of Object.entries(values)) {
149
+ const field = document.querySelector(selector);
150
+ if (!field) { now[selector] = "no such field"; continue; }
151
+ field.value = value;
152
+ field.dispatchEvent(new Event("input", { bubbles: true }));
153
+ field.dispatchEvent(new Event("change", { bubbles: true }));
154
+ now[selector] = field.value; // read back, so the caller sees what the page kept
155
+ }
156
+ return now;
157
+ }
158
+
159
+ const values = JSON.parse(readFileSync(valuesFile, "utf8"));
160
+ console.log(await tool("javascript_execute", { code: `(${fill})(${JSON.stringify(values)})` }));
161
+
162
+ // A file goes from disk to the page; the model never carries its bytes.
163
+ if (photo) {
164
+ const data = readFileSync(photo).toString("base64");
165
+ console.log(await tool("file_upload", { selector: "input[type=file]", files: [{ name: basename(photo), data }] }));
166
+ }
167
+ ```
168
+
169
+ The agent passes the script the `sessionToken` it got from `tabs_create`, so
170
+ the script acts on that session's tabs and nothing else, like the agent itself.
171
+ The script reads its own files, with its own rights. A failed tool call comes
172
+ back with `isError`, which the helper above turns into an exception, so a page
173
+ that has changed stops the script and the agent takes over with the ordinary
174
+ tools.
175
+
101
176
  ## Wonder: when synthetic input is not enough
102
177
 
103
178
  Some pages ignore a perfect click. A single wheel event carrying 1600px gives
@@ -138,7 +213,9 @@ in the mouse-dynamics literature, so do not build on it as camouflage.
138
213
  scoped to that session's groups, so concurrent agents never share tabs —
139
214
  even when they pick the same task name. By default the agent can only see
140
215
  and act on tabs in its own groups — never yours. You can click a group in
141
- the toolbar popover to watch, and widen access in settings.
216
+ the toolbar popover to watch, and widen access in settings. Extension pages,
217
+ those settings among them, are off limits to every tool, so that choice
218
+ stays yours.
142
219
  - **Your focus is never taken**: nothing the agent does brings a tab or window
143
220
  forward on you. Chrome's `tabs.create` makes a new tab active by default and
144
221
  `windows.create` focuses the new window by default; TaskWindow always opens
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskwindow",
3
- "version": "0.2.19",
3
+ "version": "0.2.21",
4
4
  "description": "TaskWindow local daemon: bridges the TaskWindow Chrome extension to any MCP client over Streamable HTTP",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "scripts": {
11
11
  "start": "node src/index.js",
12
- "test": "node --test test/agents.test.mjs test/pairing.test.mjs test/extension-bootstrap.test.mjs test/extension-connection.test.mjs test/extension-idle.test.mjs test/extension-cdp.test.mjs test/extension-dialog.test.mjs test/extension-javascript.test.mjs test/extension-tabs.test.mjs test/extension-responsive.test.mjs test/extension-human.test.mjs test/extension-click-ref.test.mjs test/bridge.test.mjs test/tool-contract.test.mjs test/updates.test.mjs && node test/run.mjs"
12
+ "test": "node --test test/agents.test.mjs test/pairing.test.mjs test/extension-bootstrap.test.mjs test/extension-connection.test.mjs test/extension-idle.test.mjs test/extension-cdp.test.mjs test/extension-dialog.test.mjs test/extension-javascript.test.mjs test/extension-tabs.test.mjs test/extension-responsive.test.mjs test/extension-human.test.mjs test/extension-click-ref.test.mjs test/extension-pages.test.mjs test/bridge.test.mjs test/tool-contract.test.mjs test/updates.test.mjs && node test/run.mjs"
13
13
  },
14
14
  "engines": {
15
15
  "node": ">=18"
package/src/bridge.js CHANGED
@@ -47,21 +47,25 @@ export class Bridge {
47
47
  // Single active extension connection: newest wins.
48
48
  if (this.ext && this.ext !== ws) {
49
49
  this.logger.log("[bridge] replacing existing extension connection");
50
+ this.#failAllPending(new Error("TaskWindow extension connection changed"));
50
51
  try {
51
52
  this.ext.close(4000, "superseded by a new extension connection");
52
53
  } catch {}
53
54
  }
54
55
  this.ext = ws;
56
+ this.connectionId = randomUUID();
57
+ this.lastHello = null;
55
58
  this.lastExtMessage = Date.now();
56
59
 
57
60
  ws.on("message", (raw) => this.#onMessage(ws, raw));
58
61
  ws.on("close", () => {
59
62
  if (this.ext === ws) {
60
63
  this.ext = null;
64
+ this.connectionId = null;
61
65
  this.lastHello = null;
62
66
  this.logger.log("[bridge] extension disconnected");
67
+ this.#failAllPending(new Error("TaskWindow extension disconnected"));
63
68
  }
64
- this.#failAllPending(new Error("TaskWindow extension disconnected"));
65
69
  });
66
70
  ws.on("error", () => {});
67
71
  });
@@ -133,7 +137,8 @@ export class Bridge {
133
137
  } catch {
134
138
  return;
135
139
  }
136
- if (ws === this.ext) this.lastExtMessage = Date.now();
140
+ if (ws !== this.ext) return;
141
+ this.lastExtMessage = Date.now();
137
142
  switch (msg.type) {
138
143
  case "hello":
139
144
  this.lastHello = msg;
package/src/index.js CHANGED
@@ -551,6 +551,8 @@ const server = http.createServer(async (req, res) => {
551
551
  version: VERSION,
552
552
  latestVersion: updates.latest,
553
553
  extensionConnected: bridge.connected,
554
+ scopedSessions: bridge.connected && bridge.lastHello?.scopedSessions === true,
555
+ scopedConnectionId: bridge.connected ? bridge.connectionId : null,
554
556
  extensionVersion: bridge.lastHello?.version || null,
555
557
  extensionId: bridge.lastHello?.id || null,
556
558
  port: config.port,
@@ -626,7 +628,8 @@ const server = http.createServer(async (req, res) => {
626
628
  return;
627
629
  }
628
630
 
629
- if (url.pathname === "/mcp") {
631
+ const session = /^\/mcp\/session\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/.exec(url.pathname);
632
+ if (url.pathname === "/mcp" || session) {
630
633
  const auth = req.headers.authorization || "";
631
634
  if (auth !== `Bearer ${config.token}`) {
632
635
  sendJson(res, 401, { error: "invalid or missing bearer token" });
@@ -649,7 +652,16 @@ const server = http.createServer(async (req, res) => {
649
652
  sendJson(res, 400, { error: "invalid JSON body" });
650
653
  return;
651
654
  }
652
- await handleMcp(req, res, body);
655
+ if (session && Array.isArray(body)) {
656
+ sendJson(res, 400, { error: "Send one browser operation per request" });
657
+ return;
658
+ }
659
+ const connection = req.headers["x-taskwindow-connection"];
660
+ if (session && connection !== undefined && connection !== bridge.connectionId) {
661
+ sendJson(res, 409, { error: "The Chrome connection changed. Request approval again." });
662
+ return;
663
+ }
664
+ await handleMcp(req, res, body, session ? "scoped:" + session[1] : null);
653
665
  } catch (err) {
654
666
  if (!res.headersSent) sendJson(res, 500, { error: err.message });
655
667
  else res.end();
package/src/mcp-http.js CHANGED
@@ -8,9 +8,9 @@ import { registerTools } from "./tools.js";
8
8
  * Streamable HTTP can hit it.
9
9
  */
10
10
  export function createMcpRequestHandler({ bridge, version, updates = null, logger = console }) {
11
- return async function handleMcpRequest(req, res, parsedBody) {
11
+ return async function handleMcpRequest(req, res, parsedBody, scope = null) {
12
12
  const server = new McpServer({ name: "taskwindow", version });
13
- registerTools(server, { bridge, version, updates, logger });
13
+ registerTools(server, { bridge, version, updates, logger, scope });
14
14
  const transport = new StreamableHTTPServerTransport({
15
15
  sessionIdGenerator: undefined,
16
16
  enableJsonResponse: true,
package/src/tools.js CHANGED
@@ -46,6 +46,48 @@ export function unawaitedPromiseNote(tool, args, result, extensionVersion) {
46
46
  );
47
47
  }
48
48
 
49
+ /** The first extension that keeps its tools off extension pages itself. */
50
+ export const REFUSES_EXTENSION_PAGES_SINCE = "0.2.20";
51
+ // Any chain of schemes ending in chrome-extension: (blob:, view-source:), so
52
+ // an address that merely mentions one further in stays a web page.
53
+ const EXTENSION_PAGE = /^(?:[a-z][a-z0-9+.-]*:)*chrome-extension:/i;
54
+ const EXTENSION_PAGES_OFF_LIMITS =
55
+ "Extension pages are off limits: TaskWindow tools do not open or act on a browser extension's own pages (chrome-extension://...), TaskWindow's included.";
56
+ const OPENS_A_URL = new Set(["tabs_create", "navigate", "set_viewport"]);
57
+
58
+ /**
59
+ * TaskWindow's own pages (settings, popover) run with the extension's rights,
60
+ * so a tool acting on one would be acting as the extension. The extension
61
+ * refuses them itself from REFUSES_EXTENSION_PAGES_SINCE on; refusing the
62
+ * address here as well covers an older one until Chrome updates it.
63
+ */
64
+ export function extensionPageRefusal(tool, args) {
65
+ if (!OPENS_A_URL.has(tool) || typeof args?.url !== "string") return null;
66
+ return EXTENSION_PAGE.test(args.url.trim()) ? EXTENSION_PAGES_OFF_LIMITS : null;
67
+ }
68
+
69
+ /**
70
+ * The other half for an older extension: its javascript_execute runs on
71
+ * whatever page the tab shows, so the check travels in front of the script and
72
+ * runs in the page itself. On one line, so error line numbers still match the
73
+ * caller's script. A version that is not plain x.y.z compares as equal to
74
+ * anything, so it is taken as older: the check costs a page nothing.
75
+ */
76
+ export function guardExtensionPages(tool, args, extensionVersion) {
77
+ if (tool !== "javascript_execute" || typeof args?.code !== "string") return args;
78
+ const checksItself = /^\d+\.\d+\.\d+$/.test(String(extensionVersion)) && compareVersions(extensionVersion, REFUSES_EXTENSION_PAGES_SINCE) >= 0;
79
+ if (checksItself) return args;
80
+ const check = `if (/^chrome-extension:/.test(location.origin)) throw new Error(${JSON.stringify(EXTENSION_PAGES_OFF_LIMITS)});`;
81
+ return { ...args, code: `${check} ${args.code}` };
82
+ }
83
+
84
+ /** What goes to the extension for a call, or a refusal thrown before anything is sent. */
85
+ function prepareCall(tool, args, extensionVersion) {
86
+ const refusal = clickByRefRefusal(tool, args, extensionVersion) || extensionPageRefusal(tool, args);
87
+ if (refusal) throw new Error(refusal);
88
+ return guardExtensionPages(tool, args, extensionVersion);
89
+ }
90
+
49
91
  const tabId = z.number().int().describe("Tab ID from tabs_list. Defaults to the active tab in your session's task groups.");
50
92
 
51
93
  // Injected into every browser tool below (see toolDefs) rather than spread by
@@ -265,7 +307,7 @@ const rawDefs = [
265
307
  description:
266
308
  "Structured accessibility-style snapshot of the page: a text tree of interactive elements and content, " +
267
309
  "each labelled with a ref (e.g. e42) you can pass to form_input and file_upload (and to computer clicks, for a model that cannot see screenshots). Cheaper and more reliable " +
268
- "than a screenshot for forms and navigation.",
310
+ "than a screenshot for forms and navigation. A same-origin iframe is read as part of the page; a cross-origin one is a single iframe line.",
269
311
  inputSchema: { tabId: tabId.optional() },
270
312
  timeoutMs: 20_000,
271
313
  },
@@ -279,7 +321,7 @@ const rawDefs = [
279
321
  },
280
322
  {
281
323
  name: "get_page_text",
282
- description: "Extract the page's visible text content (like copy-pasting the page body).",
324
+ description: "Extract the page's visible text content (like copy-pasting the page body), same-origin iframes included.",
283
325
  inputSchema: {
284
326
  tabId: tabId.optional(),
285
327
  maxLength: z.number().int().min(100).max(500_000).optional().describe("Truncate output to this many characters (default 50000)"),
@@ -290,7 +332,7 @@ const rawDefs = [
290
332
  name: "form_input",
291
333
  description:
292
334
  "Fill a form field: text inputs, textareas, checkboxes, radios, <select>s and contenteditable elements. " +
293
- "Targets the element by ref (from read_page/find) or a CSS selector.",
335
+ "Targets the element by ref (from read_page/find) or a CSS selector; both reach into same-origin iframes.",
294
336
  inputSchema: {
295
337
  value: z.union([z.string(), z.number(), z.boolean()]).describe("Value to set. For checkboxes/radios use true/false; for selects use the option value or visible text."),
296
338
  ref: z.string().optional().describe("Element ref from read_page/find (e.g. e42)"),
@@ -304,7 +346,7 @@ const rawDefs = [
304
346
  name: "file_upload",
305
347
  description:
306
348
  "Attach local file content to a file input (<input type=file>). The file bytes are transferred through the " +
307
- "daemon; target the input by ref or CSS selector.",
349
+ "daemon; target the input by ref or CSS selector, also inside a same-origin iframe.",
308
350
  inputSchema: {
309
351
  files: z.array(z.object({
310
352
  name: z.string().describe("File name (shown to the site)"),
@@ -468,14 +510,29 @@ function toMcpResult(result) {
468
510
  return { content };
469
511
  }
470
512
 
471
- export function registerTools(server, { bridge, version, updates = null, logger = console }) {
513
+ // Only single, tab-scoped operations. Shortcuts and batches schedule subsequent
514
+ // operations beyond the authorizing client's per-request revocation check.
515
+ const SESSION_TOOLS = new Set([
516
+ "tabs_create", "tabs_list", "tabs_close", "navigate", "reload", "read_page",
517
+ "find", "get_page_text", "form_input", "computer", "dialog",
518
+ ]);
519
+
520
+ export function registerTools(server, { bridge, version, updates = null, logger = console, scope = null }) {
521
+ const connection = bridge.connectionId;
472
522
  const notice = () =>
473
523
  updates?.notice({
474
524
  extensionVersion: bridge.lastHello?.version || null,
475
525
  extensionStore: bridge.lastHello?.id === STORE_EXTENSION_ID,
476
526
  }) ?? null;
477
527
  for (const def of toolDefs) {
478
- server.registerTool(def.name, { description: def.description, inputSchema: def.inputSchema }, async (args) => {
528
+ if (scope && !SESSION_TOOLS.has(def.name)) continue;
529
+ const inputSchema = { ...def.inputSchema };
530
+ if (scope) {
531
+ delete inputSchema.sessionToken;
532
+ delete inputSchema.save_to_disk;
533
+ delete inputSchema.human;
534
+ }
535
+ server.registerTool(def.name, { description: def.description, inputSchema }, async (args) => {
479
536
  try {
480
537
  // The sessionToken is stated once, in the first tabs_create result, and
481
538
  // the session it names is meant to run for a whole job — so it is
@@ -506,6 +563,20 @@ export function registerTools(server, { bridge, version, updates = null, logger
506
563
  },
507
564
  });
508
565
  }
566
+ if (scope) {
567
+ if (args.url !== undefined && !["https:", "http:"].includes(new URL(args.url).protocol)) {
568
+ throw new Error("Shared sessions can open HTTP and HTTPS pages only");
569
+ }
570
+ if (def.name === "computer" && args.action === "idle") {
571
+ throw new Error("Send one browser action at a time in a shared session");
572
+ }
573
+ if (connection !== bridge.connectionId) throw new Error("The Chrome connection changed. Request approval again.");
574
+ const result = await bridge.sendTool("session_tool", { name: def.name, args, scope }, def.timeoutMs);
575
+ if (def.name === "tabs_create") {
576
+ return toMcpResult({ text: `opened tab ${result.data.id} in this session` });
577
+ }
578
+ return toMcpResult(result);
579
+ }
509
580
  if (def.name === "browser_batch") return echoSession(await runBatch(args, bridge, logger));
510
581
  // save_to_disk is a daemon-side concern: the extension has no disk
511
582
  // access, so it is stripped here and applied to the returned image.
@@ -515,11 +586,10 @@ export function registerTools(server, { bridge, version, updates = null, logger
515
586
  // it. The retry with that token (same task and url) then gets the tab
516
587
  // the first call opened, not a second tab in a second group.
517
588
  if (def.name === "tabs_create" && !forwardedArgs.sessionToken) forwardedArgs.sessionToken = randomUUID();
518
- const refusal = clickByRefRefusal(def.name, forwardedArgs, bridge.lastHello?.version);
519
- if (refusal) throw new Error(refusal);
589
+ const sentArgs = prepareCall(def.name, forwardedArgs, bridge.lastHello?.version);
520
590
  let result;
521
591
  try {
522
- result = await bridge.sendTool(def.name, forwardedArgs, def.timeoutMs);
592
+ result = await bridge.sendTool(def.name, sentArgs, def.timeoutMs);
523
593
  } catch (err) {
524
594
  if (err.code !== "TIMEOUT") throw err;
525
595
  throw new Error(`${err.message}. ${timeoutAdvice(def.name, forwardedArgs)}`);
@@ -604,9 +674,7 @@ async function runBatch({ steps, sessionToken }, bridge, logger) {
604
674
  if (!parsed.success) {
605
675
  throw new Error(`invalid params: ${parsed.error.issues.map((e) => `${e.message} at ${e.path.join(".") || "(root)"}`).join("; ")}`);
606
676
  }
607
- const refusal = clickByRefRefusal(tool, parsed.data, bridge.lastHello?.version);
608
- if (refusal) throw new Error(refusal);
609
- const result = await bridge.sendTool(tool, parsed.data, def.timeoutMs);
677
+ const result = await bridge.sendTool(tool, prepareCall(tool, parsed.data, bridge.lastHello?.version), def.timeoutMs);
610
678
  const promiseNote = unawaitedPromiseNote(tool, parsed.data, result, bridge.lastHello?.version);
611
679
  if (promiseNote) result.text = `{}\n${promiseNote}`;
612
680
  results.push({ step: i + 1, tool, ok: true, result });