taskwindow 0.1.11 → 0.1.12

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
@@ -12,90 +12,54 @@ MCP over HTTP.
12
12
 
13
13
  ## Setup (5 minutes)
14
14
 
15
- ### 1. Install and start the daemon
16
-
17
- Requires Node 18+.
15
+ Requires Node 18+ and Chrome/Chromium 116+.
18
16
 
19
17
  ```bash
20
18
  npm install -g taskwindow
21
19
  taskwindow install
22
20
  ```
23
21
 
24
- That installs a login service (the daemon starts now and after every laptop
25
- restart — no terminal needed) and prints:
26
-
27
- ```
28
- [taskwindow] login service installed (~/Library/LaunchAgents/com.clawnify.taskwindow.plist)
29
- [taskwindow] pairing code: A6LU5X — enter it in the TaskWindow extension options
30
- ```
31
-
32
- Keep the pairing code for step 3. (Prefer running it by hand? `npx taskwindow`
33
- in a terminal works too — it just won't survive a restart.)
34
-
35
- The installer also asks which coding agents should use TaskWindow. Choose one
36
- or more, or choose **None** to set them up later in step 4.
22
+ The guided installer:
37
23
 
38
- ### 2. Install the Chrome extension
24
+ - shows a checkbox list of detected coding agents (choose any combination, or **None**);
25
+ - installs the background daemon as a login service;
26
+ - downloads the extension to the visible `TaskWindow Extension` folder in your home directory;
27
+ - opens `chrome://extensions` and waits for a verified connection.
39
28
 
40
- You already have the CLI — add the extension:
29
+ In Chrome, turn on **Developer mode**, click **Load unpacked**, and choose the
30
+ `TaskWindow Extension` folder. Chrome requires these two manual clicks for
31
+ unpacked extensions. TaskWindow then pairs automatically with a short-lived,
32
+ single-use setup code and the installer prints `ready ✓` only after Chrome is
33
+ connected.
41
34
 
42
- ```bash
43
- taskwindow install --extension
44
- ```
45
-
46
- That downloads the latest release, unpacks it, opens Chrome at
47
- `chrome://extensions`, and prints the last 3 clicks (Developer mode →
48
- Load unpacked → select the visible `TaskWindow Extension` folder in your home
49
- directory). Chrome's own policy requires those clicks — no tool can do them
50
- for you. A Web Store listing (one-click install + auto-updates) is planned.
35
+ ### Try it
51
36
 
52
- ### 3. Pair the extension with the daemon
53
-
54
- 1. Click the TaskWindow toolbar icon → **Settings**
55
- 2. Type the 6-character pairing code from step 1 → **Pair**
56
- 3. The dot turns green: connected ✓
37
+ Ask your agent: *"Open example.com in a new tab and take a screenshot."*
57
38
 
58
- (Manual token paste also works — `~/.taskwindow/token`.)
39
+ A green tab group named after your task appears in its own window — that's
40
+ the agent's workspace. Screenshot done. Now try:
41
+ *"Find the sign-up link and read the page's headings."*
59
42
 
60
- ### 4. Connect your coding agent (one agent at a time, only when you ask)
43
+ ### Repair and advanced commands
61
44
 
62
45
  ```bash
63
- taskwindow install --claude # Claude Code (user scope: every repo)
64
- taskwindow install --cursor # Cursor
65
- ```
66
-
67
- **OpenCode** — add to `opencode.json`:
68
-
69
- ```json
70
- {
71
- "$schema": "https://opencode.ai/config.json",
72
- "mcp": {
73
- "taskwindow": {
74
- "type": "remote",
75
- "url": "http://127.0.0.1:9377/mcp",
76
- "enabled": true,
77
- "headers": { "Authorization": "Bearer <token from ~/.taskwindow/token>" }
78
- }
79
- }
80
- }
46
+ taskwindow doctor # diagnose daemon, extension, versions, and agents
47
+ taskwindow pair # create a manual one-time pairing code
48
+ taskwindow install --extension # repair or update only the extension
49
+ taskwindow install --claude # add Claude Code without repeating setup
50
+ taskwindow install --cursor # add Cursor without repeating setup
51
+ taskwindow install --opencode # add OpenCode without repeating setup
81
52
  ```
82
53
 
83
- Nothing is registered for agents you don't name. For anything else, the
84
- config is an HTTP MCP server at `http://127.0.0.1:9377/mcp` with header
85
- `Authorization: Bearer <token>` (the token is in `~/.taskwindow/token`).
86
-
87
- ### 5. Try it
88
-
89
- Ask your agent: *"Open example.com in a new tab and take a screenshot."*
90
-
91
- A green tab group named after your task appears in its own window — that's
92
- the agent's workspace. Screenshot done. Now try:
93
- *"Find the sign-up link and read the page's headings."*
54
+ Use `taskwindow install --no-extension` to install only the daemon and selected
55
+ agents. For another MCP client, connect to `http://127.0.0.1:9377/mcp` with
56
+ `Authorization: Bearer <token>`; the token is stored in `~/.taskwindow/token`.
94
57
 
95
58
  ## What the agent gets
96
59
 
97
60
  | Area | Tools |
98
61
  |---|---|
62
+ | Status | `taskwindow_status` (daemon/extension readiness and recovery guidance) |
99
63
  | Tabs | `tabs_list`, `tabs_create`, `tabs_close`, `navigate` |
100
64
  | See | `computer` (screenshot + click/type/key/scroll), `read_page`, `find`, `get_page_text` |
101
65
  | Act | `form_input`, `file_upload`, `upload_image`, `javascript_execute` |
@@ -109,9 +73,10 @@ the agent's workspace. Screenshot done. Now try:
109
73
  only see and act on tabs in its own groups — never yours. You can click a
110
74
  group in the toolbar popover to watch, and the user can widen access in
111
75
  settings.
112
- - **Pairing**: the daemon listens on 127.0.0.1 only; the extension pairs with
113
- a 6-character code printed at daemon start. MCP requests require a bearer
114
- token.
76
+ - **Pairing**: the daemon listens on 127.0.0.1 only. During setup, the CLI gives
77
+ the extension a short-lived, single-use code; the long-lived bearer token is
78
+ returned only after the code is claimed. Manual codes are available with
79
+ `taskwindow pair`.
115
80
  - **Agent actions are visible**: a phantom cursor and glow show where the
116
81
  agent is acting; while it does, Chrome shows a
117
82
  *"started debugging this browser"* infobar — an unavoidable Chrome policy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskwindow",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
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/run.mjs"
12
+ "test": "node --test test/pairing.test.mjs test/extension-bootstrap.test.mjs && node test/run.mjs"
13
13
  },
