taskwindow 0.2.3 → 0.2.4

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
@@ -44,14 +44,21 @@ open by a pinned tab no agent can close. Screenshot done. Now try:
44
44
  ### Repair and advanced commands
45
45
 
46
46
  ```bash
47
+ taskwindow update # update daemon + extension to the latest release, no clicks
47
48
  taskwindow doctor # diagnose daemon, extension, versions, and agents
48
49
  taskwindow pair # create a manual one-time pairing code
49
- taskwindow install # re-run setup; also repairs and updates the extension
50
+ taskwindow install # re-run first-time setup; also repairs the extension
50
51
  taskwindow install --claude # add Claude Code without repeating setup
51
52
  taskwindow install --cursor # add Cursor without repeating setup
52
53
  taskwindow install --opencode # add OpenCode without repeating setup
53
54
  ```
54
55
 
56
+ When a newer release exists, agents are told once per session (in the
57
+ `tabs_create` result and in `taskwindow_status`) to ask you before running
58
+ `taskwindow update`. The daemon learns this by asking the npm registry for the
59
+ package's latest version at most once a day; create `~/.taskwindow/no-update-check`
60
+ to turn that off.
61
+
55
62
  Use `taskwindow install --no-extension` to install only the daemon and selected
56
63
  agents. For another MCP client, connect to `http://127.0.0.1:9377/mcp` with
57
64
  `Authorization: Bearer <token>`; the token is stored in `~/.taskwindow/token`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskwindow",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
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/pairing.test.mjs test/extension-bootstrap.test.mjs test/extension-tabs.test.mjs test/tool-contract.test.mjs && node test/run.mjs"
12
+ "test": "node --test test/pairing.test.mjs test/extension-bootstrap.test.mjs test/extension-tabs.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/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import http from "node:http";
3
3
  import { fileURLToPath } from "node:url";
4
- import { readFileSync } from "node:fs";
5
- import { join } from "node:path";
4
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
5
+ import { basename, delimiter, dirname, join } from "node:path";
6
+ import { execFileSync, spawnSync } from "node:child_process";
6
7
  import { loadConfig } from "./config.js";
7
8
  import { Bridge } from "./bridge.js";
8
9
  import { createMcpRequestHandler } from "./mcp-http.js";
@@ -11,10 +12,20 @@ import {
11
12
  installService,
12
13
  uninstallService,
13
14
  installExtension,
15
+ downloadExtensionZip,
16
+ refreshExtensionFiles,
14
17
  removeExtensionBootstrap,
15
18
  } from "./service.js";
16
19
  import { PairingManager } from "./pairing.js";
17
- import { readHealth, requestPairCode, waitForDaemon, waitForExtension } from "./setup-client.js";
20
+ import {
21
+ readHealth,
22
+ requestPairCode,
23
+ requestExtensionReload,
24
+ waitForDaemon,
25
+ waitForExtension,
26
+ waitForExtensionVersion,
27
+ } from "./setup-client.js";
28
+ import { UpdateChecker, fetchLatestVersion, isNewer, readUpdateState, updateCheckDisabled } from "./updates.js";
18
29
  import { createRequire } from "node:module";
19
30
 
20
31
  const { version: VERSION } = createRequire(import.meta.url)("../package.json");
@@ -174,13 +185,57 @@ function installedExtensionVersion() {
174
185
  }
175
186
  }
176
187
 
