@fffangchenghao/dsh-web-search 0.19.3 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +194 -33
  3. package/README.zh-CN.md +171 -34
  4. package/SECURITY.md +42 -7
  5. package/client.js +131 -9
  6. package/docs/store-evidence.md +10 -5
  7. package/lib/advanced-search.d.ts +107 -0
  8. package/lib/advanced-search.js +255 -0
  9. package/lib/bridge.d.ts +16 -0
  10. package/lib/bridge.js +160 -0
  11. package/lib/cache.d.ts +11 -4
  12. package/lib/cache.js +9 -5
  13. package/lib/config.d.ts +19 -3
  14. package/lib/config.js +24 -0
  15. package/lib/domain-tool.d.ts +5 -0
  16. package/lib/domain-tool.js +45 -6
  17. package/lib/engine-test.d.ts +116 -0
  18. package/lib/engine-test.js +256 -0
  19. package/lib/engines.d.ts +11 -1
  20. package/lib/engines.js +118 -19
  21. package/lib/errors.d.ts +16 -2
  22. package/lib/errors.js +40 -1
  23. package/lib/index.d.ts +24 -2
  24. package/lib/index.js +304 -20
  25. package/lib/inject.d.ts +43 -0
  26. package/lib/inject.js +1 -0
  27. package/lib/markdown.js +18 -1
  28. package/lib/mirrors.d.ts +23 -0
  29. package/lib/mirrors.js +69 -0
  30. package/lib/official-feed.d.ts +114 -0
  31. package/lib/official-feed.js +288 -0
  32. package/lib/official-support.d.ts +74 -0
  33. package/lib/official-support.js +134 -0
  34. package/lib/platform-tool.d.ts +77 -0
  35. package/lib/platform-tool.js +173 -0
  36. package/lib/platforms.d.ts +178 -0
  37. package/lib/platforms.js +1035 -0
  38. package/lib/query-router.d.ts +29 -0
  39. package/lib/query-router.js +58 -0
  40. package/lib/read-page.js +2 -1
  41. package/lib/research-cache.d.ts +115 -0
  42. package/lib/research-cache.js +275 -0
  43. package/lib/research.d.ts +45 -4
  44. package/lib/research.js +505 -22
  45. package/lib/search-many.d.ts +7 -1
  46. package/lib/search-many.js +7 -2
  47. package/lib/system-prompt.d.ts +27 -0
  48. package/lib/system-prompt.js +50 -0
  49. package/lib/tool-suite.d.ts +97 -0
  50. package/lib/tool-suite.js +224 -0
  51. package/lib/transport.d.ts +33 -2
  52. package/lib/transport.js +42 -9
  53. package/lib/types.d.ts +20 -0
  54. package/lib/types.js +9 -1
  55. package/lib/untrusted.d.ts +33 -0
  56. package/lib/untrusted.js +42 -0
  57. package/lib/verticals.d.ts +3 -1
  58. package/lib/verticals.js +26 -7
  59. package/package.json +5 -3
  60. package/skills/dsh-web-search/SKILL.md +21 -6
package/client.js CHANGED
@@ -47,22 +47,28 @@
47
47
  var ENTRY = 'web-search-bing';
48
48
  var PACKAGE_NAME = 'dsh-web-search-bing';
49
49
  /** Keep in step with package.json; compared with the npm registry. */
50
- var VERSION = '0.19.3';
50
+ var VERSION = '0.20.0';
51
51
  /** Snapshot used while no configuration service is reachable. */
52
52
  var EMPTY_STATE = { status: 'unavailable', value: undefined, base: undefined, user: undefined, revision: undefined, writable: false };
53
53
 
54
54
  // English copy. Every label the page renders lives here.
