taskwindow 0.2.18 → 0.2.20

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.
Files changed (3) hide show
  1. package/README.md +69 -1
  2. package/package.json +2 -2
  3. package/src/tools.js +74 -10
package/README.md CHANGED
@@ -98,6 +98,72 @@ taking the daemon connection from each other. For another MCP client, connect to
98
98
  | Debug | `read_console_messages`, `read_network_requests` |
99
99
  | Efficiency | `browser_batch` (multi-step in one call), `gif_record`, `set_viewport` (responsive view), `shortcuts_*` |
100
100
 
101
+ The page tools (`read_page`, `find`, `get_page_text`, `form_input`,
102
+ `file_upload`, `upload_image` and clicks by ref) read same-origin iframes as
103
+ part of the page, so an app that shows its pages inside its own shell frame
104
+ works like any other. A cross-origin iframe stays a single `iframe` line.
105
+
106
+ ## Flows: a script instead of twenty turns
107
+
108
+ A job an agent repeats, such as filling the same long form every day, does not
109
+ need a model turn per field. The agent works the page out once, writes a
110
+ script, and from then on runs the script: one turn, the same steps every time.
111
+ TaskWindow needs nothing extra for this, because a script can call the same
112
+ tools the agent does. Each call is one HTTP request to the daemon, with no
113
+ handshake before it.
114
+
115
+ ```js
116
+ // node flow.mjs <sessionToken> values.json [photo.jpg]
117
+ import { readFileSync } from "node:fs";
118
+ import { homedir } from "node:os";
119
+ import { basename } from "node:path";
120
+
121
+ const [sessionToken, valuesFile, photo] = process.argv.slice(2);
122
+ const token = process.env.TASKWINDOW_TOKEN || readFileSync(`${homedir()}/.taskwindow/token`, "utf8").trim();
123
+
124
+ async function tool(name, args = {}) {
125
+ const res = await fetch(`http://127.0.0.1:${process.env.TASKWINDOW_PORT || 9377}/mcp`, {
126
+ method: "POST",
127
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
128
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: { sessionToken, ...args } } }),
129
+ });
130
+ const { result, error } = await res.json();
131
+ const text = (result?.content || []).filter((c) => c.type === "text").map((c) => c.text).join("\n");
132
+ if (error || result?.isError) throw new Error(error?.message || text);
133
+ return text;
134
+ }
135
+
136
+ // The page side, written once. It runs in the page; the values arrive as data, never as code.
137
+ function fill(values) {
138
+ const now = {};
139
+ for (const [selector, value] of Object.entries(values)) {
140
+ const field = document.querySelector(selector);
141
+ if (!field) { now[selector] = "no such field"; continue; }
142
+ field.value = value;
143
+ field.dispatchEvent(new Event("input", { bubbles: true }));
144
+ field.dispatchEvent(new Event("change", { bubbles: true }));
145
+ now[selector] = field.value; // read back, so the caller sees what the page kept
146
+ }
147
+ return now;
148
+ }
149
+
150
+ const values = JSON.parse(readFileSync(valuesFile, "utf8"));
151
+ console.log(await tool("javascript_execute", { code: `(${fill})(${JSON.stringify(values)})` }));
152
+
153
+ // A file goes from disk to the page; the model never carries its bytes.
154
+ if (photo) {
155
+ const data = readFileSync(photo).toString("base64");
156
+ console.log(await tool("file_upload", { selector: "input[type=file]", files: [{ name: basename(photo), data }] }));
157
+ }
158
+ ```
159
+
160
+ The agent passes the script the `sessionToken` it got from `tabs_create`, so
161
+ the script acts on that session's tabs and nothing else, like the agent itself.
162
+ The script reads its own files, with its own rights. A failed tool call comes
163
+ back with `isError`, which the helper above turns into an exception, so a page
164
+ that has changed stops the script and the agent takes over with the ordinary
165
+ tools.
166
+
101
167
  ## Wonder: when synthetic input is not enough
102
168
 
103
169
  Some pages ignore a perfect click. A single wheel event carrying 1600px gives
@@ -138,7 +204,9 @@ in the mouse-dynamics literature, so do not build on it as camouflage.
138
204
  scoped to that session's groups, so concurrent agents never share tabs —
139
205
  even when they pick the same task name. By default the agent can only see
140
206
  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.
207
+ the toolbar popover to watch, and widen access in settings. Extension pages,
208
+ those settings among them, are off limits to every tool, so that choice
209
+ stays yours.
142
210
  - **Your focus is never taken**: nothing the agent does brings a tab or window
143
211
  forward on you. Chrome's `tabs.create` makes a new tab active by default and
144
212
  `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.18",
3
+ "version": "0.2.20",
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-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/tools.js CHANGED
@@ -25,6 +25,69 @@ export function clickByRefRefusal(tool, args, extensionVersion) {
25
25
  );
26
26
  }
27
27
 
