opencode-moli 0.0.0-stage → 2.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 27painter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # Moli Browser for OpenCode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A native OpenCode V2 plugin that exposes the installed Moli headless browser.
4
+ It uses the same browser core as the DSH and Codex adapters in this repository.
5
+
6
+ ## What it registers
7
+
8
+ - A `websearch` provider named `moli`, backed by Moli. When no
9
+ `websearch.provider` is configured, the plugin makes `moli` the default, so
10
+ OpenCode's built-in `websearch` tool works without an API key.
11
+ - Three tools in the `moli` namespace:
12
+ - `moli_fetch` — rendered Markdown, HTML, a semantic tree, a CSS-selector
13
+ match, a JavaScript expression result, or a JSON envelope.
14
+ - `moli_capture` — a PNG screenshot or PDF written to an explicit path.
15
+ - `moli_probe` — inspect the local executable, or install the official Moli
16
+ release with `action: "install"`.
17
+
18
+ ## Build
19
+
20
+ From the repository root:
21
+
22
+ ```powershell
23
+ npm run build:opencode
24
+ ```
25
+
26
+ The build copies the shared `lib/moli.js` and `lib/install.js` into
27
+ `plugins/opencode-moli/dist/lib`, so the package is self-contained.
28
+
29
+ ## Install
30
+
31
+ Add the plugin directory to `opencode.json` or `opencode.jsonc`:
32
+
33
+ ```json
34
+ {
35
+ "plugins": ["D:/dsh_plugins/dsh-moli/plugins/opencode-moli"]
36
+ }
37
+ ```
38
+
39
+ Restart OpenCode after changing the plugin list. Once the package is published,
40
+ the entry can be the package name instead of a path.
41
+
42
+ ## Configuration
43
+
44
+ The object form passes plugin options:
45
+
46
+ ```json
47
+ {
48
+ "plugins": [
49
+ {
50
+ "package": "D:/dsh_plugins/dsh-moli/plugins/opencode-moli",
51
+ "options": {
52
+ "exePath": "C:/Users/me/AppData/Local/Moli/bin/moli.exe",
53
+ "proxy": "http://127.0.0.1:7890",
54
+ "searchUrls": ["https://www.bing.com/search?q={query}"],
55
+ "insecureTls": false
56
+ }
57
+ }
58
+ ]
59
+ }
60
+ ```
61
+
62
+ | Option | Default | Meaning |
63
+ |---|---|---|
64
+ | `exePath` | auto-detected | Absolute path to the Moli executable |
65
+ | `proxy` | `MOLI_PROXY`, `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY` | Forward proxy for search and fetch calls |
66
+ | `searchUrls` | Bing → DuckDuckGo HTML → Brave | Search URL templates containing `{query}` |
67
+ | `searchLimit` | `10` | Maximum results per search (capped at 20) |
68
+ | `searchAttemptTimeoutMs` | `20000` | Deadline for each fallback provider |
69
+ | `defaultTimeoutMs` | `30000` | Default page-readiness timeout |
70
+ | `maxChars` | `200000` | Inline text truncation budget |
71
+ | `insecureTls` | `true` | Skip TLS host verification. The repository's default assumes a filtering proxy that cannot reach the certificate-revocation responder; set `false` on a healthy network. |
72
+ | `installTimeoutMs` | `180000` | Deadline for `moli_probe action="install"` |
73
+
74
+ Environment variables with the same names as the Codex adapter are also read:
75
+ `MOLI_BIN`, `MOLI_PROXY`, `MOLI_SEARCH_URL`, `MOLI_SEARCH_URLS`,
76
+ `MOLI_SEARCH_ATTEMPT_TIMEOUT_MS`, `MOLI_TIMEOUT_MS`, `MOLI_MAX_CHARS`,
77
+ `MOLI_INSTALL_TIMEOUT_MS`, and `MOLI_INSECURE_TLS`.
78
+
79
+ ## Search behavior
80
+
81
+ `moli` renders the configured search page with Moli and extracts the ordinary
82
+ result links. It tries each provider until one returns at least one structured
83
+ result; an empty or "no results" page falls through to the next provider. This is
84
+ free and keyless, but the result quality and anti-bot behavior are those of the
85
+ public search pages, not a paid search API.
86
+
87
+ ## Security
88
+
89
+ See the repository's [SECURITY.md](https://github.com/27painter/dsh-moli/blob/main/SECURITY.md).
90
+ This plugin is independent of OpenCode and Moli/Lexmount.
package/dist/index.js ADDED
@@ -0,0 +1,515 @@
1
+ /**
2
+ * OpenCode adapter for the local Moli headless browser.
3
+ *
4
+ * Two registrations, both through the V2 plugin API:
5
+ * - a websearch provider, so OpenCode's built-in `websearch` tool can search
6
+ * through the local browser instead of a paid search API;
7
+ * - `moli_fetch` / `moli_capture` / `moli_probe`, for pages that need real
8
+ * rendering, a CSS selector, an evaluated expression, or a binary artifact.
9
+ *
10
+ * The build copies the shared browser core into ./lib. It is the same core the
11
+ * DSH and Codex adapters use and imports only Node built-ins, so this file
12
+ * contains no host-specific process plumbing: no DSH sandbox workarounds, no
13
+ * MCP transport.
14
+ */
15
+ import { Plugin } from '@opencode/plugin'
16
+ import { MANUAL_INSTALL, installMoli } from './lib/install.js'
17
+ import { findMoli, moliCandidates, probe, runFetch } from './lib/moli.js'
18
+
19
+ const SERVER_VERSION = '2.1.1'
20
+ const DEFAULT_SEARCH_URLS = [
21
+ 'https://www.bing.com/search?q={query}',
22
+ 'https://html.duckduckgo.com/html/?q={query}',
23
+ 'https://search.brave.com/search?q={query}',
24
+ ]
25
+
26
+ const DEFAULTS = {
27
+ defaultTimeoutMs: 30000,
28
+ searchAttemptTimeoutMs: 20000,
29
+ maxChars: 200000,
30
+ installTimeoutMs: 180000,
31
+ searchLimit: 10,
32
+ // Same default as the DSH plugin: behind a filtering proxy Schannel cannot
33
+ // reach the revocation responder, so certificate checks fail on ordinary
34
+ // sites. Set insecureTls: false to enforce them on a healthy network.
35
+ insecureTls: true,
36
+ }
37
+
38
+ function positiveInteger(value, fallback) {
39
+ return Number.isInteger(value) && value > 0 ? value : fallback
40
+ }
41
+
42
+ function envBoolean(value, fallback = false) {
43
+ if (typeof value !== 'string' || value.trim() === '') return fallback
44
+ return /^(1|true|yes|on)$/iu.test(value.trim())
45
+ }
46
+
47
+ function envString(name) {
48
+ const value = process.env[name]
49
+ return typeof value === 'string' ? value.trim() : ''
50
+ }
51
+
52
+ function searchUrlList(options) {
53
+ const configured = Array.isArray(options.searchUrls)
54
+ ? options.searchUrls.filter(url => typeof url === 'string' && url.trim() !== '').map(url => url.trim())
55
+ : []
56
+ if (configured.length > 0) return configured
57
+ const env = envString('MOLI_SEARCH_URLS') || envString('MOLI_SEARCH_URL')
58
+ if (env === '') return DEFAULT_SEARCH_URLS
59
+ const urls = env.split('|').map(url => url.trim()).filter(url => url !== '')
60
+ return urls.length > 0 ? urls : DEFAULT_SEARCH_URLS
61
+ }
62
+
63
+ function readConfig(options) {
64
+ const raw = options !== null && typeof options === 'object' ? options : {}
65
+ const proxy = typeof raw.proxy === 'string' && raw.proxy.trim() !== ''
66
+ ? raw.proxy.trim()
67
+ : (envString('MOLI_PROXY')
68
+ || envString('HTTPS_PROXY')
69
+ || envString('HTTP_PROXY')
70
+ || envString('ALL_PROXY'))
71
+ return {
72
+ exePath: typeof raw.exePath === 'string' && raw.exePath.trim() !== ''
73
+ ? raw.exePath.trim()
74
+ : envString('MOLI_BIN'),
75
+ proxy,
76
+ searchUrls: searchUrlList(raw),
77
+ defaultTimeoutMs: positiveInteger(raw.defaultTimeoutMs, positiveInteger(Number(envString('MOLI_TIMEOUT_MS')), DEFAULTS.defaultTimeoutMs)),
78
+ searchAttemptTimeoutMs: positiveInteger(raw.searchAttemptTimeoutMs, positiveInteger(Number(envString('MOLI_SEARCH_ATTEMPT_TIMEOUT_MS')), DEFAULTS.searchAttemptTimeoutMs)),
79
+ maxChars: positiveInteger(raw.maxChars, positiveInteger(Number(envString('MOLI_MAX_CHARS')), DEFAULTS.maxChars)),
80
+ installTimeoutMs: positiveInteger(raw.installTimeoutMs, positiveInteger(Number(envString('MOLI_INSTALL_TIMEOUT_MS')), DEFAULTS.installTimeoutMs)),
81
+ searchLimit: positiveInteger(raw.searchLimit, DEFAULTS.searchLimit),
82
+ insecureTls: typeof raw.insecureTls === 'boolean' ? raw.insecureTls : envBoolean(envString('MOLI_INSECURE_TLS'), DEFAULTS.insecureTls),
83
+ }
84
+ }
85
+
86
+ /**
87
+ * The input schemas are the same raw JSON Schema documents the DSH and Codex
88
+ * adapters publish. OpenCode accepts a JSON Schema directly as a tool input.
89
+ */
90
+ const FETCH_INPUT_SCHEMA = {
91
+ type: 'object',
92
+ additionalProperties: false,
93
+ required: ['url'],
94
+ properties: {
95
+ url: { type: 'string', description: 'Absolute http:// or https:// URL to render.' },
96
+ dump: {
97
+ type: 'string',
98
+ enum: ['html', 'markdown', 'json', 'semantic_tree', 'semantic_tree_text', 'screenshot', 'screenshot_full', 'pdf'],
99
+ description: 'Output format. Omit for rendered HTML. `markdown` is the cheapest way to read a page. `json` carries status and final_url; screenshot/pdf need writeTo.',
100
+ },
101
+ writeTo: {
102
+ type: 'string',
103
+ description: 'Absolute path to save the output. Required for screenshot/pdf; optional for text dumps larger than maxChars.',
104
+ },
105
+ selector: {
106
+ type: 'string',
107
+ description: 'Return the text of the elements this CSS selector matches instead of the whole page. The cheap way to read one container out of a noisy listing page. Cannot be combined with dump or eval.',
108
+ },
109
+ eval: {
110
+ type: 'string',
111
+ description: 'JavaScript expression evaluated once the page is ready; its value is returned instead of the page. With dump, the expression value is discarded by the engine and only the resulting page is returned.',
112
+ },
113
+ scroll: {
114
+ type: 'string',
115
+ description: 'Scroll before capture: pixels as a string ("800", "-500" to go up), or "top" / "bottom". Use it for lazy lists and intersection observers.',
116
+ },
117
+ wait: {
118
+ type: 'string',
119
+ enum: ['domcontentloaded', 'load', 'networkidle', 'domstable', 'done'],
120
+ description: 'Readiness stage to wait for. Defaults to `done`.',
121
+ },
122
+ waitSelector: { type: 'string', description: 'Wait until this CSS selector matches.' },
123
+ waitScript: { type: 'string', description: 'Wait until this JavaScript expression is truthy.' },
124
+ waitResponseUrl: { type: 'string', description: 'Wait for a response whose URL contains this substring.' },
125
+ waitResponseJson: { type: 'string', description: 'Wait for a JSON response field matching PATH=VALUE.' },
126
+ failOnHttpError: { type: 'boolean', description: 'Treat a final HTTP status of 400 or above as a failure while preserving the response body.' },
127
+ delayMs: { type: 'integer', minimum: 0, description: 'Extra milliseconds to wait after readiness.' },
128
+ timeoutMs: { type: 'integer', minimum: 1, description: 'Readiness deadline in milliseconds.' },
129
+ maxChars: { type: 'integer', minimum: 1, description: 'Inline text truncation budget.' },
130
+ headers: { type: 'array', items: { type: 'string' }, description: 'Extra request headers as "Name: value".' },
131
+ userAgent: { type: 'string', description: 'Override the User-Agent.' },
132
+ layout: { type: 'boolean', description: 'Force the layout renderer on. Implied by screenshot and pdf.' },
133
+ scrollbars: { type: 'boolean', description: 'Show native scrollbars in rendered output.' },
134
+ noJs: { type: 'boolean', description: 'Disable page-authored JavaScript.' },
135
+ noCss: { type: 'boolean', description: 'Disable page-authored CSS.' },
136
+ resources: { type: 'boolean', description: 'Also fetch images, fonts, audio, video, and text tracks.' },
137
+ withFrames: { type: 'boolean', description: 'Include subframes in the output.' },
138
+ insecureTls: { type: 'boolean', description: 'Skip TLS host verification for this call.' },
139
+ proxy: { type: 'string', description: 'Forward proxy for this call. Loopback URLs always bypass it.' },
140
+ profileDir: { type: 'string', description: 'Moli profile directory carrying imported cookies or storage.' },
141
+ cookieFile: { type: 'string', description: 'Netscape/curl cookie-jar file to send.' },
142
+ },
143
+ }
144
+
145
+ const CAPTURE_INPUT_SCHEMA = {
146
+ type: 'object',
147
+ additionalProperties: false,
148
+ required: ['url', 'dump', 'writeTo'],
149
+ properties: {
150
+ url: { type: 'string', description: 'Absolute page URL.' },
151
+ dump: { type: 'string', enum: ['screenshot', 'screenshot_full', 'pdf'], description: 'Binary artifact format.' },
152
+ writeTo: { type: 'string', description: 'Absolute output path ending in .png or .pdf.' },
153
+ wait: { type: 'string', enum: ['domcontentloaded', 'load', 'networkidle', 'domstable', 'done'] },
154
+ waitSelector: { type: 'string' },
155
+ scroll: { type: 'string' },
156
+ delayMs: { type: 'integer', minimum: 0 },
157
+ timeoutMs: { type: 'integer', minimum: 1 },
158
+ headers: { type: 'array', items: { type: 'string' } },
159
+ userAgent: { type: 'string' },
160
+ scrollbars: { type: 'boolean' },
161
+ resources: { type: 'boolean' },
162
+ withFrames: { type: 'boolean' },
163
+ insecureTls: { type: 'boolean' },
164
+ proxy: { type: 'string' },
165
+ profileDir: { type: 'string' },
166
+ cookieFile: { type: 'string' },
167
+ },
168
+ }
169
+
170
+ const PROBE_INPUT_SCHEMA = {
171
+ type: 'object',
172
+ additionalProperties: false,
173
+ properties: {
174
+ action: { type: 'string', enum: ['probe', 'install'], description: '`probe` (default) only inspects; `install` downloads and runs the official release installer.' },
175
+ expectedSha256: { type: 'string', description: 'With action "install": abort unless the downloaded installer matches this SHA256.' },
176
+ },
177
+ }
178
+
179
+ /** Read a value from a URL's search result page. Kept in sync with the Codex adapter. */
180
+ function searchScript(limit) {
181
+ return `(() => {
182
+ const decodeResultUrl = href => {
183
+ try {
184
+ const parsed = new URL(href, location.href);
185
+ const bingTarget = parsed.searchParams.get('u');
186
+ if (bingTarget !== null) {
187
+ const base64 = (bingTarget.startsWith('a1') ? bingTarget.slice(2) : bingTarget)
188
+ .replace(/-/g, '+').replace(/_/g, '/');
189
+ const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
190
+ const decoded = atob(padded);
191
+ if (/^https?:\\/\\//i.test(decoded)) return decoded;
192
+ }
193
+ return parsed.href;
194
+ } catch {
195
+ return href;
196
+ }
197
+ };
198
+ const text = node => {
199
+ const inner = (node?.innerText ?? '').trim();
200
+ return inner !== '' ? inner : (node?.textContent ?? '').trim();
201
+ };
202
+ const clean = value => value
203
+ .replace(/https?:\\/\\/\\S+/giu, '')
204
+ .replace(/\\s+/gu, ' ')
205
+ .replace(/\\s*Read more\\s*$/iu, '')
206
+ .trim();
207
+ const noResults = /There are no results|did not match any documents|No results found|No results for/iu.test(document.body.innerText);
208
+ if (noResults) return JSON.stringify([]);
209
+ const selectors = ['li.b_algo', 'div.snippet[data-type="web"]', 'div.snippet', 'div.result', 'div.web-result', '[data-testid="result"]'];
210
+ // Brave wraps results in <article>. Bing also uses <article> for unrelated
211
+ // top-story cards when a query has no results, so scope that selector to the
212
+ // engine that means it instead of returning news as search hits.
213
+ if (/search\\.brave\\.com$/iu.test(location.hostname)) selectors.push('article');
214
+ const containers = [];
215
+ const seenNodes = new Set();
216
+ for (const selector of selectors) {
217
+ for (const node of document.querySelectorAll(selector)) {
218
+ if (!seenNodes.has(node)) {
219
+ seenNodes.add(node);
220
+ containers.push(node);
221
+ }
222
+ }
223
+ }
224
+ const candidates = containers.length > 0
225
+ ? containers
226
+ : [...document.querySelectorAll('a[href]')].filter(anchor => {
227
+ try {
228
+ const url = new URL(anchor.getAttribute('href') ?? '', location.href);
229
+ return /^https?:$/i.test(url.protocol) && url.hostname !== location.hostname;
230
+ } catch {
231
+ return false;
232
+ }
233
+ });
234
+ const seenUrls = new Set();
235
+ const results = candidates.map(node => {
236
+ const anchor = node.matches?.('a[href]') ? node : node.querySelector('h2 a, a.result__a, a[href]');
237
+ const url = decodeResultUrl(anchor?.getAttribute('href') ?? '');
238
+ return {
239
+ title: clean(text(node.querySelector?.('h2') ?? anchor)),
240
+ url,
241
+ snippet: clean(text(node.querySelector?.('.result__snippet, .b_caption p, .b_lineclamp2, .b_lineclamp3, p') ?? node)),
242
+ };
243
+ }).filter(item => {
244
+ if (item.title === '' || !/^https?:\\/\\//i.test(item.url) || seenUrls.has(item.url)) return false;
245
+ seenUrls.add(item.url);
246
+ return true;
247
+ }).slice(0, ${String(limit)});
248
+ return JSON.stringify(results);
249
+ })()`
250
+ }
251
+
252
+ function searchUrl(query, template) {
253
+ const encoded = encodeURIComponent(query)
254
+ if (template.includes('{query}')) return template.replaceAll('{query}', encoded)
255
+ return `${template}${template.includes('?') ? '&' : '?'}q=${encoded}`
256
+ }
257
+
258
+ function providerLabel(url) {
259
+ try {
260
+ return new URL(url).hostname || url
261
+ } catch {
262
+ return url
263
+ }
264
+ }
265
+
266
+ function missingEngine() {
267
+ return {
268
+ ok: false,
269
+ error: 'moli was not found',
270
+ hint: 'Call moli_probe with action "install", set MOLI_BIN, or install Moli from the official release.',
271
+ manualInstall: MANUAL_INSTALL,
272
+ }
273
+ }
274
+
275
+ function renderFetchValue(value) {
276
+ if (value.ok !== true) {
277
+ const status = typeof value.status === 'number' ? ` (HTTP ${String(value.status)})` : ''
278
+ const lines = [`Moli fetch failed for ${String(value.url)}${status}: ${String(value.error ?? 'unknown error')}`]
279
+ if (value.sandboxTlsBlock === true) lines.push('Cause: TLS client credentials were unavailable in this process (HTTPS only).')
280
+ if (value.unreachable === true) lines.push('Cause: the host did not answer; a local forward proxy is the usual fix on this network.')
281
+ else if (value.possiblyUnreachable === true) lines.push('Cause: the host did not answer in time; it may be blocked, or the page may simply be slow.')
282
+ else if (value.conditionTimedOut === true) lines.push('Cause: the page loaded, but the wait condition never became true — this is not a network problem.')
283
+ if (typeof value.hint === 'string' && value.hint !== '') lines.push(`Next: ${value.hint}`)
284
+ if (value.httpError === true && value.kind === 'binary' && typeof value.path === 'string') {
285
+ lines.push(`The error page was still written to ${value.path} (${String(value.bytes)} bytes).`)
286
+ } else if (value.httpError === true && typeof value.content === 'string' && value.content !== '') {
287
+ lines.push('', 'The server\'s response body:', '', value.content)
288
+ } else if (typeof value.selector === 'string') {
289
+ lines.push(`Selector: ${JSON.stringify(value.selector)}`
290
+ + (typeof value.matched === 'number' ? ` (matched ${String(value.matched)})` : ''))
291
+ }
292
+ return lines.join('\n')
293
+ }
294
+ if (value.kind === 'binary') {
295
+ return `${String(value.dump)} written to ${String(value.path)} (${String(value.bytes)} bytes). Read that file to inspect it.`
296
+ }
297
+ const parts = []
298
+ if (value.evalDiscarded === true) {
299
+ parts.push('Note: the `eval` expression was dropped because `dump` was given too — the engine discards the expression value in that combination. What follows is the page, not the expression.')
300
+ }
301
+ if (typeof value.selector === 'string' && typeof value.matched === 'number') {
302
+ parts.push(`Selector ${JSON.stringify(value.selector)} matched ${String(value.matched)} element(s).`)
303
+ }
304
+ if (typeof value.note === 'string' && value.note !== '') parts.push(value.note)
305
+ parts.push(String(value.content ?? ''))
306
+ return parts.join('\n\n')
307
+ }
308
+
309
+ function renderProbeValue(value) {
310
+ if (value.ok === true && typeof value.exe === 'string') {
311
+ return `Installed ${String(value.version)} at ${String(value.exe)} (installer SHA256 ${String(value.installerSha256)}, ${String(value.installerBytes)} bytes). Run moli_probe again to verify HTTPS.`
312
+ }
313
+ if (value.ok === false) {
314
+ const lines = [`Moli installation failed: ${String(value.error)}`]
315
+ if (typeof value.installerSha256 === 'string') lines.push(`Installer SHA256: ${value.installerSha256}`)
316
+ if (typeof value.note === 'string' && value.note !== '') lines.push(value.note)
317
+ lines.push(`Manual install — PowerShell: ${MANUAL_INSTALL.powershell}`)
318
+ lines.push(`Manual install — Linux/macOS: ${MANUAL_INSTALL.shell}`)
319
+ return lines.join('\n')
320
+ }
321
+ if (value.installed !== true) {
322
+ return [
323
+ 'moli was not found. Call moli_probe with action "install", or set the plugin option `exePath`.',
324
+ `Manual install — PowerShell: ${MANUAL_INSTALL.powershell}`,
325
+ `Manual install — Linux/macOS: ${MANUAL_INSTALL.shell}`,
326
+ ].join('\n')
327
+ }
328
+ const lines = [
329
+ `${String(value.version).startsWith('moli') ? String(value.version) : `moli ${String(value.version)}`} at ${String(value.exe)}`,
330
+ value.httpsOk === true ? 'HTTPS fetch works from this process.' : `HTTPS fetch failed: ${String(value.detail)}`,
331
+ ]
332
+ if (value.revocationBlock === true) {
333
+ lines.push('The certificate-revocation responder is unreachable through this network; insecureTls already relaxes that check.')
334
+ }
335
+ return lines.join('\n')
336
+ }
337
+
338
+ export default Plugin.define({
339
+ id: 'moli',
340
+ async setup(ctx) {
341
+ const config = readConfig(ctx.options)
342
+ // Resolved once at setup and refreshed after an explicit install, so a
343
+ // plugin load never blocks and no call re-runs discovery.
344
+ let cachedExe = findMoli(config.exePath)
345
+ const engine = () => cachedExe
346
+
347
+ const policy = (args) => ({
348
+ timeoutMs: positiveInteger(args.timeoutMs, config.defaultTimeoutMs),
349
+ maxChars: positiveInteger(args.maxChars, config.maxChars),
350
+ proxy: typeof args.proxy === 'string' && args.proxy !== '' ? args.proxy : config.proxy,
351
+ insecureTls: typeof args.insecureTls === 'boolean' ? args.insecureTls : config.insecureTls,
352
+ })
353
+
354
+ const executeFetch = (args) => {
355
+ const exe = engine()
356
+ if (exe === undefined) return missingEngine()
357
+ const settings = policy(args)
358
+ return runFetch({
359
+ exe,
360
+ args: { ...args, timeoutMs: settings.timeoutMs },
361
+ maxChars: settings.maxChars,
362
+ proxy: settings.proxy,
363
+ insecureTls: settings.insecureTls,
364
+ })
365
+ }
366
+
367
+ const executeSearch = (query, args = {}, signal) => {
368
+ const trimmed = typeof query === 'string' ? query.trim() : ''
369
+ if (trimmed === '') return { ok: false, error: 'query must not be empty', results: [] }
370
+ const exe = engine()
371
+ if (exe === undefined) return missingEngine()
372
+ const limit = Math.max(1, Math.min(20, positiveInteger(args.limit, config.searchLimit)))
373
+ const settings = policy(args)
374
+ const attempts = []
375
+ const attemptTimeoutMs = Math.min(settings.timeoutMs, config.searchAttemptTimeoutMs)
376
+ for (const template of config.searchUrls) {
377
+ if (signal?.aborted === true) return { ok: false, error: 'search aborted', results: [] }
378
+ const target = searchUrl(trimmed, template)
379
+ const provider = providerLabel(template)
380
+ const started = Date.now()
381
+ const result = runFetch({
382
+ exe,
383
+ args: {
384
+ url: target,
385
+ eval: searchScript(limit),
386
+ wait: 'domcontentloaded',
387
+ delayMs: 600,
388
+ timeoutMs: attemptTimeoutMs,
389
+ },
390
+ maxChars: 100000,
391
+ proxy: settings.proxy,
392
+ insecureTls: settings.insecureTls,
393
+ })
394
+ const elapsedMs = Date.now() - started
395
+ if (result.ok !== true) {
396
+ attempts.push({ provider, searchUrl: target, ok: false, count: 0, elapsedMs, error: String(result.error ?? 'unknown error') })
397
+ continue
398
+ }
399
+ let results
400
+ try {
401
+ results = JSON.parse(result.content)
402
+ } catch {
403
+ attempts.push({ provider, searchUrl: target, ok: false, count: 0, elapsedMs, error: 'the rendered search page did not produce parseable result JSON' })
404
+ continue
405
+ }
406
+ if (!Array.isArray(results)) {
407
+ attempts.push({ provider, searchUrl: target, ok: false, count: 0, elapsedMs, error: 'the search result payload was not an array' })
408
+ continue
409
+ }
410
+ attempts.push({ provider, searchUrl: target, ok: true, count: results.length, elapsedMs })
411
+ if (results.length === 0) continue
412
+ return { ok: true, query: trimmed, provider, searchUrl: target, count: results.length, results, attempts }
413
+ }
414
+ return {
415
+ ok: false,
416
+ query: trimmed,
417
+ error: `all configured search providers failed or returned no results (${String(attempts.length)} tried)`,
418
+ hint: config.proxy === ''
419
+ ? 'The host may block direct browser egress. Set the plugin option `proxy`, or set MOLI_SEARCH_URLS to reachable providers separated by |.'
420
+ : 'Check that the configured proxy is reachable and that at least one provider page exposes ordinary result links. Try moli_fetch on an attempt searchUrl for diagnostics.',
421
+ results: [],
422
+ attempts,
423
+ }
424
+ }
425
+
426
+ await ctx.websearch.transform((editor) => {
427
+ // Respect an explicit provider choice, including `false` (disabled). Only
428
+ // supply the default when the user has not selected one.
429
+ const selected = editor.default.get()
430
+ editor.add({
431
+ id: 'moli',
432
+ name: 'Moli (local browser)',
433
+ async execute(input, context) {
434
+ if (context.signal.aborted) return []
435
+ const value = executeSearch(input.query, {}, context.signal)
436
+ if (value.ok !== true) {
437
+ console.error(`[opencode-moli] websearch failed: ${String(value.error)}`)
438
+ return []
439
+ }
440
+ return value.results.map(result => ({
441
+ url: String(result.url),
442
+ title: String(result.title ?? ''),
443
+ content: String(result.snippet ?? ''),
444
+ time: {},
445
+ }))
446
+ },
447
+ })
448
+ // A plugin-provided default is what makes the built-in websearch tool use
449
+ // the local browser without a first-use provider prompt.
450
+ if (selected === undefined) editor.default.set('moli')
451
+ })
452
+
453
+ await ctx.tool.transform((editor) => {
454
+ editor.namespace({
455
+ name: 'moli',
456
+ description: 'Moli local headless browser: rendered pages, CSS selectors, evaluated values, screenshots, and PDFs.',
457
+ })
458
+ editor.add({
459
+ name: 'fetch',
460
+ description: 'Fetch a URL with the local Moli headless browser and return rendered Markdown, HTML, a semantic tree, a JSON envelope, a CSS-selector match, or a JavaScript expression result. Use it for pages that need real rendering; prefer the built-in webfetch for plain text. Screenshot and PDF dumps need writeTo.',
461
+ input: FETCH_INPUT_SCHEMA,
462
+ options: { namespace: 'moli', codemode: true },
463
+ async execute(input) {
464
+ return { content: renderFetchValue(executeFetch(input)) }
465
+ },
466
+ })
467
+ editor.add({
468
+ name: 'capture',
469
+ description: 'Render a page with Moli and write a screenshot or PDF to an explicit absolute path.',
470
+ input: CAPTURE_INPUT_SCHEMA,
471
+ options: { namespace: 'moli', codemode: true },
472
+ async execute(input) {
473
+ return { content: renderFetchValue(executeFetch(input)) }
474
+ },
475
+ })
476
+ editor.add({
477
+ name: 'probe',
478
+ description: 'Report the local Moli executable, version, and whether HTTPS fetching works, or install the official Moli release with action "install".',
479
+ input: PROBE_INPUT_SCHEMA,
480
+ options: { namespace: 'moli', codemode: true },
481
+ async execute(input) {
482
+ if (input.action === 'install') {
483
+ const outcome = await installMoli({
484
+ exePath: config.exePath,
485
+ expectedSha256: input.expectedSha256,
486
+ timeoutMs: config.installTimeoutMs,
487
+ proxy: config.proxy,
488
+ locate: findMoli,
489
+ candidates: moliCandidates(config.exePath),
490
+ })
491
+ if (outcome.ok === true) cachedExe = outcome.exe
492
+ return { content: renderProbeValue({ ...outcome, installed: outcome.ok === true }) }
493
+ }
494
+ const exe = engine()
495
+ if (exe === undefined) {
496
+ return { content: renderProbeValue({ installed: false, detail: 'moli not found. Re-run with action "install" to download it.' }) }
497
+ }
498
+ const result = probe(exe, 'https://example.com', config.insecureTls)
499
+ return {
500
+ content: renderProbeValue({
501
+ installed: true,
502
+ exe: result.exe,
503
+ version: result.version,
504
+ httpsOk: result.httpsOk,
505
+ detail: result.detail,
506
+ revocationBlock: result.revocationBlock,
507
+ }),
508
+ }
509
+ },
510
+ })
511
+ })
512
+
513
+ console.error(`[opencode-moli] ${SERVER_VERSION}: registered websearch provider "moli" and moli_fetch / moli_capture / moli_probe (${cachedExe ?? 'moli missing'})`)
514
+ },
515
+ })