55
55
  var en = {
56
56
  title: 'Web search (Bing)',
57
- description: 'Edit the key-free search provider: engine allow-list, wait policy, proxy, result budget, ranking, cache, cooldowns and dedicated sources. Model tools: web_search, research, domain_search, search_many, read_page.',
57
+ description: 'Edit the key-free search provider: engine allow-list, wait policy, proxy, result budget, ranking, cache, cooldowns and dedicated sources. Model tools: web_search, web_fetch and one unified web_tools action tool (legacy eight-name mode is opt-in).',
58
58
  jumpTo: 'Jump to',
59
59
  latest: 'Latest on npm',
60
60
  upToDate: 'up to date',
61
61
  updateAvailable: 'update available',
62
62
  'group.engines': 'Engines and transport',
63
63
  'group.ranking': 'Results and ranking',
64
+ 'group.fetch': 'Fetching',
64
65
  'group.cache': 'Cache and cooldowns',
65
66
  'group.domain': 'Dedicated sources',
67
+ 'group.tools': 'Model tools',
68
+ 'field.toolSurface': 'Tool surface',
69
+ 'hint.toolSurface': 'unified exposes one web_tools with eight actions and is the recommended context-efficient mode; legacy keeps the old eight names for existing prompts. Restart the plugin after changing this.',
70
+ 'toolSurface.unified': 'Unified (one web_tools)',
71
+ 'toolSurface.legacy': 'Legacy (eight names)',
66
72
  'wait.auto': 'Auto (query language)',
67
73
  'wait.all': 'All engines',
68
74
  'wait.fast': 'Fastest answer',
@@ -113,6 +119,22 @@
113
119
  'timeRange.week': 'Past 7 days',
114
120
  'timeRange.month': 'Past 30 days',
115
121
  'timeRange.year': 'Past year',
122
+ 'field.blockedDomains': 'Blocked sites',
123
+ 'hint.blockedDomains': 'Domains that must never appear (spam.example, ads.example); subdomains are blocked too. Empty blocks nothing.',
124
+ 'field.safeSearch': 'Safe search',
125
+ 'hint.safeSearch': 'Applies only to Bing and DuckDuckGo; off keeps each engine default',
126
+ 'safeSearch.off': 'Off (engine default)',
127
+ 'safeSearch.moderate': 'Moderate',
128
+ 'safeSearch.strict': 'Strict',
129
+ 'field.fallbackOn': 'Fallback on',
130
+ 'hint.fallbackOn': 'Failure classes that may switch to a fallback engine. Empty means never fall back; all six means search never fails just because one engine did.',
131
+ 'testTitle': 'Engine health',
132
+ 'testHint': 'Run one tiny query through each engine. This does not use the cache or change cooldowns.',
133
+ 'testButton': 'Test engines',
134
+ 'testRunning': 'Testing…',
135
+ 'testUnavailable': 'The test endpoint is not available in this deployment.',
136
+ 'testFailed': 'The test could not run.',
137
+ 'testSummary': 'OK / failed',
116
138
  'field.cacheTtlMs': 'Cache lifetime',
117
139
  'hint.cacheTtlMs': 'How long an identical question reuses its cached answer (ms)',
118
140
  'field.cacheEntries': 'Cache size',
@@ -145,13 +167,20 @@
145
167
  title: '网页搜索(Bing)',
146
168
  jumpTo: '跳到',
147
169
  latest: 'npm 最新版',
170
+ autoUpdateHint: '自动更新:用 npm 安装,并保持 profile 更新器(dsh-autoupdater)开启;link:/file: 安装会被跳过,因为替换本地 checkout 会破坏开发目录。',
148
171
  upToDate: '已是最新',
149
172
  updateAvailable: '有新版本',
150
- description: '编辑免密钥搜索提供方:引擎白名单、等待策略、代理、结果上限、排序、缓存、冷却与专用检索源。模型工具:web_search、research、domain_search、search_many、read_page。',
173
+ description: '编辑免密钥搜索提供方:引擎白名单、等待策略、代理、结果上限、排序、缓存、冷却与专用检索源。模型工具:web_search、web_fetch,以及一个统一的 web_tools action 工具(旧版八个工具名可选)。',
151
174
  'group.engines': '引擎与传输',
152
175
  'group.ranking': '结果与排序',
176
+ 'group.fetch': '抓取',
153
177
  'group.cache': '缓存与冷却',
154
178
  'group.domain': '专用检索',
179
+ 'group.tools': '模型工具',
180
+ 'field.toolSurface': '工具面',
181
+ 'hint.toolSurface': 'unified 只暴露一个 web_tools、用 action 调用八种能力,推荐且更省上下文;legacy 保留原来的八个工具名,兼容旧提示词。修改后需要重启插件。',
182
+ 'toolSurface.unified': '统一(一个 web_tools)',
183
+ 'toolSurface.legacy': '旧版(八个工具名)',
155
184
  'wait.auto': '自动(按提问语言)',
156
185
  'wait.all': '等待全部引擎',
157
186
  'wait.fast': '最快回答',
@@ -202,6 +231,22 @@
202
231
  'timeRange.week': '最近 7 天',
203
232
  'timeRange.month': '最近 30 天',
204
233
  'timeRange.year': '最近 1 年',
234
+ 'field.blockedDomains': '屏蔽网站',
235
+ 'hint.blockedDomains': '永远不要出现在结果里的网站(如 spam.example、ads.example),子域名也会被屏蔽;留空表示不屏蔽。',
236
+ 'field.safeSearch': '安全搜索',
237
+ 'hint.safeSearch': '只影响 Bing 和 DuckDuckGo;off 保持引擎默认',
238
+ 'safeSearch.off': '关闭(引擎默认)',
239
+ 'safeSearch.moderate': '适中',
240
+ 'safeSearch.strict': '严格',
241
+ 'field.fallbackOn': '哪些失败可回退',
242
+ 'hint.fallbackOn': '允许切换到备用引擎的失败类别;留空表示任何失败都不回退,六类全选表示一个引擎失败不会让搜索失败。',
243
+ 'testTitle': '引擎健康',
244
+ 'testHint': '用一条短查询逐个测试引擎;不会使用缓存,也不会改变冷却状态。',
245
+ 'testButton': '测试引擎',
246
+ 'testRunning': '测试中…',
247
+ 'testUnavailable': '当前部署没有提供测试接口。',
248
+ 'testFailed': '测试没能执行。',
249
+ 'testSummary': '成功 / 失败',
205
250
  'field.cacheTtlMs': '缓存保留多久',
206
251
  'hint.cacheTtlMs': '同一问题复用旧结果多久(毫秒);想更快见新内容就调小',
207
252
  'field.cacheEntries': '缓存条数上限',
@@ -235,10 +280,10 @@
235
280
  { key: 'wait', group: 'engines', kind: 'select', options: ['auto', 'all', 'fast'] },
236
281
  { key: 'timeoutMs', group: 'engines', kind: 'number', integer: true, min: 500 },
237
282
  { key: 'proxy', group: 'engines', kind: 'text' },
238
- { key: 'fetchFormat', group: 'engines', kind: 'select', options: ['markdown', 'text'] },
239
- { key: 'fetchMaxLength', group: 'engines', kind: 'number', integer: true, min: 1000, max: 200000 },
240
- { key: 'renderJs', group: 'engines', kind: 'select', options: ['auto', 'always', 'off'] },
241
- { key: 'renderTimeoutMs', group: 'engines', kind: 'number', integer: true, min: 1000, max: 120000 },
283
+ { key: 'fetchFormat', group: 'fetch', kind: 'select', options: ['markdown', 'text'] },
284
+ { key: 'fetchMaxLength', group: 'fetch', kind: 'number', integer: true, min: 1000, max: 200000 },
285
+ { key: 'renderJs', group: 'fetch', kind: 'select', options: ['auto', 'always', 'off'] },
286
+ { key: 'renderTimeoutMs', group: 'fetch', kind: 'number', integer: true, min: 1000, max: 120000 },
242
287
  { key: 'anysearchApiKey', group: 'engines', kind: 'text' },
243
288
  { key: 'anysearchDomain', group: 'engines', kind: 'text' },
244
289
  { key: 'limit', group: 'ranking', kind: 'number', integer: true, min: 1, max: 20 },
@@ -248,6 +293,9 @@
248
293
  { key: 'freshnessBoost', group: 'ranking', kind: 'number', min: 0, max: 10 },
249
294
  { key: 'freshnessDays', group: 'ranking', kind: 'number', integer: true, min: 1 },
250
295
  { key: 'timeRange', group: 'ranking', kind: 'select', options: ['off', 'day', 'week', 'month', 'year'] },
296
+ { key: 'blockedDomains', group: 'engines', kind: 'list' },
297
+ { key: 'safeSearch', group: 'engines', kind: 'select', options: ['off', 'moderate', 'strict'] },
298
+ { key: 'fallbackOn', group: 'engines', kind: 'list' },
251
299
  { key: 'cacheTtlMs', group: 'cache', kind: 'number', integer: true, min: 0 },
252
300
  { key: 'cacheEntries', group: 'cache', kind: 'number', integer: true, min: 0 },
253
301
  { key: 'cachePersist', group: 'cache', kind: 'select', options: ['true', 'false'], boolean: true },
@@ -256,11 +304,12 @@
256
304
  { key: 'maxCooldownMs', group: 'cache', kind: 'number', integer: true, min: 0 },
257
305
  { key: 'domainSources', group: 'domain', kind: 'list' },
258
306
  { key: 'domainLimit', group: 'domain', kind: 'number', integer: true, min: 1, max: 20 },
259
- { key: 'domainTimeoutMs', group: 'domain', kind: 'number', integer: true, min: 500 }
307
+ { key: 'domainTimeoutMs', group: 'domain', kind: 'number', integer: true, min: 500 },
308
+ { key: 'toolSurface', group: 'tools', kind: 'select', options: ['unified', 'legacy'] }
260
309
  ];