188
+ /**
189
+ * The `taskwindow` that PATH resolves to, if it isn't this one. Global installs
190
+ * under different Node versions (nvm, Homebrew, /usr/local) leave older copies
191
+ * behind, and an older copy earlier on PATH silently runs instead of the one
192
+ * `npm install -g taskwindow@latest` just put down — a pre-`doctor` version
193
+ * even falls through to daemon mode and dies on the busy port.
194
+ */
195
+ function shadowingInstall() {
196
+ const real = (p) => {
197
+ try {
198
+ return realpathSync(p);
199
+ } catch {
200
+ return null;
201
+ }
202
+ };
203
+ const self = real(process.argv[1]);
204
+ for (const dir of (process.env.PATH || "").split(delimiter)) {
205
+ if (!dir) continue;
206
+ const bin = join(dir, "taskwindow");
207
+ if (!existsSync(bin)) continue;
208
+ const target = real(bin);
209
+ if (!target || target === self) return null; // first hit is us: no shadow
210
+ let version = "unknown";
211
+ try {
212
+ version = JSON.parse(readFileSync(join(dirname(target), "..", "package.json"), "utf8")).version || version;
213
+ } catch {}
214
+ return { bin, version };
215
+ }
216
+ return null;
217
+ }
218
+
219
+ function warnIfShadowed() {
220
+ const other = shadowingInstall();
221
+ if (!other) return false;
222
+ console.log(
223
+ `✗ \`taskwindow\` on your PATH is v${other.version} at ${other.bin}, not this v${VERSION} — ` +
224
+ `remove it (npm uninstall -g taskwindow with the npm that owns that prefix, or delete the link) so commands run the current version`
225
+ );
226
+ return true;
227
+ }
228
+
177
229
  async function runDoctor(config) {
178
230
  const health = await readHealth(config.port);
179
231
  const installedVersion = installedExtensionVersion();
180
232
  const agents = inspectAgents();
181
233
  console.log(`TaskWindow doctor (CLI v${VERSION})`);
234
+ warnIfShadowed();
235
+ const known = updateCheckDisabled(config.dir) ? null : (health?.latestVersion || readUpdateState(config.dir).latest);
236
+ if (known && isNewer(known, VERSION)) console.log(`↑ TaskWindow v${known} is available (CLI v${VERSION}) — run: taskwindow update`);
182
237
  if (health) {
183
- const versionNote = health.version === VERSION ? "" : ` — CLI is v${VERSION}; run taskwindow install to update`;
238
+ const versionNote = health.version === VERSION ? "" : ` — CLI is v${VERSION}; run taskwindow update`;
184
239
  console.log(`✓ Daemon running (v${health.version}, port ${health.port})${versionNote}`);
185
240
  } else {
186
241
  console.log("✗ Daemon not running — run: taskwindow install");
@@ -189,7 +244,7 @@ async function runDoctor(config) {
189
244
  else console.log("✗ Extension files not installed — run: taskwindow install");
190
245
  if (health?.extensionConnected) {
191
246
  const versionNote = installedVersion && health.extensionVersion && installedVersion !== health.extensionVersion
192
- ? ` — installed files are v${installedVersion}; reload the extension in Chrome`
247
+ ? ` — installed files are v${installedVersion}; run taskwindow update (or reload the extension in Chrome)`
193
248
  : "";
194
249
  console.log(`✓ Chrome extension connected (v${health.extensionVersion || "unknown"})${versionNote}`);
195
250
  } else {
@@ -204,7 +259,97 @@ async function runDoctor(config) {
204
259
  return !!health && health.extensionConnected === true;
205
260
  }
206
261
 
262
+ /**
263
+ * The global npm install this CLI runs from: its prefix and the npm that owns
264
+ * it. `npm install -g` with the npm on PATH can belong to another Node (nvm,
265
+ * Homebrew, /usr/local) and would plant a second copy — the shadowing problem
266
+ * — so updates target the prefix these files live under.
267
+ */
268
+ function owningInstall() {
269
+ const self = realpathSync(process.argv[1]); // <prefix>/lib/node_modules/taskwindow/src/index.js
270
+ const pkgRoot = dirname(dirname(self));
271
+ const nodeModules = dirname(pkgRoot);
272
+ if (basename(nodeModules) !== "node_modules" || basename(pkgRoot) !== "taskwindow") {
273
+ throw new Error(`this taskwindow (${self}) is not a global npm install — update it the way you installed it`);
274
+ }
275
+ let prefix = dirname(nodeModules);
276
+ if (basename(prefix) === "lib") prefix = dirname(prefix);
277
+ const npm = [join(prefix, "bin", "npm"), join(dirname(process.execPath), "npm")].find((p) => existsSync(p)) || "npm";
278
+ return { prefix, npm };
279
+ }
280
+
281
+ function printManualReload() {
282
+ console.log("[taskwindow] the extension could not reload itself — in Chrome open chrome://extensions and click reload on TaskWindow");
283
+ }
284
+
285
+ /**
286
+ * `taskwindow update`: non-interactive, safe to run mid-session (agents run it
287
+ * with the user's OK). Stage 1 (old CLI): install the newer npm package into
288
+ * the owning prefix, then re-exec the NEW CLI for stage 2 so the rest runs on
289
+ * current code. Stage 2: refresh the extension files, restart the daemon on
290
+ * the new code, then have the extension reload itself — daemon first, because
291
+ * only the new daemon knows how to ask.
292
+ */
293
+ async function runUpdate(config, flags) {
294
+ const force = flags.includes("--force");
295
+ const staged = flags.includes("--stage2");
296
+ const extFlag = flags.indexOf("--extension");
297
+ const zipArg = extFlag !== -1 && flags[extFlag + 1] && !flags[extFlag + 1].startsWith("--") ? flags[extFlag + 1] : null;
298
+
299
+ if (!staged) {
300
+ warnIfShadowed();
301
+ let latest = null;
302
+ try {
303
+ latest = await fetchLatestVersion();
304
+ } catch (err) {
305
+ console.log(`[taskwindow] couldn't reach the npm registry (${err.message}) — refreshing the local install only`);
306
+ }
307
+ if (latest && isNewer(latest, VERSION)) {
308
+ const { prefix, npm } = owningInstall();
309
+ console.log(`[taskwindow] updating v${VERSION} → v${latest} (${prefix})`);
310
+ execFileSync(npm, ["install", "-g", "--prefix", prefix, `taskwindow@${latest}`], { stdio: "inherit" });
311
+ const rest = ["update", "--stage2", ...flags.filter((f) => f !== "--force" || force)];
312
+ const child = spawnSync(process.execPath, [realpathSync(process.argv[1]), ...rest], { stdio: "inherit" });
313
+ return child.status === 0;
314
+ }
315
+ const health = await readHealth(config.port);
316
+ const filesVersion = installedExtensionVersion();
317
+ const current =
318
+ health?.version === VERSION &&
319
+ filesVersion === VERSION &&
320
+ (!health?.extensionConnected || health.extensionVersion === VERSION);
321
+ if (current && !force) {
322
+ console.log(`[taskwindow] already up to date (v${VERSION})${latest ? "" : " as far as the local install goes"}`);
323
+ return true;
324
+ }
325
+ }
326
+
327
+ // Stage 2 (or nothing newer on npm, but the local pieces disagree).
328
+ refreshExtensionFiles(zipArg || downloadExtensionZip(VERSION));
329
+ console.log(`[taskwindow] extension files refreshed (v${installedExtensionVersion() || "?"}, ${extensionInstallDir()})`);
330
+ await ensureDaemon(config, { forceInstall: true });
331
+ const health = await waitForExtension(config.port, 90_000);
332
+ if (!health) {
333
+ console.log("[taskwindow] the extension did not reconnect — enable TaskWindow in Chrome, then run: taskwindow doctor");
334
+ return false;
335
+ }
336
+ if (health.extensionVersion !== VERSION) {
337
+ const reload = await requestExtensionReload(config);
338
+ if (!reload.ok) {
339
+ printManualReload();
340
+ } else if (!(await waitForExtensionVersion(config.port, VERSION))) {
341
+ console.log("[taskwindow] the extension reloaded but has not reconnected on the new version yet");
342
+ printManualReload();
343
+ }
344
+ }
345
+ return runDoctor(config);
346
+ }
347
+
207
348
  try {
349
+ if (verb === "update") {
350
+ const ok = await runUpdate(loadConfig(), flags);
351
+ process.exit(ok ? 0 : 1);
352
+ }
208
353
  if (verb === "install") {
209
354
  const config = loadConfig();
210
355
  const extFlag = flags.indexOf("--extension");
@@ -236,6 +381,7 @@ try {
236
381
  } else if (fullInstall) {
237
382
  console.log("[taskwindow] daemon and coding-agent setup complete (--no-extension selected)");
238
383
  }
384
+ warnIfShadowed();
239
385
  process.exit(ready ? 0 : 1);
240
386
  }
241
387
  if (verb === "pair") {
@@ -267,7 +413,10 @@ const config = loadConfig();
267
413
  const bridge = new Bridge({ token: config.token });
268
414
  const pairing = new PairingManager();
269
415
 
270
- const handleMcp = createMcpRequestHandler({ bridge, version: VERSION });
416
+ const updates = new UpdateChecker({ version: VERSION, dir: config.dir });
417
+ updates.start();
418
+
419
+ const handleMcp = createMcpRequestHandler({ bridge, version: VERSION, updates });
271
420
 
272
421
  const pairFailures = []; // timestamps of failed attempts, rolling window
273
422
  const PAIR_WINDOW_MS = 60_000;
@@ -315,6 +464,7 @@ const server = http.createServer(async (req, res) => {
315
464
  sendJson(res, 200, {
316
465
  ok: true,
317
466
  version: VERSION,
467
+ latestVersion: updates.latest,
318
468
  extensionConnected: bridge.connected,
319
469
  extensionVersion: bridge.lastHello?.version || null,
320
470
  port: config.port,
@@ -322,6 +472,27 @@ const server = http.createServer(async (req, res) => {
322
472
  return;
323
473
  }
324
474
 
475
+ // `taskwindow update` asks the extension to reload itself (re-reading the
476
+ // unpacked files). Same bearer token as pairing requests; it rides the
477
+ // ordinary tool-call channel but is not an MCP tool, so agents can't call it.
478
+ if (url.pathname === "/extension/reload") {
479
+ if (req.method !== "POST") {
480
+ sendJson(res, 405, { error: "method not allowed; POST to reload the extension" });
481
+ return;
482
+ }
483
+ if (req.headers.authorization !== `Bearer ${config.token}`) {
484
+ sendJson(res, 401, { error: "invalid or missing bearer token" });
485
+ return;
486
+ }
487
+ try {
488
+ await bridge.sendTool("reload_extension", {}, 5000);
489
+ sendJson(res, 200, { ok: true });
490
+ } catch (err) {
491
+ sendJson(res, 503, { error: err.message });
492
+ }
493
+ return;
494
+ }
495
+
325
496
  if (url.pathname === "/pair/request") {
326
497
  if (req.method !== "POST") {
327
498
  sendJson(res, 405, { error: "method not allowed; POST to request a pairing code" });
package/src/mcp-http.js CHANGED
@@ -7,10 +7,10 @@ import { registerTools } from "./tools.js";
7
7
  * server+transport pair. No session state — any MCP client that speaks
8
8
  * Streamable HTTP can hit it.
9
9
  */
10
- export function createMcpRequestHandler({ bridge, version, logger = console }) {
10
+ export function createMcpRequestHandler({ bridge, version, updates = null, logger = console }) {
11
11
  return async function handleMcpRequest(req, res, parsedBody) {
12
12
  const server = new McpServer({ name: "taskwindow", version });
13
- registerTools(server, { bridge, version, logger });
13
+ registerTools(server, { bridge, version, updates, logger });
14
14
  const transport = new StreamableHTTPServerTransport({
15
15
  sessionIdGenerator: undefined,
16
16
  enableJsonResponse: true,
package/src/service.js CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { homedir, platform } from "node:os";
7
7
  import { join } from "node:path";
8
- import { chmodSync, writeFileSync, unlinkSync, mkdirSync } from "node:fs";
8
+ import { chmodSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, rmSync } from "node:fs";
9
9
  import { execFileSync, execSync } from "node:child_process";
10
10
 
11
11
  const LABEL = "com.clawnify.taskwindow";
@@ -121,11 +121,51 @@ WantedBy=default.target
121
121
  * programmatic unpacked installs, so a human does the final 3 clicks — the
122
122
  * command does everything else.
123
123
  */
124
+ /**
125
+ * Download the extension zip of one release (`version` like "0.2.4"; omit for
126
+ * the latest release). Returns the local zip path.
127
+ */
128
+ export function downloadExtensionZip(version) {
129
+ const releaseApi = version
130
+ ? `https://api.github.com/repos/clawnify/taskwindow/releases/tags/v${version}`
131
+ : "https://api.github.com/repos/clawnify/taskwindow/releases/latest";
132
+ try {
133
+ const release = JSON.parse(execFileSync("curl", ["-sL", releaseApi], { maxBuffer: 20e6 }).toString());
134
+ const asset = (release.assets || []).find((a) => a.name.startsWith("TaskWindow-extension-"));
135
+ if (!asset) throw new Error(`no extension asset in the ${version ? `v${version}` : "latest"} release`);
136
+ mkdirSync(join(homedir(), ".taskwindow"), { recursive: true });
137
+ const zipPath = join(homedir(), ".taskwindow", asset.name);
138
+ execFileSync("curl", ["-sL", "-o", zipPath, asset.browser_download_url]);
139
+ console.log(`[taskwindow] downloaded ${asset.name}`);
140
+ return zipPath;
141
+ } catch (err) {
142
+ throw new Error(
143
+ `couldn't download the extension zip (${err.message}). Download it from ` +
144
+ "https://github.com/clawnify/taskwindow/releases and re-run with --extension <zip>"
145
+ );
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Replace the unpacked extension files with a zip's contents. The folder path
151
+ * is what Chrome has loaded, so it is kept and emptied rather than recreated;
152
+ * emptying first means files dropped by the new version don't linger.
153
+ */
154
+ export function refreshExtensionFiles(zipPath) {
155
+ const extDir = extensionInstallDir();
156
+ mkdirSync(extDir, { recursive: true });
157
+ for (const entry of readdirSync(extDir)) {
158
+ if (entry === BOOTSTRAP_FILENAME) continue;
159
+ rmSync(join(extDir, entry), { recursive: true, force: true });
160
+ }
161
+ execFileSync("unzip", ["-oq", zipPath, "-d", extDir]);
162
+ return extDir;
163
+ }
164
+
124
165
  export function installExtension(zipPath, { port, pairingCode } = {}) {
125
166
  // This folder must remain visible in macOS's file picker: Chrome asks the
126
167
  // user to select it after clicking "Load unpacked", and Finder hides paths
127
168
  // whose names begin with a period by default.
128
- const extDir = extensionInstallDir();
129
169
  const open = (u) => {
130
170
  try {
131
171
  execFileSync("open", ["-a", "Google Chrome", u]);
@@ -135,26 +175,7 @@ export function installExtension(zipPath, { port, pairingCode } = {}) {
135
175
  }
136
176
  };
137
177
 
138
- if (!zipPath) {
139
- // No zip given: fetch the latest release asset from GitHub.
140
- try {
141
- const api = "https://api.github.com/repos/clawnify/taskwindow/releases/latest";
142
- const release = JSON.parse(execFileSync("curl", ["-sL", api], { maxBuffer: 20e6 }).toString());
143
- const asset = (release.assets || []).find((a) => a.name.startsWith("TaskWindow-extension-"));
144
- if (!asset) throw new Error("no extension asset in the latest release");
145
- zipPath = join(homedir(), ".taskwindow", asset.name);
146
- execFileSync("curl", ["-sL", "-o", zipPath, asset.browser_download_url]);
147
- console.log(`[taskwindow] downloaded ${asset.name}`);
148
- } catch (err) {
149
- throw new Error(
150
- `couldn't download the extension zip (${err.message}). Download it from ` +
151
- "https://github.com/clawnify/taskwindow/releases and re-run with --extension <zip>"
152
- );
153
- }
154
- }
155
-
156
- mkdirSync(extDir, { recursive: true });
157
- execFileSync("unzip", ["-oq", zipPath, "-d", extDir]);
178
+ const extDir = refreshExtensionFiles(zipPath || downloadExtensionZip());
158
179
  if (pairingCode && port) {
159
180
  const bootstrapPath = extensionBootstrapPath();
160
181
  writeFileSync(bootstrapPath, JSON.stringify({ code: pairingCode, port }, null, 2) + "\n", { mode: 0o600 });
@@ -58,3 +58,28 @@ export async function requestPairCode({ port, token }) {
58
58
  return body;
59
59
  }
60
60
 
61
+ /** Extension connected and running exactly `version` (after an update/reload). */
62
+ export function waitForExtensionVersion(port, version, timeoutMs = 90_000) {
63
+ return waitForHealth(port, (health) => health.extensionConnected === true && health.extensionVersion === version, timeoutMs);
64
+ }
65
+
66
+ /**
67
+ * Ask the daemon to have the extension reload itself (re-reads the unpacked
68
+ * files from disk). Resolves {ok:true} or {ok:false, error} — an extension
69
+ * that predates the reload handler answers "Unknown tool", and a daemon that
70
+ * predates the endpoint answers 404; both mean "reload by hand".
71
+ */
72
+ export async function requestExtensionReload({ port, token }) {
73
+ try {
74
+ const response = await fetchWithTimeout(
75
+ `http://127.0.0.1:${port}/extension/reload`,
76
+ { method: "POST", headers: { authorization: `Bearer ${token}` } },
77
+ 10_000
78
+ );
79
+ const body = await response.json().catch(() => ({}));
80
+ if (!response.ok) return { ok: false, error: body.error || `HTTP ${response.status}` };
81
+ return { ok: true };
82
+ } catch (err) {
83
+ return { ok: false, error: err.message };
84
+ }
85
+ }
package/src/tools.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import { z } from "zod";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
2
5
 
3
6
  const tabId = z.number().int().describe("Tab ID from tabs_list. Defaults to the active tab in your session's task groups.");
4
7
 
@@ -83,7 +86,8 @@ const rawDefs = [
83
86
  "Actions: screenshot (PNG of the viewport, or full page with fullPage), left_click / right_click / " +
84
87
  "middle_click / double_click / triple_click (at x,y), type (text into the focused element), " +
85
88
  "key (named key press, e.g. Enter, Tab, Escape, ArrowLeft, Backspace), scroll (by dx/dy pixels), " +
86
- "mouse_move, wait. Coordinates come from the last screenshot. NOTE: while attached, Chrome shows a " +
89
+ "mouse_move, wait. Screenshots are in CSS pixels (1 image pixel = 1 coordinate unit, on any display density), so " +
90
+ "read x,y straight off the last screenshot. NOTE: while attached, Chrome shows a " +
87
91
  '"TaskWindow started debugging this browser" infobar — this is unavoidable with CDP-based control.',
88
92
  inputSchema: {
89
93
  action: z.enum([
@@ -99,6 +103,12 @@ const rawDefs = [
99
103
  dy: z.number().int().optional().describe("Vertical scroll delta in pixels (positive scrolls down)"),
100
104
  ms: z.number().int().min(0).max(10_000).optional().describe('Milliseconds for the "wait" action (max 10000)'),
101
105
  fullPage: z.boolean().optional().describe('For "screenshot": capture the whole scrollable page instead of the viewport'),
106
+ save_to_disk: z
107
+ .boolean()
108
+ .optional()
109
+ .describe(
110
+ 'For "screenshot": also write the PNG to a local file and return its path in the result, so it can be read, attached or handed to other tools. Default false.'
111
+ ),
102
112
  },
103
113
  timeoutMs: 30_000,
104
114
  },
@@ -196,6 +206,7 @@ const rawDefs = [
196
206
  name: "javascript_execute",
197
207
  description:
198
208
  "Run JavaScript in the page's main world (same context as the site's own scripts) and return the result. " +
209
+ "Evaluated over the DevTools protocol, so the page's Content Security Policy does not block it. " +
199
210
  "The final expression's value is returned if JSON-serializable. Use sparingly — prefer read_page/find/form_input.",
200
211
  inputSchema: {
201
212
  code: z.string().describe("JavaScript source to evaluate, e.g. \"document.title\""),
@@ -305,7 +316,8 @@ function toMcpResult(result) {
305
316
  return { content };
306
317
  }
307
318
 
308
- export function registerTools(server, { bridge, version, logger = console }) {
319
+ export function registerTools(server, { bridge, version, updates = null, logger = console }) {
320
+ const notice = () => updates?.notice({ extensionVersion: bridge.lastHello?.version || null }) ?? null;
309
321
  for (const def of toolDefs) {
310
322
  server.registerTool(def.name, { description: def.description, inputSchema: def.inputSchema }, async (args) => {
311
323
  try {
@@ -315,17 +327,39 @@ export function registerTools(server, { bridge, version, logger = console }) {
315
327
  data: {
316
328
  daemon: "running",
317
329
  daemonVersion: version,
330
+ latestVersion: updates?.latest ?? null,
318
331
  extensionConnected: connected,
319
332
  extensionVersion: bridge.lastHello?.version || null,
320
333
  recovery: connected
321
334
  ? null
322
335
  : "Open Chrome and enable TaskWindow. If it remains disconnected, run `taskwindow doctor`, then `taskwindow pair`.",
336
+ update: notice(),
323
337
  },
324
338
  });
325
339
  }
326
340
  if (def.name === "browser_batch") return await runBatch(args, bridge, logger);
327
- const result = await bridge.sendTool(def.name, args, def.timeoutMs);
328
- return toMcpResult(result);
341
+ // save_to_disk is a daemon-side concern: the extension has no disk
342
+ // access, so it is stripped here and applied to the returned image.
343
+ const { save_to_disk, ...forwardedArgs } = args;
344
+ const result = await bridge.sendTool(def.name, forwardedArgs, def.timeoutMs);
345
+ if (save_to_disk && result?.image) {
346
+ try {
347
+ const savedPath = await saveImageToDisk(result.image);
348
+ result.text = `${result.text || "image"}\nSaved to: ${savedPath}`;
349
+ } catch (err) {
350
+ logger.error(`[mcp] save_to_disk failed:`, err.message);
351
+ result.text = `${result.text || "image"}\nError saving to disk: ${err.message}`;
352
+ }
353
+ }
354
+ const mcp = toMcpResult(result);
355
+ // tabs_create is the first call of every agent session, so a newer
356
+ // release (or a stale extension) is mentioned once per session, here,
357
+ // instead of on every response.
358
+ if (def.name === "tabs_create") {
359
+ const line = notice();
360
+ if (line) mcp.content.push({ type: "text", text: line });
361
+ }
362
+ return mcp;
329
363
  } catch (err) {
330
364
  logger.error(`[mcp] ${def.name} failed:`, err.message);
331
365
  return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
@@ -334,6 +368,19 @@ export function registerTools(server, { bridge, version, logger = console }) {
334
368
  }
335
369
  }
336
370
 
371
+ /**
372
+ * Write an image result to the session temp dir (OS-cleaned, like Claude's
373
+ * chrome extension does). Timestamped naming so repeat shots never overwrite.
374
+ */
375
+ async function saveImageToDisk(image) {
376
+ const dir = path.join(os.tmpdir(), "taskwindow-screenshots");
377
+ await mkdir(dir, { recursive: true });
378
+ const ext = image.mimeType === "image/jpeg" ? "jpg" : "png";
379
+ const filePath = path.join(dir, `taskwindow-${Date.now()}-${process.pid}.${ext}`);
380
+ await writeFile(filePath, Buffer.from(image.data, "base64"));
381
+ return filePath;
382
+ }
383
+
337
384
  async function runBatch({ steps, sessionToken }, bridge, logger) {
338
385
  const results = [];
339
386
  for (let i = 0; i < steps.length; i++) {
package/src/updates.js ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * "Is there a newer TaskWindow?" — asked of the npm registry (the same place
3
+ * `npm install -g taskwindow@latest` resolves, so a version announced here is
4
+ * always installable), at most once a day, persisted so daemon restarts don't
5
+ * re-ask. Nothing about the machine is sent: it is a GET of the package's
6
+ * dist-tags. Opt out with the `no-update-check` marker file in the TaskWindow
7
+ * dir (the daemon runs under launchd/systemd and sees no shell environment) or
8
+ * TASKWINDOW_NO_UPDATE_CHECK=1 for ad-hoc runs.
9
+ *
10
+ * The result reaches agents as a line in `tabs_create` results (the first tool
11
+ * every agent calls) and in `taskwindow_status`; see notice().
12
+ */
13
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+
16
+ export const REGISTRY_URL = "https://registry.npmjs.org/-/package/taskwindow/dist-tags";
17
+ export const STATE_FILE = "update-check.json";
18
+ export const OPT_OUT_FILE = "no-update-check";
19
+ const MAX_AGE_MS = 24 * 60 * 60 * 1000;
20
+ const RECHECK_MS = 6 * 60 * 60 * 1000;
21
+ const SEMVER = /^\d+\.\d+\.\d+$/;
22
+
23
+ /** Strict x.y.z compare; anything else (pre-releases, garbage) is never "newer". */
24
+ export function compareVersions(a, b) {
25
+ if (!SEMVER.test(String(a)) || !SEMVER.test(String(b))) return 0;
26
+ const pa = String(a).split(".").map(Number);
27
+ const pb = String(b).split(".").map(Number);
28
+ for (let i = 0; i < 3; i++) {
29
+ if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1;
30
+ }
31
+ return 0;
32
+ }
33
+
34
+ export function isNewer(candidate, current) {
35
+ return compareVersions(candidate, current) > 0;
36
+ }
37
+
38
+ /** One network round trip; throws on failure or on a malformed answer. */
39
+ export async function fetchLatestVersion({ url = process.env.TASKWINDOW_UPDATE_CHECK_URL || REGISTRY_URL, fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
40
+ const controller = new AbortController();
41
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
42
+ try {
43
+ const response = await fetchImpl(url, { signal: controller.signal, headers: { accept: "application/json" } });
44
+ if (!response.ok) throw new Error(`registry answered HTTP ${response.status}`);
45
+ const body = await response.json();
46
+ const latest = body?.latest;
47
+ // Only a plain x.y.z ever gets interpolated into text an agent reads.
48
+ if (!SEMVER.test(String(latest))) throw new Error("registry answer had no plain x.y.z latest version");
49
+ return String(latest);
50
+ } finally {
51
+ clearTimeout(timer);
52
+ }
53
+ }
54
+
55
+ export function readUpdateState(dir) {
56
+ try {
57
+ const state = JSON.parse(readFileSync(join(dir, STATE_FILE), "utf8"));
58
+ return {
59
+ checkedAt: Number(state?.checkedAt) || 0,
60
+ latest: SEMVER.test(String(state?.latest)) ? String(state.latest) : null,
61
+ };
62
+ } catch {
63
+ return { checkedAt: 0, latest: null };
64
+ }
65
+ }
66
+
67
+ export function updateCheckDisabled(dir, env = process.env) {
68
+ return env.TASKWINDOW_NO_UPDATE_CHECK === "1" || existsSync(join(dir, OPT_OUT_FILE));
69
+ }
70
+
71
+ /** The line agents get. `null` when everything is current (or unknown). */
72
+ export function updateNotice({ version, latest, extensionVersion }) {
73
+ const problems = [];
74
+ if (latest && isNewer(latest, version)) {
75
+ problems.push(`TaskWindow ${latest} is available (this daemon is ${version}).`);
76
+ }
77
+ if (extensionVersion && extensionVersion !== version) {
78
+ problems.push(`The TaskWindow Chrome extension is ${extensionVersion} while the daemon is ${version}.`);
79
+ }
80
+ if (problems.length === 0) return null;
81
+ return (
82
+ `${problems.join(" ")} Ask the user for permission, then run \`taskwindow update\` in a terminal ` +
83
+ "(about a minute; open tabs survive, the tools reconnect on their own — check with taskwindow_status). " +
84
+ "Never run it without the user's OK."
85
+ );
86
+ }
87
+
88
+ export class UpdateChecker {
89
+ constructor({ version, dir, fetchImpl, now = Date.now, logger = console }) {
90
+ this.version = version;
91
+ this.dir = dir;
92
+ this.fetchImpl = fetchImpl;
93
+ this.now = now;
94
+ this.logger = logger;
95
+ this.state = readUpdateState(dir);
96
+ this.timer = null;
97
+ }
98
+
99
+ get disabled() {
100
+ return updateCheckDisabled(this.dir);
101
+ }
102
+
103
+ /** Latest known version, from this process or an earlier one via the state file. */
104
+ get latest() {
105
+ return this.state.latest;
106
+ }
107
+
108
+ notice({ extensionVersion } = {}) {
109
+ return updateNotice({ version: this.version, latest: this.disabled ? null : this.latest, extensionVersion });
110
+ }
111
+
112
+ /** Refresh if the last check is older than a day (or `force`). Never throws. */
113
+ async check({ force = false } = {}) {
114
+ if (this.disabled) return null;
115
+ const fresh = this.state.checkedAt > 0 && this.now() - this.state.checkedAt < MAX_AGE_MS;
116
+ if (!force && fresh) return this.state.latest;
117
+ try {
118
+ const latest = await fetchLatestVersion({ fetchImpl: this.fetchImpl });
119
+ this.state = { checkedAt: this.now(), latest };
120
+ try {
121
+ writeFileSync(join(this.dir, STATE_FILE), JSON.stringify(this.state, null, 2) + "\n");
122
+ } catch {}
123
+ if (isNewer(latest, this.version)) this.logger.log(`[taskwindow] update available: ${latest} (running ${this.version}) — taskwindow update`);
124
+ return latest;
125
+ } catch (err) {
126
+ this.logger.log(`[taskwindow] update check skipped: ${err.message}`);
127
+ return this.state.latest;
128
+ }
129
+ }
130
+
131
+ start() {
132
+ if (this.disabled) return;
133
+ this.check();
134
+ this.timer = setInterval(() => this.check(), RECHECK_MS);
135
+ this.timer.unref?.();
136
+ }
137
+
138
+ stop() {
139
+ clearInterval(this.timer);
140
+ this.timer = null;
141
+ }
142
+ }