-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser.lua
More file actions
936 lines (891 loc) · 41.1 KB
/
Copy pathbrowser.lua
File metadata and controls
936 lines (891 loc) · 41.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
local truncate = require("maki.truncate")
local ToolView = require("maki.tool_view")
local output_limits = require("maki.output_limits")
local opts = maki.api.register_options(output_limits.extend({
cmd = { default = "node", desc = "Node.js binary to run the server script." },
server_timeout = { default = 15, min = 1, desc = "Timeout in seconds for each server command." },
}))
local NOT_INSTALLED_MSG = "Playwright not found. Install with: npm install playwright && npx playwright install chromium"
local NO_BROWSER_MSG = "Browser not launched. Use browser_launch first."
-- Server state. The server is started with 'exec' and NO trailing '&', so the
-- tracked job pid IS the node process (see ensure_server).
local server = {
ready = false,
cmd_path = nil,
resp_path = nil,
pid = nil,
job_id = nil,
stdout_log = nil,
pending = {},
next_id = 1,
startup_queue = {},
base_dir = nil,
}
-- A server is "running" only if the flag is set AND the process is actually
-- alive. Trusting the flag alone wedged the plugin: if the server died (timeout,
-- crash, external kill) without stop_server() running, ready stayed true forever,
-- ensure_server() short-circuited and every later call wrote into a dead
-- cmd.jsonl and hung until timeout.
--
-- IMPORTANT: this is a READ-ONLY predicate with NO side effects. An earlier
-- version called stop_server() here to "reset" state, which killed a HEALTHY
-- server (SIGTERM + delayed SIGKILL) whenever the liveness probe misfired --
-- it left a SIGKILLed server and an orphaned tmpDir after a successful launch.
-- Recovery is handled by ensure_server()/callers instead.
local function server_alive(pid)
if not pid then return false end
local id = maki.fn.jobstart(string.format("kill -0 %d 2>/dev/null", pid))
local res = maki.fn.jobwait(id, 500)
-- Only a definite non-zero exit means dead. A nil result (jobwait timed out
-- or maki could not run it) must NOT be treated as death, or we kill live servers.
return not (res and res.exit_code ~= 0)
end
local function server_running()
if not server.ready then return false end
local a = server_alive(server.pid)
return a
end
local function artifact_dir()
if not server.base_dir then
local cwd = maki.uv.cwd() or ""
server.base_dir = maki.fs.joinpath(cwd, ".maki", "browser", os.date("%Y-%m-%dT%H-%M-%S"))
end
return server.base_dir
end
local function save_artifact(subdir, filename, content)
local dir = maki.fs.joinpath(artifact_dir(), subdir)
maki.fs.mkdir(dir, { parents = true })
local path = maki.fs.joinpath(dir, filename)
maki.fs.write(path, content)
return path
end
-- Kill the server process by PID (SIGTERM first so it can close Chromium
-- cleanly via its signal handler, SIGKILL as a fallback for stragglers).
-- Falls back to the in-band close command if the pid is unknown.
-- All three paths are scoped to THIS instance (own pid / own job id / own
-- cmd.jsonl) — never path-based, so other maki instances are never touched.
local function kill_server()
if server.pid then
maki.fn.jobstart(string.format("kill -TERM %d 2>/dev/null; exit 0", server.pid))
-- Give the server a moment to close the browser, then force-kill if needed.
maki.fn.jobstart(string.format("(sleep 2 && kill -KILL %d) 2>/dev/null &", server.pid))
server.pid = nil
server.job_id = nil
return
end
-- No pid (read_setup never parsed stdout, e.g. failed/slow startup). We own
-- this job id, so jobstop reaps it directly instead of leaking a PPID 1 node.
if server.job_id then
maki.fn.jobstop(server.job_id)
server.job_id = nil
return
end
if server.cmd_path then
local cmd = maki.json.encode({ id = "close_force", tool = "close" })
local escaped = cmd:gsub("'", "'\\''")
maki.fn.jobstart(string.format("echo '%s' >> '%s'", escaped, server.cmd_path))
end
end
function stop_server()
kill_server()
server.ready = false
server.cmd_path = nil
server.resp_path = nil
server.pid = nil
server.job_id = nil
server.pending = {}
-- Drop this launch's stdout log so a later read_setup can never pick it up.
if server.stdout_log then
maki.fs.rm(server.stdout_log)
server.stdout_log = nil
end
end
-- Start a short-lived keep-alive job. The runtime kills handlers that return
-- nil unless at least one job is alive. The sleep dies after 10s, but by then
-- ctx:finish() has already been called by the async response callback.
-- A new one is spawned per handler invocation — the old one dying is harmless.
local function ensure_keepalive()
maki.fn.jobstart("sleep 10")
end
-- Poll resp.jsonl for new lines, deliver them to registered pending callbacks.
local function poll_responses()
local data, _ = maki.fs.read(server.resp_path)
if not data then return end
for line in data:gmatch("[^\n]+") do
local msg, _ = maki.json.decode(line)
if msg and msg.id then
local cb = server.pending[msg.id]
if cb then
server.pending[msg.id] = nil
cb(msg)
end
end
end
-- Truncate resp file to prevent unbounded growth
if #data > 65536 then
local last_newline = data:match(".*\n()")
if last_newline then
local remainder = data:sub(last_newline)
maki.fs.write(server.resp_path, remainder)
end
end
end
local function send_command(tool, params, on_response)
if not server.cmd_path then
server.startup_queue[#server.startup_queue + 1] = function()
send_command(tool, params, on_response)
end
return
end
local id = tostring(server.next_id)
server.next_id = server.next_id + 1
server.pending[id] = function(msg)
if msg.error then on_response(nil, msg.error) else on_response(msg.result, nil) end
end
local cmd = maki.json.encode({ id = id, tool = tool, params = params or {} })
local escaped = cmd:gsub("'", "'\\''")
local append_id = maki.fn.jobstart(string.format("echo '%s' >> '%s'", escaped, server.cmd_path))
maki.fn.jobwait(append_id, 2000)
-- Spin and poll in a background task
maki.async.run(function()
local start = os.time()
while server.pending[id] do
if os.time() - start > opts.server_timeout then
local cb = server.pending[id]
server.pending[id] = nil
cb({ error = "command timed out after " .. tostring(opts.server_timeout) .. "s" })
return
end
poll_responses()
if server.pending[id] then
local sleep_id = maki.fn.jobstart("sleep 0.05")
maki.fn.jobwait(sleep_id, 100)
end
end
end)
end
-- Dispatch a browser tool: guard → send → keep handler alive → return nil.
-- `f` receives (result, err, ctx) and must call ctx:finish(...).
local function dispatch(input, ctx, tool, params, f)
if not server_running() then
return { llm_output = NO_BROWSER_MSG, is_error = true }
end
send_command(tool, params, function(result, err)
f(result, err, ctx)
end)
ensure_keepalive()
return nil
end
local function ensure_server()
if server_running() then
return nil
end
-- If we believed a server was running but it is gone, clear the stale IPC
-- paths/pid so the relaunch below does not write into a dead cmd.jsonl.
-- kill_server() here is safe: it only SIGTERMs server.pid, and we have just
-- established that pid is not alive (a no-op), then drops the handles.
if server.ready then stop_server() end
if maki.fn.executable(opts.cmd) ~= 1 then
return "Node.js not found. Please install Node.js to use browser tools."
end
local check_id = maki.fn.jobstart(opts.cmd .. " -e \"require('playwright')\"")
local check_result = maki.fn.jobwait(check_id, 5000)
if not check_result or check_result.exit_code ~= 0 then
if not check_result then maki.fn.jobstop(check_id) end
return NOT_INSTALLED_MSG
end
local cwd = maki.uv.cwd() or "/tmp"
local server_dir = maki.fs.joinpath(cwd, ".maki", "browser")
maki.fs.mkdir(server_dir, { parents = true })
local server_path = maki.fs.joinpath(server_dir, "server.js")
maki.fs.write(server_path, [=[const { chromium } = require("playwright");
const fs = require("fs");
const path = require("path");
const os = require("os");
const DEFAULT_TIMEOUT = 10000;
const MAX_RESPONSE_BODY = 2000;
const MAX_CONSOLE_ENTRY = 1000;
let browser = null;
let context = null;
let page = null;
let networkLog = [];
let consoleLog = [];
let downloads = []; // [{ seq, filename, url, path, bytes, error }]
let downloadSeq = 0;
let navigations = []; // main-frame URLs, in order
let pendingRequests = new Map(); // request object -> networkLog entry
let collectorsAttached = false; // are the page listeners registered for the current page?
let cmdOffset = 0;
async function collectBody(response) {
try {
const body = await response.text();
return body.length > MAX_RESPONSE_BODY ? body.substring(0, MAX_RESPONSE_BODY) + "..." : body;
} catch { return "[binary or streamed body]"; }
}
function startNetworkCollection() {
networkLog = [];
pendingRequests = new Map();
page.on("request", (req) => {
const entry = { method: req.method(), url: req.url(), resourceType: req.resourceType(), status: null, body: null };
networkLog.push(entry);
pendingRequests.set(req, entry);
});
// A single response listener for the whole context. Registering one listener
// per request (the previous design) leaked a listener per request and made
// every listener scan every future response.
page.on("response", async (res) => {
const req = res.request();
const entry = pendingRequests.get(req);
if (!entry) return;
entry.status = res.status();
pendingRequests.delete(req);
if (req.resourceType() === "xhr" || req.resourceType() === "fetch") {
try { entry.body = await collectBody(res); } catch {}
}
});
}
function startDownloadCollection() {
downloads = [];
downloadSeq = 0;
navigations = [];
page.on("download", async (d) => {
const rec = {
seq: ++downloadSeq,
filename: d.suggestedFilename(),
url: d.url ? d.url() : null,
path: null, bytes: null, error: null,
};
// Push before awaiting: the record must exist the instant the click returns.
downloads.push(rec);
try {
const p = await d.path(); // resolves once the download completes
rec.path = p;
try { rec.bytes = fs.statSync(p).size; } catch (e) { rec.error = "stat failed: " + e.message; }
} catch (e) {
rec.error = "download failed: " + e.message;
}
if (d.failure) { try { rec.failure = await d.failure(); } catch (e) {} }
});
page.on("framenavigated", (f) => {
if (f === page.mainFrame()) navigations.push(f.url());
});
}
async function waitForDownloadsSince(seq, timeoutMs) {
const deadline = Date.now() + (timeoutMs || 2000);
// The "download" event (and therefore the record push) is dispatched
// asynchronously by Playwright, so it can land after click() resolves. Wait for
// the first record to appear, then wait for each one to finish resolving.
while (Date.now() < deadline) {
const started = downloads.filter(function(d) { return d.seq > seq; });
if (started.length > 0) {
const unresolved = started.filter(function(d) { return d.path === null && !d.error; });
if (unresolved.length === 0) break;
}
await new Promise(function(r) { setTimeout(r, 25); });
}
return downloads.filter(function(d) { return d.seq > seq; });
}
function startConsoleCollection() {
consoleLog = [];
page.on("console", (msg) => {
const text = msg.text().length > MAX_CONSOLE_ENTRY ? msg.text().substring(0, MAX_CONSOLE_ENTRY) + "..." : msg.text();
consoleLog.push({ level: msg.type(), text });
});
page.on("pageerror", (err) => { consoleLog.push({ level: "error", text: err.message }); });
}
const handlers = {
async launch(params) {
if (browser) {
if (params.reset_state) {
await context.close();
context = await browser.newContext({ acceptDownloads: true });
page = await context.newPage();
networkLog = []; consoleLog = [];
// New page: its listeners are gone with the old one, so re-register.
collectorsAttached = false;
}
} else {
browser = await chromium.launch({ headless: params.headless !== false });
browser.on("disconnected", function() {
browser = null; context = null; page = null;
collectorsAttached = false;
cleanupAndExit(0);
});
// acceptDownloads is explicit and deliberate (it is the default anyway).
context = await browser.newContext({ acceptDownloads: true });
page = await context.newPage();
collectorsAttached = false;
}
if (params.viewport_width || params.viewport_height) {
await page.setViewportSize({ width: params.viewport_width || 1280, height: params.viewport_height || 720 });
}
// Re-registering listeners on every launch would attach duplicates to the same
// page: each extra "download" listener pushes its own copy of the same download
// (and every extra network/console listener duplicates its entries too). Only
// attach once per page.
if (!collectorsAttached) {
startNetworkCollection(); startConsoleCollection(); startDownloadCollection();
collectorsAttached = true;
}
await page.goto(params.url, { waitUntil: "domcontentloaded" });
return { title: await page.title(), url: page.url() };
},
async click(params) {
if (!page) return { error: "browser not launched" };
const before = downloadSeq, navBefore = navigations.length;
await page.locator(params.selector).click({ timeout: params.timeout || DEFAULT_TIMEOUT });
const ec = consoleLog.filter(function(e) { return e.level === "error"; }).length;
// The download event is dispatched asynchronously, so it may not have landed
// yet; always wait a short bounded time for one to appear and settle.
const newDownloads = await waitForDownloadsSince(before, 2000);
return {
url: page.url(),
networkRequests: networkLog.length,
consoleErrors: ec > 0 ? ec + " console errors" : "none",
downloads: newDownloads,
navigationCount: navigations.length - navBefore,
lastNavigation: navigations.length > 0 ? navigations[navigations.length - 1] : null,
};
},
async downloads(params) {
const list = downloads.slice();
if (params.clear) { downloads = []; downloadSeq = 0; }
return { downloads: list };
},
async fill(params) {
if (!page) return { error: "browser not launched" };
var loc = page.locator(params.selector);
if (params.clear !== false) await loc.fill("");
await loc.fill(params.value);
return { filled: params.selector, value: params.value };
},
async evaluate(params) {
if (!page) return { error: "browser not launched" };
var code = params.code.trim();
var wrapped = "(function() { " + code + " })()";
var result = await page.evaluate("eval(" + JSON.stringify(wrapped) + ")");
return { result: JSON.stringify(result) };
},
async content(params) {
if (!page) return { error: "browser not launched" };
if (params.selector) return { html: await page.locator(params.selector).innerHTML() };
return { html: await page.content() };
},
async assert_text(params) {
if (!page) return { error: "browser not launched" };
var target = params.selector || "body";
var locator = page.locator(target).filter({ hasText: params.text });
var count = await locator.count();
var exists = count > 0;
var expected = params.should_exist !== false;
var detail;
if (exists === expected) {
detail = expected
? 'Text "' + params.text + '" found on page' + (params.selector ? " in " + params.selector : "") + "."
: 'Text "' + params.text + '" correctly absent from page.';
return { passed: true, detail: detail };
}
detail = expected
? 'Text "' + params.text + '" NOT found on page' + (params.selector ? " in " + params.selector : "") + "."
: 'Text "' + params.text + '" was found but should NOT be on the page.';
return { passed: false, detail: detail };
},
async network_log(params) {
var entries = networkLog.slice();
if (params.filter_url) entries = entries.filter(function(e) { return e.url.includes(params.filter_url); });
var max = params.max_entries || 20;
if (entries.length > max) entries = entries.slice(entries.length - max);
return { entries };
},
console_log(params) {
var entries = consoleLog.slice();
if (params.level) entries = entries.filter(function(e) { return e.level === params.level; });
var max = params.max_entries || 20;
if (entries.length > max) entries = entries.slice(entries.length - max);
return { entries };
},
async screenshot(params) {
if (!page) return { error: "browser not launched" };
var buf;
if (params.selector) buf = await page.locator(params.selector).screenshot({ type: "png" });
else buf = await page.screenshot({ type: "png", fullPage: !!params.full_page });
return { image: buf.toString("base64"), media_type: "image/png" };
},
async close() {
// Playwright deletes saved downloads when the browser closes — warn first.
const files = downloads.map(function(d) { return d.path || d.filename; });
if (context) { await context.close().catch(function() {}); context = null; page = null; }
if (browser) { await browser.close().catch(function() {}); browser = null; }
return { closed: true, downloads: files };
},
};
var tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "maki-browser-"));
var cmdPath = path.join(tmpDir, "cmd.jsonl");
var respPath = path.join(tmpDir, "resp.jsonl");
var pidPath = path.join(tmpDir, "pid");
fs.writeFileSync(cmdPath, "");
fs.writeFileSync(respPath, "");
fs.writeFileSync(pidPath, process.pid + "\n");
function send(msg) { fs.appendFileSync(respPath, JSON.stringify(msg) + "\n"); }
process.stdout.write(tmpDir + "\n");
process.stdout.write(cmdPath + "\n");
process.stdout.write(respPath + "\n");
async function handleCommand(line) {
if (!line || !line.trim()) return;
var msg;
try { msg = JSON.parse(line); } catch (e) { return; }
var handler = handlers[msg.tool];
if (!handler) { send({ id: msg.id, error: "unknown tool: " + msg.tool }); return; }
try {
var result = await handler(msg.params || {});
if (result.error) send({ id: msg.id, error: result.error });
else send({ id: msg.id, result: result });
} catch (err) { send({ id: msg.id, error: err.message }); }
// Grace period before exiting: the client polls resp.jsonl on an interval, and
// process.on("exit") deletes tmpDir (including resp.jsonl). Exiting immediately
// made the close response unreadable — the file was gone before the next poll.
// Stay alive long enough for at least one poll cycle to pick the response up.
if (msg.tool === "close") { setTimeout(function() { process.exit(0); }, 1000); }
}
function pollCommands() {
try {
var data = fs.readFileSync(cmdPath, "utf8");
if (data.length > cmdOffset) {
var newData = data.substring(cmdOffset);
cmdOffset = data.length;
var parts = newData.split("\n");
for (var i = 0; i < parts.length; i++) { if (parts[i].trim()) handleCommand(parts[i]); }
}
} catch (e) {}
setTimeout(pollCommands, 50);
}
setTimeout(pollCommands, 200);
function cleanupAndExit(code) {
handlers.close();
setTimeout(function() { process.exit(code == null ? 0 : code); }, 150);
}
process.on("SIGTERM", function() { cleanupAndExit(0); });
process.on("SIGHUP", function() { cleanupAndExit(0); });
process.on("uncaughtException", function() { cleanupAndExit(1); });
process.on("exit", function() {
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch (e) {}
});]=])
-- 'exec' so the shell REPLACES itself with node: the tracked job pid *is* the
-- server, so jobstop/signals reap it directly.
-- - With a trailing '&' node is reparented to launchd (PPID 1) and job
-- control can never reach it.
-- - Without 'exec' the tracked pid is only the parent shell, which does NOT
-- forward signals; killing it orphans node to PPID 1.
--
-- IMPORTANT: the stdout log path is UNIQUE PER LAUNCH. It used to be a fixed
-- path (/tmp/maki-browser-stdout.log). After browser_close, that file still
-- held the PREVIOUS session's 3 lines, so a relaunch's read_setup() parsed the
-- stale paths, exited immediately pointing at the old (now deleted) tmpdir,
-- and the launch command was appended to a dead cmd.jsonl -> 10s hang.
-- A unique path guarantees any content read belongs to THIS launch.
server.stdout_log = string.format("/tmp/maki-browser-stdout-%d-%d.log", os.time(), server.next_id)
local cmd = "exec " .. opts.cmd .. " " .. server_path
.. " > " .. server.stdout_log .. " 2>/tmp/maki-browser-stderr.log"
-- scope="plugin": the DEFAULT scope is "task", which ends the job with the
-- current call -- maki would SIGKILL the server the moment browser_launch's
-- handler returned, killing it immediately after a successful launch.
-- "plugin" keeps it alive until the plugin unloads/reloads, which is exactly
-- the server's intended lifetime, and lets jobstop/job_id reaping still work.
server.job_id = maki.fn.jobstart(cmd, { scope = "plugin" })
local function read_setup()
local stdout, _ = maki.fs.read(server.stdout_log)
if not stdout then return end
local parts = {}
for line in stdout:gmatch("[^\n]+") do
parts[#parts + 1] = line
if #parts >= 3 then break end
end
if #parts >= 3 then
-- Guard against accepting a stale/partial read: the referenced tmpdir and
-- its pid file must actually exist before we adopt these IPC paths.
local pid_file = maki.fs.joinpath(parts[1], "pid")
local pid_data, _ = maki.fs.read(pid_file)
if not pid_data then
return
end
local pid = pid_data:match("(%d+)")
if not pid then return end
server.cmd_path = parts[2]
server.resp_path = parts[3]
server.pid = tonumber(pid)
local q = server.startup_queue
server.startup_queue = {}
for _, fn in ipairs(q) do fn() end
end
end
local waited = 0
while not server.cmd_path and waited < 5000 do
read_setup()
local sleep_id = maki.fn.jobstart("sleep 0.1")
maki.fn.jobwait(sleep_id, 200)
waited = waited + 200
end
if not server.cmd_path then
return "Playwright server failed to start"
end
server.ready = true
return nil
end
-- ═════════════════════════════════════════════════════════════════════════════
-- TOOLS
-- ═════════════════════════════════════════════════════════════════════════════
maki.api.register_tool({
name = "browser_launch",
kind = "browser",
description = [[Launch a Chromium browser and navigate to a URL, or navigate to a new URL in an already-open browser.
Call this before any other browser tools. By default, browser state (cookies, localStorage, event logs) is preserved across navigations — you don't need to re-login. Set reset_state=true for a clean slate. Set headless=false to see the browser window when debugging. Returns the page title and URL after navigation.]],
schema = {
type = "object", required = { "url" }, additionalProperties = false,
properties = {
url = { type = "string", description = "URL to navigate to (e.g. http://localhost:3000)" },
headless = { type = "boolean", description = "Run in headless mode (default true). Set false to see the browser window." },
viewport_width = { type = "integer", description = "Viewport width in pixels (default 1280)" },
viewport_height = { type = "integer", description = "Viewport height in pixels (default 720)" },
reset_state = { type = "boolean", description = "Create a fresh browser context (clear cookies, storage, logs). Default false." },
},
},
handler = function(input, ctx)
if not input.url then return { llm_output = "error: url is required", is_error = true } end
local err = ensure_server()
if err then return { llm_output = "error: " .. err, is_error = true } end
send_command("launch", {
url = input.url, headless = input.headless,
viewport_width = input.viewport_width, viewport_height = input.viewport_height,
reset_state = input.reset_state,
}, function(result, cmd_err)
if cmd_err then ctx:finish({ llm_output = "error: " .. cmd_err, is_error = true }); return end
local mode = (input.reset_state and " (fresh context)") or ""
ctx:finish({ llm_output = string.format("Launched at %s\ntitle: %s%s", result.url, result.title, mode) })
end)
ensure_keepalive()
return nil
end,
header = function(input)
local s = input.url
if input.reset_state then s = s .. " [fresh]" end
return s
end,
})
maki.api.register_tool({
name = "browser_click",
kind = "browser",
description = [[Click an element on the page specified by a CSS selector. Waits for the element to be visible and ready before clicking. Use this to trigger events like form submissions, button clicks, or navigation. Returns a summary of what happened after the click (URL, network activity, console errors).
If the click triggers a file download, the result lists the saved file(s) with filename, size and path — check this line before concluding nothing happened, because a download leaves the URL unchanged. Downloads are stored in a Playwright temp file that is deleted when the browser closes, so inspect or copy it during the session.]],
schema = {
type = "object", required = { "selector" }, additionalProperties = false,
properties = {
selector = { type = "string", description = "CSS selector for the element to click (e.g. '#submit', '.nav a', 'button')" },
timeout = { type = "integer", description = "Max wait time in ms for the element (default 10000)" },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "click", { selector = input.selector, timeout = input.timeout }, function(result, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
local navs = result.navigationCount or 0
local lines = {
string.format("Clicked %s", input.selector),
string.format(" URL: %s", result.url),
string.format(" Network: %s", (result.networkRequests or 0) .. " requests"),
string.format(" Console: %s", result.consoleErrors or "none"),
}
if navs > 0 then
local last = result.lastNavigation and (" (last: " .. result.lastNavigation .. ")") or ""
lines[#lines + 1] = string.format(" Navigations: %d%s", navs, last)
else
lines[#lines + 1] = " Navigations: none"
end
local dls = result.downloads or {}
for _, d in ipairs(dls) do
local size = d.bytes and (" (" .. d.bytes .. " bytes)") or ""
local loc = d.path and ("\n saved: " .. d.path) or ""
local derr = d.error and (" [ERROR: " .. d.error .. "]") or ""
lines[#lines + 1] = string.format(" DOWNLOADED: %s%s%s%s", d.filename or "?", size, derr, loc)
end
local out = table.concat(lines, "\n")
if #dls > 0 then
local saved = save_artifact("downloads", os.date("%H-%M-%S") .. "_downloads.json", maki.json.encode(dls))
ctx:finish({ llm_output = out, written_path = saved })
else
ctx:finish({ llm_output = out })
end
end)
end,
header = function(input) return "click " .. (input.selector or "") end,
})
maki.api.register_tool({
name = "browser_fill",
kind = "browser",
description = [[Type text into a form field. Clears existing content first unless clear=false. Use before browser_click to fill forms. Returns confirmation with the selector and value used.]],
schema = {
type = "object", required = { "selector", "value" }, additionalProperties = false,
properties = {
selector = { type = "string", description = "CSS selector for the input/textarea to fill (e.g. '#email', 'input[name=q]')" },
value = { type = "string", description = "Text to type into the field" },
clear = { type = "boolean", description = "Clear existing content first (default true)" },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "fill", { selector = input.selector, value = input.value, clear = input.clear }, function(_, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
ctx:finish({ llm_output = string.format("Filled %s with: %s", input.selector, input.value) })
end)
end,
header = function(input) return "fill " .. (input.selector or "") end,
})
maki.api.register_tool({
name = "browser_evaluate",
kind = "browser",
description = [[Execute JavaScript in the browser page and return the result. Use this to inspect DOM state (e.g., 'return document.querySelector(".result").textContent'), check JavaScript variables, or simulate behavior not covered by other browser tools. The return value is JSON-serialized.]],
schema = {
type = "object", required = { "code" }, additionalProperties = false,
properties = {
code = { type = "string", description = "JavaScript code to execute in the page. Use 'return' to get a value back. The result is JSON-serialized." },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "evaluate", { code = input.code }, function(result, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
local max_lines, max_bytes = output_limits.resolve(opts, ctx)
ctx:finish({ llm_output = truncate(result.result or "undefined", max_lines, max_bytes) })
end)
end,
header = function(input)
local code = input.code or ""
if #code > 60 then return code:sub(1, 57) .. "..." end
return code
end,
})
maki.api.register_tool({
name = "browser_content",
kind = "browser",
description = [[Get the rendered HTML content of the page or a specific element. Use this to verify that partials were inserted correctly, template content rendered, or the DOM is in the expected state. Returns the HTML. Output may be truncated if very large.]],
schema = {
type = "object", additionalProperties = false,
properties = {
selector = { type = "string", description = "CSS selector to get HTML from a specific element. Omit for whole page." },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "content", { selector = input.selector }, function(result, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
local html = result.html or ""
local max_lines, max_bytes = output_limits.resolve(opts, ctx)
local llm_output = truncate(html, max_lines, max_bytes)
local tol = ctx:tool_output_lines()
local view_opts = { max_lines = (tol and tol.other) or 10, keep = "tail" }
local buf = maki.ui.buf()
local view = ToolView.new(buf, view_opts)
view:append_text(html)
view:finish()
ctx:finish({ llm_output = llm_output, body = buf })
end)
end,
header = function(input) return input.selector and ("content " .. input.selector) or "page content" end,
restore = function(input, output, is_error, ctx)
return ToolView.restore(output, { max_lines = 10, keep = "tail" })
end,
})
maki.api.register_tool({
name = "browser_assert_text",
kind = "browser",
description = [[Check whether specific text appears on the page. Use this to verify that content was rendered correctly after an action. Returns PASS or FAIL with detail. This is the primary verification tool — use it to confirm that events triggered the right DOM updates.
- Set should_exist=false to assert that text is NOT present (e.g., verifying an error message went away).
- Use selector to scope the search to a specific element.]],
schema = {
type = "object", required = { "text" }, additionalProperties = false,
properties = {
text = { type = "string", description = "Text to search for on the page" },
selector = { type = "string", description = "Limit search to this CSS selector (optional)" },
should_exist = { type = "boolean", description = "Expected: true = text must be present, false = text must NOT be present (default true)" },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "assert_text", {
text = input.text, selector = input.selector, should_exist = input.should_exist,
}, function(result, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
local llm = (result.passed and "PASS: " or "FAIL: ") .. (result.detail or "")
ctx:finish({ llm_output = llm, is_error = not result.passed })
end)
end,
header = function(input)
local prefix = (input.should_exist == false) and "assert missing: " or "assert: "
return prefix .. (input.text or "")
end,
})
maki.api.register_tool({
name = "browser_network_log",
kind = "browser",
description = [[View the log of network requests and responses since browser_launch or last clear. Use this to verify that the right endpoints were called, partial HTML was fetched, or API responses returned the expected data. Each entry shows method, URL, and status code. Use filter_url to narrow results.
Note: This queries the live server, so repeated calls show the same data unless clear=true.]],
schema = {
type = "object", additionalProperties = false,
properties = {
clear = { type = "boolean", description = "Clear the log after returning it (default false)" },
filter_url = { type = "string", description = "Only show requests matching this URL pattern (substring match)" },
max_entries = { type = "integer", description = "Max entries to return (default 20)" },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "network_log", {
filter_url = input.filter_url, max_entries = input.max_entries,
}, function(result, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
local entries = result.entries or {}
local lines = {}
for _, e in ipairs(entries) do
local status = e.status and (" [" .. e.status .. "]") or ""
local body = ""
if e.body then
local s = #e.body > 500 and e.body:sub(1, 500) .. "..." or e.body
body = "\n body: " .. s
end
lines[#lines + 1] = string.format(" %s %s%s%s", e.method or "?", e.url, status, body)
end
local text = #lines > 0 and table.concat(lines, "\n") or "(no network requests)"
local llm_output = string.format("%d network requests:\n%s", #entries, text)
if #entries > 0 then
local saved = save_artifact("network", os.date("%H-%M-%S") .. "_network.json", maki.json.encode(entries))
ctx:finish({ llm_output = llm_output, written_path = saved })
else
ctx:finish({ llm_output = llm_output })
end
end)
end,
header = function(input) return input.filter_url and ("net [" .. input.filter_url .. "]") or "network log" end,
})
maki.api.register_tool({
name = "browser_downloads",
kind = "browser",
description = [[List the files downloaded since browser_launch (or since the last clear=true). Each entry shows the filename, size in bytes, the saved path, and any error. Use this to confirm that a click produced a download — a download leaves the page URL unchanged, so without this list it is indistinguishable from a reload.
Caveat: the saved path is a Playwright temp file that is deleted when the browser closes, so inspect or copy it during the session if it matters.]],
schema = {
type = "object", additionalProperties = false,
properties = {
clear = { type = "boolean", description = "Clear the list after returning it (default false)" },
max_entries = { type = "integer", description = "Max entries to return (default 20)" },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "downloads", { clear = input.clear }, function(result, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
local entries = result.downloads or {}
local max = input.max_entries or 20
if #entries > max then
local tail = {}
for i = #entries - max + 1, #entries do tail[#tail + 1] = entries[i] end
entries = tail
end
local lines = {}
for _, d in ipairs(entries) do
local size = d.bytes and (" (" .. d.bytes .. " bytes)") or " (size unknown)"
local derr = d.error and (" [ERROR: " .. d.error .. "]") or ""
lines[#lines + 1] = string.format(" %s%s%s\n saved: %s", d.filename or "?", size, derr, d.path or "(not saved)")
end
local text = #entries > 0 and table.concat(lines, "\n") or "(no downloads)"
local llm_output = string.format("%d downloads:\n%s", #entries, text)
if #entries > 0 then
local saved = save_artifact("downloads", os.date("%H-%M-%S") .. "_downloads.json", maki.json.encode(entries))
ctx:finish({ llm_output = llm_output, written_path = saved })
else
ctx:finish({ llm_output = llm_output })
end
end)
end,
header = function(input) return "downloads" end,
})
maki.api.register_tool({
name = "browser_console_log",
kind = "browser",
description = [[View the browser console log since browser_launch or last clear. Use this to check for JavaScript errors, debug log messages, or warnings. Filter by level to focus on errors only.]],
schema = {
type = "object", additionalProperties = false,
properties = {
level = { type = "string", description = "Filter by log level: 'error', 'warn', 'log', or omit for all" },
max_entries = { type = "integer", description = "Max entries to return (default 20)" },
},
},
handler = function(input, ctx)
return dispatch(input, ctx, "console_log", {
level = input.level, max_entries = input.max_entries,
}, function(result, err, ctx)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
local entries = result.entries or {}
local lines = {}
for _, e in ipairs(entries) do
lines[#lines + 1] = string.format(" [%s] %s", e.level or "log", e.text)
end
local text = #lines > 0 and table.concat(lines, "\n") or "(no console entries)"
local llm_output = string.format("%d console entries:\n%s", #entries, text)
if #lines > 0 then
save_artifact("console", os.date("%H-%M-%S") .. "_console.log", table.concat(lines, "\n"))
end
ctx:finish({ llm_output = llm_output })
end)
end,
header = function(input) return input.level and ("console [" .. input.level .. "]") or "console log" end,
})
maki.api.register_tool({
name = "browser_screenshot",
kind = "browser",
description = [[Take a screenshot of the current page or a specific element. Use this when visual inspection is needed — for example, to check layout, overlapping elements, or visual regressions. Returns an inline image. In headless mode this is the primary way to 'see' the page.]],
schema = {
type = "object", additionalProperties = false,
properties = {
selector = { type = "string", description = "CSS selector to screenshot a specific element (optional, defaults to full page)" },
full_page = { type = "boolean", description = "Capture the full scrollable page (default false)" },
},
},
handler = function(input, ctx)
if not server_running() then
return { llm_output = NO_BROWSER_MSG, is_error = true }
end
send_command("screenshot", {
selector = input.selector, full_page = input.full_page,
}, function(result, err)
if err then ctx:finish({ llm_output = "error: " .. err, is_error = true }); return end
ctx:finish({
llm_output = "Screenshot of " .. (input.selector or "full page"),
image = { media_type = result.media_type or "image/png", data = result.image },
})
end)
ensure_keepalive()
return nil
end,
header = function(input) return input.selector and ("screenshot: " .. input.selector) or "screenshot" end,
})
maki.api.register_tool({
name = "browser_close",
kind = "browser",
description = [[Close the browser window and stop the Playwright server. Use this at the end of a testing session. All state is lost. Call browser_launch to start a fresh session later. Any files downloaded during the session are deleted with the browser, so copy anything you still need before closing.]],
schema = { type = "object", additionalProperties = false, properties = {} },
handler = function(input, ctx)
if server_running() then
send_command("close", {}, function(result, _)
local files = (result and result.downloads) or {}
local msg = "Browser closed."
if #files > 0 then
msg = msg .. string.format(" %d downloaded file(s) were deleted with the browser:\n %s",
#files, table.concat(files, "\n "))
end
-- Finish the tool call BEFORE tearing down server state: stop_server()
-- nils cmd_path/resp_path and clears pending, so finishing afterwards
-- risked losing the response if teardown interleaved with the poll loop.
ctx:finish({ llm_output = msg })
stop_server()
end)
ensure_keepalive()
return nil
end
stop_server()
return { llm_output = "Browser closed." }
end,
})
maki.api.create_autocmd("plugin_unload", {
callback = function() stop_server() end,
})