261
310
 
262
311
  /** Groups in render order. */
263
- var GROUPS = ['engines', 'ranking', 'cache', 'domain'].map(function (group) {
312
+ var GROUPS = ['engines', 'ranking', 'fetch', 'cache', 'domain', 'tools'].map(function (group) {
264
313
  return { key: group, fields: FIELDS.filter(function (field) { return field.group === group; }) };
265
314
  });
266
315
 
@@ -479,6 +528,9 @@
479
528
  var latestPair = React.useState(null);
480
529
  var latest = latestPair[0];
481
530
  var setLatest = latestPair[1];
531
+ var testPair = React.useState({ phase: 'idle', value: null, error: null });
532
+ var test = testPair[0];
533
+ var setTest = testPair[1];
482
534
 
483
535
  // Ask the npm registry once per mount. A failure (offline, proxy
484
536
  // down, registry error) hides the line instead of showing an
@@ -520,6 +572,41 @@
520
572
  }
521
573
  }
522
574
 
575
+ function runEngineTest() {
576
+ if (test.phase === 'running') return;
577
+ setTest({ phase: 'running', value: null, error: null });
578
+ var request;
579
+ try {
580
+ request = fetch('/api/dsh-web-search/engine-test', {
581
+ method: 'POST',
582
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
583
+ body: JSON.stringify({ query: 'DeepSeek Harness' })
584
+ });
585
+ } catch (error) {
586
+ setTest({ phase: 'failed', value: null, error: t('testUnavailable') });
587
+ return;
588
+ }
589
+ Promise.resolve(request).then(function (response) {
590
+ return Promise.resolve(response.text()).then(function (text) {
591
+ var body = null;
592
+ try {
593
+ body = text.length === 0 ? null : JSON.parse(text);
594
+ } catch (ignored) {
595
+ body = null;
596
+ }
597
+ if (!response.ok || body === null || body.ok !== true || body.value === undefined) {
598
+ var fallback = response.status === 404 || response.status === 405
599
+ ? t('testUnavailable')
600
+ : t('testFailed');
601
+ throw new Error(body !== null && typeof body.message === 'string' ? body.message : fallback);
602
+ }
603
+ setTest({ phase: 'done', value: body.value, error: null });
604
+ });
605
+ }).catch(function (error) {
606
+ setTest({ phase: 'failed', value: null, error: error instanceof Error ? error.message : t('testUnavailable') });
607
+ });
608
+ }
609
+
523
610
  function save() {
524
611
  if (!ready || state.writable === false || phase === 'saving') return;
525
612
  var nextErrors = {};
@@ -564,6 +651,9 @@
564
651
  style: { margin: 0, fontSize: '12px', color: newer ? 'var(--dsw-alias-state-warn-primary)' : 'var(--dsw-alias-label-tertiary)' },
565
652
  role: 'status'
566
653
  }, t('latest') + ': ' + latest + (newer ? ' — ' + t('updateAvailable') : ' — ' + t('upToDate'))));
