dsh-free-search 0.9.82 → 0.9.83
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/README.md +11 -22
- package/bin/restore.js +82 -82
- package/lib/activity.js +341 -0
- package/lib/client.js +591 -6
- package/lib/engines/aliyun.js +2 -1
- package/lib/engines/anysearch.js +2 -1
- package/lib/engines/baidu.js +2 -1
- package/lib/engines/brave.js +2 -1
- package/lib/engines/claude.js +2 -1
- package/lib/engines/deepseek-official.js +2 -1
- package/lib/engines/deepseek-tools.js +2 -1
- package/lib/engines/degoog.js +2 -1
- package/lib/engines/doubao.js +2 -1
- package/lib/engines/exa.js +3 -2
- package/lib/engines/firecrawl.js +2 -1
- package/lib/engines/gemini.js +2 -1
- package/lib/engines/google.js +2 -1
- package/lib/engines/jina.js +2 -1
- package/lib/engines/keenable.js +3 -2
- package/lib/engines/kimi.js +2 -1
- package/lib/engines/metaso.js +2 -1
- package/lib/engines/openai.js +2 -1
- package/lib/engines/outcrawl.js +2 -1
- package/lib/engines/parallel.js +3 -2
- package/lib/engines/perplexity.js +2 -1
- package/lib/engines/searxng.js +2 -1
- package/lib/engines/serpbase.js +2 -1
- package/lib/engines/serper.js +2 -1
- package/lib/engines/serply.js +2 -1
- package/lib/engines/shared.js +2 -1
- package/lib/engines/specstream.js +2 -1
- package/lib/engines/tavily.js +2 -1
- package/lib/engines/tinyfish.js +2 -1
- package/lib/engines/yandex.js +2 -1
- package/lib/engines/you.js +2 -1
- package/lib/engines/yuanbao.js +2 -1
- package/lib/engines/zhipu.js +2 -1
- package/lib/fetch_provider.js +41 -2
- package/lib/fetch_upstream.js +1 -1
- package/lib/index.js +229 -28
- package/lib/platform_engines.js +13 -12
- package/lib/proxy_fetch.js +538 -0
- package/lib/research.js +2 -2
- package/lib/restore.js +234 -234
- package/lib/serp_engines.js +3 -2
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -257,16 +257,6 @@ dsh web
|
|
|
257
257
|
Error: configured web provider "ddg" is not registered
|
|
258
258
|
```
|
|
259
259
|
|
|
260
|
-
**已经卸掉了、忘了删?** 插件不在也能修——新增的 `restore` 命令直接改配置文件,不加载插件:
|
|
261
|
-
|
|
262
|
-
```
|
|
263
|
-
npx dsh-free-search restore # 所有 profile
|
|
264
|
-
npx dsh-free-search restore --profile web # 只清一个
|
|
265
|
-
npx dsh-free-search restore --dry-run # 只看会改什么,不写
|
|
266
|
-
```
|
|
267
|
-
|
|
268
|
-
它只删本插件自己写进去的两个值(`searchProvider: ddg`、`fetchProvider: fs-quality-fetch`);你自己显式选的 provider 不动;删完只剩 `id` + `name` 的行整行去掉;注释、顺序、引号风格和 CRLF 都保留;写入前先备份成 `*.bak-before-free-search-restore`。改完重启 `dsh` 让 web 服务重建。
|
|
269
|
-
|
|
270
260
|
更早的 DSH(0.1.x)由 patch 静态覆盖 config,不需要也更不该手写这段,这里不再赘述。
|
|
271
261
|
|
|
272
262
|
#### DSH 的「DeepSeek 搜索 API」开关
|
|
@@ -652,7 +642,7 @@ npx -y -p dsh-free-search dsh-free-search-mcp
|
|
|
652
642
|
|
|
653
643
|
#### 离线自检断言(tools/)
|
|
654
644
|
|
|
655
|
-
仓库自带 **
|
|
645
|
+
仓库自带 **108 个**零依赖断言脚本(合计 **1372 项**)
|
|
656
646
|
|
|
657
647
|
| 脚本 | 覆盖 | 运行(项数) |
|
|
658
648
|
|---|---|---|
|
|
@@ -692,7 +682,16 @@ npx -y -p dsh-free-search dsh-free-search-mcp
|
|
|
692
682
|
| `assert-serper.mjs` | Serper.dev 引擎(#157):端点常量、`X-API-KEY` 鉴权(非 Bearer)、`num` 上限 100、`tbs` 时间语法(含绝对日期 `cd_min`)、`organic` 映射、401/403/429 错误分类、缺 key 快速失败、catalog 与 MCP/设置页接线 | `node tools/assert-serper.mjs`(10) |
|
|
693
683
|
| `assert-tavily-endpoint.mjs` | Tavily 兼容端点(#153):留空 = 官方地址、base 自动补 `/search`、query/hash 被剥离、非 http(s) 拒绝、key 只走 Authorization 头、401 点名端点、配置与设置页接线 | `node tools/assert-tavily-endpoint.mjs`(8) |
|
|
694
684
|
| `assert-hint-card.mjs` | 字段说明悬停卡:长说明不再占正文、卡片经 portal 挂到 body(否则被卡片 `overflow:clip` 裁掉)、Esc 关闭、聚焦打开/失焦关闭、悬停有延迟、触屏可点、卡片不越出视口、深浅色都覆盖、标签文字在图标按钮外(否则被压成一字一行)、点图标不连带切换复选框 | `node tools/assert-hint-card.mjs`(14) |
|
|
685
|
+
| `assert-activity-panel.mjs` | 右侧栏搜索动态(#144):记录只在内存不落盘、历史上限 50、来源上限 8、按会话隔离、进行中/完成状态、引擎结果分类(成功/失败类别/跳过原因)、清空、默认关闭、旧宿主无右侧栏服务时整体跳过、tab 正文+标题+引导入口注册、bridge 路由走统一守卫、工具分发携带会话、轮询随卸载停止、中英文案 | `node tools/assert-activity-panel.mjs`(15) |
|
|
686
|
+
| `assert-activity-wiring.mjs` | 搜索动态接线(#144 回归):配置项默认关闭且能完整往返、座位标志只在服务注入后才置位、加载时已开启也能挂载、tab id 三处共用、引导入口带 commandId 且标题/描述是函数、package.json 声明 `dsh-client-ui-sidebar-right` 为可选 peer 与 client inject、服务缺失时有 try/catch 兜底 | `node tools/assert-activity-wiring.mjs`(8) |
|
|
687
|
+
| `assert-activity-pipeline.mjs` | 搜索动态数据面端到端:工具钩子把会话带进搜索链、记录归属该会话、进行中可见当前引擎、结束后离开 in-flight、引擎结果与来源往返完好、无归属记录仍可见、会话之间不串、底部计数已接线、两条 bridge 路由都过统一守卫、面板轮询随卸载停止 | `node tools/assert-activity-pipeline.mjs`(20) |
|
|
695
688
|
| `assert-restore-cli.mjs` | 卸载后清理入口(#159):`restore` 子命令不依赖插件运行时、只删插件自己写进去的 `searchProvider: ddg` / `fetchProvider: fs-quality-fetch`、用户显式选的 provider 不动、只剩 id+name 的空行整行删除、注释/顺序/引号/CRLF 保留、写入前备份、重复运行无副作用、`--dry-run` 不写、`--profile` 只清指定 profile、参数不明时拒绝写入 | `node tools/assert-restore-cli.mjs`(12) |
|
|
689
|
+
| `assert-upgrade-version.mjs` | 一键升级以实际安装结果为准(#163):读回 profile 里真正落下的版本、与 registry 比较、冷却拦截单独报 `upgrade-blocked`、成功路径报 installed 而非 latest、读不到安装状态时不算成功、界面 toast 用 installed、被拦截时用告警色并保留原文案 | `node tools/assert-upgrade-version.mjs`(8) |
|
|
690
|
+
| `assert-search-proxy.mjs` | 搜索代理(#155)的规则层:http/https/socks5 地址解析、凭据百分号解码、无 scheme 视为 http、socks5h 交给代理解析、非法协议拒绝、`no_proxy` 优先于显式设置、空设置不接管环境变量代理、活动代理是配置层写入的模块状态、搜索路径不再直连全局 `fetch`、该设置只管引擎(天气/更新检查/抓取层保持平台 fetch)、界面中英双语文案、SOCKS5 由本仓库自己实现、重定向三档语义、abort/timeout 保持原生 error 名、HTTP/1.1 请求必须走我们自己的隧道 socket(`agent: false` 与 `https.request` 都会静默绕过代理)、新增依赖为零 | `node tools/assert-search-proxy.mjs`(18) |
|
|
691
|
+
| `assert-proxy-tunnel.mjs` | 代理隧道实测(#155):本地 CONNECT 代理与手写 SOCKS5 服务端,验证方法/路径/body/host 透传、Basic 凭据解码、每次请求一条隧道且响应后关闭、`follow`/`manual`/`error` 三档重定向语义、303 把 POST 降为 GET、gzip 解压、CONNECT 407 明确报错、代理接受 CONNECT 后立刻断开时不回落直连、不可达代理快速失败、`no_proxy` 绕过隧道、SOCKS5 无认证与用户名密码两档、认证被拒与断线报错 | `node tools/assert-proxy-tunnel.mjs`(17) |
|
|
692
|
+
| `assert-fetch-alpn.mjs` | #162:https 每一跳都声明 `ALPNProtocols: ["http/1.1"]`(只此一个,不带 h2——响应按 HTTP/1.1 解析)、http 目标不声明、按重定向目标的协议逐跳判断、browser 层被跳过时 errors 里写明原因、两个 HTML 返回点都经过瘦身 | `node tools/assert-fetch-alpn.mjs`(7) |
|
|
693
|
+
| `assert-fetch-html-slim.mjs` | #161:`slimHtml()` 去掉 style/script/noscript/template/注释、只清超长 base64 `data:`(短图标保留)、普通页面逐字节不变、幂等、大小写与跨行标签、构造一个 260 KB 内联 CSS 的页面后同样 200,000 字符预算下正文确实在 | `node tools/assert-fetch-html-slim.mjs`(9) |
|
|
694
|
+
| `assert-browser-path.mjs` | T1.5 浏览器路径(#160):留空仍走内置候选表、纯空格等同空值、自定义路径原样使用、路径不存在时不回落到其它浏览器、探测缓存随配置失效、provider 收到的是配置值而非硬编码、配置项默认空、设置页能完整读写、输入框只在 T1.5 开启时出现、中英文提示都写明不回落规则 | `node tools/assert-browser-path.mjs`(9) |
|
|
696
695
|
| `assert-control-chrome.mjs` | 字段标题与复选框外观:标题字号/字重要高于正文、复选框由样式绘制(`appearance:none` + CSS 勾)、不确定态有独立横线、聚焦有描边、深浅色都覆盖、分组自动换行、全选不拉满整行、工具行复选框不再固定 150px | `node tools/assert-control-chrome.mjs`(9) |
|
|
697
696
|
| `assert-checkbox-labels.mjs` | 复选框不再重复标签:左侧栏入口 / 斜杠命令 / 免 key 优先三项各只出现一次标签、标签位于复选框同一行、其它输入类字段仍保留独立标题 | `node tools/assert-checkbox-labels.mjs`(5) |
|
|
698
697
|
| `assert-dropdown.mjs` | 自绘下拉:设置页不再有原生 `<select>`、11 处全部走同一个组件、保留 `onChange({ target })` 契约与 listbox 语义、键盘(↑↓/Home/End/Enter/Esc/Tab)可用、浮层限高滚动、深浅色都有样式 | `node tools/assert-dropdown.mjs`(6) |
|
|
@@ -1044,16 +1043,6 @@ So **remove those `- id: web` lines before disabling or uninstalling this plugin
|
|
|
1044
1043
|
Error: configured web provider "ddg" is not registered
|
|
1045
1044
|
```
|
|
1046
1045
|
|
|
1047
|
-
**Already uninstalled and forgot?** The `restore` command fixes the profile patch without loading the plugin:
|
|
1048
|
-
|
|
1049
|
-
```
|
|
1050
|
-
npx dsh-free-search restore # every profile
|
|
1051
|
-
npx dsh-free-search restore --profile web # one profile
|
|
1052
|
-
npx dsh-free-search restore --dry-run # report only, write nothing
|
|
1053
|
-
```
|
|
1054
|
-
|
|
1055
|
-
It removes only the two values this plugin wrote (`searchProvider: ddg`, `fetchProvider: fs-quality-fetch`); a provider you chose yourself is left alone; a row left with just `id` + `name` is dropped entirely; comments, ordering, quoting and CRLF survive; and it writes a `*.bak-before-free-search-restore` backup first. Restart `dsh` afterwards so the web service rebuilds.
|
|
1056
|
-
|
|
1057
1046
|
Older DSH (0.1.x) used a static patch layer for this; writing that row by hand there is neither needed nor recommended.
|
|
1058
1047
|
|
|
1059
1048
|
#### DSH's "DeepSeek search API" switch
|
|
@@ -1436,7 +1425,7 @@ Restart `dsh web` after switching to apply changes.
|
|
|
1436
1425
|
|
|
1437
1426
|
#### Offline self-check assertions (`tools/`)
|
|
1438
1427
|
|
|
1439
|
-
**
|
|
1428
|
+
**One hundred and eight** zero-dependency assertion scripts ship with the repo (**1372 assertions** total)
|
|
1440
1429
|
|
|
1441
1430
|
| Script | Covers | Run (count) |
|
|
1442
1431
|
|---|---|---|
|
package/bin/restore.js
CHANGED
|
@@ -1,82 +1,82 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// #159: restore the web provider fields this plugin wrote into the profile patch.
|
|
3
|
-
//
|
|
4
|
-
// Runs without loading the plugin, so it also works after the plugin was
|
|
5
|
-
// disabled or uninstalled - the exact state the residue is stuck in.
|
|
6
|
-
//
|
|
7
|
-
// npx dsh-free-search restore
|
|
8
|
-
// npx dsh-free-search restore --profile web --dry-run
|
|
9
|
-
import { cleanProfiles, describeResults, dshHomeDir } from "../lib/restore.js";
|
|
10
|
-
|
|
11
|
-
const args = process.argv.slice(2);
|
|
12
|
-
|
|
13
|
-
// Flags are parsed first: an unknown or bare invocation must never fall through
|
|
14
|
-
// to a real write. Anything short of an explicit `restore` prints usage and exits.
|
|
15
|
-
const HELP_FLAGS = new Set(["--help", "-h", "help", "--usage"]);
|
|
16
|
-
if (args.length === 0 || args.some((arg) => HELP_FLAGS.has(arg))) {
|
|
17
|
-
printUsage();
|
|
18
|
-
process.exit(args.length === 0 ? 2 : 0);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
const command = args[0];
|
|
22
|
-
if (command !== "restore") {
|
|
23
|
-
console.error(`unknown command "${command}"`);
|
|
24
|
-
printUsage();
|
|
25
|
-
process.exit(2);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const profileIndex = args.indexOf("--profile");
|
|
29
|
-
const profile = profileIndex >= 0 ? args[profileIndex + 1] : undefined;
|
|
30
|
-
if (profileIndex >= 0 && (profile === undefined || profile.startsWith("-"))) {
|
|
31
|
-
console.error("--profile needs a profile name");
|
|
32
|
-
process.exit(2);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const homeIndex = args.indexOf("--home");
|
|
36
|
-
const home = homeIndex >= 0 ? args[homeIndex + 1] : dshHomeDir();
|
|
37
|
-
if (homeIndex >= 0 && (home === undefined || home.startsWith("-"))) {
|
|
38
|
-
console.error("--home needs a directory");
|
|
39
|
-
process.exit(2);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// An unknown flag is a typo, not consent to overwrite a profile patch.
|
|
43
|
-
const KNOWN_FLAGS = new Set(["restore", "--profile", "--home", "--dry-run"]);
|
|
44
|
-
const valueFlags = new Set(["--profile", "--home"]);
|
|
45
|
-
for (let i = 0; i < args.length; i += 1) {
|
|
46
|
-
const arg = args[i];
|
|
47
|
-
if (KNOWN_FLAGS.has(arg)) {
|
|
48
|
-
if (valueFlags.has(arg)) i += 1;
|
|
49
|
-
continue;
|
|
50
|
-
}
|
|
51
|
-
console.error(`unknown argument "${arg}"`);
|
|
52
|
-
printUsage();
|
|
53
|
-
process.exit(2);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const dryRun = args.includes("--dry-run");
|
|
57
|
-
|
|
58
|
-
const results = cleanProfiles({ home, profile, dryRun });
|
|
59
|
-
for (const line of describeResults(results)) console.log(line);
|
|
60
|
-
if (results.some((result) => result.ok && result.changed) && !dryRun) {
|
|
61
|
-
console.log("\nbackups were written next to each patch as *.bak-before-free-search-restore");
|
|
62
|
-
console.log("restart dsh so the web service rebuilds with the restored providers");
|
|
63
|
-
}
|
|
64
|
-
if (dryRun && results.some((result) => result.ok && result.changed)) {
|
|
65
|
-
console.log("\n(dry run: nothing was written)");
|
|
66
|
-
}
|
|
67
|
-
process.exit(results.every((result) => result.ok) ? 0 : 1);
|
|
68
|
-
|
|
69
|
-
function printUsage() {
|
|
70
|
-
console.log(`Usage:
|
|
71
|
-
dsh-free-search restore [--profile <name>] [--home <dir>] [--dry-run]
|
|
72
|
-
|
|
73
|
-
Removes the "searchProvider: ddg" / "fetchProvider: fs-quality-fetch" values
|
|
74
|
-
this plugin wrote into a profile's cordis.patch.yml. Values you set yourself are
|
|
75
|
-
left untouched, and a patch line surviving only because of them is dropped.
|
|
76
|
-
|
|
77
|
-
--profile <name> clean one profile under <home>/profiles
|
|
78
|
-
--home <dir> DSH home (defaults to $DSH_HOME or ~/.dsh)
|
|
79
|
-
--dry-run report what would change without writing
|
|
80
|
-
|
|
81
|
-
Nothing is written unless the word "restore" is the first argument.`);
|
|
82
|
-
}
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// #159: restore the web provider fields this plugin wrote into the profile patch.
|
|
3
|
+
//
|
|
4
|
+
// Runs without loading the plugin, so it also works after the plugin was
|
|
5
|
+
// disabled or uninstalled - the exact state the residue is stuck in.
|
|
6
|
+
//
|
|
7
|
+
// npx dsh-free-search restore
|
|
8
|
+
// npx dsh-free-search restore --profile web --dry-run
|
|
9
|
+
import { cleanProfiles, describeResults, dshHomeDir } from "../lib/restore.js";
|
|
10
|
+
|
|
11
|
+
const args = process.argv.slice(2);
|
|
12
|
+
|
|
13
|
+
// Flags are parsed first: an unknown or bare invocation must never fall through
|
|
14
|
+
// to a real write. Anything short of an explicit `restore` prints usage and exits.
|
|
15
|
+
const HELP_FLAGS = new Set(["--help", "-h", "help", "--usage"]);
|
|
16
|
+
if (args.length === 0 || args.some((arg) => HELP_FLAGS.has(arg))) {
|
|
17
|
+
printUsage();
|
|
18
|
+
process.exit(args.length === 0 ? 2 : 0);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const command = args[0];
|
|
22
|
+
if (command !== "restore") {
|
|
23
|
+
console.error(`unknown command "${command}"`);
|
|
24
|
+
printUsage();
|
|
25
|
+
process.exit(2);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const profileIndex = args.indexOf("--profile");
|
|
29
|
+
const profile = profileIndex >= 0 ? args[profileIndex + 1] : undefined;
|
|
30
|
+
if (profileIndex >= 0 && (profile === undefined || profile.startsWith("-"))) {
|
|
31
|
+
console.error("--profile needs a profile name");
|
|
32
|
+
process.exit(2);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const homeIndex = args.indexOf("--home");
|
|
36
|
+
const home = homeIndex >= 0 ? args[homeIndex + 1] : dshHomeDir();
|
|
37
|
+
if (homeIndex >= 0 && (home === undefined || home.startsWith("-"))) {
|
|
38
|
+
console.error("--home needs a directory");
|
|
39
|
+
process.exit(2);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// An unknown flag is a typo, not consent to overwrite a profile patch.
|
|
43
|
+
const KNOWN_FLAGS = new Set(["restore", "--profile", "--home", "--dry-run"]);
|
|
44
|
+
const valueFlags = new Set(["--profile", "--home"]);
|
|
45
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
46
|
+
const arg = args[i];
|
|
47
|
+
if (KNOWN_FLAGS.has(arg)) {
|
|
48
|
+
if (valueFlags.has(arg)) i += 1;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
console.error(`unknown argument "${arg}"`);
|
|
52
|
+
printUsage();
|
|
53
|
+
process.exit(2);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const dryRun = args.includes("--dry-run");
|
|
57
|
+
|
|
58
|
+
const results = cleanProfiles({ home, profile, dryRun });
|
|
59
|
+
for (const line of describeResults(results)) console.log(line);
|
|
60
|
+
if (results.some((result) => result.ok && result.changed) && !dryRun) {
|
|
61
|
+
console.log("\nbackups were written next to each patch as *.bak-before-free-search-restore");
|
|
62
|
+
console.log("restart dsh so the web service rebuilds with the restored providers");
|
|
63
|
+
}
|
|
64
|
+
if (dryRun && results.some((result) => result.ok && result.changed)) {
|
|
65
|
+
console.log("\n(dry run: nothing was written)");
|
|
66
|
+
}
|
|
67
|
+
process.exit(results.every((result) => result.ok) ? 0 : 1);
|
|
68
|
+
|
|
69
|
+
function printUsage() {
|
|
70
|
+
console.log(`Usage:
|
|
71
|
+
dsh-free-search restore [--profile <name>] [--home <dir>] [--dry-run]
|
|
72
|
+
|
|
73
|
+
Removes the "searchProvider: ddg" / "fetchProvider: fs-quality-fetch" values
|
|
74
|
+
this plugin wrote into a profile's cordis.patch.yml. Values you set yourself are
|
|
75
|
+
left untouched, and a patch line surviving only because of them is dropped.
|
|
76
|
+
|
|
77
|
+
--profile <name> clean one profile under <home>/profiles
|
|
78
|
+
--home <dir> DSH home (defaults to $DSH_HOME or ~/.dsh)
|
|
79
|
+
--dry-run report what would change without writing
|
|
80
|
+
|
|
81
|
+
Nothing is written unless the word "restore" is the first argument.`);
|
|
82
|
+
}
|
package/lib/activity.js
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
// #144:搜索动态面板的数据面。
|
|
2
|
+
//
|
|
3
|
+
// 宿主的 tools/execute 是「分发前后」的 waterfall,可以把整个工具执行体包在
|
|
4
|
+
// 一个 AsyncLocalStorage 里,于是搜索链内部任何 await 之后都还知道「这次是哪个
|
|
5
|
+
// 会话调用的」。这比给 provider.search 传参更可靠:宿主自己的 web_search 也走
|
|
6
|
+
// ctx.web.search,同样会落进这个上下文。
|
|
7
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
|
+
|
|
9
|
+
const HISTORY_MAX = 50;
|
|
10
|
+
const SOURCES_MAX = 8;
|
|
11
|
+
const ENGINES_MAX = 48;
|
|
12
|
+
|
|
13
|
+
const storage = new AsyncLocalStorage();
|
|
14
|
+
const runStorage = new AsyncLocalStorage();
|
|
15
|
+
|
|
16
|
+
let seq = 0;
|
|
17
|
+
let history = [];
|
|
18
|
+
let inflight = [];
|
|
19
|
+
// 临时诊断:面板空着时需要能分清「钩子没触发」和「钩子触发但记录丢了」。
|
|
20
|
+
let sawHook = 0;
|
|
21
|
+
let began = 0;
|
|
22
|
+
let finished = 0;
|
|
23
|
+
let engineCalls = 0;
|
|
24
|
+
let engineDropped = 0;
|
|
25
|
+
|
|
26
|
+
/** 在给定的会话上下文里执行 fn;sessionId 为空时也照样执行,只是不带归属。 */
|
|
27
|
+
export function withSession(sessionId, fn) {
|
|
28
|
+
return storage.run({ sessionId: String(sessionId ?? "") }, fn);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 当前异步上下文里的会话 id(没有则为空串)。 */
|
|
32
|
+
export function ctxSession() {
|
|
33
|
+
return runStorage.getStore()?.sessionId ?? "";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 当前异步上下文里的对话轮次(0 = 未知)。 */
|
|
37
|
+
export function ctxTurn() {
|
|
38
|
+
return Number(runStorage.getStore()?.turn) || 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 当前异步上下文里正在进行的搜索(没有则为 undefined)。 */
|
|
42
|
+
export function currentRun() {
|
|
43
|
+
return runStorage.getStore();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const now = () => Date.now();
|
|
47
|
+
|
|
48
|
+
function hostOf(url) {
|
|
49
|
+
try {
|
|
50
|
+
return new URL(String(url ?? "")).host || "";
|
|
51
|
+
} catch {
|
|
52
|
+
return "";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function trimSources(sources) {
|
|
57
|
+
if (!Array.isArray(sources)) return [];
|
|
58
|
+
const out = [];
|
|
59
|
+
for (const source of sources) {
|
|
60
|
+
if (out.length >= SOURCES_MAX) break;
|
|
61
|
+
const url = String(source?.url ?? "");
|
|
62
|
+
const title = String(source?.title ?? "").trim() || url;
|
|
63
|
+
out.push({ title, url, host: hostOf(url) });
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 开始一次搜索。返回的句柄在结束时要交给 finish()。 */
|
|
69
|
+
export function begin({ query, engine, mode, timeRange, sessionId, turn } = {}) {
|
|
70
|
+
const run = {
|
|
71
|
+
id: `a${(seq += 1)}`,
|
|
72
|
+
// 归属:显式传入 > 工具分发上下文里的会话 > 空(全局视图)。
|
|
73
|
+
sessionId: String(sessionId ?? ctxSession() ?? ""),
|
|
74
|
+
// 轮次:同一次对话里第几轮。拿不到就是 0,面板据此决定要不要显示。
|
|
75
|
+
turn: Number.isFinite(Number(turn)) && Number(turn) > 0 ? Number(turn) : ctxTurn(),
|
|
76
|
+
query: String(query ?? "").slice(0, 400),
|
|
77
|
+
mode: String(mode ?? ""),
|
|
78
|
+
timeRange: String(timeRange ?? ""),
|
|
79
|
+
startedAt: now(),
|
|
80
|
+
currentEngine: "",
|
|
81
|
+
engines: [],
|
|
82
|
+
sources: [],
|
|
83
|
+
totalResults: 0,
|
|
84
|
+
};
|
|
85
|
+
inflight.push(run);
|
|
86
|
+
began += 1;
|
|
87
|
+
activeRun = run;
|
|
88
|
+
return run;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 把一次搜索放进异步上下文里跑,让内部各层都能拿到它。 */
|
|
92
|
+
export function runWith(run, fn) {
|
|
93
|
+
return runStorage.run(run, fn);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 把工具分发上下文(会话 + 轮次)套在工具体上。 */
|
|
97
|
+
export function withToolScope(scope, fn) {
|
|
98
|
+
const sessionId = String(scope?.sessionId ?? "");
|
|
99
|
+
const turn = Number(scope?.turn) || 0;
|
|
100
|
+
return runStorage.run({ sessionId, turn }, fn);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 工具分发钩子被调用的次数(诊断用)。 */
|
|
104
|
+
export function noteHook() {
|
|
105
|
+
sawHook += 1;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 诊断:记录一次「钩子拿到了 agent 但取不出会话 id」的形状,只留首个样本。 */
|
|
109
|
+
let missShape = null;
|
|
110
|
+
export function noteMiss(exec) {
|
|
111
|
+
if (missShape !== null) return;
|
|
112
|
+
const agent = exec?.agent;
|
|
113
|
+
const shape = agent === undefined
|
|
114
|
+
? "agent: undefined"
|
|
115
|
+
: [
|
|
116
|
+
"keys=" + Object.keys(agent).join(","),
|
|
117
|
+
"typeof id=" + typeof agent.id,
|
|
118
|
+
"idValue=" + JSON.stringify(agent.id ?? null).slice(0, 40),
|
|
119
|
+
"has session=" + (agent.session !== undefined),
|
|
120
|
+
"session keys=" + (agent.session === undefined ? "-" : Object.keys(agent.session).join(",")),
|
|
121
|
+
].join(" ");
|
|
122
|
+
missShape = shape;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 诊断快照。
|
|
127
|
+
*
|
|
128
|
+
* 关键的一对是 sessionHistory / history:只给全局总数看不出隔离是否生效,
|
|
129
|
+
* 面板到底读到的是「本会话的记录」还是「全库的记录」必须并排显示。
|
|
130
|
+
*/
|
|
131
|
+
export function stats(sessionId = "") {
|
|
132
|
+
const key = String(sessionId ?? "");
|
|
133
|
+
const owns = (entry) => key === "" || entry.sessionId === key;
|
|
134
|
+
return {
|
|
135
|
+
sawHook,
|
|
136
|
+
began,
|
|
137
|
+
finished,
|
|
138
|
+
history: history.length,
|
|
139
|
+
inflight: inflight.length,
|
|
140
|
+
sessionHistory: history.filter(owns).length,
|
|
141
|
+
sessionInflight: inflight.filter(owns).length,
|
|
142
|
+
attributed: history.some((entry) => entry.sessionId !== ""),
|
|
143
|
+
engineCalls,
|
|
144
|
+
engineDropped,
|
|
145
|
+
missShape,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function findEngine(run, engine) {
|
|
150
|
+
return run.engines.find((entry) => entry.id === engine && entry.status === "running");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 模块级「当前 run」。
|
|
155
|
+
*
|
|
156
|
+
* 引擎事件不能只靠 AsyncLocalStorage:engineRuntime.run() 是一个并发限流器,
|
|
157
|
+
* 它把回调排进队列后,执行时的异步上下文已经换掉了,ALS 里取不到 run,
|
|
158
|
+
* 于是 engineStart/engineEnd 被静默丢弃(面板只剩「引擎 暂无」)。
|
|
159
|
+
* 这里留一个模块级引用兜底:begin 时记下,finish 时清掉。
|
|
160
|
+
*/
|
|
161
|
+
let activeRun = null;
|
|
162
|
+
|
|
163
|
+
/** 标记某个引擎开始尝试。 */
|
|
164
|
+
export function engineStart(run, engine) {
|
|
165
|
+
engineCalls += 1;
|
|
166
|
+
const target = run ?? activeRun;
|
|
167
|
+
if (!target || !engine) { engineDropped += 1; return; }
|
|
168
|
+
target.currentEngine = engine;
|
|
169
|
+
if (target.engines.length >= ENGINES_MAX) return;
|
|
170
|
+
target.engines.push({ id: String(engine), status: "running", count: 0, startedAt: now() });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 结束某个引擎的尝试:count>0 为成功,error 表示失败,skipped 表示跳过。 */
|
|
174
|
+
export function engineEnd(run, engine, { count = 0, error, skipped } = {}) {
|
|
175
|
+
const target = run ?? activeRun;
|
|
176
|
+
if (!target || !engine) { engineDropped += 1; return; }
|
|
177
|
+
const entry = findEngine(target, engine);
|
|
178
|
+
if (!entry) return;
|
|
179
|
+
entry.count = Number(count) || 0;
|
|
180
|
+
entry.ms = Math.max(0, now() - (entry.startedAt ?? now()));
|
|
181
|
+
entry.status = skipped ? "skipped" : entry.count > 0 ? "ok" : "failed";
|
|
182
|
+
if (entry.status === "failed") entry.failureClass = failureClassOf(error);
|
|
183
|
+
if (entry.status === "skipped") entry.skipReason = skipReasonOf(error);
|
|
184
|
+
target.currentEngine = "";
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function failureClassOf(error) {
|
|
188
|
+
const message = String(error?.message ?? error ?? "").toLowerCase();
|
|
189
|
+
if (error?.class) return String(error.class);
|
|
190
|
+
if (/\b429\b|rate limit|too many requests/.test(message)) return "quota";
|
|
191
|
+
if (/\b40[13]\b|unauthorized|invalid api key/.test(message)) return "auth";
|
|
192
|
+
if (/403|captcha|bot|blocked/.test(message)) return "bot-wall";
|
|
193
|
+
if (/timeout|econnreset|enotfound|network|fetch failed/.test(message)) return "transient";
|
|
194
|
+
if (/0 results|parse|invalid/.test(message)) return "invalid-response";
|
|
195
|
+
return "unknown";
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function skipReasonOf(error) {
|
|
199
|
+
const message = String(error?.message ?? error ?? "").toLowerCase();
|
|
200
|
+
if (/time/.test(message)) return "time-filter";
|
|
201
|
+
if (/key|credential/.test(message)) return "no-key";
|
|
202
|
+
if (/disabled/.test(message)) return "disabled";
|
|
203
|
+
return "skipped";
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** 结束一次搜索。result 为成功结果,error 为失败。 */
|
|
207
|
+
export function finish(run, { result, error } = {}) {
|
|
208
|
+
if (!run) return;
|
|
209
|
+
inflight = inflight.filter((entry) => entry !== run);
|
|
210
|
+
if (activeRun === run) activeRun = null;
|
|
211
|
+
finished += 1;
|
|
212
|
+
|
|
213
|
+
// 缓存命中的引擎记录由 noteCacheHit 在命中点写入(那里能拿到缓存里的
|
|
214
|
+
// provider)。这里只兜底:如果命中路径没记上,至少别让引擎栏空着。
|
|
215
|
+
if (result?._cache === "hit" && run.engines.length === 0) {
|
|
216
|
+
noteCacheHit(run, result?.provider ?? result?.engine, Array.isArray(result?.sources) ? result.sources.length : 0);
|
|
217
|
+
}
|
|
218
|
+
const endedAt = now();
|
|
219
|
+
const record = {
|
|
220
|
+
id: run.id,
|
|
221
|
+
sessionId: run.sessionId,
|
|
222
|
+
query: run.query,
|
|
223
|
+
mode: run.mode,
|
|
224
|
+
timeRange: run.timeRange,
|
|
225
|
+
turn: run.turn ?? 0,
|
|
226
|
+
startedAt: run.startedAt,
|
|
227
|
+
endedAt,
|
|
228
|
+
ms: endedAt - run.startedAt,
|
|
229
|
+
ok: !error,
|
|
230
|
+
engines: run.engines.map(({ id, status, count, ms, failureClass, skipReason, cached }) => ({
|
|
231
|
+
id,
|
|
232
|
+
status,
|
|
233
|
+
count,
|
|
234
|
+
ms: Math.max(0, ms ?? 0),
|
|
235
|
+
...(failureClass === undefined ? {} : { failureClass }),
|
|
236
|
+
...(skipReason === undefined ? {} : { skipReason }),
|
|
237
|
+
...(cached === true ? { cached: true } : {}),
|
|
238
|
+
})),
|
|
239
|
+
sources: trimSources(result?.sources),
|
|
240
|
+
totalResults: Array.isArray(result?.sources) ? result.sources.length : 0,
|
|
241
|
+
cache: result?._cache === "hit" ? "hit" : "miss",
|
|
242
|
+
...(error === undefined ? {} : { error: String(error?.message ?? error).slice(0, 300) }),
|
|
243
|
+
};
|
|
244
|
+
history.unshift(record);
|
|
245
|
+
if (history.length > HISTORY_MAX) history = history.slice(0, HISTORY_MAX);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 记一次缓存命中。
|
|
250
|
+
*
|
|
251
|
+
* 缓存命中会从 provider.search 的早退分支直接返回,根本不进引擎循环,
|
|
252
|
+
* 于是 run.engines 是空的,面板只能显示「引擎 暂无」。
|
|
253
|
+
* 缓存条目里保存着当时的 provider(= 真正跑出这批结果的引擎),用它补一条。
|
|
254
|
+
*/
|
|
255
|
+
export function noteCacheHit(run, engine, count) {
|
|
256
|
+
const id = String(engine ?? "").trim() || "cache";
|
|
257
|
+
const target = run ?? activeRun;
|
|
258
|
+
if (!target) return;
|
|
259
|
+
// 已经有同样一条就不再重复(同一引擎命中两次缓存的情况)。
|
|
260
|
+
const existing = target.engines.find((entry) => entry.id === id && entry.cached === true);
|
|
261
|
+
if (existing !== undefined) {
|
|
262
|
+
existing.count = Number(count) || existing.count;
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
target.engines.push({
|
|
266
|
+
id,
|
|
267
|
+
status: "ok",
|
|
268
|
+
count: Number(count) || 0,
|
|
269
|
+
startedAt: target.startedAt,
|
|
270
|
+
ms: 0,
|
|
271
|
+
cached: true,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 某个会话的快照:进行中的条目 + 最近一次完成 + 历史。 */
|
|
276
|
+
export function snapshot(sessionId = "") {
|
|
277
|
+
const key = String(sessionId ?? "");
|
|
278
|
+
const owns = (entry) => key === "" || entry.sessionId === key;
|
|
279
|
+
const current = inflight.filter(owns).map((run) => ({
|
|
280
|
+
id: run.id,
|
|
281
|
+
query: run.query,
|
|
282
|
+
turn: run.turn ?? 0,
|
|
283
|
+
currentEngine: run.currentEngine,
|
|
284
|
+
enginesDone: run.engines.filter((entry) => entry.status !== "running").length,
|
|
285
|
+
enginesTotal: Math.max(run.engines.length, run.enginesDone),
|
|
286
|
+
engines: run.engines.map(({ id, status, count }) => ({ id, status, count })),
|
|
287
|
+
startedAt: run.startedAt,
|
|
288
|
+
ms: now() - run.startedAt,
|
|
289
|
+
}));
|
|
290
|
+
const forSession = history.filter(owns);
|
|
291
|
+
// 归因兜底:如果这条会话名下一条都没有,而全库记录也全都没带会话 id
|
|
292
|
+
// (宿主没给 agent 身份的情形),就让面板显示这些记录,否则面板永远是空的。
|
|
293
|
+
// 只要有任何记录带了别的会话 id,就不越权显示。
|
|
294
|
+
const unattributed = history.every((entry) => entry.sessionId === "");
|
|
295
|
+
const visible = forSession.length > 0 || key === "" || !unattributed ? forSession : history;
|
|
296
|
+
// 同一份兜底也要用在 in-flight 上,否则「进行中」那一块永远是空的。
|
|
297
|
+
const currentVisible = !unattributed || key === "" || current.length > 0
|
|
298
|
+
? current
|
|
299
|
+
: inflight.map((run) => ({
|
|
300
|
+
id: run.id,
|
|
301
|
+
query: run.query,
|
|
302
|
+
currentEngine: run.currentEngine,
|
|
303
|
+
enginesDone: run.engines.filter((entry) => entry.status !== "running").length,
|
|
304
|
+
enginesTotal: Math.max(run.engines.length, run.enginesDone),
|
|
305
|
+
engines: run.engines.map(({ id, status, count }) => ({ id, status, count })),
|
|
306
|
+
startedAt: run.startedAt,
|
|
307
|
+
ms: now() - run.startedAt,
|
|
308
|
+
}));
|
|
309
|
+
return {
|
|
310
|
+
current: currentVisible,
|
|
311
|
+
latest: visible[0] ?? null,
|
|
312
|
+
history: visible.slice(0, HISTORY_MAX),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** 清空记录(只影响内存)。 */
|
|
317
|
+
export function clear(sessionId = "") {
|
|
318
|
+
const key = String(sessionId ?? "");
|
|
319
|
+
if (key === "") {
|
|
320
|
+
history = [];
|
|
321
|
+
inflight = [];
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
history = history.filter((entry) => entry.sessionId !== key);
|
|
325
|
+
inflight = inflight.filter((entry) => entry.sessionId !== key);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 测试用:把模块状态恢复干净。 */
|
|
329
|
+
export function resetForTests() {
|
|
330
|
+
seq = 0;
|
|
331
|
+
activeRun = null;
|
|
332
|
+
engineCalls = 0;
|
|
333
|
+
engineDropped = 0;
|
|
334
|
+
history = [];
|
|
335
|
+
inflight = [];
|
|
336
|
+
sawHook = 0;
|
|
337
|
+
began = 0;
|
|
338
|
+
finished = 0;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export const ACTIVITY_LIMITS = { HISTORY_MAX, SOURCES_MAX, ENGINES_MAX };
|