windows-use 0.1.0

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.
@@ -0,0 +1,1034 @@
1
+ // src/mcp/server.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+
5
+ // src/mcp/session-registry.ts
6
+ import crypto from "crypto";
7
+
8
+ // src/agent/context-manager.ts
9
+ var ContextManager = class {
10
+ messages = [];
11
+ maxMessages;
12
+ constructor(maxMessages) {
13
+ this.maxMessages = maxMessages;
14
+ }
15
+ append(message) {
16
+ this.messages.push(message);
17
+ }
18
+ /** Returns the system prompt + the most recent messages within the window. */
19
+ getWindow() {
20
+ if (this.messages.length === 0) return [];
21
+ const systemPrompt = this.messages[0]?.role === "system" ? this.messages[0] : null;
22
+ const nonSystem = systemPrompt ? this.messages.slice(1) : this.messages;
23
+ const windowSize = this.maxMessages - (systemPrompt ? 1 : 0);
24
+ const windowed = nonSystem.length > windowSize ? nonSystem.slice(-windowSize) : nonSystem;
25
+ return systemPrompt ? [systemPrompt, ...windowed] : windowed;
26
+ }
27
+ /** Total messages stored (before windowing). */
28
+ get length() {
29
+ return this.messages.length;
30
+ }
31
+ };
32
+
33
+ // src/agent/llm-client.ts
34
+ import OpenAI from "openai";
35
+ var LLMClient = class {
36
+ client;
37
+ model;
38
+ constructor(config) {
39
+ this.client = new OpenAI({
40
+ apiKey: config.apiKey,
41
+ baseURL: config.baseURL
42
+ });
43
+ this.model = config.model;
44
+ }
45
+ async chat(messages, tools) {
46
+ return this.client.chat.completions.create({
47
+ model: this.model,
48
+ messages,
49
+ tools: tools.length > 0 ? tools : void 0,
50
+ tool_choice: tools.length > 0 ? "auto" : void 0
51
+ });
52
+ }
53
+ };
54
+
55
+ // src/agent/system-prompt.ts
56
+ function buildSystemPrompt() {
57
+ return `You are a precise Windows and browser automation agent. Your job is to execute instructions by calling the tools available to you.
58
+
59
+ ## Workflow
60
+ 1. Take a screenshot first to understand the current state of the screen.
61
+ 2. Plan the minimal sequence of actions needed.
62
+ 3. Execute each action one at a time, then verify by taking another screenshot.
63
+ 4. When the task is done, you are blocked, or you need guidance, call \`report\` immediately.
64
+
65
+ ## Rules
66
+ - ALWAYS take a screenshot before your first action to understand the current state.
67
+ - After every mouse click or keyboard action, take a screenshot to verify the result.
68
+ - Call ONE tool at a time. Never request multiple tools in parallel.
69
+ - Before each tool call, briefly state what you are about to do and why.
70
+ - After receiving a tool result, describe what you observed.
71
+ - For browser tasks, prefer using browser_* tools over clicking on-screen coordinates.
72
+ - For terminal tasks, prefer \`run_command\` over GUI interactions when possible.
73
+ - Do not read or write files unless the instruction explicitly asks for it.
74
+
75
+ ## report Tool
76
+ Call \`report\` when:
77
+ - **"completed"**: The task is done successfully. Summarize what was accomplished.
78
+ - **"blocked"**: You cannot proceed (CAPTCHA, login wall, unexpected error). Explain what's blocking you.
79
+ - **"need_guidance"**: You need a decision or clarification. Describe what you need.
80
+
81
+ Calling \`report\` stops your execution. Include a concise summary and optionally a screenshot as evidence.
82
+
83
+ ## Important
84
+ - Do NOT keep retrying the same failing action. If something fails twice, call \`report\` with status "blocked".
85
+ - If a UI element is not where you expect it, try scrolling first before giving up.
86
+ - Keep your responses concise. Focus on actions, not explanations.`;
87
+ }
88
+
89
+ // src/agent/runner.ts
90
+ var AgentRunner = class {
91
+ llmClient;
92
+ contextManager;
93
+ toolRegistry;
94
+ config;
95
+ toolContext;
96
+ initialized = false;
97
+ constructor(llmClient, contextManager, toolRegistry, config, toolContext) {
98
+ this.llmClient = llmClient;
99
+ this.contextManager = contextManager;
100
+ this.toolRegistry = toolRegistry;
101
+ this.config = config;
102
+ this.toolContext = toolContext;
103
+ }
104
+ async run(instruction) {
105
+ if (!this.initialized) {
106
+ this.contextManager.append({
107
+ role: "system",
108
+ content: buildSystemPrompt()
109
+ });
110
+ this.initialized = true;
111
+ }
112
+ this.contextManager.append({
113
+ role: "user",
114
+ content: instruction
115
+ });
116
+ let stepsUsed = 0;
117
+ while (stepsUsed < this.config.maxSteps) {
118
+ stepsUsed++;
119
+ const remaining = this.config.maxSteps - stepsUsed;
120
+ const messages = this.contextManager.getWindow();
121
+ if (remaining <= 3 && remaining >= 0) {
122
+ messages.push({
123
+ role: "system",
124
+ content: `\u26A0\uFE0F You have ${remaining} steps remaining. Call \`report\` NOW to summarize your progress. If you do not call report, your work will be lost.`
125
+ });
126
+ }
127
+ const tools = this.toolRegistry.toOpenAIFormat();
128
+ let response;
129
+ try {
130
+ response = await this.llmClient.chat(messages, tools);
131
+ } catch (err) {
132
+ const msg = err instanceof Error ? err.message : String(err);
133
+ return {
134
+ status: "blocked",
135
+ summary: `LLM API error: ${msg}`,
136
+ stepsUsed
137
+ };
138
+ }
139
+ const choice = response.choices[0];
140
+ if (!choice) {
141
+ return {
142
+ status: "blocked",
143
+ summary: "LLM returned empty response",
144
+ stepsUsed
145
+ };
146
+ }
147
+ const message = choice.message;
148
+ if (choice.finish_reason === "stop" || !message.tool_calls?.length) {
149
+ const text = message.content ?? "";
150
+ this.contextManager.append({ role: "assistant", content: text });
151
+ return {
152
+ status: "need_guidance",
153
+ summary: text || "Agent stopped without calling report.",
154
+ stepsUsed
155
+ };
156
+ }
157
+ this.contextManager.append(message);
158
+ for (const toolCall of message.tool_calls) {
159
+ let args;
160
+ try {
161
+ args = JSON.parse(toolCall.function.arguments);
162
+ } catch {
163
+ this.contextManager.append({
164
+ role: "tool",
165
+ tool_call_id: toolCall.id,
166
+ content: "Error: could not parse tool arguments as JSON"
167
+ });
168
+ continue;
169
+ }
170
+ let result;
171
+ try {
172
+ result = await this.toolRegistry.execute(
173
+ toolCall.function.name,
174
+ args,
175
+ this.toolContext
176
+ );
177
+ } catch (err) {
178
+ const msg = err instanceof Error ? err.message : String(err);
179
+ this.contextManager.append({
180
+ role: "tool",
181
+ tool_call_id: toolCall.id,
182
+ content: `Error executing tool: ${msg}`
183
+ });
184
+ continue;
185
+ }
186
+ if (result.type === "report") {
187
+ this.contextManager.append({
188
+ role: "tool",
189
+ tool_call_id: toolCall.id,
190
+ content: "Report submitted. Returning control to caller."
191
+ });
192
+ return {
193
+ status: result.status,
194
+ summary: result.summary,
195
+ screenshot: result.screenshot,
196
+ data: result.data,
197
+ stepsUsed
198
+ };
199
+ }
200
+ if (result.type === "image") {
201
+ this.contextManager.append({
202
+ role: "tool",
203
+ tool_call_id: toolCall.id,
204
+ content: [
205
+ { type: "text", text: "Screenshot captured." },
206
+ {
207
+ type: "image_url",
208
+ image_url: {
209
+ url: `data:${result.mimeType};base64,${result.base64}`
210
+ }
211
+ }
212
+ ]
213
+ });
214
+ } else {
215
+ this.contextManager.append({
216
+ role: "tool",
217
+ tool_call_id: toolCall.id,
218
+ content: result.content
219
+ });
220
+ }
221
+ }
222
+ }
223
+ return {
224
+ status: "blocked",
225
+ summary: `Exceeded maximum steps limit (${this.config.maxSteps}). Task may be incomplete.`,
226
+ stepsUsed
227
+ };
228
+ }
229
+ };
230
+
231
+ // src/tools/browser/client.ts
232
+ var BrowserClient = class {
233
+ browser = null;
234
+ context = null;
235
+ _page = null;
236
+ cdpUrl;
237
+ constructor(cdpUrl) {
238
+ this.cdpUrl = cdpUrl;
239
+ }
240
+ async connect() {
241
+ if (this.browser) return;
242
+ const { chromium } = await import("playwright");
243
+ this.browser = await chromium.connectOverCDP(this.cdpUrl);
244
+ const contexts = this.browser.contexts();
245
+ this.context = contexts[0] ?? await this.browser.newContext();
246
+ const pages = this.context.pages();
247
+ this._page = pages[0] ?? await this.context.newPage();
248
+ }
249
+ async getPage() {
250
+ await this.connect();
251
+ return this._page;
252
+ }
253
+ /** Create a new tab and switch to it. */
254
+ async newPage() {
255
+ await this.connect();
256
+ this._page = await this.context.newPage();
257
+ return this._page;
258
+ }
259
+ async close() {
260
+ if (this.browser) {
261
+ await this.browser.close().catch(() => {
262
+ });
263
+ this.browser = null;
264
+ this.context = null;
265
+ this._page = null;
266
+ }
267
+ }
268
+ get connected() {
269
+ return this.browser !== null && this.browser.isConnected();
270
+ }
271
+ };
272
+
273
+ // src/tools/zod-to-json.ts
274
+ function zodToJsonSchema(schema) {
275
+ return convertZodType(schema);
276
+ }
277
+ function convertZodType(schema) {
278
+ const def = schema._def;
279
+ const typeName = def?.typeName;
280
+ switch (typeName) {
281
+ case "ZodObject": {
282
+ const shape = schema.shape;
283
+ const properties = {};
284
+ const required = [];
285
+ for (const [key, value] of Object.entries(shape)) {
286
+ properties[key] = convertZodType(value);
287
+ if (!isOptional(value)) {
288
+ required.push(key);
289
+ }
290
+ }
291
+ return {
292
+ type: "object",
293
+ properties,
294
+ ...required.length > 0 ? { required } : {}
295
+ };
296
+ }
297
+ case "ZodString": {
298
+ const result = { type: "string" };
299
+ if (def.description) result.description = def.description;
300
+ return result;
301
+ }
302
+ case "ZodNumber": {
303
+ const result = { type: "number" };
304
+ if (def.description) result.description = def.description;
305
+ return result;
306
+ }
307
+ case "ZodBoolean": {
308
+ const result = { type: "boolean" };
309
+ if (def.description) result.description = def.description;
310
+ return result;
311
+ }
312
+ case "ZodEnum": {
313
+ const result = {
314
+ type: "string",
315
+ enum: def.values
316
+ };
317
+ if (def.description) result.description = def.description;
318
+ return result;
319
+ }
320
+ case "ZodArray": {
321
+ const result = {
322
+ type: "array",
323
+ items: convertZodType(def.type)
324
+ };
325
+ if (def.description) result.description = def.description;
326
+ return result;
327
+ }
328
+ case "ZodOptional":
329
+ return convertZodType(def.innerType);
330
+ case "ZodDefault":
331
+ return convertZodType(def.innerType);
332
+ case "ZodEffects":
333
+ return convertZodType(def.schema);
334
+ case "ZodUnknown":
335
+ return {};
336
+ default:
337
+ return { type: "string" };
338
+ }
339
+ }
340
+ function isOptional(schema) {
341
+ const def = schema._def;
342
+ const typeName = def?.typeName;
343
+ return typeName === "ZodOptional" || typeName === "ZodDefault";
344
+ }
345
+
346
+ // src/tools/registry.ts
347
+ var ToolRegistry = class {
348
+ tools = /* @__PURE__ */ new Map();
349
+ register(tool) {
350
+ this.tools.set(tool.name, tool);
351
+ }
352
+ get(name) {
353
+ return this.tools.get(name);
354
+ }
355
+ toOpenAIFormat() {
356
+ return Array.from(this.tools.values()).map((tool) => ({
357
+ type: "function",
358
+ function: {
359
+ name: tool.name,
360
+ description: tool.description,
361
+ parameters: zodToJsonSchema(tool.parameters)
362
+ }
363
+ }));
364
+ }
365
+ async execute(name, args, context) {
366
+ const tool = this.tools.get(name);
367
+ if (!tool) {
368
+ return { type: "text", content: `Error: unknown tool "${name}"` };
369
+ }
370
+ const parsed = tool.parameters.safeParse(args);
371
+ if (!parsed.success) {
372
+ return {
373
+ type: "text",
374
+ content: `Error: invalid arguments for "${name}": ${parsed.error.message}`
375
+ };
376
+ }
377
+ return tool.execute(parsed.data, context);
378
+ }
379
+ };
380
+
381
+ // src/tools/windows/screenshot.ts
382
+ import { z } from "zod";
383
+ var screenshotTool = {
384
+ name: "screenshot",
385
+ description: "Capture the full screen and return it as an image. Use this to see what is currently displayed.",
386
+ parameters: z.object({}),
387
+ async execute() {
388
+ const { Monitor } = await import("node-screenshots");
389
+ const monitors = Monitor.all();
390
+ const primary = monitors.find((m) => m.isPrimary()) ?? monitors[0];
391
+ if (!primary) {
392
+ return { type: "text", content: "Error: No monitor found" };
393
+ }
394
+ const image = primary.captureImageSync();
395
+ const buf = image.toPngSync();
396
+ return {
397
+ type: "image",
398
+ base64: buf.toString("base64"),
399
+ mimeType: "image/png"
400
+ };
401
+ }
402
+ };
403
+
404
+ // src/tools/windows/mouse.ts
405
+ import { z as z2 } from "zod";
406
+ async function getNutJs() {
407
+ return import("@nut-tree-fork/nut-js");
408
+ }
409
+ var mouseClickTool = {
410
+ name: "mouse_click",
411
+ description: "Click the mouse at the given screen coordinates.",
412
+ parameters: z2.object({
413
+ x: z2.number().describe("X coordinate on screen"),
414
+ y: z2.number().describe("Y coordinate on screen"),
415
+ button: z2.enum(["left", "right", "middle"]).default("left").describe("Mouse button")
416
+ }),
417
+ async execute(args) {
418
+ const nut = await getNutJs();
419
+ const point = new nut.Point(args.x, args.y);
420
+ await nut.mouse.move(nut.straightTo(point));
421
+ const buttonMap = {
422
+ left: nut.Button.LEFT,
423
+ right: nut.Button.RIGHT,
424
+ middle: nut.Button.MIDDLE
425
+ };
426
+ await nut.mouse.click(buttonMap[args.button]);
427
+ return { type: "text", content: `Clicked ${args.button} at (${args.x}, ${args.y})` };
428
+ }
429
+ };
430
+ var mouseMoveTool = {
431
+ name: "mouse_move",
432
+ description: "Move the mouse to the given screen coordinates without clicking.",
433
+ parameters: z2.object({
434
+ x: z2.number().describe("X coordinate on screen"),
435
+ y: z2.number().describe("Y coordinate on screen")
436
+ }),
437
+ async execute(args) {
438
+ const nut = await getNutJs();
439
+ const point = new nut.Point(args.x, args.y);
440
+ await nut.mouse.move(nut.straightTo(point));
441
+ return { type: "text", content: `Mouse moved to (${args.x}, ${args.y})` };
442
+ }
443
+ };
444
+ var mouseScrollTool = {
445
+ name: "mouse_scroll",
446
+ description: "Scroll the mouse wheel.",
447
+ parameters: z2.object({
448
+ direction: z2.enum(["up", "down"]).describe("Scroll direction"),
449
+ amount: z2.number().positive().default(3).describe("Number of scroll steps")
450
+ }),
451
+ async execute(args) {
452
+ const nut = await getNutJs();
453
+ for (let i = 0; i < args.amount; i++) {
454
+ if (args.direction === "down") {
455
+ await nut.mouse.scrollDown(1);
456
+ } else {
457
+ await nut.mouse.scrollUp(1);
458
+ }
459
+ }
460
+ return { type: "text", content: `Scrolled ${args.direction} ${args.amount} steps` };
461
+ }
462
+ };
463
+
464
+ // src/tools/windows/keyboard.ts
465
+ import { z as z3 } from "zod";
466
+ async function getNutJs2() {
467
+ return import("@nut-tree-fork/nut-js");
468
+ }
469
+ var keyboardTypeTool = {
470
+ name: "keyboard_type",
471
+ description: "Type text using the keyboard. The text is typed character by character.",
472
+ parameters: z3.object({
473
+ text: z3.string().describe("The text to type")
474
+ }),
475
+ async execute(args) {
476
+ const nut = await getNutJs2();
477
+ await nut.keyboard.type(args.text);
478
+ return { type: "text", content: `Typed: "${args.text}"` };
479
+ }
480
+ };
481
+ function resolveKey(nut, keyName) {
482
+ const keyMap = {
483
+ "ctrl": "LeftControl",
484
+ "control": "LeftControl",
485
+ "shift": "LeftShift",
486
+ "alt": "LeftAlt",
487
+ "meta": "LeftWin",
488
+ "win": "LeftWin",
489
+ "windows": "LeftWin",
490
+ "enter": "Return",
491
+ "return": "Return",
492
+ "tab": "Tab",
493
+ "escape": "Escape",
494
+ "esc": "Escape",
495
+ "backspace": "Backspace",
496
+ "delete": "Delete",
497
+ "space": "Space",
498
+ "up": "Up",
499
+ "down": "Down",
500
+ "left": "Left",
501
+ "right": "Right",
502
+ "home": "Home",
503
+ "end": "End",
504
+ "pageup": "PageUp",
505
+ "pagedown": "PageDown",
506
+ "f1": "F1",
507
+ "f2": "F2",
508
+ "f3": "F3",
509
+ "f4": "F4",
510
+ "f5": "F5",
511
+ "f6": "F6",
512
+ "f7": "F7",
513
+ "f8": "F8",
514
+ "f9": "F9",
515
+ "f10": "F10",
516
+ "f11": "F11",
517
+ "f12": "F12"
518
+ };
519
+ const normalized = keyName.toLowerCase().trim();
520
+ const mapped = keyMap[normalized] ?? keyName;
521
+ const key = nut.Key[mapped];
522
+ if (key !== void 0) return key;
523
+ if (mapped.length === 1) {
524
+ const upper = mapped.toUpperCase();
525
+ const k = nut.Key[upper];
526
+ if (k !== void 0) return k;
527
+ }
528
+ throw new Error(`Unknown key: "${keyName}"`);
529
+ }
530
+ var keyboardPressTool = {
531
+ name: "keyboard_press",
532
+ description: 'Press a key combination. Examples: ["Ctrl", "C"] for copy, ["Enter"] for enter, ["Alt", "F4"] to close window.',
533
+ parameters: z3.object({
534
+ keys: z3.array(z3.string()).min(1).describe("Array of key names to press simultaneously")
535
+ }),
536
+ async execute(args) {
537
+ const nut = await getNutJs2();
538
+ const resolved = args.keys.map((k) => resolveKey(nut, k));
539
+ await nut.keyboard.pressKey(...resolved);
540
+ await nut.keyboard.releaseKey(...resolved);
541
+ return { type: "text", content: `Pressed: ${args.keys.join("+")}` };
542
+ }
543
+ };
544
+
545
+ // src/tools/windows/command.ts
546
+ import { z as z4 } from "zod";
547
+ import { exec } from "child_process";
548
+ var MAX_OUTPUT_LENGTH = 1e4;
549
+ var runCommandTool = {
550
+ name: "run_command",
551
+ description: "Execute a shell command and return its output. Uses PowerShell on Windows.",
552
+ parameters: z4.object({
553
+ command: z4.string().describe("The command to execute"),
554
+ timeout: z4.number().positive().default(3e4).describe("Timeout in milliseconds")
555
+ }),
556
+ async execute(args) {
557
+ return new Promise((resolve) => {
558
+ exec(
559
+ args.command,
560
+ {
561
+ timeout: args.timeout,
562
+ maxBuffer: 1024 * 1024,
563
+ shell: "powershell.exe",
564
+ windowsHide: true
565
+ },
566
+ (error, stdout, stderr) => {
567
+ let output = "";
568
+ if (stdout) output += stdout;
569
+ if (stderr) output += `
570
+ [stderr] ${stderr}`;
571
+ if (error && error.killed) output += "\n[timeout] Command timed out";
572
+ else if (error) output += `
573
+ [exit code ${error.code}]`;
574
+ if (output.length > MAX_OUTPUT_LENGTH) {
575
+ output = output.slice(0, MAX_OUTPUT_LENGTH) + "\n...(truncated)";
576
+ }
577
+ resolve({ type: "text", content: output.trim() || "(no output)" });
578
+ }
579
+ );
580
+ });
581
+ }
582
+ };
583
+
584
+ // src/tools/file/read.ts
585
+ import { z as z5 } from "zod";
586
+ import { readFile } from "fs/promises";
587
+ var MAX_FILE_SIZE = 1e5;
588
+ var fileReadTool = {
589
+ name: "file_read",
590
+ description: "Read the contents of a file at the given path.",
591
+ parameters: z5.object({
592
+ path: z5.string().describe("Absolute path to the file")
593
+ }),
594
+ async execute(args) {
595
+ try {
596
+ const content = await readFile(args.path, "utf-8");
597
+ if (content.length > MAX_FILE_SIZE) {
598
+ return {
599
+ type: "text",
600
+ content: content.slice(0, MAX_FILE_SIZE) + "\n...(truncated)"
601
+ };
602
+ }
603
+ return { type: "text", content };
604
+ } catch (err) {
605
+ const msg = err instanceof Error ? err.message : String(err);
606
+ return { type: "text", content: `Error reading file: ${msg}` };
607
+ }
608
+ }
609
+ };
610
+
611
+ // src/tools/file/write.ts
612
+ import { z as z6 } from "zod";
613
+ import { writeFile, mkdir } from "fs/promises";
614
+ import { dirname } from "path";
615
+ var fileWriteTool = {
616
+ name: "file_write",
617
+ description: "Write content to a file at the given path. Creates parent directories if needed.",
618
+ parameters: z6.object({
619
+ path: z6.string().describe("Absolute path to the file"),
620
+ content: z6.string().describe("Content to write")
621
+ }),
622
+ async execute(args) {
623
+ try {
624
+ await mkdir(dirname(args.path), { recursive: true });
625
+ await writeFile(args.path, args.content, "utf-8");
626
+ return { type: "text", content: `File written: ${args.path}` };
627
+ } catch (err) {
628
+ const msg = err instanceof Error ? err.message : String(err);
629
+ return { type: "text", content: `Error writing file: ${msg}` };
630
+ }
631
+ }
632
+ };
633
+
634
+ // src/tools/browser/navigate.ts
635
+ import { z as z7 } from "zod";
636
+ var browserNavigateTool = {
637
+ name: "browser_navigate",
638
+ description: "Navigate the browser to a URL.",
639
+ parameters: z7.object({
640
+ url: z7.string().describe("The URL to navigate to")
641
+ }),
642
+ async execute(args, ctx) {
643
+ const browser = await ctx.getBrowser();
644
+ const page = await browser.getPage();
645
+ await page.goto(args.url, { waitUntil: "domcontentloaded", timeout: 3e4 });
646
+ const title = await page.title();
647
+ return { type: "text", content: `Navigated to: ${args.url}
648
+ Page title: ${title}` };
649
+ }
650
+ };
651
+
652
+ // src/tools/browser/click.ts
653
+ import { z as z8 } from "zod";
654
+ var browserClickTool = {
655
+ name: "browser_click",
656
+ description: "Click an element on the web page using a CSS selector or text content.",
657
+ parameters: z8.object({
658
+ selector: z8.string().describe('CSS selector or text to find the element (e.g., "button.submit", "text=Login")')
659
+ }),
660
+ async execute(args, ctx) {
661
+ const browser = await ctx.getBrowser();
662
+ const page = await browser.getPage();
663
+ await page.click(args.selector, { timeout: 1e4 });
664
+ return { type: "text", content: `Clicked element: ${args.selector}` };
665
+ }
666
+ };
667
+
668
+ // src/tools/browser/type.ts
669
+ import { z as z9 } from "zod";
670
+ var browserTypeTool = {
671
+ name: "browser_type",
672
+ description: "Type text into an input field on the web page.",
673
+ parameters: z9.object({
674
+ selector: z9.string().describe("CSS selector for the input element"),
675
+ text: z9.string().describe("Text to type"),
676
+ clear: z9.boolean().default(true).describe("Whether to clear the field before typing")
677
+ }),
678
+ async execute(args, ctx) {
679
+ const browser = await ctx.getBrowser();
680
+ const page = await browser.getPage();
681
+ if (args.clear) {
682
+ await page.fill(args.selector, args.text, { timeout: 1e4 });
683
+ } else {
684
+ await page.type(args.selector, args.text, { timeout: 1e4 });
685
+ }
686
+ return { type: "text", content: `Typed "${args.text}" into ${args.selector}` };
687
+ }
688
+ };
689
+
690
+ // src/tools/browser/screenshot.ts
691
+ import { z as z10 } from "zod";
692
+ var browserScreenshotTool = {
693
+ name: "browser_screenshot",
694
+ description: "Take a screenshot of the current browser page.",
695
+ parameters: z10.object({
696
+ fullPage: z10.boolean().default(false).describe("Whether to capture the full scrollable page")
697
+ }),
698
+ async execute(args, ctx) {
699
+ const browser = await ctx.getBrowser();
700
+ const page = await browser.getPage();
701
+ const buf = await page.screenshot({
702
+ type: "png",
703
+ fullPage: args.fullPage
704
+ });
705
+ return {
706
+ type: "image",
707
+ base64: buf.toString("base64"),
708
+ mimeType: "image/png"
709
+ };
710
+ }
711
+ };
712
+
713
+ // src/tools/browser/content.ts
714
+ import { z as z11 } from "zod";
715
+ var MAX_CONTENT_LENGTH = 2e4;
716
+ var browserContentTool = {
717
+ name: "browser_content",
718
+ description: "Get the text content of the current web page. Returns visible text, not HTML.",
719
+ parameters: z11.object({}),
720
+ async execute(_args, ctx) {
721
+ const browser = await ctx.getBrowser();
722
+ const page = await browser.getPage();
723
+ const url = page.url();
724
+ const title = await page.title();
725
+ let text = await page.innerText("body").catch(() => "");
726
+ if (text.length > MAX_CONTENT_LENGTH) {
727
+ text = text.slice(0, MAX_CONTENT_LENGTH) + "\n...(truncated)";
728
+ }
729
+ return {
730
+ type: "text",
731
+ content: `URL: ${url}
732
+ Title: ${title}
733
+
734
+ ${text}`
735
+ };
736
+ }
737
+ };
738
+
739
+ // src/tools/browser/scroll.ts
740
+ import { z as z12 } from "zod";
741
+ var browserScrollTool = {
742
+ name: "browser_scroll",
743
+ description: "Scroll the current web page.",
744
+ parameters: z12.object({
745
+ direction: z12.enum(["up", "down"]).describe("Scroll direction"),
746
+ amount: z12.number().positive().default(500).describe("Pixels to scroll")
747
+ }),
748
+ async execute(args, ctx) {
749
+ const browser = await ctx.getBrowser();
750
+ const page = await browser.getPage();
751
+ const delta = args.direction === "down" ? args.amount : -args.amount;
752
+ await page.evaluate((d) => window.scrollBy(0, d), delta);
753
+ return { type: "text", content: `Scrolled ${args.direction} ${args.amount}px` };
754
+ }
755
+ };
756
+
757
+ // src/tools/control/report.ts
758
+ import { z as z13 } from "zod";
759
+ var reportTool = {
760
+ name: "report",
761
+ description: "Report progress back to the caller. Call this when the task is completed, when you are blocked, or when you need guidance. Calling this STOPS your execution immediately.",
762
+ parameters: z13.object({
763
+ status: z13.enum(["completed", "blocked", "need_guidance"]).describe(
764
+ '"completed" = task done, "blocked" = cannot proceed, "need_guidance" = need a decision'
765
+ ),
766
+ summary: z13.string().describe("Concise human-readable summary of what was accomplished or what the problem is"),
767
+ include_screenshot: z13.boolean().default(false).describe("Whether to capture and include a screenshot of the current state"),
768
+ data: z13.unknown().optional().describe("Optional structured data to return")
769
+ }),
770
+ async execute(args) {
771
+ let screenshot;
772
+ if (args.include_screenshot) {
773
+ try {
774
+ const { Monitor } = await import("node-screenshots");
775
+ const monitors = Monitor.all();
776
+ const primary = monitors.find((m) => m.isPrimary()) ?? monitors[0];
777
+ if (primary) {
778
+ const image = primary.captureImageSync();
779
+ const buf = image.toPngSync();
780
+ screenshot = buf.toString("base64");
781
+ }
782
+ } catch {
783
+ }
784
+ }
785
+ return {
786
+ type: "report",
787
+ status: args.status,
788
+ summary: args.summary,
789
+ screenshot,
790
+ data: args.data
791
+ };
792
+ }
793
+ };
794
+
795
+ // src/tools/index.ts
796
+ function createToolRegistry() {
797
+ const registry2 = new ToolRegistry();
798
+ registry2.register(screenshotTool);
799
+ registry2.register(mouseClickTool);
800
+ registry2.register(mouseMoveTool);
801
+ registry2.register(mouseScrollTool);
802
+ registry2.register(keyboardTypeTool);
803
+ registry2.register(keyboardPressTool);
804
+ registry2.register(runCommandTool);
805
+ registry2.register(fileReadTool);
806
+ registry2.register(fileWriteTool);
807
+ registry2.register(browserNavigateTool);
808
+ registry2.register(browserClickTool);
809
+ registry2.register(browserTypeTool);
810
+ registry2.register(browserScreenshotTool);
811
+ registry2.register(browserContentTool);
812
+ registry2.register(browserScrollTool);
813
+ registry2.register(reportTool);
814
+ return registry2;
815
+ }
816
+
817
+ // src/mcp/session-registry.ts
818
+ var SessionRegistry = class {
819
+ sessions = /* @__PURE__ */ new Map();
820
+ create(config) {
821
+ const id = crypto.randomUUID();
822
+ const contextManager = new ContextManager(config.contextWindowSize);
823
+ const llmClient = new LLMClient(config);
824
+ const browserClient = new BrowserClient(config.cdpUrl);
825
+ const toolRegistry = createToolRegistry();
826
+ const toolContext = {
827
+ sessionId: id,
828
+ cdpUrl: config.cdpUrl,
829
+ getBrowser: () => {
830
+ return browserClient.connect().then(() => browserClient);
831
+ }
832
+ };
833
+ const runner = new AgentRunner(
834
+ llmClient,
835
+ contextManager,
836
+ toolRegistry,
837
+ config,
838
+ toolContext
839
+ );
840
+ const timeoutHandle = setTimeout(
841
+ () => this.destroy(id),
842
+ config.timeoutMs
843
+ );
844
+ const session = {
845
+ id,
846
+ createdAt: /* @__PURE__ */ new Date(),
847
+ lastActivityAt: /* @__PURE__ */ new Date(),
848
+ config,
849
+ runner,
850
+ browserClient,
851
+ timeoutHandle
852
+ };
853
+ this.sessions.set(id, session);
854
+ return session;
855
+ }
856
+ get(id) {
857
+ return this.sessions.get(id);
858
+ }
859
+ touch(id) {
860
+ const session = this.sessions.get(id);
861
+ if (!session) return;
862
+ session.lastActivityAt = /* @__PURE__ */ new Date();
863
+ clearTimeout(session.timeoutHandle);
864
+ session.timeoutHandle = setTimeout(
865
+ () => this.destroy(id),
866
+ session.config.timeoutMs
867
+ );
868
+ }
869
+ async destroy(id) {
870
+ const session = this.sessions.get(id);
871
+ if (!session) return;
872
+ clearTimeout(session.timeoutHandle);
873
+ await session.browserClient.close().catch(() => {
874
+ });
875
+ this.sessions.delete(id);
876
+ }
877
+ async destroyAll() {
878
+ await Promise.allSettled(
879
+ [...this.sessions.keys()].map((id) => this.destroy(id))
880
+ );
881
+ }
882
+ };
883
+
884
+ // src/mcp/tools.ts
885
+ import { z as z15 } from "zod";
886
+
887
+ // src/config/schema.ts
888
+ import { z as z14 } from "zod";
889
+ var ConfigSchema = z14.object({
890
+ apiKey: z14.string().min(1, "API key is required"),
891
+ baseURL: z14.string().url("Must be a valid URL"),
892
+ model: z14.string().min(1, "Model name is required"),
893
+ maxSteps: z14.number().int().positive().default(50),
894
+ contextWindowSize: z14.number().int().positive().default(20),
895
+ cdpUrl: z14.string().default("http://localhost:9222"),
896
+ timeoutMs: z14.number().default(3e5)
897
+ });
898
+
899
+ // src/config/loader.ts
900
+ function loadConfig(overrides) {
901
+ const raw = {
902
+ apiKey: overrides?.apiKey ?? process.env.WINDOWS_USE_API_KEY ?? "",
903
+ baseURL: overrides?.baseURL ?? process.env.WINDOWS_USE_BASE_URL ?? "",
904
+ model: overrides?.model ?? process.env.WINDOWS_USE_MODEL ?? "",
905
+ maxSteps: overrides?.maxSteps ?? intEnv("WINDOWS_USE_MAX_STEPS") ?? 50,
906
+ contextWindowSize: overrides?.contextWindowSize ?? intEnv("WINDOWS_USE_CONTEXT_WINDOW") ?? 20,
907
+ cdpUrl: overrides?.cdpUrl ?? process.env.WINDOWS_USE_CDP_URL ?? "http://localhost:9222",
908
+ timeoutMs: overrides?.timeoutMs ?? intEnv("WINDOWS_USE_TIMEOUT_MS") ?? 3e5
909
+ };
910
+ return ConfigSchema.parse(raw);
911
+ }
912
+ function intEnv(name) {
913
+ const val = process.env[name];
914
+ if (val === void 0) return void 0;
915
+ const n = parseInt(val, 10);
916
+ return isNaN(n) ? void 0 : n;
917
+ }
918
+
919
+ // src/mcp/tools.ts
920
+ function registerMcpTools(server2, registry2) {
921
+ server2.tool(
922
+ "create_session",
923
+ "Create a new automation session with a small LLM agent. Returns a session_id.",
924
+ {
925
+ api_key: z15.string().optional().describe("LLM API key (or set WINDOWS_USE_API_KEY env)"),
926
+ base_url: z15.string().optional().describe("OpenAI-compatible base URL (or set WINDOWS_USE_BASE_URL env)"),
927
+ model: z15.string().optional().describe("Model name (or set WINDOWS_USE_MODEL env)"),
928
+ cdp_url: z15.string().optional().describe("Chrome CDP URL (default: http://localhost:9222)"),
929
+ timeout_ms: z15.number().optional().describe("Session inactivity timeout in ms (default: 300000)"),
930
+ max_steps: z15.number().optional().describe("Max tool-calling steps per instruction (default: 50)")
931
+ },
932
+ async (args) => {
933
+ const config = loadConfig({
934
+ apiKey: args.api_key,
935
+ baseURL: args.base_url,
936
+ model: args.model,
937
+ cdpUrl: args.cdp_url,
938
+ timeoutMs: args.timeout_ms,
939
+ maxSteps: args.max_steps
940
+ });
941
+ const session = registry2.create(config);
942
+ return {
943
+ content: [
944
+ {
945
+ type: "text",
946
+ text: JSON.stringify({ session_id: session.id })
947
+ }
948
+ ]
949
+ };
950
+ }
951
+ );
952
+ server2.tool(
953
+ "send_instruction",
954
+ "Send a task instruction to the agent in a session. The agent executes it and returns a status report.",
955
+ {
956
+ session_id: z15.string().describe("Session ID from create_session"),
957
+ instruction: z15.string().describe("What you want the agent to do, in natural language")
958
+ },
959
+ async (args) => {
960
+ const session = registry2.get(args.session_id);
961
+ if (!session) {
962
+ return {
963
+ content: [
964
+ {
965
+ type: "text",
966
+ text: JSON.stringify({
967
+ error: `Session "${args.session_id}" not found or expired`
968
+ })
969
+ }
970
+ ],
971
+ isError: true
972
+ };
973
+ }
974
+ registry2.touch(args.session_id);
975
+ const result = await session.runner.run(args.instruction);
976
+ registry2.touch(args.session_id);
977
+ const content = [
978
+ {
979
+ type: "text",
980
+ text: JSON.stringify({
981
+ status: result.status,
982
+ summary: result.summary,
983
+ steps_used: result.stepsUsed,
984
+ ...result.data !== void 0 ? { data: result.data } : {}
985
+ })
986
+ }
987
+ ];
988
+ if (result.screenshot) {
989
+ content.push({
990
+ type: "image",
991
+ data: result.screenshot,
992
+ mimeType: "image/png"
993
+ });
994
+ }
995
+ return { content };
996
+ }
997
+ );
998
+ server2.tool(
999
+ "done_session",
1000
+ "Terminate a session and free all resources.",
1001
+ {
1002
+ session_id: z15.string().describe("Session ID to terminate")
1003
+ },
1004
+ async (args) => {
1005
+ await registry2.destroy(args.session_id);
1006
+ return {
1007
+ content: [
1008
+ {
1009
+ type: "text",
1010
+ text: JSON.stringify({ success: true })
1011
+ }
1012
+ ]
1013
+ };
1014
+ }
1015
+ );
1016
+ }
1017
+
1018
+ // src/mcp/server.ts
1019
+ var server = new McpServer({
1020
+ name: "windows-use",
1021
+ version: "0.1.0"
1022
+ });
1023
+ var registry = new SessionRegistry();
1024
+ registerMcpTools(server, registry);
1025
+ async function shutdown() {
1026
+ await registry.destroyAll();
1027
+ process.exit(0);
1028
+ }
1029
+ process.on("SIGINT", shutdown);
1030
+ process.on("SIGTERM", shutdown);
1031
+ var transport = new StdioServerTransport();
1032
+ await server.connect(transport);
1033
+ console.error("[windows-use] MCP server started");
1034
+ //# sourceMappingURL=server.js.map