654
+ children.push(h('p', {
655
+ key: 'auto-update', style: { margin: 0, fontSize: '11px', lineHeight: 1.5, color: 'var(--dsw-alias-label-tertiary)' }, role: 'note'
656
+ }, t('autoUpdateHint')));
567
657
  }
568
658
 
569
659
  if (!ready) {
@@ -654,6 +744,38 @@
654
744
  ]);
655
745
  })));
656
746
 
747
+ var testStatus = null;
748
+ if (test.phase === 'running') {
749
+ testStatus = h('p', { key: 'test-running', style: hintStyle, role: 'status' }, t('testRunning'));
750
+ } else if (test.phase === 'failed') {
751
+ testStatus = h('p', { key: 'test-failed', style: errorStyle, role: 'alert' }, test.error === null ? t('testFailed') : test.error);
752
+ } else if (test.phase === 'done' && test.value !== null) {
753
+ var rows = (Array.isArray(test.value.results) ? test.value.results : []).map(function (result) {
754
+ var kind = result.ok === true ? 'OK' : 'FAIL';
755
+ var detail = result.ok === true
756
+ ? String(result.latencyMs) + 'ms · ' + String(result.count) + ' result(s)'
757
+ : (typeof result.failureKind === 'string' ? '[' + result.failureKind + '] ' : '') + (typeof result.reason === 'string' ? result.reason : '');
758
+ return h('li', { key: result.engine, style: { margin: '2px 0', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: '12px' } },
759
+ result.engine + ': ' + kind + ' · ' + detail);
760
+ });
761
+ testStatus = h('div', { key: 'test-done' }, [
762
+ h('p', { key: 'summary', style: hintStyle, role: 'status' }, t('testSummary') + ': ' + String(test.value.ok) + ' / ' + String(test.value.failed)),
763
+ h('ul', { key: 'rows', style: { margin: 0, paddingLeft: '18px' } }, rows)
764
+ ]);
765
+ }
766
+ children.push(h('section', { key: 'engine-test', style: groupStyle }, [
767
+ h('h4', { key: 'title', style: { margin: 0, fontSize: '13px', lineHeight: 1.4, color: 'var(--dsw-alias-label-primary)' } }, t('testTitle')),
768
+ h('p', { key: 'hint', style: hintStyle }, t('testHint')),
769
+ h('div', { key: 'actions', style: { display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' } }, [
770
+ h('button', {
771
+ key: 'run', type: 'button', style: buttonStyle,
772
+ disabled: test.phase === 'running',
773
+ onClick: runEngineTest
774
+ }, t(test.phase === 'running' ? 'testRunning' : 'testButton')),
775
+ testStatus
776
+ ])
777
+ ]));
778
+
657
779
  var footer = [
658
780
  h('button', {
659
781
  key: 'save', type: 'button', style: primaryStyle,
@@ -23,7 +23,7 @@ Only `0.2.1-rc.2` is declared, because that is the version actually exercised.
23
23
  ## Environment
24
24
 
25
25
  - macOS (arm64), DeepSeek Harness **0.2.1-rc.2** (`dsh --version`), Node 22.18+.
26
- - Runtime artifacts: `lib/` is committed to this repository (40 files, 468 KiB),
26
+ - Runtime artifacts: `lib/` is committed to this repository (76 files, 876 KiB),
27
27
  so the fixed commit's tree contains `lib/index.js` and `lib/index.d.ts`.
28
28
  - Disposable profile for the destructive steps: a fresh `DSH_HOME` created with
29
29
  `mktemp -d`; the real `~/.dsh` was never written to. Bundled pnpm 11.28.5.
@@ -58,10 +58,15 @@ Two independent observations:
58
58
  status: "schema" }], total: 1 }
59
59
  ```
60
60
 
61
- `status: "schema"` means the entry is active and its 26-field Config schema is
62
- projected, which is what the Settings page renders. The three tools
63
- (`read_page`, `search_many`, `domain_search`) and the search/fetch providers
64
- are registered from the same mount; the GUI lists the plugin as 运行中.
61
+ `status: "schema"` means the entry is active; the current build projects a
62
+ 29-field Config schema. Eight tools (`domain_search`, `search_many`,
63
+ `advanced_search`, `read_page`, `research`, `cache_search`, `platform_search`,
64
+ `engine_test`) and the
65
+ search/fetch providers are registered from the same mount; the GUI lists the
66
+ plugin as 运行中. This probe was retaken after a restart with the current
67
+ build; a live `advanced_search` window note and a fresh npm publish date were
68
+ observed through those tools, so the list is a live observation rather than a
69
+ projection.
65
70
 
66
71
  2. **Disposable profile, composed tree.** `dsh --profile e2e --dump-config`
67
72
  composes the full tree without error and contains the entry above.
@@ -0,0 +1,107 @@
1
+ import type { EngineFailure, Source, TimeRange } from './types.ts';
2
+ import type { ToolContent, ToolJsonSchema } from './domain-tool.ts';
3
+ /** The name this tool prefers. */
4
+ export declare const ADVANCED_SEARCH_TOOL_NAME = "advanced_search";
5
+ /** The name used when another plugin already registered `advanced_search`. */
6
+ export declare const ADVANCED_SEARCH_FALLBACK_NAME = "web_search_advanced";
7
+ /** Default result budget when the caller names none. */
8
+ export declare const ADVANCED_SEARCH_DEFAULT_LIMIT = 5;
9
+ /** Largest result budget the tool accepts; the deployment limit still caps it. */
10
+ export declare const ADVANCED_SEARCH_MAX_LIMIT = 20;
11
+ /** What one advanced search produced, including the window that was applied. */
12
+ export interface AdvancedSearchOutcome {
13
+ sources: Source[];
14
+ failures: string[];
15
+ /** Structured failures, kept for callers that want the business class. */
16
+ failureDetails?: EngineFailure[];
17
+ /** Short policy note, such as why the fallback tier was used or skipped. */
18
+ note?: string;
19
+ /** True when the deployment's configured limit cut the requested budget. */
20
+ truncated: boolean;
21
+ /** The effective window, after applying the deployment default if omitted. */
22
+ timeRange: TimeRange;
23
+ }
24
+ /** What the tool returns to the model. */
25
+ export interface AdvancedSearchValue {
26
+ query: string;
27
+ timeRange: TimeRange;
28
+ sources: Source[];
29
+ failures: string[];
30
+ note?: string;
31
+ truncated: boolean;
32
+ }
33
+ /**
34
+ * Explain an undated row when a window is active.
35
+ *
36
+ * The engine path prefers dated results inside the window, but falls back to
37
+ * undated rows when no dated result lands inside it. Saying so keeps the model
38
+ * from presenting an undated row as a confirmed "this week" item.
39
+ * @param sources - the rows returned by the search.
40
+ * @param timeRange - the effective window.
41
+ * @returns one sentence, or `undefined` when every row is dated or the window is off.
42
+ */
43
+ export declare function undatedWindowNote(sources: readonly Source[], timeRange: TimeRange): string | undefined;
44
+ /** Run one search with an optional window; `undefined` means the deployment default. */
45
+ export type AdvancedSearchRunner = (query: string, limit: number, timeRange: TimeRange | undefined, signal?: AbortSignal) => Promise<AdvancedSearchOutcome>;
46
+ /** A tool definition in the host registry's native shape. */
47
+ export interface AdvancedSearchDefinition {
48
+ name: string;
49
+ description: string;
50
+ parameters: ToolJsonSchema;
51
+ output: {
52
+ schema: ToolJsonSchema;
53
+ render: (args: unknown, value: AdvancedSearchValue) => ToolContent[];
54
+ };
55
+ timeoutMs?: number;
56
+ isConcurrencySafe?: (args: unknown) => boolean;
57
+ execute: (args: unknown, exec: {
58
+ signal?: AbortSignal;
59
+ }) => Promise<AdvancedSearchValue>;
60
+ }
61
+ /** The slice of the tool registry this module needs. */
62
+ export interface AdvancedSearchRegistryLike {
63
+ register(definition: AdvancedSearchDefinition): unknown;
64
+ get?(name: string, scope?: unknown): unknown;
65
+ }
66
+ /** Construction seams. */
67
+ export interface AdvancedSearchOptions {
68
+ /** Registration diagnostics. */
69
+ warn?: (message: string) => void;
70
+ }
71
+ /** A successful registration plus the exact way to undo it. */
72
+ export interface AdvancedSearchRegistration {
73
+ name: string;
74
+ dispose: () => void;
75
+ }
76
+ /**
77
+ * Remove a relative window phrase that the structured window already carries.
78
+ * "过去 7 天内 Chrome…" searches for `7` and `内`, not for Chrome; with an
79
+ * explicit `timeRange` the phrase is redundant and only adds noise.
80
+ * @param query - the caller's query.
81
+ * @returns the query without a relative-time phrase, or the original when the
82
+ * removal would leave nothing.
83
+ */
84
+ export declare function stripRelativeWindow(query: string): string;
85
+ /** Format the model-facing result text. */
86
+ export declare function formatAdvancedSearchValue(value: AdvancedSearchValue): string;
87
+ /**
88
+ * Build the tool definition the host registry accepts.
89
+ * @param name - `advanced_search`, or the fallback when that name is taken.
90
+ * @param runSearch - executes one search through the plugin's normal path.
91
+ * @returns a registry-ready definition.
92
+ */
93
+ export declare function createAdvancedSearchDefinition(name: string, runSearch: AdvancedSearchRunner): AdvancedSearchDefinition;
94
+ /**
95
+ * Pick the tool name this deployment can accept.
96
+ * @param tools - the live registry.
97
+ * @returns the preferred or fallback name.
98
+ */
99
+ export declare function pickAdvancedSearchToolName(tools: AdvancedSearchRegistryLike): string;
100
+ /**
101
+ * Register the tool when a registry is available.
102
+ * @param tools - the live registry.
103
+ * @param runSearch - executes one search through the plugin's normal path.
104
+ * @param options - diagnostics.
105
+ * @returns the registered name and its disposer, or `undefined` when skipped.
106
+ */
107
+ export declare function registerAdvancedSearchTool(tools: AdvancedSearchRegistryLike, runSearch: AdvancedSearchRunner, options?: AdvancedSearchOptions): AdvancedSearchRegistration | undefined;
@@ -0,0 +1,255 @@
1
+ /**
2
+ * The model-facing `advanced_search` tool: one search with a per-call date
3
+ * window.
4
+ *
5
+ * `web_search` takes only a query and a result count, and the Settings
6
+ * `timeRange` applies to every ordinary search. This tool is the narrow escape
7
+ * hatch for the common case where only one question needs a window ("what
8
+ * changed this week?"), without asking the user to change a global setting.
9
+ *
10
+ * It shares the engine, cache and cooldown path with `web_search`; the only
11
+ * difference is the `timeRange` override, so an `off` call can reuse an ordinary
12
+ * cached search and a `week` call gets its own cache key.
13
+ *
14
+ * @module @fangchenghao/dsh-web-search/advanced-search
15
+ */
16
+ import { TIME_RANGES } from "./freshness.js";
17
+ import { wrapUntrustedContent } from "./untrusted.js";
18
+ /** The name this tool prefers. */
19
+ export const ADVANCED_SEARCH_TOOL_NAME = 'advanced_search';
20
+ /** The name used when another plugin already registered `advanced_search`. */
21
+ export const ADVANCED_SEARCH_FALLBACK_NAME = 'web_search_advanced';
22
+ /** Default result budget when the caller names none. */
23
+ export const ADVANCED_SEARCH_DEFAULT_LIMIT = 5;
24
+ /** Largest result budget the tool accepts; the deployment limit still caps it. */
25
+ export const ADVANCED_SEARCH_MAX_LIMIT = 20;
26
+ /**
27
+ * Explain an undated row when a window is active.
28
+ *
29
+ * The engine path prefers dated results inside the window, but falls back to
30
+ * undated rows when no dated result lands inside it. Saying so keeps the model
31
+ * from presenting an undated row as a confirmed "this week" item.
32
+ * @param sources - the rows returned by the search.
33
+ * @param timeRange - the effective window.
34
+ * @returns one sentence, or `undefined` when every row is dated or the window is off.
35
+ */
36
+ export function undatedWindowNote(sources, timeRange) {
37
+ if (timeRange === 'off')
38
+ return undefined;
39
+ const undated = sources.filter((source) => source.publishedAt === undefined).length;
40
+ if (undated === 0)
41
+ return undefined;
42
+ return `The ${timeRange} publication window is on, but ${undated} of ${sources.length} result(s) have no publication date, so they are not proven to fall inside it.`;
43
+ }
44
+ /** True for a value usable as a record. */
45
+ function isRecord(value) {
46
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
47
+ }
48
+ /** The parameter schema, in the registry's raw JSON-Schema dialect. */
49
+ function parameterSchema() {
50
+ return {
51
+ type: 'object',
52
+ additionalProperties: false,
53
+ properties: {
54
+ query: {
55
+ type: 'string',
56
+ description: 'The search query. Put the distinctive words in it; do not paste a whole document.',
57
+ },
58
+ maxResults: {
59
+ type: 'integer',
60
+ description: `Results wanted, 1–${ADVANCED_SEARCH_MAX_LIMIT}; defaults to ${ADVANCED_SEARCH_DEFAULT_LIMIT}. The deployment limit still caps it.`,
61
+ },
62
+ timeRange: {
63
+ type: 'string',
64
+ enum: [...TIME_RANGES],
65
+ description: 'Publication window for this call: off, day, week, month or year. Omit to use the deployment setting; off disables the window for this query only.',
66
+ },
67
+ },
68
+ required: ['query'],
69
+ };
70
+ }
71
+ /** The output schema, in the same dialect. */
72
+ function outputSchema() {
73
+ return {
74
+ type: 'object',
75
+ additionalProperties: false,
76
+ properties: {
77
+ query: { type: 'string' },
78
+ timeRange: { type: 'string', enum: [...TIME_RANGES] },
79
+ sources: {
80
+ type: 'array',
81
+ items: {
82
+ type: 'object',
83
+ additionalProperties: false,
84
+ properties: {
85
+ url: { type: 'string' },
86
+ title: { type: 'string' },
87
+ snippet: { type: 'string' },
88
+ publishedAt: { type: 'string' },
89
+ },
90
+ required: ['url'],
91
+ },
92
+ },
93
+ failures: { type: 'array', items: { type: 'string' } },
94
+ note: { type: 'string' },
95
+ truncated: { type: 'boolean' },
96
+ },
97
+ required: ['query', 'timeRange', 'sources', 'failures', 'truncated'],
98
+ };
99
+ }
100
+ /** Parse model arguments into a validated shape, throwing on nonsense. */
101
+ function parseArgs(args) {
102
+ if (!isRecord(args))
103
+ throw new Error('advanced_search requires arguments');
104
+ const rawQuery = args['query'];
105
+ if (typeof rawQuery !== 'string' || rawQuery.trim().length === 0) {
106
+ throw new Error('advanced_search requires a non-empty query');
107
+ }
108
+ const query = rawQuery.trim();
109
+ const rawLimit = args['maxResults'];
110
+ let maxResults = ADVANCED_SEARCH_DEFAULT_LIMIT;
111
+ if (rawLimit !== undefined) {
112
+ if (typeof rawLimit !== 'number' || !Number.isInteger(rawLimit)
113
+ || rawLimit < 1 || rawLimit > ADVANCED_SEARCH_MAX_LIMIT) {
114
+ throw new Error(`advanced_search maxResults must be an integer between 1 and ${ADVANCED_SEARCH_MAX_LIMIT}`);
115
+ }
116
+ maxResults = rawLimit;
117
+ }
118
+ const rawRange = args['timeRange'];
119
+ if (rawRange === undefined)
120
+ return { query, maxResults };
121
+ if (typeof rawRange !== 'string' || !TIME_RANGES.includes(rawRange)) {
122
+ throw new Error(`advanced_search timeRange must be one of ${TIME_RANGES.join(', ')}`);
123
+ }
124
+ return { query, maxResults, timeRange: rawRange };
125
+ }
126
+ /**
127
+ * Remove a relative window phrase that the structured window already carries.
128
+ * "过去 7 天内 Chrome…" searches for `7` and `内`, not for Chrome; with an
129
+ * explicit `timeRange` the phrase is redundant and only adds noise.
130
+ * @param query - the caller's query.
131
+ * @returns the query without a relative-time phrase, or the original when the
132
+ * removal would leave nothing.
133
+ */
134
+ export function stripRelativeWindow(query) {
135
+ const cleaned = query
136
+ .replace(/(?:过去|最近)\s*(?:\d+|一|几|半)\s*(?:天|日|周|星期|个月|月|年)(?:内|里|以内)?/gu, ' ')
137
+ .replace(/\b(?:in\s+the\s+)?(?:past|last)\s+\d+\s+(?:days?|weeks?|months?|years?)\b/giu, ' ')
138
+ .replace(/\s+/gu, ' ')
139
+ .replace(/^[\s,,。.;;::]+|[\s,,。.;;::]+$/gu, '')
140
+ .trim();
141
+ return cleaned.length > 0 ? cleaned : query;
142
+ }
143
+ /** Format the model-facing result text. */
144
+ export function formatAdvancedSearchValue(value) {
145
+ const head = `Search: ${JSON.stringify(value.query)} (timeRange=${value.timeRange}) — `
146
+ + `${value.sources.length} result(s)${value.truncated ? ' (truncated)' : ''}.`;
147
+ const lines = value.sources.map((source, index) => {
148
+ const title = source.title !== undefined && source.title.length > 0 ? source.title : source.url;
149
+ const parts = [`${index + 1}. ${title}`, ` ${source.url}`];
150
+ if (source.snippet !== undefined && source.snippet.length > 0)
151
+ parts.push(` ${source.snippet}`);
152
+ if (source.publishedAt !== undefined && source.publishedAt.length > 0)
153
+ parts.push(` ${source.publishedAt}`);
154
+ return parts.join('\n');
155
+ });
156
+ if (value.note !== undefined && value.note.length > 0)
157
+ lines.push(`Note: ${value.note}`);
158
+ if (value.failures.length > 0)
159
+ lines.push(`failures: ${value.failures.join('; ')}`);
160
+ return [head, '', ...lines].join('\n').trimEnd();
161
+ }
162
+ /**
163
+ * Build the tool definition the host registry accepts.
164
+ * @param name - `advanced_search`, or the fallback when that name is taken.
165
+ * @param runSearch - executes one search through the plugin's normal path.
166
+ * @returns a registry-ready definition.
167
+ */
168
+ export function createAdvancedSearchDefinition(name, runSearch) {
169
+ return {
170
+ name,
171
+ description: 'Search the web with an optional publication-time window for this call. Use it instead of web_search when one query needs results from the last day, week, month or year. Returns ranked candidates (URL, title, snippet, date), not page bodies.',
172
+ parameters: parameterSchema(),
173
+ output: {
174
+ schema: outputSchema(),
175
+ render: (_args, value) => [{ type: 'text', text: wrapUntrustedContent(formatAdvancedSearchValue(value)) }],
176
+ },
177
+ timeoutMs: 30_000,
178
+ isConcurrencySafe: () => true,
179
+ async execute(args, exec) {
180
+ const parsed = parseArgs(args);
181
+ const searchQuery = parsed.timeRange === undefined || parsed.timeRange === 'off'
182
+ ? parsed.query
183
+ : stripRelativeWindow(parsed.query);
184
+ const outcome = await runSearch(searchQuery, parsed.maxResults, parsed.timeRange, exec.signal);
185
+ return {
186
+ query: parsed.query,
187
+ timeRange: outcome.timeRange,
188
+ sources: outcome.sources.slice(0, parsed.maxResults).map((source) => ({ ...source })),
189
+ failures: [...outcome.failures],
190
+ ...(outcome.note === undefined ? {} : { note: outcome.note }),
191
+ truncated: outcome.truncated || outcome.sources.length > parsed.maxResults,
192
+ };
193
+ },
194
+ };
195
+ }
196
+ /**
197
+ * Pick the tool name this deployment can accept.
198
+ * @param tools - the live registry.
199
+ * @returns the preferred or fallback name.
200
+ */
201
+ export function pickAdvancedSearchToolName(tools) {
202
+ if (typeof tools.get !== 'function')
203
+ return ADVANCED_SEARCH_TOOL_NAME;
204
+ try {
205
+ return tools.get(ADVANCED_SEARCH_TOOL_NAME) === undefined
206
+ ? ADVANCED_SEARCH_TOOL_NAME
207
+ : ADVANCED_SEARCH_FALLBACK_NAME;
208
+ }
209
+ catch {
210
+ return ADVANCED_SEARCH_TOOL_NAME;
211
+ }
212
+ }
213
+ /** Report a registration failure without throwing out of the plugin. */
214
+ function report(options, error) {
215
+ const message = error instanceof Error ? error.message : String(error);
216
+ try {
217
+ options.warn?.(`advanced_search registration skipped: ${message}`);
218
+ }
219
+ catch {
220
+ // A diagnostic callback must never break plugin loading.
221
+ }
222
+ }
223
+ /**
224
+ * Register the tool when a registry is available.
225
+ * @param tools - the live registry.
226
+ * @param runSearch - executes one search through the plugin's normal path.
227
+ * @param options - diagnostics.
228
+ * @returns the registered name and its disposer, or `undefined` when skipped.
229
+ */
230
+ export function registerAdvancedSearchTool(tools, runSearch, options = {}) {
231
+ const name = pickAdvancedSearchToolName(tools);
232
+ try {
233
+ const registered = tools.register(createAdvancedSearchDefinition(name, runSearch));
234
+ const disposeHost = typeof registered === 'function' ? registered : undefined;
235
+ let disposed = false;
236
+ return {
237
+ name,
238
+ dispose: () => {
239
+ if (disposed)
240
+ return;
241
+ disposed = true;
242
+ try {
243
+ disposeHost?.();
244
+ }
245
+ catch {
246
+ // Disposal must stay contained; the plugin is already going away.
247
+ }
248
+ },
249
+ };
250
+ }
251
+ catch (error) {
252
+ report(options, error);
253
+ return undefined;
254
+ }
255
+ }
@@ -0,0 +1,16 @@
1
+ import type { EngineTestRunner } from './engine-test.ts';
2
+ import type { InjectableHost, ServiceContext } from './inject.ts';
3
+ /** Route prefix the client fetches; kept stable for the shipped settings page. */
4
+ export declare const ENGINE_TEST_BRIDGE_PATH = "/api/dsh-web-search/engine-test";
5
+ /** The injected services this bridge needs; `webServer` may be absent. */
6
+ export type BridgeContext = ServiceContext;
7
+ /** A context that may support `inject`; test hosts often do not. */
8
+ export type InjectableContext = InjectableHost;
9
+ export type { WebServerLike } from './inject.ts';
10
+ /**
11
+ * Register the engine-test endpoint.
12
+ * @param ctx - injectable plugin context.
13
+ * @param runTest - engine test runner shared with the model tool.
14
+ * @returns a disposer, or `undefined` when the host has no injectable server.
15
+ */
16
+ export declare function registerEngineTestBridge(ctx: InjectableContext, runTest: EngineTestRunner): (() => void) | undefined;