micro-models-agent 0.57.0 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/CHANGELOG.md +481 -476
  2. package/README.md +358 -358
  3. package/dist/certification/certifications.json +493 -493
  4. package/dist/cli/commands.js +447 -0
  5. package/dist/cli/completer.js +167 -0
  6. package/dist/cli/index.js +2 -0
  7. package/dist/cli/main.js +153 -0
  8. package/dist/cli/plugin-commands.js +36 -0
  9. package/dist/cli/repl-commands.js +761 -0
  10. package/dist/cli/repl.js +702 -0
  11. package/dist/cli/run-result.js +33 -0
  12. package/dist/cli/security-commands.js +164 -0
  13. package/dist/cli/setup.js +237 -0
  14. package/dist/config/config.js +276 -0
  15. package/dist/config/defaults.js +141 -0
  16. package/dist/config/domains.js +179 -0
  17. package/dist/config/experts.js +15 -0
  18. package/dist/config/index.js +4 -0
  19. package/dist/config/security.js +213 -0
  20. package/dist/config/types.js +1 -0
  21. package/dist/core/agent-moe.js +102 -0
  22. package/dist/core/agent.js +1018 -0
  23. package/dist/core/bootstrap.js +481 -0
  24. package/dist/core/crash-handler.js +51 -0
  25. package/dist/core/environment.js +199 -0
  26. package/dist/core/index.js +2 -0
  27. package/dist/core/prompt-builder.js +76 -0
  28. package/dist/core/session-logger.js +251 -0
  29. package/dist/core/types.js +1 -0
  30. package/dist/core/version.js +26 -0
  31. package/dist/core/workspace.js +76 -0
  32. package/dist/i18n/en.json +679 -0
  33. package/dist/i18n/index.js +46 -0
  34. package/dist/i18n/ru.json +679 -0
  35. package/dist/index.js +22 -0
  36. package/dist/llm/image-utils.js +143 -0
  37. package/dist/llm/index.js +4 -0
  38. package/dist/llm/model-loader.js +78 -0
  39. package/dist/llm/openai-compat.js +497 -0
  40. package/dist/llm/orchestrator.js +200 -0
  41. package/dist/llm/provider.js +10 -0
  42. package/dist/llm/response.js +39 -0
  43. package/dist/llm/token-counter.js +39 -0
  44. package/dist/llm/types.js +1 -0
  45. package/dist/logger/app-logger.js +189 -0
  46. package/dist/logger/file-log.js +151 -0
  47. package/dist/logger/index.js +1 -0
  48. package/dist/migration/backup.js +45 -0
  49. package/dist/migration/detect.js +50 -0
  50. package/dist/migration/index.js +2 -0
  51. package/dist/modules/artifacts/store.js +61 -0
  52. package/dist/modules/browser/actions.js +76 -0
  53. package/dist/modules/browser/bridge-client.js +199 -0
  54. package/dist/modules/browser/bridge-path.js +10 -0
  55. package/dist/modules/browser/bridge-server.mjs +219 -219
  56. package/dist/modules/browser/cookie-store.js +24 -0
  57. package/dist/modules/browser/driver.js +136 -0
  58. package/dist/modules/browser/index.js +7 -0
  59. package/dist/modules/browser/module.js +29 -0
  60. package/dist/modules/browser/session.js +342 -0
  61. package/dist/modules/browser/snapshot.js +148 -0
  62. package/dist/modules/browser/types.js +12 -0
  63. package/dist/modules/certification/cli.js +213 -0
  64. package/dist/modules/certification/fact-checker.js +82 -0
  65. package/dist/modules/certification/loader.js +106 -0
  66. package/dist/modules/certification/manifest.js +58 -0
  67. package/dist/modules/certification/runner.js +245 -0
  68. package/dist/modules/certification/scenarios.js +407 -0
  69. package/dist/modules/certification/types.js +1 -0
  70. package/dist/modules/context/chunk-query.js +100 -0
  71. package/dist/modules/context/fact-extractor.js +168 -0
  72. package/dist/modules/context/history.js +15 -0
  73. package/dist/modules/context/index.js +1 -0
  74. package/dist/modules/context/manager.js +440 -0
  75. package/dist/modules/execution/audit-runners.js +206 -0
  76. package/dist/modules/execution/auditor.js +218 -0
  77. package/dist/modules/execution/execution-plugin.js +431 -0
  78. package/dist/modules/execution/index.js +8 -0
  79. package/dist/modules/execution/module.js +625 -0
  80. package/dist/modules/execution/moe-executor.js +304 -0
  81. package/dist/modules/execution/plan-coverage.js +68 -0
  82. package/dist/modules/execution/plan-persister.js +46 -0
  83. package/dist/modules/execution/plan-store.js +196 -0
  84. package/dist/modules/execution/plan-tool.js +677 -0
  85. package/dist/modules/execution/plan-validator.js +153 -0
  86. package/dist/modules/execution/planner.js +94 -0
  87. package/dist/modules/execution/stuck-detector.js +746 -0
  88. package/dist/modules/execution/tracker.js +69 -0
  89. package/dist/modules/execution/types.js +1 -0
  90. package/dist/modules/execution/verifier.js +235 -0
  91. package/dist/modules/execution/windows-commands.js +41 -0
  92. package/dist/modules/hallucination/confidence.js +66 -0
  93. package/dist/modules/hallucination/consistency.js +26 -0
  94. package/dist/modules/hallucination/detector.js +47 -0
  95. package/dist/modules/hallucination/factual.js +169 -0
  96. package/dist/modules/hallucination/index.js +5 -0
  97. package/dist/modules/hallucination/js-identifiers.js +262 -0
  98. package/dist/modules/hallucination/llm-judge.js +101 -0
  99. package/dist/modules/index.js +5 -0
  100. package/dist/modules/indexer/cache.js +40 -0
  101. package/dist/modules/indexer/index.js +3 -0
  102. package/dist/modules/indexer/module.js +246 -0
  103. package/dist/modules/indexer/project-profile.js +183 -0
  104. package/dist/modules/indexer/walker.js +101 -0
  105. package/dist/modules/lsp/check-tool.js +58 -0
  106. package/dist/modules/lsp/client.js +389 -0
  107. package/dist/modules/lsp/command.js +60 -0
  108. package/dist/modules/lsp/config.js +135 -0
  109. package/dist/modules/lsp/index.js +3 -0
  110. package/dist/modules/lsp/module.js +260 -0
  111. package/dist/modules/lsp/probe.js +86 -0
  112. package/dist/modules/lsp/project-root.js +32 -0
  113. package/dist/modules/lsp/startup-check.js +144 -0
  114. package/dist/modules/lsp/types.js +1 -0
  115. package/dist/modules/mcp/client.js +399 -0
  116. package/dist/modules/mcp/index.js +3 -0
  117. package/dist/modules/mcp/module.js +142 -0
  118. package/dist/modules/mcp/registry.js +15 -0
  119. package/dist/modules/memory/index.js +1 -0
  120. package/dist/modules/memory/module.js +96 -0
  121. package/dist/modules/memory/search.js +42 -0
  122. package/dist/modules/memory/store.js +69 -0
  123. package/dist/modules/pipelines/engine.js +60 -0
  124. package/dist/modules/pipelines/index.js +3 -0
  125. package/dist/modules/pipelines/parser.js +56 -0
  126. package/dist/modules/pipelines/template.js +14 -0
  127. package/dist/modules/plugins/builtin/lint-on-write.js +334 -0
  128. package/dist/modules/plugins/builtin/notify.js +9 -0
  129. package/dist/modules/plugins/index.js +1 -0
  130. package/dist/modules/plugins/loader.js +70 -0
  131. package/dist/modules/plugins/manager.js +261 -0
  132. package/dist/modules/plugins/types.js +1 -0
  133. package/dist/modules/pricing/index.js +61 -0
  134. package/dist/modules/pricing/prices.js +129 -0
  135. package/dist/modules/processes/detect.js +34 -0
  136. package/dist/modules/processes/index.js +2 -0
  137. package/dist/modules/processes/registry.js +327 -0
  138. package/dist/modules/processes/runner.js +23 -0
  139. package/dist/modules/providers/create.js +22 -0
  140. package/dist/modules/providers/fallback.js +79 -0
  141. package/dist/modules/providers/health.js +46 -0
  142. package/dist/modules/providers/index.js +5 -0
  143. package/dist/modules/providers/manager.js +161 -0
  144. package/dist/modules/providers/presets.js +128 -0
  145. package/dist/modules/providers/registry.js +22 -0
  146. package/dist/modules/providers/types.js +1 -0
  147. package/dist/modules/registry.js +48 -0
  148. package/dist/modules/security/audit-log.js +136 -0
  149. package/dist/modules/security/audit-notifier.js +292 -0
  150. package/dist/modules/security/command-validator.js +219 -0
  151. package/dist/modules/security/content-scanner.js +53 -0
  152. package/dist/modules/security/data-sanitizer.js +89 -0
  153. package/dist/modules/security/encryption.js +242 -0
  154. package/dist/modules/security/index.js +14 -0
  155. package/dist/modules/security/network-validator.js +88 -0
  156. package/dist/modules/security/path-validator.js +203 -0
  157. package/dist/modules/security/rate-limiter.js +119 -0
  158. package/dist/modules/security/security-policies.js +531 -0
  159. package/dist/modules/security/session-encryption.js +210 -0
  160. package/dist/modules/security/session-isolation.js +95 -0
  161. package/dist/modules/session/index.js +3 -0
  162. package/dist/modules/session/manager.js +172 -0
  163. package/dist/modules/session/module.js +24 -0
  164. package/dist/modules/session/store.js +222 -0
  165. package/dist/modules/session/types.js +1 -0
  166. package/dist/modules/skills/index.js +2 -0
  167. package/dist/modules/skills/loader.js +72 -0
  168. package/dist/modules/skills/matcher.js +27 -0
  169. package/dist/modules/skills/module.js +129 -0
  170. package/dist/modules/types.js +1 -0
  171. package/dist/modules/updater/checker.js +96 -0
  172. package/dist/modules/updater/index.js +2 -0
  173. package/dist/modules/updater/module.js +116 -0
  174. package/dist/modules/user-profile/compressor.js +16 -0
  175. package/dist/modules/user-profile/index.js +1 -0
  176. package/dist/modules/user-profile/profile.js +68 -0
  177. package/dist/skills/builtin/git.md +36 -36
  178. package/dist/skills/builtin/typescript.md +35 -35
  179. package/dist/tools/approve.js +33 -0
  180. package/dist/tools/attach-image.js +101 -0
  181. package/dist/tools/bash.js +519 -0
  182. package/dist/tools/browser.js +115 -0
  183. package/dist/tools/chunk-query.js +100 -0
  184. package/dist/tools/create-dir.js +56 -0
  185. package/dist/tools/delete-file.js +63 -0
  186. package/dist/tools/download-file.js +117 -0
  187. package/dist/tools/edit-file.js +80 -0
  188. package/dist/tools/enable-tools.js +59 -0
  189. package/dist/tools/executor.js +154 -0
  190. package/dist/tools/file-info.js +47 -0
  191. package/dist/tools/filter-tools.js +17 -0
  192. package/dist/tools/glob-tool.js +27 -0
  193. package/dist/tools/grep-tool.js +125 -0
  194. package/dist/tools/hidden-tools-block.js +37 -0
  195. package/dist/tools/index.js +78 -0
  196. package/dist/tools/list-dir.js +49 -0
  197. package/dist/tools/load-skill.js +43 -0
  198. package/dist/tools/mcp-call.js +69 -0
  199. package/dist/tools/move-file.js +86 -0
  200. package/dist/tools/path-utils.js +101 -0
  201. package/dist/tools/pipeline-run.js +145 -0
  202. package/dist/tools/preview.js +2 -0
  203. package/dist/tools/process-kill.js +40 -0
  204. package/dist/tools/process-list.js +37 -0
  205. package/dist/tools/process-log.js +54 -0
  206. package/dist/tools/question.js +141 -0
  207. package/dist/tools/read-file.js +179 -0
  208. package/dist/tools/recall.js +118 -0
  209. package/dist/tools/registry.js +47 -0
  210. package/dist/tools/remember.js +68 -0
  211. package/dist/tools/scope-check.js +32 -0
  212. package/dist/tools/search-history.js +85 -0
  213. package/dist/tools/subagent.js +196 -0
  214. package/dist/tools/types.js +1 -0
  215. package/dist/tools/user-input.js +123 -0
  216. package/dist/tools/web-browse.js +87 -0
  217. package/dist/tools/web-fetch.js +119 -0
  218. package/dist/tools/web-search.js +105 -0
  219. package/dist/tools/write-file.js +82 -0
  220. package/dist/ui/box.js +77 -0
  221. package/dist/ui/colors.js +4 -0
  222. package/dist/ui/diff.js +178 -0
  223. package/dist/ui/index.js +6 -0
  224. package/dist/ui/line-editor.js +822 -0
  225. package/dist/ui/line-math.js +73 -0
  226. package/dist/ui/md-formatter.js +212 -0
  227. package/dist/ui/output.js +13 -0
  228. package/dist/ui/plan-view.js +103 -0
  229. package/dist/ui/renderer.js +259 -0
  230. package/dist/ui/spinner.js +70 -0
  231. package/dist/ui/table.js +144 -0
  232. package/package.json +51 -51
