@jayyuen66/dsh-scrapling 0.0.0-stage → 0.0.1-rc

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 JayYuen
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,317 @@
1
- # Temporary Holding Version
1
+ # @jayyuen66/dsh-scrapling
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
+ English · [中文](./README.zh-CN.md)
4
+
5
+ [Scrapling](https://github.com/D4Vinci/Scrapling) web scraping for
6
+ [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (dsh),
7
+ exposed as agent tools backed by a long-lived Python process.
8
+
9
+ ## Why this plugin exists
10
+
11
+ dsh ships `web_fetch` and `web_search`. `web_fetch` is deliberately honest and minimal:
12
+ a plain HTTP(S) GET with no JavaScript execution, an honest `User-Agent`
13
+ (`deepseek-harness/0.2.0-rc.2`, explicitly *"never a browser disguise"*), and a
14
+ turndown-based HTML-to-markdown conversion. That is a good default, but it means a
15
+ single-page application yields only its loading shell, and there is no way to ask for
16
+ "just the product table".
17
+
18
+ Measured on a page whose content exists only after JavaScript runs:
19
+
20
+ | Pipeline | Text obtained |
21
+ |---|---|
22
+ | raw HTML to text (no JS) | `SPA Shell / LOADING_PLACEHOLDER` |
23
+ | `Fetcher` (curl_cffi, still no JS) | `SPA Shell / LOADING_PLACEHOLDER` |
24
+ | `DynamicFetcher` (Playwright) | full rendered DOM, Markdown table, structured rows |
25
+
26
+ This plugin adds exactly three things dsh's built-in tools cannot do:
27
+
28
+ 1. **Browser rendering** - JavaScript execution via Playwright / patchright.
29
+ 2. **Structured extraction** - CSS/XPath selection returning data, not a wall of Markdown.
30
+ 3. **Self-healing selectors** - Scrapling's `adaptive` mode relocates an element after
31
+ the site's markup changes. Verified working: a selector that returns `None` after a
32
+ class rename returns the relocated element when `adaptive=True`.
33
+
34
+ ## Status
35
+
36
+ All eleven tools (the session family counts as four) are implemented, registered and
37
+ exercised by the test suite. Tools
38
+ are registered **conditionally**: the plugin probes what the environment can actually
39
+ do at startup and only registers tools that will work, so the model never burns a
40
+ turn on a tool that was guaranteed to fail.
41
+
42
+ | Tool | Backend | Needs a browser | Concurrency |
43
+ |---|---|---|---|
44
+ | `scrapling_fetch` | `Fetcher` (curl_cffi) | no | safe |
45
+ | `scrapling_extract` | `Selector` + CSS/XPath + `adaptive` | no | safe |
46
+ | `scrapling_render` | `DynamicFetcher` (Playwright) | yes | serialised |
47
+ | `scrapling_capture_xhr` | `capture_xhr` | yes | serialised |
48
+ | `scrapling_stealth_fetch` | `StealthyFetcher` (patchright) | yes | serialised |
49
+ | `scrapling_session_open` / `scrapling_session_fetch` / `scrapling_session_list` / `scrapling_session_close` | Scrapling session classes | depends | serialised |
50
+ | `scrapling_crawl` | Scrapling Spider framework | no | serialised, runs as a job |
51
+ | `scrapling_answer` | any of the above, plus `ctx.llm` | no (yes with `render:true`) | serialised |
52
+
53
+ `scrapling_answer` is the only tool that spends **another model call**: it fetches the page
54
+ first, then hands the text plus your question to a model and returns the conclusion instead
55
+ of the whole page. By default it follows **the model the current session is already using**
56
+ (read from the session's live request header, so a mid-session model switch is picked up),
57
+ which means the plugin does not burn a separate quota; you can pin `answerProvider` /
58
+ `answerModel` on the settings card to route page-reading to a different model.
59
+
60
+ Page text is **untrusted input** — a page can say "ignore your previous instructions". The
61
+ answer prompt frames the text explicitly as data and forbids acting on it, but that defence
62
+ is prompt-level: it lowers the risk, it does not remove it.
63
+
64
+ Everything runs against **one long-lived Python process**. That is not an
65
+ optimisation — Scrapling's session classes keep cookies, the browser engines keep a
66
+ page pool, and `adaptive` keeps a SQLite fingerprint database. A process per call
67
+ would throw all of that away.
68
+
69
+ `scrapling_crawl` returns a **job id immediately** rather than blocking: a crawl takes
70
+ minutes, a tool call has a timeout. Watch it with `job_list`, read it with
71
+ `job_output`, stop it with `job_kill`.
72
+
73
+ ## Requirements
74
+
75
+ - **Python 3.10+** with Scrapling installed, reachable via `PATH` (or set `pythonBin`).
76
+ - **Browser engines are entirely the user's responsibility.** The plugin does not
77
+ download anything. Without a browser it simply does not register the
78
+ browser-dependent tools, so the model never wastes a turn calling them.
79
+
80
+ ```sh
81
+ pip install "scrapling[rag]>=0.4.15,<0.5"
82
+ python -m playwright install chromium
83
+ ```
84
+
85
+ > **Why `rag` and not `fetchers`?** `rag` is `fetchers` plus `markdownify`, and the
86
+ > default `extractionType` is `markdown` — with plain `fetchers` the Markdown conversion
87
+ > raises `ModuleNotFoundError` on the first fetch. The Python side then tells you exactly
88
+ > which package is missing.
89
+
90
+ > **Version range**: this plugin is developed and verified against Scrapling **0.4.15**
91
+ > and depends on its `Convertor._strip_noise_tags` / `_sanitize_for_ai`, `Selector`,
92
+ > `Spider` and `SessionManager` interfaces. None of those are stable API surface, so the
93
+ > upper bound is pinned below `0.5`; outside the range the guards still run, but the
94
+ > anti-injection cleaning and the crawl path may not behave as documented.
95
+
96
+ ## Install
97
+
98
+ ```sh
99
+ dsh plugin --profile web add @jayyuen66/dsh-scrapling
100
+ ```
101
+
102
+ The plugin is also installable from the Web UI via **Sidebar -> Plugins -> Add plugin**.
103
+
104
+ ## Replacing the built-in `web_fetch` and `web_search`
105
+
106
+ The plugin registers itself as a **fetch provider** and a **search provider** on
107
+ `ctx.web`, so the built-in `web_fetch` / `web_search` tools actually run on Scrapling
108
+ instead of dsh's plain-HTTP implementation. The model still calls `web_fetch` /
109
+ `web_search` — that is what "replacing the built-in one" means here.
110
+
111
+ > **Tool names cannot be swapped; only the backend can.** `ToolRuntime.register` ends at
112
+ > `NamedEntries.insert`, which **throws** on a duplicate name
113
+ > (`tool "X" is already registered`). Registering a same-named tool is therefore closed off;
114
+ > the `ctx.web` provider seam is the supported replacement channel.
115
+
116
+ Both must be done together, or the built-in tools break:
117
+
118
+ 1. set `provideWebFetch` / `provideWebSearch` to `true` in the plugin config;
119
+ 2. set `fetchProvider` / `searchProvider` to `"scrapling"` in the **deployment** config.
120
+
121
+ > **Why both?** `ctx.web` auto-selects only when exactly one usable provider is registered.
122
+ > A second one without naming it yields `WEB_PROVIDER_AMBIGUOUS` and the tool becomes
123
+ > unavailable outright. Hence both switches default to `false`.
124
+
125
+ When `searchEndpoint` is empty the search provider's `available()` is `false` — a second
126
+ guard: enabling `provideWebSearch` without configuring an endpoint cannot displace the
127
+ built-in `web_search`.
128
+
129
+ ### Search + render in one call
130
+
131
+ Scrapling is **not** a search engine (its `google_search` option only sets a Google referer
132
+ header), so `web_search` is split in two:
133
+
134
+ - **Discovery** → a configurable search backend (deployment-level `searchEndpoint`),
135
+ expected to be SearXNG-compatible JSON: GET `<endpoint>?q=<query>&format=json` returning
136
+ `{"results": [{"url", "title", "content"}]}`. Any backend producing that shape works.
137
+ - **Reading** → this plugin's sidecar. The first `searchRenderTopN` results (3 by default)
138
+ are actually fetched and, when a browser is available, rendered through Playwright. The
139
+ body lands in `content`, the URLs in `sources`.
140
+
141
+ One `web_search` call therefore yields both "which pages are relevant" and "what those
142
+ pages actually say" — the latter being exactly the SPA content `web_fetch` structurally
143
+ cannot read. Returned URLs are re-checked one by one by this plugin's URL gate; the parsing
144
+ layer deliberately does not duplicate that policy. A page that fails to read is skipped
145
+ alone — search results routinely contain dead links.
146
+
147
+ One consequence to know: `dsh-web`'s `WebFetchBody` is a **closed** union with only
148
+ `html | text`, no `markdown`; adding a kind is a cross-package change a plugin cannot make.
149
+ So the fetch provider reports Scrapling's Markdown as `text`, which the built-in renderer
150
+ displays normally. Use `scrapling_fetch` directly when you need `html` or a CSS selector.
151
+
152
+ ## Configuration
153
+
154
+ Settings live under the **scrapling** card. Every field marked user-editable in
155
+ [`host.ts`](./host.ts) is exposed; deployment-level fields are only settable through
156
+ the `config:` block in [`cordis.patch.yml`](./cordis.patch.yml).
157
+
158
+ Notable switches:
159
+
160
+ - `pythonBin` - interpreter name or absolute path; empty means `python3` on `PATH`.
161
+ - `fetchEnabled` / `extractEnabled` / `renderEnabled` / `captureXhrEnabled` /
162
+ `sessionEnabled` / `answerEnabled` - on by default.
163
+ - `stealthEnabled` / `crawlEnabled` - **off** by default (extra browser dependency /
164
+ long-running background job).
165
+ - `extractionType` - `markdown` (default), `html` or `text`. All three paths run the
166
+ same anti-injection cleaning; `html` additionally strips event-handler attributes
167
+ (`on*`, `srcdoc`, `formaction`) and `meta refresh`, so the result is **not**
168
+ byte-for-byte raw HTML.
169
+ - `*MaxOutputChars` - per-tool output caps. `crawlMaxItems` is the deployment-side
170
+ ceiling over the model-supplied `maxPages`; an out-of-range `maxPages` (0, negative,
171
+ NaN) is passed through unchanged so the sidecar reports the parameter error rather
172
+ than this plugin silently clamping it into a legal-looking value.
173
+ - `answerProvider` / `answerModel` / `answerMaxTokens` - the model `scrapling_answer`
174
+ routes to and the per-call token ceiling. Provider and model left empty mean "follow
175
+ the model the current session is already using"; `answerMaxTokens` caps the reply.
176
+ - `mainContentOnly` / `headless` / `networkIdle` / `captureXhrPattern` /
177
+ `waitSelectorState` / `dataDir` - extraction scope, browser mode, the XHR capture
178
+ filter, the selector state a page must reach before it is read, and the sidecar
179
+ working directory. Each is documented at its declaration in [`host.ts`](./host.ts).
180
+ - `sidecarHandshakeTimeoutMs` / `fetchTimeoutMs` / `sidecarGraceMs` - the budget for the
181
+ sidecar handshake, the per-call cooperative timeout (declared as the tools' `timeoutMs`), and
182
+ how long the client waits for the process to exit after that timeout before forcing it down.
183
+ The three are on the settings card. `scrapling_crawl` is the exception: it runs as a job and
184
+ passes no timeout, because a crawl is measured in minutes and a fixed budget would tear the
185
+ process down on every success.
186
+ - `failFastOnMissingPython` - `true` (default) refuses to load when the interpreter is
187
+ unusable, because every tool needs the sidecar and a silent degrade leaves the model
188
+ discovering "all tools are missing" several turns later. `false` degrades to "all
189
+ tools unavailable" with a warning.
190
+ - `blockAds` - on by default. It stacks **on top of** the SSRF guard rather than
191
+ competing with it: the guard is registered last (so Playwright runs it first) and
192
+ yields with `route.fallback()`, leaving Scrapling's own interception handler reachable.
193
+ - `allowedHosts` - extra host names that skip the public-address check. The same setting
194
+ feeds both layers, so an explicitly allowed intranet target is not rejected by the
195
+ host-side policy before the Python side ever sees it. Pointing it at an intranet
196
+ address means giving up SSRF protection for those targets on purpose.
197
+ - `allowSyntheticDns` - accept the synthetic DNS answers a proxy hands back. A fake-IP
198
+ proxy resolves **every** domain into `198.18.0.0/15` (and TUN clients often
199
+ `100.64.0.0/10`); neither is a public unicast range, so the gate would reject every
200
+ URL and turning a proxy on would make the plugin stop working. **Off** by default —
201
+ without a proxy you have no reason to weaken the check, and with one it should be your
202
+ decision, not the model's. The relaxation applies to **resolved addresses only**: an IP
203
+ literal written into the URL is still judged strictly, so `http://169.254.169.254/`
204
+ stays blocked.
205
+
206
+ **Deployment-grade knobs** (not on the settings card; set them in the `config:` block of
207
+ `cordis.patch.yml`): `requestTimeoutSeconds`, `maxUrlLength`, `browserExecutablePath`,
208
+ `browserCdpUrl`, `searchEndpoint`, `searchRenderTopN`. The first two of the browser pair are
209
+ strong capabilities - one hands Chromium a file
210
+ to execute, the other hands the browser to a debugger endpoint - so they come only from
211
+ deployment config and are unreachable from model input.
212
+
213
+ > **Settings changes need a dsh restart.** The gate policy and the sidecar environment are
214
+ > snapshotted once when the plugin is applied; edits on the settings card take effect on the
215
+ > next start.
216
+
217
+ Disabling a tool also removes its system-prompt guidance, so the model is never told
218
+ about a capability that is not registered.
219
+
220
+ ## Security notes
221
+
222
+ - **SSRF.** Scrapling itself has no SSRF protection. This plugin adds a URL policy on
223
+ the host side (scheme allowlist, credential rejection, length cap, rejection of an
224
+ authority containing a backslash or control characters, DNS resolution with a
225
+ whole-answer-set public-address check, and IPv4-mapped / NAT64 addresses reclassified
226
+ by their embedded IPv4) and enforces it again on the Python side. **What is judged is
227
+ what gets sent**: the gate decides on the WHATWG-normalised form and the sidecar forwards
228
+ that same normalised string, otherwise "judged A, connected to B" becomes a bypass in
229
+ its own right. The browser-side guard is registered by the plugin's own code and covers
230
+ navigation, subresources, XHR and WebSocket handshakes.
231
+
232
+ Known gaps, all stated in the open:
233
+ - **Connection pinning** (an undici-level technique) is unavailable for a non-Node
234
+ transport, leaving a TOCTOU window between validation and connect. Static fetches are
235
+ covered by curl_cffi's `follow_redirects="safe"`; browser fetches by a route handler
236
+ on the Python side.
237
+ - **NAT64 prefixes are not discovered dynamically.** dsh's built-in probes the active
238
+ prefix via the `ipv4only.arpa` sentinel; this plugin covers the two standardized
239
+ prefixes (`64:ff9b::/96`, `64:ff9b:1::/48`). Declare any operator-specific prefix via
240
+ the `nat64Prefixes` setting, otherwise a private IPv4 hidden inside IPv6 is judged as
241
+ an ordinary public IPv6. Conversely, a declared prefix applies to **every** IPv6
242
+ address, not only the ones inside the RFC 6052 segment.
243
+ - **No port allowlist** (any port allowed by default), matching dsh's own built-in
244
+ fetch provider.
245
+ - **`scrapling_crawl` re-checks addresses itself, but redirect targets still rest on
246
+ domain consistency alone.** The start URL goes through `guard.url_allowed` (the same
247
+ implementation the browser path uses, so both layers agree), the crawl session sets
248
+ `follow_redirects="safe"` so curl_cffi refuses to follow a jump into a private range, and
249
+ each page's final URL is re-checked before it enters the result set. Scrapling's
250
+ `allow_domains`, though, is a string comparison that covers links found in the page and
251
+ not redirect targets - so on that seam the host gate's start-URL check is still the only
252
+ defence.
253
+ - **WebSocket coverage depends on the Playwright version.** The guard intercepts
254
+ handshakes via `route_web_socket`. Older builds lack that method, WebSocket is then
255
+ outside the guard, and the plugin says so in the log and in the capability report
256
+ rather than degrading silently.
257
+ - **Browser binary path and CDP endpoint are deployment-grade capabilities.** They come
258
+ only from deployment config and are unreachable from model input; pointing at them
259
+ hands over "run this file" and "attach the browser to this debugger".
260
+
261
+ The host-side policy is enforced by `SidecarClient.call`, so it covers every tool and
262
+ the `web_fetch` provider alike; a rejection throws `URL_BLOCKED` before the request is
263
+ written to the pipe.
264
+ - **Browser engines ignore proxy environment variables.** Playwright does not read
265
+ `HTTP_PROXY` / `HTTPS_PROXY`, so `scrapling_render` / `scrapling_capture_xhr` /
266
+ `scrapling_stealth_fetch` connect **directly** even when the rest of the system is
267
+ routed through a proxy — a browser-bound request leaves the tunnel. curl_cffi (behind
268
+ `scrapling_fetch` and the crawler) *does* honour those variables, so the two halves
269
+ behave differently on a proxy-bound network. This is stated rather than papered over:
270
+ routing the browser through a proxy means handing the plugin a deployment-grade
271
+ capability, and shipping that without a way to check it against a live proxy would be
272
+ worse than saying so. `allowSyntheticDns` above only fixes the *gate*; it does not
273
+ change where traffic goes.
274
+ - **There are quotas; the resident resources are not unbounded.** At most 8 concurrent
275
+ sessions (of which at most 3 may be `browser`/`stealth`, each a real Chromium process), at
276
+ most 2 crawls in flight, per-page bodies clipped at `maxContentChars`, 8 MB per protocol
277
+ frame, and 16 frames of pending queue. Hitting a ceiling yields a specific error code
278
+ (`SESSION_LIMIT` / `CRAWL_BUSY` / `BAD_FRAME`) the model can back off from, rather than
279
+ exhausting the machine.
280
+ - **No code execution from the model.** `page_action`, `page_setup`, `selector_config`,
281
+ `proxy`, `executablePath` and `cdpUrl` are never exposed in any tool schema. The
282
+ browser-side network guard is
283
+ installed by plugin code, never by model input.
284
+ - **Prompt-injection scrubbing** runs unconditionally on returned content; there is no
285
+ model-facing switch to turn it off.
286
+
287
+ ## Development
288
+
289
+ ```sh
290
+ pnpm install # install dependencies
291
+ pnpm run check # typecheck + lint + build + test + format check
292
+ pnpm run build # bundles host.ts / src/client-entry.ts into host.js / client.js
293
+ pnpm run test:py # end-to-end check of the Python sidecar (needs _env/.venv)
294
+ ```
295
+
296
+ Sources are all TypeScript. `host.js` and `client.js` are **build artifacts** and are
297
+ deliberately `.js`: Node refuses to strip types for packages inside `node_modules`,
298
+ which is exactly where dsh loads the plugin from.
299
+
300
+ The artifact is **ESM-only**: `require()` will not get you the plugin. That is deliberate
301
+ (the host loads it by package name), not a defect.
302
+
303
+ At build time every package declared in `dependencies`, `peerDependencies` **or**
304
+ `devDependencies` is externalised. The ones the host provides at runtime (cordis,
305
+ dsh-tools, dsh-subprocess, dsh-jobs) must not be inlined: the bundle would otherwise
306
+ carry its own private copy, splitting module-level state, and for packages that resolve
307
+ their own `package.json` relative to `import.meta.url` it would fail to load outright with
308
+ `MODULE_NOT_FOUND`. `test/publish-manifest.test.ts` imports the built artifact and asserts
309
+ that no host package body is inlined, so both halves stay pinned.
310
+
311
+ Publishing runs through [`.github/workflows/publish.yml`](./.github/workflows/publish.yml)
312
+ (manual, OIDC trusted publishing plus `--provenance`).
313
+
314
+ ## License
315
+
316
+ MIT — see [`LICENSE`](./LICENSE). Where this package stops and third-party code begins:
317
+ [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,264 @@
1
+ # @jayyuen66/dsh-scrapling
2
+
3
+ [English](./README.md) · 简体中文
4
+
5
+ 把 [Scrapling](https://github.com/D4Vinci/Scrapling) 的网页抓取能力封装成
6
+ [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)(dsh)的 agent 工具,
7
+ 后端是一个常驻的 Python 进程。
8
+
9
+ ## 为什么需要这个插件
10
+
11
+ dsh 自带 `web_fetch` 与 `web_search`。`web_fetch` 是刻意做「诚实且最小」的:
12
+ 纯 HTTP(S) GET,不执行 JavaScript,UA 也是诚实的
13
+ (`deepseek-harness/0.2.0-rc.2`,源码注释原话 "never a browser disguise"),
14
+ HTML 转 Markdown 用 turndown。作为默认档这没问题,但代价是:
15
+ **单页应用只会拿到加载中的空壳**,而且没法要求「只给我那个商品表格」。
16
+
17
+ 在一个「内容只有 JS 执行后才出现」的页面上实测:
18
+
19
+ | 管线 | 拿到的文本 |
20
+ |---|---|
21
+ | 原始 HTML 转文本(无 JS) | `SPA Shell / LOADING_PLACEHOLDER` |
22
+ | `Fetcher`(curl_cffi,同样无 JS) | `SPA Shell / LOADING_PLACEHOLDER` |
23
+ | `DynamicFetcher`(Playwright) | 完整渲染后的 DOM、Markdown 表格、结构化行 |
24
+
25
+ 本插件补的是 dsh 自带工具**做不到**的三件事:
26
+
27
+ 1. **浏览器渲染** —— 经 Playwright / patchright 执行 JavaScript。
28
+ 2. **结构化抽取** —— CSS/XPath 选择后返回数据,而不是一大坨 Markdown。
29
+ 3. **选择器自愈** —— Scrapling 的 `adaptive` 模式能在站点改版后重新定位元素。
30
+ 已实测:class 改名后原选择器返回 `None`,`adaptive=True` 时能重定位到元素。
31
+
32
+ ## 当前状态
33
+
34
+ 十一个工具(会话类算四个)全部实现、注册,并有测试覆盖。工具是**条件注册**的:插件启动时先探测运行环境
35
+ 真正具备什么,只注册能用的 —— 模型不会浪费一轮去调用一个注定失败的工具。
36
+
37
+ | 工具 | 后端 | 需要浏览器 | 并发 |
38
+ |---|---|---|---|
39
+ | `scrapling_fetch` | `Fetcher`(curl_cffi) | 否 | 可并发 |
40
+ | `scrapling_extract` | `Selector` + CSS/XPath + `adaptive` | 否 | 可并发 |
41
+ | `scrapling_render` | `DynamicFetcher`(Playwright) | 是 | 串行 |
42
+ | `scrapling_capture_xhr` | `capture_xhr` | 是 | 串行 |
43
+ | `scrapling_stealth_fetch` | `StealthyFetcher`(patchright) | 是 | 串行 |
44
+ | `scrapling_session_open` / `scrapling_session_fetch` / `scrapling_session_list` / `scrapling_session_close` | Scrapling 会话类 | 看情况 | 串行 |
45
+ | `scrapling_crawl` | Scrapling Spider 框架 | 否 | 串行,后台作业 |
46
+ | `scrapling_answer` | 上面任一抓取 + `ctx.llm` | 否(`render:true` 时是) | 串行 |
47
+
48
+ `scrapling_answer` 是唯一会**再调一次模型**的工具:先把页面抓下来,再带着问题交给模型
49
+ 作答,直接拿结论而不是整页正文。它默认跟随**当前会话正在用的模型**(读的是会话的活请求
50
+ 头,中途换模型也跟着变),所以插件不额外烧一份额度;也可以在设置卡上单独指定
51
+ `answerProvider` / `answerModel`,把「读网页」和「写代码」分给不同模型。
52
+
53
+ 网页正文是**不可信输入**——页面上可以写「忽略之前的指令」。问答的系统提示把正文显式框成
54
+ 数据并禁止执行其中的指令,但这道防线是提示层面的:它降低风险,不等于消除风险,重要页面
55
+ 仍应人工复核。
56
+
57
+ 一切都在**同一个常驻 Python 进程**里跑。这不是优化选择 —— Scrapling 的会话类要保留
58
+ cookie,浏览器引擎要保留页面池,`adaptive` 要保留 SQLite 指纹库。每次调用起一个进程,
59
+ 这些东西全都会丢。
60
+
61
+ `scrapling_crawl` **立刻返回作业 id** 而不是阻塞:一次爬取是分钟级的,而工具调用有超时。
62
+ 用 `job_list` 看进度、`job_output` 读结果、`job_kill` 中断。
63
+
64
+ ## 环境要求
65
+
66
+ - **Python 3.10+**,装好 Scrapling,能从 `PATH` 找到(或设置 `pythonBin`)。
67
+ - **浏览器完全由用户负责。** 插件不下载任何东西。没有浏览器时它只是不注册那些依赖
68
+ 浏览器的工具,模型不会浪费一轮去调用它们。
69
+
70
+ ```sh
71
+ pip install "scrapling[rag]>=0.4.15,<0.5"
72
+ python -m playwright install chromium
73
+ ```
74
+
75
+ > **为什么是 `rag` 而不是 `fetchers`?** `rag` 就是 `fetchers` 再加上 `markdownify`,而
76
+ > `extractionType` 默认就是 `markdown` —— 装成 `fetchers` 的话,第一次抓取就会在 Markdown
77
+ > 转换处抛 `ModuleNotFoundError`。Python 侧会明确告诉你是哪个包没装。
78
+
79
+ > **版本范围**:本插件在 Scrapling **0.4.15** 上开发与验证,并依赖它的
80
+ > `Convertor._strip_noise_tags` / `_sanitize_for_ai`、`Selector`、`Spider` 与
81
+ > `SessionManager` 这些接口。这些都还不是稳定 API 面,所以上界钉在 `0.5` 之前;装到
82
+ > 范围外时守卫会照常运行,但反注入清洗与爬虫链路可能不按预期。
83
+
84
+ ## 安装
85
+
86
+ ```sh
87
+ dsh plugin --profile web add @jayyuen66/dsh-scrapling
88
+ ```
89
+
90
+ 也可以在 Web 界面里 **Sidebar -> Plugins -> Add plugin** 安装。
91
+
92
+ ## 替代 dsh 内置的 `web_fetch` 与 `web_search`
93
+
94
+ 插件可以把自己注册成 `ctx.web` 的 **fetch provider** 与 **search provider**,于是内置的
95
+ `web_fetch` / `web_search` 工具实际由 Scrapling 执行,而不是 dsh 那套纯 HTTP 实现。这才是
96
+ 「替代自带的」那条路 —— 模型调用的仍然是 `web_fetch` / `web_search`。
97
+
98
+ > **工具名换不掉,只能换后端。** `ToolRuntime.register` 最终落到 `NamedEntries.insert`,
99
+ > 重名会**抛错**(`tool "X" is already registered`)。所以同名注册工具这条路是封死的,
100
+ > `ctx.web` 的 provider 接缝是官方留的替换通道。
101
+
102
+ 两件事必须**同时**做,否则反而会把内置工具弄坏:
103
+
104
+ 1. 在插件配置里把 `provideWebFetch` / `provideWebSearch` 设为 `true`。
105
+ 2. 在**部署配置**里把 `fetchProvider` / `searchProvider` 设为 `"scrapling"`。
106
+
107
+ > **为什么必须两件都做?** `ctx.web` 只在「恰好一个」可用 provider 时自动选。注册了第二个
108
+ > 却没点名,会得到 `WEB_PROVIDER_AMBIGUOUS`,对应工具直接不可用。这也是两个开关默认
109
+ > **false** 的原因。
110
+
111
+ `searchEndpoint` 留空时 search provider 的 `available()` 为 false —— 这也是一道闸:光开
112
+ `provideWebSearch` 而忘了配端点,不会把内置 `web_search` 顶掉。
113
+
114
+ ### 搜索 + 渲染一体化
115
+
116
+ Scrapling 自己**不是搜索引擎**(源码里 `google_search` 只是一个「加 Google referer 头」的
117
+ 选项),所以 `web_search` 这一段拆成两截:
118
+
119
+ - **检索** → 一个可配置的搜索后端(部署级 `searchEndpoint`),期望 SearXNG 兼容的 JSON
120
+ 接口:GET `<endpoint>?q=<query>&format=json`,回包形如
121
+ `{"results": [{"url", "title", "content"}]}`。别的后端只要能出这个形状也行。
122
+ - **读取** → 由本插件的 sidecar 完成,前 `searchRenderTopN`(默认 3)条会**真的抓下来并
123
+ 渲染**(浏览器可用时走 Playwright),正文放进 `content`,URL 放进 `sources`。
124
+
125
+ 这样一次 `web_search` 就同时拿到「哪些页面相关」与「这些页面实际说了什么」,后者正是内置
126
+ `web_fetch` 结构上读不到的 SPA 内容。返回的 URL 会逐条过本插件的 URL 闸门;解析层不重复
127
+ 一份安全策略。单条页面读不到只跳过那一条 —— 搜索结果里混着失效链接是常态。
128
+
129
+ 有一个后果需要知道:`dsh-web` 的 `WebFetchBody` 是**封闭**联合,只有 `html | text`,
130
+ 没有 `markdown`;新增一种 kind 是跨包的协同改动,不是插件能扩展的。所以 fetch provider 把
131
+ Scrapling 的 Markdown 输出报成 `text`,内置渲染路径显示完全正常。
132
+ 需要 `html` 或 CSS 选择器时请直接用 `scrapling_fetch`。
133
+
134
+ ## 配置
135
+
136
+ 设置项在 **scrapling** 卡片下。[`host.ts`](./host.ts) 里标了可编辑的字段都会出现在
137
+ 设置卡上;部署级字段只能通过 [`cordis.patch.yml`](./cordis.patch.yml) 的 `config:` 块设置。
138
+
139
+ 主要开关:
140
+
141
+ - `pythonBin` —— 解释器名或绝对路径;留空表示用 `PATH` 上的 `python3`。
142
+ - `failFastOnMissingPython` —— 解释器不可用时直接**拒绝加载**(默认 `true`),而不是降级成
143
+ 「所有工具不可用」:每个工具都要 sidecar,静默降级只会让模型在几轮之后才发现工具全都不见了。
144
+ 设成 `false` 才走降级,附一条警告。
145
+ - `fetchEnabled` / `extractEnabled` / `renderEnabled` / `captureXhrEnabled` /
146
+ `sessionEnabled` / `answerEnabled` —— 默认开。
147
+ - `stealthEnabled` / `crawlEnabled` —— **默认关**(前者多一层浏览器依赖,
148
+ 后者是重量级后台任务)。
149
+ - `extractionType` —— `markdown`(默认)/ `html` / `text`。三条路径都过同一套反注入
150
+ 清洗;`html` 额外剥掉事件处理器属性(`on*`、`srcdoc`、`formaction`)与 `meta refresh`,
151
+ 因此**拿到的不是字节级原始 HTML**。
152
+ - `allowedHosts` —— **安全相关的放行名单**,默认空(最严)。指向内网等于主动放弃那些目标
153
+ 的 SSRF 防护,抓自建/内网站点时才会需要。它同时喂 Host 闸门与 Python 侧守卫,两边同解。
154
+ - `allowSyntheticDns` —— 放行代理软件返回的**合成** DNS 答案。fake-IP 代理把**每个**域名都
155
+ 解析进 `198.18.0.0/15`(TUN 客户端常落在 `100.64.0.0/10`),两段都不是公网 unicast,
156
+ 闸门于是把每个 URL 都判成私网——开了代理反而全都抓不了。**默认关**:不开代理没有理由
157
+ 放宽判据,开了也不该由模型自己决定。放宽只作用于**解析结果**,URL 里写死的 IP 字面量
158
+ 照旧严格判定,`http://169.254.169.254/` 仍然被拒。
159
+ - `*MaxOutputChars` —— 各工具的输出封顶。宿主侧的封顶只影响进模型上下文的那一段,
160
+ 真正的字节上限在 Python 侧(`maxContentChars`)。`crawlMaxItems` 是部署侧给模型可传的
161
+ `maxPages` 封的顶;越界的 `maxPages`(0、负数、NaN)**原样透传**,让 sidecar 报参数错误,
162
+ 而不是由本插件悄悄夹成一个看起来合法的值。
163
+ - `answerProvider` / `answerModel` / `answerMaxTokens` —— `scrapling_answer` 走哪条模型路由
164
+ 以及单次回答的 token 上限。provider 与 model 都留空表示「跟随当前会话的模型」,
165
+ `answerMaxTokens` 封住回答长度。
166
+ - `sidecarHandshakeTimeoutMs` / `fetchTimeoutMs` / `sidecarGraceMs` —— sidecar 握手的等待预算、
167
+ 单次调用的协同超时(声明在各工具的 `timeoutMs` 上),以及超时之后客户端再等进程退出多久才
168
+ 强制拆掉。三项都在设置卡上。`scrapling_crawl` 是例外:它作为作业运行且不传超时——一次爬取
169
+ 是分钟级的,套一个固定预算会让每次成功都在最后一刻被判超时,然后整个进程被拆掉重来。
170
+ - `mainContentOnly` / `headless` / `networkIdle` / `blockAds` / `captureXhrPattern` /
171
+ `waitSelectorState` / `dataDir` —— 抽取范围、浏览器模式、XHR 捕获过滤、页面被读取前必须
172
+ 达到的选择器状态,以及 sidecar 的工作目录。逐项说明见 [`host.ts`](./host.ts) 里的注释。
173
+
174
+ **部署级旋钮**(不在设置卡上,只走 [`cordis.patch.yml`](./cordis.patch.yml) 的 `config:`
175
+ 块):`requestTimeoutSeconds`、`maxUrlLength`、`browserExecutablePath`、`browserCdpUrl`、
176
+ `searchEndpoint`、`searchRenderTopN`。
177
+ 其中 `browserExecutablePath` 与 `browserCdpUrl` 是强能力 —— 前者等于让 Chromium 执行指定文件,
178
+ 后者等于把浏览器交给指定调试端点 —— 所以它们只从部署配置来,模型入参到不了。
179
+
180
+ > **改完设置要重启 dsh。** 闸门策略与 sidecar 的环境变量都在插件 `apply()` 时取一次快照,
181
+ > 设置卡上的改动要等下次启动才生效。
182
+
183
+ 关掉某个工具时,它的 system prompt 指引段**也一并消失**,
184
+ 不会出现「工具没了但提示词还在」的割裂。
185
+
186
+ ## 安全说明
187
+
188
+ - **SSRF。** Scrapling 自身**没有任何** SSRF 防护。本插件在 Host 侧加一层 URL 策略
189
+ (scheme 白名单、拒绝 URL 内嵌凭据、长度上限、authority 里有反斜杠或控制字符即拒、
190
+ DNS 解析后按**整个答案集**判定是否全为公网、IPv4-mapped 与 NAT64 地址按内嵌 IPv4
191
+ 重判),并在 Python 侧再强制一次。**判的和发出去的是同一个地址**:闸门判的是 WHATWG
192
+ 归一后的结果,sidecar 转发给 Python 的也是这个归一串 —— 否则「判的是 A、连的是 B」
193
+ 本身就会成为绕过面。浏览器侧的网络守卫由插件自己的代码注册,覆盖主导航、子资源、XHR
194
+ 与 WebSocket 握手。
195
+
196
+ 已知缺口若干,都写在明处:
197
+ - **连接钉扎**(undici 层技术)对非 Node 传输不可用;校验与真正建连之间有 TOCTOU
198
+ 窗口。静态抓取由 curl_cffi 的 `follow_redirects="safe"` 兜住重定向,浏览器抓取由
199
+ Python 侧的 route handler 兜住。
200
+ - **NAT64 前缀不做动态探测。** dsh 内置会用 `ipv4only.arpa` 哨兵探测当前网络真正生效
201
+ 的前缀;本插件默认覆盖两个标准化前缀(`64:ff9b::/96`、`64:ff9b:1::/48`)。用运营商
202
+ 自建前缀的网络请用设置里的 `nat64Prefixes` 显式声明,否则藏在 IPv6 里的私网 IPv4
203
+ 会被当成普通公网 IPv6 放行。反过来,自建前缀一旦声明就**对所有 IPv6 生效**,不限于
204
+ 落在 RFC 6052 段里的那些。
205
+ - **没有端口白名单**(默认不限端口),与 dsh 内置 fetch provider 的取舍一致。
206
+ - **`scrapling_crawl` 已有自己的地址复核,但重定向目标仍只靠域名一致性。** 起点 URL 过
207
+ `guard.url_allowed`(与浏览器路径同一个实现,两侧同解),爬虫会话设了
208
+ `follow_redirects="safe"` 让 curl_cffi 拒绝跳向私网的跳转,每一页收进结果前再复判一次
209
+ 最终 URL。但 Scrapling 的 `allow_domains` 是字符串比较,只管页面里发现的链接、不管重定向
210
+ 目标 —— 重定向这条缝上真正的防线仍只有 Host 闸门起点那一道。
211
+ - **WebSocket 覆盖依赖 Playwright 版本。** 守卫用 `route_web_socket` 拦握手;更老的
212
+ Playwright 没有这个方法,那种情况下 WebSocket 不在守卫范围内,插件会往日志与能力报告
213
+ 里如实标出,不会静默降级。
214
+ - **浏览器二进制路径与 CDP 端点是部署级强能力。** 只从部署配置来,模型入参到不了;
215
+ 指向它们等于交出「执行这个文件」与「把浏览器交给这个调试端点」。
216
+
217
+ Host 侧那道策略由 `SidecarClient.call` 统一执行,因此覆盖每一个工具,也覆盖
218
+ `web_fetch` provider;判否时抛 `URL_BLOCKED`,请求根本不会写进管道。
219
+
220
+ - **浏览器引擎不认代理环境变量。** Playwright 不读 `HTTP_PROXY` / `HTTPS_PROXY`,所以
221
+ `scrapling_render` / `scrapling_capture_xhr` / `scrapling_stealth_fetch` 即使在整台机器
222
+ 都走代理时也**直连**——走浏览器的那部分请求会溜出隧道。而 `scrapling_fetch` 与爬虫底下的
223
+ curl_cffi **是**认这些变量的,于是两半在必须走代理的网络上行为不一致。这里写明而不是绕过去:
224
+ 把浏览器也送进代理等于交给本包一项部署级强能力,而在没法对着一个真实代理验证的前提下
225
+ 把它发出去,比说清楚更糟。上面的 `allowSyntheticDns` 只修闸门,**不改变流量去向**。
226
+
227
+ - **有配额,不是无上限的常驻资源。** 同开会话至多 8 个(其中 `browser`/`stealth` 至多 3
228
+ 个,每个都是一个真实的 Chromium 进程)、同时在跑的爬虫至多 2 个、单页正文按
229
+ `maxContentChars` 封顶、单个协议帧 8 MB、待处理队列 16 帧。撞上限时返回的是明确的错误码
230
+ (`SESSION_LIMIT` / `CRAWL_BUSY` / `BAD_FRAME`),由模型自己退避,而不是把机器吃光。
231
+ - **不接受来自模型的代码执行。** `page_action`、`page_setup`、`selector_config`、
232
+ `proxy`、`executablePath`、`cdpUrl` **绝不进入任何工具 schema**。浏览器侧的网络守卫
233
+ 由插件自己的代码注册,绝不来自模型入参。
234
+ - **反注入清洗无条件执行**,且不提供任何让模型关掉它的开关:`markdown`、`html`、`text`
235
+ 三条提取路径都过 Scrapling 的 `_strip_noise_tags` + `_sanitize_for_ai`,`html` 再补一道
236
+ 属性剥离。代价是 `html` 不再是字节级原始文档。
237
+
238
+ ## 开发
239
+
240
+ ```sh
241
+ pnpm install # 安装依赖
242
+ pnpm run check # 类型检查 + lint + 构建 + 测试 + 格式检查
243
+ pnpm run build # 把 host.ts / src/client-entry.ts 打成 host.js / client.js
244
+ pnpm run test:py # 端到端验证 Python sidecar(需仓库根的 _env/.venv)
245
+ ```
246
+
247
+ 源码全部是 TypeScript。`host.js` 与 `client.js` 是**构建产物**,故意用 `.js`:
248
+ Node 拒绝为 `node_modules` 里的包剥类型,而 dsh 正是从 `node_modules` 加载本插件的。
249
+
250
+ 产物是 **ESM-only**:`require()` 拿不到它,这是有意的(宿主按包名载入运行),不是缺陷。
251
+
252
+ 构建时 `dependencies` / `peerDependencies` / `devDependencies` 三张表里的包**一律外部化**。
253
+ 运行期由宿主提供的那些(cordis、dsh-tools、dsh-subprocess、dsh-jobs)若被内联,本包会拿到
254
+ 一份私有的副本 —— 模块级状态会裂成多份,更有甚者(按 `import.meta.url` 相对解析自身
255
+ package.json 的那种)一 import 就抛 `MODULE_NOT_FOUND`。`test/publish-manifest.test.ts` 会把
256
+ 产物真的载入一次、并断言没有内联的宿主包正文,把这两件事钉住。
257
+
258
+ 发布走 [`.github/workflows/publish.yml`](./.github/workflows/publish.yml)(手动触发,
259
+ OIDC trusted publishing + `--provenance`)。
260
+
261
+ ## 许可证
262
+
263
+ MIT,见 [`LICENSE`](./LICENSE)。本包代码与第三方代码的边界见
264
+ [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md)。