28
+ /** The first extension that waits for a Promise javascript_execute's script returns. */
29
+ export const AWAITS_RETURNED_PROMISE_SINCE = "0.2.19";
30
+
31
+ /**
32
+ * An older extension reports a Promise the script returned as {} instead of
33
+ * waiting for it, and that reads as a real, empty answer. The daemon cannot
34
+ * tell the two apart, so until the Web Store update arrives every {} from such
35
+ * an extension says what it may be and how to get the value.
36
+ */
37
+ export function unawaitedPromiseNote(tool, args, result, extensionVersion) {
38
+ if (tool !== "javascript_execute" || args?.awaitPromise === false) return null;
39
+ if (extensionVersion && compareVersions(extensionVersion, AWAITS_RETURNED_PROMISE_SINCE) >= 0) return null;
40
+ const value = result?.data?.result;
41
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length) return null;
42
+ return (
43
+ `Note: if the script returned a Promise (an async function call, fetch(...).then(...), new Promise(...)), this {} is the Promise, not its value. ` +
44
+ `This TaskWindow extension (${extensionVersion ? `v${extensionVersion}` : "version unknown"}) does not wait for one; v${AWAITS_RETURNED_PROMISE_SINCE} does, ` +
45
+ "and Chrome installs it from the Web Store on its own. Until then put a top-level await in front of the expression, e.g. `await fetch(url).then(r => r.status)`."
46
+ );
47
+ }
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
+
28
91
  const tabId = z.number().int().describe("Tab ID from tabs_list. Defaults to the active tab in your session's task groups.");
29
92
 
30
93
  // Injected into every browser tool below (see toolDefs) rather than spread by
@@ -244,7 +307,7 @@ const rawDefs = [
244
307
  description:
245
308
  "Structured accessibility-style snapshot of the page: a text tree of interactive elements and content, " +
246
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 " +
247
- "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.",
248
311
  inputSchema: { tabId: tabId.optional() },
249
312
  timeoutMs: 20_000,
250
313
  },
@@ -258,7 +321,7 @@ const rawDefs = [
258
321
  },
259
322
  {
260
323
  name: "get_page_text",
261
- 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.",
262
325
  inputSchema: {
263
326
  tabId: tabId.optional(),
264
327
  maxLength: z.number().int().min(100).max(500_000).optional().describe("Truncate output to this many characters (default 50000)"),
@@ -269,7 +332,7 @@ const rawDefs = [
269
332
  name: "form_input",
270
333
  description:
271
334
  "Fill a form field: text inputs, textareas, checkboxes, radios, <select>s and contenteditable elements. " +
272
- "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.",
273
336
  inputSchema: {
274
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."),
275
338
  ref: z.string().optional().describe("Element ref from read_page/find (e.g. e42)"),
@@ -283,7 +346,7 @@ const rawDefs = [
283
346
  name: "file_upload",
284
347
  description:
285
348
  "Attach local file content to a file input (<input type=file>). The file bytes are transferred through the " +
286
- "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.",
287
350
  inputSchema: {
288
351
  files: z.array(z.object({
289
352
  name: z.string().describe("File name (shown to the site)"),
@@ -494,15 +557,16 @@ export function registerTools(server, { bridge, version, updates = null, logger
494
557
  // it. The retry with that token (same task and url) then gets the tab
495
558
  // the first call opened, not a second tab in a second group.
496
559
  if (def.name === "tabs_create" && !forwardedArgs.sessionToken) forwardedArgs.sessionToken = randomUUID();
497
- const refusal = clickByRefRefusal(def.name, forwardedArgs, bridge.lastHello?.version);
498
- if (refusal) throw new Error(refusal);
560
+ const sentArgs = prepareCall(def.name, forwardedArgs, bridge.lastHello?.version);
499
561
  let result;
500
562
  try {
501
- result = await bridge.sendTool(def.name, forwardedArgs, def.timeoutMs);
563
+ result = await bridge.sendTool(def.name, sentArgs, def.timeoutMs);
502
564
  } catch (err) {
503
565
  if (err.code !== "TIMEOUT") throw err;
504
566
  throw new Error(`${err.message}. ${timeoutAdvice(def.name, forwardedArgs)}`);
505
567
  }
568
+ const promiseNote = unawaitedPromiseNote(def.name, forwardedArgs, result, bridge.lastHello?.version);
569
+ if (promiseNote) result.text = `{}\n${promiseNote}`;
506
570
  if (save_to_disk && result?.image) {
507
571
  try {
508
572
  const savedPath = await saveImageToDisk(result.image);
@@ -581,9 +645,9 @@ async function runBatch({ steps, sessionToken }, bridge, logger) {
581
645
  if (!parsed.success) {
582
646
  throw new Error(`invalid params: ${parsed.error.issues.map((e) => `${e.message} at ${e.path.join(".") || "(root)"}`).join("; ")}`);
583
647
  }
584
- const refusal = clickByRefRefusal(tool, parsed.data, bridge.lastHello?.version);
585
- if (refusal) throw new Error(refusal);
586
- const result = await bridge.sendTool(tool, parsed.data, def.timeoutMs);
648
+ const result = await bridge.sendTool(tool, prepareCall(tool, parsed.data, bridge.lastHello?.version), def.timeoutMs);
649
+ const promiseNote = unawaitedPromiseNote(tool, parsed.data, result, bridge.lastHello?.version);
650
+ if (promiseNote) result.text = `{}\n${promiseNote}`;
587
651
  results.push({ step: i + 1, tool, ok: true, result });
588
652
  } catch (err) {
589
653
  logger.error(`[mcp] batch step ${i + 1} (${tool}) failed:`, err.message);