@@ -0,0 +1,136 @@
1
+ import { chromium } from "playwright";
2
+ import { ConsoleBuffer } from "./session";
3
+ export const DIRECT_LAUNCH_TIMEOUT_MS = 8000;
4
+ export class PlaywrightDriver {
5
+ browser = null;
6
+ context = null;
7
+ page = null;
8
+ console = new ConsoleBuffer();
9
+ network = [];
10
+ async launch(cfg) {
11
+ if (this.browser)
12
+ return;
13
+ this.browser = await chromium.launch({
14
+ headless: cfg.headless,
15
+ timeout: cfg.timeoutMs,
16
+ });
17
+ this.context = await this.browser.newContext({ viewport: cfg.viewport });
18
+ this.page = await this.context.newPage();
19
+ this.page.setDefaultTimeout(cfg.timeoutMs);
20
+ this.page.on("console", (msg) => this.console.add(msg.type(), msg.text()));
21
+ this.page.on("pageerror", (err) => this.console.add("pageerror", `Page error: ${err.message}`));
22
+ this.page.on("requestfailed", (req) => {
23
+ const failure = req.failure();
24
+ this.network.push({
25
+ method: req.method(),
26
+ url: req.url(),
27
+ error: failure?.errorText || "unknown",
28
+ });
29
+ });
30
+ }
31
+ async goto(url, timeoutMs) {
32
+ this.requirePage();
33
+ this.console.clear();
34
+ this.network = [];
35
+ await this.page.goto(url, { waitUntil: "domcontentloaded", timeout: timeoutMs });
36
+ }
37
+ async evaluate(js) {
38
+ return this.requirePage().evaluate(js);
39
+ }
40
+ async content() {
41
+ return this.requirePage().content();
42
+ }
43
+ async title() {
44
+ return this.requirePage().title();
45
+ }
46
+ url() {
47
+ return this.page?.url() || "";
48
+ }
49
+ async waitForLoad(timeoutMs) {
50
+ await this.requirePage()
51
+ .waitForLoadState("domcontentloaded", { timeout: timeoutMs })
52
+ .catch(() => { });
53
+ }
54
+ async screenshot() {
55
+ return this.requirePage().screenshot({ type: "png", fullPage: false });
56
+ }
57
+ async cookies() {
58
+ if (!this.context)
59
+ return [];
60
+ return this.context.cookies();
61
+ }
62
+ async addCookies(cookies) {
63
+ if (!this.context || cookies.length === 0)
64
+ return;
65
+ await this.context.addCookies(cookies);
66
+ }
67
+ async goBack(timeoutMs) {
68
+ await this.requirePage()
69
+ .goBack({ waitUntil: "domcontentloaded", timeout: timeoutMs })
70
+ .catch(() => { });
71
+ }
72
+ async goForward(timeoutMs) {
73
+ await this.requirePage()
74
+ .goForward({ waitUntil: "domcontentloaded", timeout: timeoutMs })
75
+ .catch(() => { });
76
+ }
77
+ resetEventLog() {
78
+ this.console.clear();
79
+ this.network = [];
80
+ }
81
+ getConsole() {
82
+ return this.console.getAll();
83
+ }
84
+ getNetworkErrors() {
85
+ return this.network.slice(-15);
86
+ }
87
+ async close() {
88
+ if (this.page)
89
+ await this.page.close().catch(() => { });
90
+ if (this.context)
91
+ await this.context.close().catch(() => { });
92
+ if (this.browser)
93
+ await this.browser.close().catch(() => { });
94
+ this.page = null;
95
+ this.context = null;
96
+ this.browser = null;
97
+ }
98
+ dispose() {
99
+ this.close().catch(() => { });
100
+ }
101
+ requirePage() {
102
+ if (!this.page)
103
+ throw new Error("No page open");
104
+ return this.page;
105
+ }
106
+ }
107
+ export function createBrowserDriver(config) {
108
+ const common = {
109
+ headless: config.headless,
110
+ viewport: { width: config.viewportWidth, height: config.viewportHeight },
111
+ timeoutMs: config.navigationTimeout,
112
+ };
113
+ return (async () => {
114
+ // Playwright's pipe/websocket transport is broken under Bun on some
115
+ // platforms (see oven-sh/bun#31105, #9911). Under Bun we always use the
116
+ // Node bridge. Under Node we try the direct path first.
117
+ if (process.versions.bun) {
118
+ return launchBridge(config, common);
119
+ }
120
+ const direct = new PlaywrightDriver();
121
+ try {
122
+ await direct.launch({ ...common, timeoutMs: DIRECT_LAUNCH_TIMEOUT_MS });
123
+ return direct;
124
+ }
125
+ catch {
126
+ direct.dispose();
127
+ }
128
+ return launchBridge(config, common);
129
+ })();
130
+ }
131
+ async function launchBridge(config, common) {
132
+ const { BridgeDriver } = await import("./bridge-client");
133
+ const bridge = new BridgeDriver({ maxConsoleLineChars: config.maxConsoleLineChars });
134
+ await bridge.launch(common);
135
+ return bridge;
136
+ }
@@ -0,0 +1,7 @@
1
+ export { BrowserModule } from "./module";
2
+ export { BrowserSession, BrowserActionTracker, ConsoleBuffer } from "./session";
3
+ export { CookieStore } from "./cookie-store";
4
+ export { createBrowserDriver, PlaywrightDriver } from "./driver";
5
+ export { BridgeDriver } from "./bridge-client";
6
+ export { extractInteractiveElements, formatSnapshot, truncateText } from "./snapshot";
7
+ export { DEFAULT_BROWSER_CONFIG } from "./types";
@@ -0,0 +1,29 @@
1
+ import { createBrowserTool, closeBrowserSession } from "../../tools/browser";
2
+ export class BrowserModule {
3
+ name = "browser";
4
+ getSystemPromptBlock() {
5
+ return {
6
+ content: [
7
+ "You have a headless browser tool. Use it to navigate websites, click links, fill forms, and read page content.",
8
+ "Workflow: open(url) → read snapshot → click/type on element numbers → read updated snapshot.",
9
+ 'Each snapshot includes a "Content" section with the visible page text, a "Console" section with browser messages, and network errors. Use these to understand the page, detect JS errors, and verify the result of your actions.',
10
+ 'Always start with "open" action. Use element numbers from snapshot for click/type targets.',
11
+ 'Use "screenshot" action only if the model supports vision. Otherwise rely on the text snapshot.',
12
+ ].join("\n"),
13
+ priority: "normal",
14
+ essential: false,
15
+ estimatedTokens: 80,
16
+ };
17
+ }
18
+ getToolDefinitions() {
19
+ return [createBrowserTool()];
20
+ }
21
+ getPlugin() {
22
+ return {
23
+ name: "browser",
24
+ onSessionEnd: () => {
25
+ closeBrowserSession();
26
+ },
27
+ };
28
+ }
29
+ }
@@ -0,0 +1,342 @@
1
+ import { createBrowserDriver } from "./driver";
2
+ import { extractInteractiveElements, formatSnapshot } from "./snapshot";
3
+ import { buildClickScript, buildTypeScript, buildScrollScript, buildIndexInjectionScript, buildTextExtractionScript, } from "./actions";
4
+ import { CookieStore } from "./cookie-store";
5
+ import { t } from "../../i18n/index";
6
+ const CONSOLE_MAX_LINE = 400;
7
+ export class ConsoleBuffer {
8
+ entries = [];
9
+ maxEntries;
10
+ constructor(maxEntries = 20) {
11
+ this.maxEntries = maxEntries;
12
+ }
13
+ add(type, text) {
14
+ const clean = String(text).replace(/\s+/g, " ").trim();
15
+ if (!clean)
16
+ return;
17
+ const line = clean.length > CONSOLE_MAX_LINE ? clean.slice(0, CONSOLE_MAX_LINE) + "…" : clean;
18
+ this.entries.push({ type, text: line });
19
+ if (this.entries.length > this.maxEntries) {
20
+ this.entries.splice(0, this.entries.length - this.maxEntries);
21
+ }
22
+ }
23
+ clear() {
24
+ this.entries = [];
25
+ }
26
+ getAll() {
27
+ return [...this.entries];
28
+ }
29
+ get size() {
30
+ return this.entries.length;
31
+ }
32
+ }
33
+ export class BrowserActionTracker {
34
+ history = [];
35
+ threshold;
36
+ constructor(threshold = 3) {
37
+ this.threshold = threshold;
38
+ }
39
+ record(action, args, url) {
40
+ this.history.push({ action, args, url });
41
+ if (this.history.length < this.threshold)
42
+ return null;
43
+ const recent = this.history.slice(-this.threshold);
44
+ const allSame = recent.every((h) => h.action === recent[0].action &&
45
+ h.url === recent[0].url &&
46
+ JSON.stringify(h.args) === JSON.stringify(recent[0].args));
47
+ if (allSame) {
48
+ return t("browser.repeated_action", {
49
+ action,
50
+ threshold: this.threshold,
51
+ });
52
+ }
53
+ return null;
54
+ }
55
+ reset() {
56
+ this.history = [];
57
+ }
58
+ }
59
+ export class BrowserSession {
60
+ driver = null;
61
+ config;
62
+ cookieStore;
63
+ state = {
64
+ isOpen: false,
65
+ url: null,
66
+ title: null,
67
+ elementCount: 0,
68
+ };
69
+ actionTracker = new BrowserActionTracker(3);
70
+ constructor(config) {
71
+ this.config = config;
72
+ this.cookieStore = new CookieStore(config.cookieDir);
73
+ }
74
+ getState() {
75
+ return { ...this.state };
76
+ }
77
+ async execute(action, args) {
78
+ try {
79
+ let result;
80
+ switch (action) {
81
+ case "open":
82
+ result = await this.open(String(args.url || ""));
83
+ break;
84
+ case "click":
85
+ result = await this.click(Number(args.target));
86
+ break;
87
+ case "type":
88
+ result = await this.type(Number(args.target), String(args.text || ""));
89
+ break;
90
+ case "scroll":
91
+ result = await this.scroll(String(args.direction || "down"));
92
+ break;
93
+ case "back":
94
+ result = await this.back();
95
+ break;
96
+ case "forward":
97
+ result = await this.forward();
98
+ break;
99
+ case "screenshot":
100
+ result = await this.screenshot();
101
+ break;
102
+ case "snapshot":
103
+ result = await this.snapshot();
104
+ break;
105
+ case "close":
106
+ result = await this.close();
107
+ break;
108
+ case "wait":
109
+ result = await this.wait(Number(args.ms || 1000));
110
+ break;
111
+ default:
112
+ return {
113
+ success: false,
114
+ output: t("browser.unknown_action", { action }),
115
+ };
116
+ }
117
+ if (action !== "open") {
118
+ const warning = this.actionTracker.record(action, args, this.driver?.url() || "");
119
+ if (warning && result.success) {
120
+ result.output = result.output + "\n\n⚠️ " + warning;
121
+ }
122
+ }
123
+ return result;
124
+ }
125
+ catch (err) {
126
+ return {
127
+ success: false,
128
+ output: t("browser.error", { message: err.message }),
129
+ };
130
+ }
131
+ }
132
+ async ensureDriver() {
133
+ if (!this.driver) {
134
+ return { success: false, output: t("browser.no_page") };
135
+ }
136
+ return null;
137
+ }
138
+ async launch() {
139
+ if (this.driver)
140
+ return;
141
+ this.driver = await createBrowserDriver(this.config);
142
+ const savedCookies = await this.cookieStore.load();
143
+ if (savedCookies.length > 0) {
144
+ await this.driver.addCookies(savedCookies);
145
+ }
146
+ }
147
+ async saveCookies() {
148
+ if (!this.driver)
149
+ return;
150
+ const cookies = await this.driver.cookies();
151
+ await this.cookieStore.save(cookies);
152
+ }
153
+ async takeSnapshot() {
154
+ if (!this.driver)
155
+ return "No page open.";
156
+ await this.driver.evaluate(buildIndexInjectionScript());
157
+ const html = await this.driver.content();
158
+ const url = this.driver.url();
159
+ const title = await this.driver.title();
160
+ let content = "";
161
+ try {
162
+ content = String(await this.driver.evaluate(buildTextExtractionScript()));
163
+ }
164
+ catch {
165
+ content = "";
166
+ }
167
+ const allElements = extractInteractiveElements(html, this.config.maxElements + 5);
168
+ const truncated = allElements.length > this.config.maxElements;
169
+ const elements = allElements.slice(0, this.config.maxElements);
170
+ this.state = {
171
+ isOpen: true,
172
+ url,
173
+ title,
174
+ elementCount: elements.length,
175
+ };
176
+ return formatSnapshot({
177
+ url,
178
+ title,
179
+ elements,
180
+ content,
181
+ console: this.driver.getConsole(),
182
+ networkErrors: this.driver.getNetworkErrors(),
183
+ truncated,
184
+ });
185
+ }
186
+ async open(url) {
187
+ if (!url)
188
+ return { success: false, output: t("browser.url_required") };
189
+ // Security: block dangerous schemes (file:, chrome:, about:, data:).
190
+ if (/^(file|chrome|about|data|javascript|view-source):/i.test(url)) {
191
+ return { success: false, output: `[SECURITY BLOCKED] scheme not allowed: ${url}` };
192
+ }
193
+ if (!url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("file://")) {
194
+ const isLocalhost = /^(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?$/i.test(url);
195
+ url = isLocalhost ? "http://" + url : "https://" + url;
196
+ }
197
+ await this.launch();
198
+ if (!this.driver)
199
+ return { success: false, output: t("browser.create_page_failed") };
200
+ this.actionTracker.reset();
201
+ this.driver.resetEventLog();
202
+ try {
203
+ await this.driver.goto(url, this.config.navigationTimeout);
204
+ }
205
+ catch (err) {
206
+ return {
207
+ success: false,
208
+ output: t("browser.nav_failed", { message: err.message }),
209
+ };
210
+ }
211
+ const snapshot = await this.takeSnapshot();
212
+ await this.saveCookies();
213
+ return { success: true, output: snapshot };
214
+ }
215
+ async click(target) {
216
+ const err = await this.ensureDriver();
217
+ if (err)
218
+ return err;
219
+ if (!this.driver)
220
+ return { success: false, output: "No page" };
221
+ if (!target || target < 1) {
222
+ return { success: false, output: t("browser.invalid_target") };
223
+ }
224
+ try {
225
+ await this.driver.evaluate(buildClickScript(target));
226
+ await this.driver.waitForLoad(5000);
227
+ await new Promise((r) => setTimeout(r, 500));
228
+ const snapshot = await this.takeSnapshot();
229
+ await this.saveCookies();
230
+ return { success: true, output: snapshot };
231
+ }
232
+ catch (err) {
233
+ return {
234
+ success: false,
235
+ output: t("browser.click_failed", { message: err.message }),
236
+ };
237
+ }
238
+ }
239
+ async type(target, text) {
240
+ const err = await this.ensureDriver();
241
+ if (err)
242
+ return err;
243
+ if (!this.driver)
244
+ return { success: false, output: "No page" };
245
+ if (!target || target < 1) {
246
+ return { success: false, output: t("browser.invalid_target_short") };
247
+ }
248
+ if (!text) {
249
+ return { success: false, output: t("browser.text_required") };
250
+ }
251
+ try {
252
+ await this.driver.evaluate(buildTypeScript(target, text));
253
+ const snapshot = await this.takeSnapshot();
254
+ return { success: true, output: snapshot };
255
+ }
256
+ catch (err) {
257
+ return {
258
+ success: false,
259
+ output: t("browser.type_failed", { message: err.message }),
260
+ };
261
+ }
262
+ }
263
+ async scroll(direction) {
264
+ const err = await this.ensureDriver();
265
+ if (err)
266
+ return err;
267
+ if (!this.driver)
268
+ return { success: false, output: "No page" };
269
+ const dir = direction;
270
+ if (!["up", "down", "top", "bottom"].includes(dir)) {
271
+ return { success: false, output: t("browser.direction_invalid") };
272
+ }
273
+ try {
274
+ await this.driver.evaluate(buildScrollScript(dir));
275
+ await new Promise((r) => setTimeout(r, 300));
276
+ const snapshot = await this.takeSnapshot();
277
+ return { success: true, output: snapshot };
278
+ }
279
+ catch (err) {
280
+ return {
281
+ success: false,
282
+ output: t("browser.scroll_failed", { message: err.message }),
283
+ };
284
+ }
285
+ }
286
+ async back() {
287
+ const err = await this.ensureDriver();
288
+ if (err)
289
+ return err;
290
+ if (!this.driver)
291
+ return { success: false, output: "No page" };
292
+ await this.driver.goBack(this.config.navigationTimeout);
293
+ await new Promise((r) => setTimeout(r, 300));
294
+ const snapshot = await this.takeSnapshot();
295
+ return { success: true, output: snapshot };
296
+ }
297
+ async forward() {
298
+ const err = await this.ensureDriver();
299
+ if (err)
300
+ return err;
301
+ if (!this.driver)
302
+ return { success: false, output: "No page" };
303
+ await this.driver.goForward(this.config.navigationTimeout);
304
+ await new Promise((r) => setTimeout(r, 300));
305
+ const snapshot = await this.takeSnapshot();
306
+ return { success: true, output: snapshot };
307
+ }
308
+ async screenshot() {
309
+ const err = await this.ensureDriver();
310
+ if (err)
311
+ return err;
312
+ if (!this.driver)
313
+ return { success: false, output: "No page" };
314
+ const buffer = await this.driver.screenshot();
315
+ const snapshot = await this.takeSnapshot();
316
+ return { success: true, output: snapshot, screenshot: buffer };
317
+ }
318
+ async snapshot() {
319
+ const err = await this.ensureDriver();
320
+ if (err)
321
+ return err;
322
+ const snap = await this.takeSnapshot();
323
+ return { success: true, output: snap };
324
+ }
325
+ async wait(ms) {
326
+ const err = await this.ensureDriver();
327
+ if (err)
328
+ return err;
329
+ await new Promise((r) => setTimeout(r, Math.min(ms, 10000)));
330
+ const snapshot = await this.takeSnapshot();
331
+ return { success: true, output: snapshot };
332
+ }
333
+ async close() {
334
+ await this.saveCookies();
335
+ if (this.driver) {
336
+ await this.driver.close();
337
+ this.driver = null;
338
+ }
339
+ this.state = { isOpen: false, url: null, title: null, elementCount: 0 };
340
+ return { success: true, output: t("browser.closed") };
341
+ }
342
+ }
@@ -0,0 +1,148 @@
1
+ import { t } from "../../i18n/index";
2
+ import { DEFAULT_BROWSER_CONFIG } from "./types";
3
+ function inferRole(tag, type) {
4
+ const t = tag.toLowerCase();
5
+ if (t === "a")
6
+ return "link";
7
+ if (t === "button")
8
+ return "button";
9
+ if (t === "input") {
10
+ const inputType = type?.toLowerCase();
11
+ if (inputType === "submit" || inputType === "button")
12
+ return "button";
13
+ if (inputType === "checkbox")
14
+ return "checkbox";
15
+ if (inputType === "radio")
16
+ return "radio";
17
+ return "textbox";
18
+ }
19
+ if (t === "textarea")
20
+ return "textbox";
21
+ if (t === "select")
22
+ return "combobox";
23
+ return "widget";
24
+ }
25
+ function getName(tag, attrs, html, matchIndex) {
26
+ const fromAttr = attrs["aria-label"] ||
27
+ attrs["placeholder"] ||
28
+ attrs["title"] ||
29
+ attrs["alt"] ||
30
+ attrs["value"] ||
31
+ attrs["name"] ||
32
+ "";
33
+ if (fromAttr)
34
+ return fromAttr;
35
+ const afterTag = html.slice(matchIndex);
36
+ const closeIdx = afterTag.indexOf(">");
37
+ if (closeIdx === -1)
38
+ return "";
39
+ const afterOpen = afterTag.slice(closeIdx + 1);
40
+ const endTag = `</${tag}>`;
41
+ const endIdx = afterOpen.indexOf(endTag);
42
+ if (endIdx === -1)
43
+ return "";
44
+ const text = afterOpen
45
+ .slice(0, endIdx)
46
+ .replace(/<[^>]+>/g, "")
47
+ .trim();
48
+ return text.slice(0, 50);
49
+ }
50
+ export function extractInteractiveElements(html, maxElements = 30) {
51
+ const elements = [];
52
+ const tagRegex = /<(a|button|input|textarea|select|div|span)([^>]*)>/gi;
53
+ let match;
54
+ while ((match = tagRegex.exec(html)) !== null) {
55
+ if (elements.length >= maxElements)
56
+ break;
57
+ const tag = match[1].toLowerCase();
58
+ const attrStr = match[2];
59
+ const attrs = {};
60
+ const attrRegex = /(\w[\w-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
61
+ let attrMatch;
62
+ while ((attrMatch = attrRegex.exec(attrStr)) !== null) {
63
+ attrs[attrMatch[1].toLowerCase()] = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? "";
64
+ }
65
+ if (attrs["style"]?.includes("display:none") || attrs["style"]?.includes("display: none"))
66
+ continue;
67
+ if (attrs["hidden"] !== undefined)
68
+ continue;
69
+ if (attrs["aria-hidden"] === "true")
70
+ continue;
71
+ if (tag === "input" && attrs["type"] === "hidden")
72
+ continue;
73
+ const role = attrs["role"] || inferRole(tag, attrs["type"]);
74
+ const isInteractive = ["a", "button", "input", "textarea", "select"].includes(tag) || attrs["role"] !== undefined;
75
+ if (!isInteractive)
76
+ continue;
77
+ if (tag === "a" && !attrs["href"])
78
+ continue;
79
+ const name = getName(tag, attrs, html, match.index);
80
+ elements.push({
81
+ index: elements.length + 1,
82
+ tag,
83
+ role,
84
+ name,
85
+ value: attrs["value"],
86
+ href: attrs["href"],
87
+ visible: true,
88
+ });
89
+ }
90
+ return elements;
91
+ }
92
+ export function truncateText(text, maxChars) {
93
+ if (maxChars <= 0)
94
+ return "";
95
+ if (text.length <= maxChars)
96
+ return text;
97
+ const cut = text.slice(0, maxChars);
98
+ const lastNewline = cut.lastIndexOf("\n");
99
+ const safe = lastNewline > maxChars * 0.6 ? cut.slice(0, lastNewline) : cut;
100
+ return `${safe}\n${t("browser.truncated")}`;
101
+ }
102
+ export function formatSnapshot(snapshot, maxContentChars = DEFAULT_BROWSER_CONFIG.maxContentChars) {
103
+ const lines = [];
104
+ lines.push(`Page: "${snapshot.title}"`);
105
+ lines.push(`URL: ${snapshot.url}`);
106
+ lines.push("");
107
+ if (snapshot.elements.length === 0 && !snapshot.truncated) {
108
+ lines.push(t("browser.no_elements"));
109
+ }
110
+ else {
111
+ for (const el of snapshot.elements) {
112
+ let line = `[${el.index}] ${el.role}`;
113
+ if (el.name)
114
+ line += ` "${el.name}"`;
115
+ if (el.href)
116
+ line += ` → ${el.href}`;
117
+ if (el.value)
118
+ line += ` = "${el.value}"`;
119
+ lines.push(line);
120
+ }
121
+ if (snapshot.truncated) {
122
+ lines.push("");
123
+ lines.push(t("browser.more_elements"));
124
+ }
125
+ }
126
+ if (snapshot.content) {
127
+ lines.push("");
128
+ lines.push(t("browser.content_header"));
129
+ for (const line of truncateText(snapshot.content, maxContentChars).split("\n")) {
130
+ lines.push(`- ${line}`);
131
+ }
132
+ }
133
+ if (snapshot.console.length > 0) {
134
+ lines.push("");
135
+ lines.push(t("browser.console_header"));
136
+ for (const entry of snapshot.console) {
137
+ lines.push(`[${entry.type}] ${entry.text}`);
138
+ }
139
+ }
140
+ if (snapshot.networkErrors.length > 0) {
141
+ lines.push("");
142
+ lines.push(t("browser.network_errors_header"));
143
+ for (const err of snapshot.networkErrors) {
144
+ lines.push(`${err.method} ${err.url} → ${err.error}`);
145
+ }
146
+ }
147
+ return lines.join("\n");
148
+ }
@@ -0,0 +1,12 @@
1
+ export const DEFAULT_BROWSER_CONFIG = {
2
+ headless: true,
3
+ maxElements: 30,
4
+ maxContentChars: 2500,
5
+ maxConsoleEntries: 40,
6
+ maxConsoleLineChars: 400,
7
+ screenshotMaxWidth: 1280,
8
+ cookieDir: "",
9
+ viewportWidth: 1280,
10
+ viewportHeight: 720,
11
+ navigationTimeout: 15000,
12
+ };