14
14
  "engines": {
15
15
  "node": ">=18"
package/src/agents.js CHANGED
@@ -6,9 +6,55 @@
6
6
  */
7
7
  import { homedir } from "node:os";
8
8
  import { join, dirname } from "node:path";
9
- import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
9
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
10
10
  import { execFileSync } from "node:child_process";
11
11
 
12
+ function commandExists(command) {
13
+ try {
14
+ execFileSync("which", [command], { stdio: "ignore" });
15
+ return true;
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+
21
+ function readJson(path) {
22
+ try {
23
+ return JSON.parse(readFileSync(path, "utf8"));
24
+ } catch {
25
+ return {};
26
+ }
27
+ }
28
+
29
+ export function inspectAgents() {
30
+ const claudePath = join(homedir(), ".claude.json");
31
+ const cursorPath = join(homedir(), ".cursor", "mcp.json");
32
+ const openCodePath = join(homedir(), ".config", "opencode", "opencode.json");
33
+ const claude = readJson(claudePath);
34
+ const cursor = readJson(cursorPath);
35
+ const openCode = readJson(openCodePath);
36
+ return [
37
+ {
38
+ id: "claude",
39
+ label: "Claude Code",
40
+ detected: commandExists("claude") || existsSync(claudePath),
41
+ configured: !!claude.mcpServers?.taskwindow,
42
+ },
43
+ {
44
+ id: "cursor",
45
+ label: "Cursor",
46
+ detected: commandExists("cursor") || existsSync(join(homedir(), ".cursor")),
47
+ configured: !!cursor.mcpServers?.taskwindow,
48
+ },
49
+ {
50
+ id: "opencode",
51
+ label: "OpenCode",
52
+ detected: commandExists("opencode") || existsSync(join(homedir(), ".config", "opencode")),
53
+ configured: !!openCode.mcp?.taskwindow,
54
+ },
55
+ ];
56
+ }
57
+
12
58
  export function registerClaude({ port, token }) {
13
59
  try {
14
60
  // Replace an older registration, if any.
package/src/index.js CHANGED
@@ -1,26 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
  import http from "node:http";
3
- import { randomBytes } from "node:crypto";
4
3
  import { fileURLToPath } from "node:url";
4
+ import { readFileSync } from "node:fs";
5
+ import { join } from "node:path";
5
6
  import { loadConfig } from "./config.js";
6
7
  import { Bridge } from "./bridge.js";
7
8
  import { createMcpRequestHandler } from "./mcp-http.js";
8
- import { installService, uninstallService, installExtension } from "./service.js";
9
+ import {
10
+ extensionInstallDir,
11
+ installService,
12
+ uninstallService,
13
+ installExtension,
14
+ removeExtensionBootstrap,
15
+ } from "./service.js";
16
+ import { PairingManager } from "./pairing.js";
17
+ import { readHealth, requestPairCode, waitForDaemon, waitForExtension } from "./setup-client.js";
9
18
  import { createRequire } from "node:module";
10
19
 
11
20
  const { version: VERSION } = createRequire(import.meta.url)("../package.json");
12
- import { registerClaude, registerCursor, registerOpenCode, unregisterAgents } from "./agents.js";
21
+ import { inspectAgents, registerClaude, registerCursor, registerOpenCode, unregisterAgents } from "./agents.js";
13
22
  import { clearLine, cursorTo, emitKeypressEvents, moveCursor } from "node:readline";
14
23
 
15
- // One-time pairing: the daemon prints a short code at startup; the extension
16
- // exchanges it for the real token via POST /pair (loopback-only). This defends
17
- // the pairing endpoint against other local user accounts; a same-user process
18
- // could read the token file directly, so the code adds no obstacle there.
19
- const PAIR_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no 0/O/1/I
20
- const pairCode = Array.from(randomBytes(6))
21
- .map((b) => PAIR_ALPHABET[b % PAIR_ALPHABET.length])
22
- .join("");
23
-
24
24
  // `taskwindow install` manages the login service and offers to register the
25
25
  // MCP server with one or more coding agents. Component-only installs do not
26
26
  // reopen the interactive picker.
@@ -29,15 +29,22 @@ const verb = args[0];
29
29
  const flags = args.slice(1);
30
30
 
31
31
  const AGENT_CHOICES = [
32
- ["Claude Code", registerClaude],
33
- ["Cursor", registerCursor],
34
- ["OpenCode", registerOpenCode],
32
+ ["claude", "Claude Code", registerClaude],
33
+ ["cursor", "Cursor", registerCursor],
34
+ ["opencode", "OpenCode", registerOpenCode],
35
35
  ];
36
36
 
37
37
  function selectCodingAgents() {
38
- const choices = [...AGENT_CHOICES.map(([label]) => label), "None (set up later)"];
38
+ const agentState = new Map(inspectAgents().map((agent) => [agent.id, agent]));
39
+ const choices = [
40
+ ...AGENT_CHOICES.map(([id, label]) => ({ label, detected: agentState.get(id)?.detected === true })),
41
+ { label: "None (set up later)", detected: false },
42
+ ];
39
43
  const noneIndex = choices.length - 1;
40
- const selected = new Set([noneIndex]);
44
+ const detected = choices
45
+ .map((choice, index) => (index !== noneIndex && choice.detected ? index : null))
46
+ .filter((index) => index !== null);
47
+ const selected = new Set(detected.length ? detected : [noneIndex]);
41
48
  let focused = 0;
42
49
  let rendered = false;
43
50
 
@@ -49,12 +56,13 @@ function selectCodingAgents() {
49
56
 
50
57
  const render = () => {
51
58
  if (rendered) moveCursor(process.stdout, 0, -choices.length);
52
- for (const [index, label] of choices.entries()) {
59
+ for (const [index, choice] of choices.entries()) {
53
60
  cursorTo(process.stdout, 0);
54
61
  clearLine(process.stdout, 0);
55
62
  const pointer = index === focused ? ">" : " ";
56
63
  const checkbox = selected.has(index) ? "[x]" : "[ ]";
57
- process.stdout.write(`${pointer} ${checkbox} ${label}\n`);
64
+ const suffix = choice.detected ? " (detected)" : "";
65
+ process.stdout.write(`${pointer} ${checkbox} ${choice.label}${suffix}\n`);
58
66
  }
59
67
  rendered = true;
60
68
  };
@@ -113,7 +121,7 @@ async function pickAndRegisterAgents(config) {
113
121
  }
114
122
  const registered = [];
115
123
  for (const index of picks) {
116
- const [label, register] = AGENT_CHOICES[index];
124
+ const [, label, register] = AGENT_CHOICES[index];
117
125
  try {
118
126
  await register(config);
119
127
  registered.push(label);
@@ -123,30 +131,127 @@ async function pickAndRegisterAgents(config) {
123
131
  }
124
132
  console.log(
125
133
  registered.length
126
- ? `[taskwindow] registered: ${registered.join(", ")} — pair the extension with code ${pairCode} if it hasn't asked`
134
+ ? `[taskwindow] registered: ${registered.join(", ")}`
127
135
  : "[taskwindow] no agents registered — run taskwindow install again to pick some"
128
136
  );
129
137
  }
130
138
 
139
+ async function ensureDaemon(config, { forceInstall = false, allowInstall = true } = {}) {
140
+ const current = await readHealth(config.port);
141
+ if (!forceInstall && current?.version === VERSION) {
142
+ console.log(`[taskwindow] daemon already running (v${current.version})`);
143
+ return current;
144
+ }
145
+ if (!allowInstall) {
146
+ if (current) return current;
147
+ throw new Error("the daemon is not running; re-run without --no-service");
148
+ }
149
+ installService(fileURLToPath(new URL("./index.js", import.meta.url)));
150
+ const health = await waitForDaemon(config.port);
151
+ if (!health) throw new Error(`daemon did not become ready on port ${config.port}`);
152
+ return health;
153
+ }
154
+
155
+ async function installAndConnectExtension(config, zipPath) {
156
+ const pairing = await requestPairCode(config);
157
+ installExtension(zipPath, { port: config.port, pairingCode: pairing.code });
158
+ console.log("[taskwindow] waiting up to 5 minutes for the extension to connect…");
159
+ const health = await waitForExtension(config.port);
160
+ if (!health) {
161
+ console.error("[taskwindow] extension not connected yet — finish the Chrome steps, then run: taskwindow doctor");
162
+ return false;
163
+ }
164
+ removeExtensionBootstrap();
165
+ console.log(`[taskwindow] ready ✓ — daemon v${health.version}, extension v${health.extensionVersion || "unknown"}`);
166
+ return true;
167
+ }
168
+
169
+ function installedExtensionVersion() {
170
+ try {
171
+ return JSON.parse(readFileSync(join(extensionInstallDir(), "manifest.json"), "utf8")).version || null;
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+
177
+ async function runDoctor(config) {
178
+ const health = await readHealth(config.port);
179
+ const installedVersion = installedExtensionVersion();
180
+ const agents = inspectAgents();
181
+ console.log(`TaskWindow doctor (CLI v${VERSION})`);
182
+ if (health) {
183
+ const versionNote = health.version === VERSION ? "" : ` — CLI is v${VERSION}; run taskwindow install to update`;
184
+ console.log(`✓ Daemon running (v${health.version}, port ${health.port})${versionNote}`);
185
+ } else {
186
+ console.log("✗ Daemon not running — run: taskwindow install");
187
+ }
188
+ if (installedVersion) console.log(`✓ Extension files installed (v${installedVersion}, ${extensionInstallDir()})`);
189
+ else console.log("✗ Extension files not installed — run: taskwindow install --extension");
190
+ if (health?.extensionConnected) {
191
+ const versionNote = installedVersion && health.extensionVersion && installedVersion !== health.extensionVersion
192
+ ? ` — installed files are v${installedVersion}; reload the extension in Chrome`
193
+ : "";
194
+ console.log(`✓ Chrome extension connected (v${health.extensionVersion || "unknown"})${versionNote}`);
195
+ } else {
196
+ console.log("✗ Chrome extension not connected — enable it in Chrome, then run: taskwindow pair");
197
+ }
198
+ for (const agent of agents) {
199
+ console.log(`${agent.configured ? "✓" : "○"} ${agent.label}${agent.configured ? " configured" : " not configured"}`);
200
+ }
201
+ if (!agents.some((agent) => agent.configured)) {
202
+ console.log(" Add an agent with: taskwindow install --claude|--cursor|--opencode");
203
+ }
204
+ return !!health && health.extensionConnected === true;
205
+ }
206
+
131
207
  try {
132
208
  if (verb === "install") {
133
209
  const config = loadConfig();
134
- if (!flags.includes("--no-service")) {
135
- installService(fileURLToPath(new URL("./index.js", import.meta.url)));
136
- }
137
210
  const extFlag = flags.indexOf("--extension");
138
- if (extFlag !== -1) {
139
- installExtension(flags[extFlag + 1] && !flags[extFlag + 1].startsWith("--") ? flags[extFlag + 1] : null);
140
- }
141
- if (flags.includes("--claude") || flags.includes("--cursor") || flags.includes("--opencode")) {
211
+ const hasAgentFlags = flags.includes("--claude") || flags.includes("--cursor") || flags.includes("--opencode");
212
+ const fullInstall = extFlag === -1 && !hasAgentFlags;
213
+ const wantsExtension = extFlag !== -1 || (fullInstall && !flags.includes("--no-extension"));
214
+
215
+ if (fullInstall) {
216
+ await pickAndRegisterAgents(config);
217
+ } else if (hasAgentFlags) {
142
218
  if (flags.includes("--claude")) registerClaude(config);
143
219
  if (flags.includes("--cursor")) registerCursor(config);
144
220
  if (flags.includes("--opencode")) registerOpenCode(config);
145
- } else if (extFlag === -1) {
146
- await pickAndRegisterAgents(config);
147
221
  }
222
+
223
+ if (fullInstall || wantsExtension) {
224
+ await ensureDaemon(config, {
225
+ forceInstall: fullInstall,
226
+ allowInstall: !flags.includes("--no-service"),
227
+ });
228
+ }
229
+
230
+ let ready = true;
231
+ if (wantsExtension) {
232
+ const zipPath = extFlag !== -1 && flags[extFlag + 1] && !flags[extFlag + 1].startsWith("--")
233
+ ? flags[extFlag + 1]
234
+ : null;
235
+ ready = await installAndConnectExtension(config, zipPath);
236
+ } else if (fullInstall) {
237
+ console.log("[taskwindow] daemon and coding-agent setup complete (--no-extension selected)");
238
+ }
239
+ process.exit(ready ? 0 : 1);
240
+ }
241
+ if (verb === "pair") {
242
+ const config = loadConfig();
243
+ const health = await readHealth(config.port);
244
+ if (!health) throw new Error("the daemon is not running; run taskwindow install first");
245
+ const pairing = await requestPairCode(config);
246
+ console.log(`[taskwindow] pairing code: ${pairing.code}`);
247
+ console.log(`[taskwindow] valid for ${Math.round(pairing.expiresInSeconds / 60)} minutes and one use`);
248
+ console.log("[taskwindow] open the TaskWindow extension → Settings, enter the code, then click Pair");
148
249
  process.exit(0);
149
250
  }
251
+ if (verb === "doctor" || verb === "status") {
252
+ const healthy = await runDoctor(loadConfig());
253
+ process.exit(healthy ? 0 : 1);
254
+ }
150
255
  if (verb === "uninstall") {
151
256
  if (!flags.includes("--keep-agents")) unregisterAgents({ port: 9377 });
152
257
  if (!flags.includes("--no-service")) uninstallService();
@@ -160,13 +265,10 @@ try {
160
265
 
161
266
  const config = loadConfig();
162
267
  const bridge = new Bridge({ token: config.token });
268
+ const pairing = new PairingManager();
163
269
 
164
270
  const handleMcp = createMcpRequestHandler({ bridge, version: VERSION });
165
271
 
166
- // One-time pairing: the daemon prints a short code at startup; the extension
167
- // exchanges it for the real token via POST /pair (loopback-only). This defends
168
- // the pairing endpoint against other local user accounts; a same-user process
169
- // could read the token file directly, so the code adds no obstacle there.
170
272
  const pairFailures = []; // timestamps of failed attempts, rolling window
171
273
  const PAIR_WINDOW_MS = 60_000;
172
274
  const PAIR_MAX_FAILURES = 5;
@@ -214,12 +316,30 @@ const server = http.createServer(async (req, res) => {
214
316
  ok: true,
215
317
  version: VERSION,
216
318
  extensionConnected: bridge.connected,
319
+ extensionVersion: bridge.lastHello?.version || null,
217
320
  port: config.port,
218
321
  });
219
322
  return;
220
323
  }
221
324
 
325
+ if (url.pathname === "/pair/request") {
326
+ if (req.method !== "POST") {
327
+ sendJson(res, 405, { error: "method not allowed; POST to request a pairing code" });
328
+ return;
329
+ }
330
+ if (req.headers.authorization !== `Bearer ${config.token}`) {
331
+ sendJson(res, 401, { error: "invalid or missing bearer token" });
332
+ return;
333
+ }
334
+ sendJson(res, 200, pairing.issue());
335
+ return;
336
+ }
337
+
222
338
  if (url.pathname === "/pair") {
339
+ if (req.method !== "POST") {
340
+ sendJson(res, 405, { error: "method not allowed; POST a pairing code" });
341
+ return;
342
+ }
223
343
  if (pairRateLimited()) {
224
344
  sendJson(res, 429, { error: "too many failed pairing attempts; wait a minute" });
225
345
  return;
@@ -232,9 +352,9 @@ const server = http.createServer(async (req, res) => {
232
352
  return;
233
353
  }
234
354
  const code = String(body?.code || "").trim().toUpperCase();
235
- if (code !== pairCode) {
355
+ if (!pairing.claim(code)) {
236
356
  pairFailures.push(Date.now());
237
- sendJson(res, 403, { error: "invalid pairing code" });
357
+ sendJson(res, 403, { error: "invalid or expired pairing code" });
238
358
  return;
239
359
  }
240
360
  sendJson(res, 200, { token: config.token });
@@ -288,9 +408,7 @@ server.on("error", (err) => {
288
408
  server.listen(config.port, "127.0.0.1", () => {
289
409
  console.log(`[taskwindow] daemon listening on http://127.0.0.1:${config.port}`);
290
410
  console.log(`[taskwindow] MCP endpoint: http://127.0.0.1:${config.port}/mcp`);
291
- console.log(`[taskwindow] pairing code: ${pairCode} — enter it in the TaskWindow extension options to connect (valid while this daemon runs)`);
292
- console.log(`[taskwindow] your MCP client config: endpoint http://127.0.0.1:${config.port}/mcp, header "Authorization: Bearer ${config.token}"`);
293
- console.log(`[taskwindow] register an agent with: taskwindow install --claude (or --cursor)`);
411
+ console.log("[taskwindow] run taskwindow doctor for connection status or taskwindow pair for manual pairing");
294
412
  console.log(`[taskwindow] waiting for the TaskWindow extension to connect on ws://127.0.0.1:${config.port}/ws`);
295
413
  });
296
414
 
package/src/mcp-http.js CHANGED
@@ -10,7 +10,7 @@ import { registerTools } from "./tools.js";
10
10
  export function createMcpRequestHandler({ bridge, version, logger = console }) {
11
11
  return async function handleMcpRequest(req, res, parsedBody) {
12
12
  const server = new McpServer({ name: "taskwindow", version });
13
- registerTools(server, { bridge, logger });
13
+ registerTools(server, { bridge, version, logger });
14
14
  const transport = new StreamableHTTPServerTransport({
15
15
  sessionIdGenerator: undefined,
16
16
  enableJsonResponse: true,
package/src/pairing.js ADDED
@@ -0,0 +1,40 @@
1
+ import { randomBytes } from "node:crypto";
2
+
3
+ const PAIR_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no 0/O/1/I
4
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
5
+
6
+ function createCode() {
7
+ return Array.from(randomBytes(6))
8
+ .map((byte) => PAIR_ALPHABET[byte % PAIR_ALPHABET.length])
9
+ .join("");
10
+ }
11
+
12
+ /** Short-lived, single-use codes for exchanging the daemon token. */
13
+ export class PairingManager {
14
+ constructor({ ttlMs = DEFAULT_TTL_MS, now = () => Date.now(), generateCode = createCode } = {}) {
15
+ this.ttlMs = ttlMs;
16
+ this.now = now;
17
+ this.generateCode = generateCode;
18
+ this.code = null;
19
+ this.expiresAt = 0;
20
+ }
21
+
22
+ issue() {
23
+ this.code = this.generateCode();
24
+ this.expiresAt = this.now() + this.ttlMs;
25
+ return {
26
+ code: this.code,
27
+ expiresAt: new Date(this.expiresAt).toISOString(),
28
+ expiresInSeconds: Math.ceil(this.ttlMs / 1000),
29
+ };
30
+ }
31
+
32
+ claim(candidate) {
33
+ const normalized = String(candidate || "").trim().toUpperCase();
34
+ if (!this.code || this.now() >= this.expiresAt || normalized !== this.code) return false;
35
+ this.code = null;
36
+ this.expiresAt = 0;
37
+ return true;
38
+ }
39
+ }
40
+
package/src/service.js CHANGED
@@ -5,10 +5,26 @@
5
5
  */
6
6
  import { homedir, platform } from "node:os";
7
7
  import { join } from "node:path";
8
- import { writeFileSync, unlinkSync, mkdirSync } from "node:fs";
9
- import { execSync } from "node:child_process";
8
+ import { chmodSync, writeFileSync, unlinkSync, mkdirSync } from "node:fs";
9
+ import { execFileSync, execSync } from "node:child_process";
10
10
 
11
11
  const LABEL = "com.clawnify.taskwindow";
12
+ const EXTENSION_DIRNAME = "TaskWindow Extension";
13
+ const BOOTSTRAP_FILENAME = "taskwindow-bootstrap.json";
14
+
15
+ export function extensionInstallDir(home = homedir()) {
16
+ return join(home, EXTENSION_DIRNAME);
17
+ }
18
+
19
+ export function extensionBootstrapPath(home = homedir()) {
20
+ return join(extensionInstallDir(home), BOOTSTRAP_FILENAME);
21
+ }
22
+
23
+ export function removeExtensionBootstrap(home = homedir()) {
24
+ try {
25
+ unlinkSync(extensionBootstrapPath(home));
26
+ } catch {}
27
+ }
12
28
 
13
29
  function nodePath() {
14
30
  return process.execPath;
@@ -105,14 +121,14 @@ WantedBy=default.target
105
121
  * programmatic unpacked installs, so a human does the final 3 clicks — the
106
122
  * command does everything else.
107
123
  */
108
- export function installExtension(zipPath) {
124
+ export function installExtension(zipPath, { port, pairingCode } = {}) {
109
125
  // This folder must remain visible in macOS's file picker: Chrome asks the
110
126
  // user to select it after clicking "Load unpacked", and Finder hides paths
111
127
  // whose names begin with a period by default.
112
- const extDir = join(homedir(), "TaskWindow Extension");
128
+ const extDir = extensionInstallDir();
113
129
  const open = (u) => {
114
130
  try {
115
- execSync(`open -a "Google Chrome" "${u}"`);
131
+ execFileSync("open", ["-a", "Google Chrome", u]);
116
132
  return true;
117
133
  } catch {
118
134
  return false;
@@ -123,21 +139,27 @@ export function installExtension(zipPath) {
123
139
  // No zip given: fetch the latest release asset from GitHub.
124
140
  try {
125
141
  const api = "https://api.github.com/repos/clawnify/taskwindow/releases/latest";
126
- const release = JSON.parse(execSync(`curl -sL "${api}"`, { maxBuffer: 20e6 }).toString());
142
+ const release = JSON.parse(execFileSync("curl", ["-sL", api], { maxBuffer: 20e6 }).toString());
127
143
  const asset = (release.assets || []).find((a) => a.name.startsWith("TaskWindow-extension-"));
128
144
  if (!asset) throw new Error("no extension asset in the latest release");
129
145
  zipPath = join(homedir(), ".taskwindow", asset.name);
130
- execSync(`curl -sL -o "${zipPath}" "${asset.browser_download_url}"`);
146
+ execFileSync("curl", ["-sL", "-o", zipPath, asset.browser_download_url]);
131
147
  console.log(`[taskwindow] downloaded ${asset.name}`);
132
148
  } catch (err) {
133
- console.error(`[taskwindow] couldn't download the extension zip (${err.message}).`);
134
- console.error(`[taskwindow] download it from https://github.com/clawnify/taskwindow/releases and re-run with --extension <zip>`);
135
- return;
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
+ );
136
153
  }
137
154
  }
138
155
 
139
156
  mkdirSync(extDir, { recursive: true });
140
- execSync(`unzip -oq "${zipPath}" -d "${extDir}"`);
157
+ execFileSync("unzip", ["-oq", zipPath, "-d", extDir]);
158
+ if (pairingCode && port) {
159
+ const bootstrapPath = extensionBootstrapPath();
160
+ writeFileSync(bootstrapPath, JSON.stringify({ code: pairingCode, port }, null, 2) + "\n", { mode: 0o600 });
161
+ chmodSync(bootstrapPath, 0o600);
162
+ }
141
163
  console.log(`[taskwindow] extension unpacked to ${extDir}`);
142
164
  if (open("chrome://extensions")) {
143
165
  console.log("[taskwindow] opened chrome://extensions in Chrome — finish in 3 clicks:");
@@ -146,7 +168,8 @@ export function installExtension(zipPath) {
146
168
  }
147
169
  console.log(" 1. turn on Developer mode (top right)");
148
170
  console.log(` 2. click "Load unpacked" and select: ${extDir}`);
149
- console.log(" 3. done — the extension pairs itself from here (options page if it asks)");
171
+ console.log(" 3. TaskWindow will connect automatically");
172
+ return extDir;
150
173
  }
151
174
 
152
175
  export function uninstallService() {
@@ -0,0 +1,60 @@
1
+ const RETRY_MS = 300;
2
+
3
+ function delay(ms) {
4
+ return new Promise((resolve) => setTimeout(resolve, ms));
5
+ }
6
+
7
+ async function fetchWithTimeout(url, options = {}, timeoutMs = 1500) {
8
+ const controller = new AbortController();
9
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
10
+ try {
11
+ return await fetch(url, { ...options, signal: controller.signal });
12
+ } finally {
13
+ clearTimeout(timer);
14
+ }
15
+ }
16
+
17
+ export async function readHealth(port) {
18
+ try {
19
+ const response = await fetchWithTimeout(`http://127.0.0.1:${port}/health`);
20
+ if (!response.ok) return null;
21
+ return await response.json();
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ async function waitForHealth(port, predicate, timeoutMs) {
28
+ const deadline = Date.now() + timeoutMs;
29
+ do {
30
+ const health = await readHealth(port);
31
+ if (health && predicate(health)) return health;
32
+ await delay(RETRY_MS);
33
+ } while (Date.now() < deadline);
34
+ return null;
35
+ }
36
+
37
+ export function waitForDaemon(port, timeoutMs = 10_000) {
38
+ return waitForHealth(port, (health) => health.ok === true, timeoutMs);
39
+ }
40
+
41
+ export function waitForExtension(port, timeoutMs = 5 * 60 * 1000) {
42
+ return waitForHealth(port, (health) => health.extensionConnected === true, timeoutMs);
43
+ }
44
+
45
+ export async function requestPairCode({ port, token }) {
46
+ const response = await fetchWithTimeout(
47
+ `http://127.0.0.1:${port}/pair/request`,
48
+ {
49
+ method: "POST",
50
+ headers: { authorization: `Bearer ${token}` },
51
+ },
52
+ 3000
53
+ );
54
+ const body = await response.json().catch(() => ({}));
55
+ if (!response.ok || !body.code) {
56
+ throw new Error(body.error || `pairing request failed (HTTP ${response.status})`);
57
+ }
58
+ return body;
59
+ }
60
+
package/src/tools.js CHANGED
@@ -7,6 +7,13 @@ const tabId = z.number().int().describe("Tab ID from tabs_list. Defaults to the
7
7
  // into text blocks.
8
8
 
9
9
  const toolDefs = [
10
+ {
11
+ name: "taskwindow_status",
12
+ description:
13
+ "Check whether the local TaskWindow daemon and Chrome extension are ready. Call this when browser tools report a connection problem; it returns the exact recovery action without requiring the extension.",
14
+ inputSchema: {},
15
+ local: true,
16
+ },
10
17
  {
11
18
  name: "tabs_list",
12
19
  description:
@@ -232,7 +239,7 @@ const toolDefs = [
232
239
  },
233
240
  ];
234
241
 
235
- const toolNames = new Set(toolDefs.map((t) => t.name));
242
+ const toolNames = new Set(toolDefs.filter((tool) => !tool.local).map((tool) => tool.name));
236
243
 
237
244
  function toMcpResult(result) {
238
245
  const content = [];
@@ -255,10 +262,24 @@ function toMcpResult(result) {
255
262
  return { content };
256
263
  }
257
264
 
258
- export function registerTools(server, { bridge, logger = console }) {
265
+ export function registerTools(server, { bridge, version, logger = console }) {
259
266
  for (const def of toolDefs) {
260
267
  server.registerTool(def.name, { description: def.description, inputSchema: def.inputSchema }, async (args) => {
261
268
  try {
269
+ if (def.local) {
270
+ const connected = bridge.connected;
271
+ return toMcpResult({
272
+ data: {
273
+ daemon: "running",
274
+ daemonVersion: version,
275
+ extensionConnected: connected,
276
+ extensionVersion: bridge.lastHello?.version || null,
277
+ recovery: connected
278
+ ? null
279
+ : "Open Chrome and enable TaskWindow. If it remains disconnected, run `taskwindow doctor`, then `taskwindow pair`.",
280
+ },
281
+ });
282
+ }
262
283
  if (def.name === "browser_batch") return await runBatch(args, bridge, logger);
263
284
  const result = await bridge.sendTool(def.name, args, def.timeoutMs);
264
285
  return toMcpResult(result);