dsh-web-search-workbuddy 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,15 @@ workbuddy2api-go gateway's agenttool web-search passthrough, with
6
6
  [workbuddy-manager](https://github.com/WaveBird/workbuddy-manager) as the
7
7
  entry proxy — so **one `wbk_` key serves both the chat route and `web_search`**.
8
8
 
9
+ **v0.4.1**: optionally owns the model-facing `web_search` tool so the model
10
+ itself can choose `allowedDomains` / `blockedDomains` / `freshness` /
11
+ `maxResults` per call — without patching the official `dsh-tool-web` package.
12
+ Original provider-only mode (v0.4.0) remains the default.
13
+
14
+ **v0.4.0**: forwards every parameter `workbuddy.cn/agenttool/v1/search`
15
+ supports (`type`, `max_results`, `allowed_domains`, `blocked_domains`,
16
+ `freshness`) — see [Protocol](#protocol).
17
+
9
18
  ```
10
19
  DSH session ── ctx.web.search() ──▶ this provider
11
20
  │ POST {manager}:7864/v1/tools/search (wbk_ key)
@@ -27,17 +36,19 @@ expecting the gateway key):
27
36
 
28
37
  | Component | Required version / state | Why |
29
38
  |---|---|---|
30
- | **workbuddy-manager** | **≥ the `feat/web-search-passthrough` branch** ([PR #2](https://github.com/WaveBird/workbuddy-manager/pull/2)). Baseline tested: `v2.11.14` + the PR's 3 commits (`dce9acc` route, `5e88629` realm fix, `c33e122` docs). It will ship in a release **after v2.11.14** — until then, deploy the branch or cherry-pick. | The `POST /v1/tools/search` passthrough route **does not exist** in upstream releases ≤ v2.11.14. Older managers return `405` and this provider cannot work through them. |
39
+ | **workbuddy-manager** | **≥ the `feat/web-search-passthrough` branch** ([PR #2](https://github.com/WaveBird/workbuddy-manager/pull/2), upstream [PR #430](https://github.com/ithtelab/workbuddy-manager/pull/430)). Baseline tested: `v2.11.14` + the PR's 3 commits (`dce9acc` route, `5e88629` realm fix, `c33e122` docs). For the v0.4.0 full-parameter set also take the small API follow-up: `/v1/tools/search` validates `type`/`max_results`/`allowed_domains`/`blocked_domains`/`freshness` and forwards the body verbatim. It will ship in a release **after v2.11.14** — until then, deploy the branch or cherry-pick. | The `POST /v1/tools/search` passthrough route **does not exist** in upstream releases ≤ v2.11.14. Older managers return `405` and this provider cannot work through them. |
31
40
  | **workbuddy2api-go gateway** | Built from the upstream snapshot **`upstream-id 801cebba` (v2.11.14 / 0056 patches)** plus [`0057-web-search-tool.patch`](https://github.com/WaveBird/workbuddy-manager/blob/feat/web-search-passthrough/dev/upstream-patches/0057-web-search-tool.patch) (shipped inside the manager PR above). | The `POST /v1/tools/search` handler, account-pool rotation, and 15001 quota cooldown live in this patch; the stock gateway has no agenttool route. |
32
41
  | **DeepSeek Harness (DSH)** | `0.2.2-rc.2` (web seam contract `ctx.web.registerSearchProvider` / `WebSearchProvider` shape). Tested against `0.2.2-rc.1` and `rc.2`; any version keeping that seam shape works. | The provider registers into `ctx.web`; a breaking seam change would require a plugin update. |
42
+ | **Realm coverage (CN + Global)** | Both realms supported. The gateway routes agenttool by account realm (CN → `www.workbuddy.cn`, Global → `www.workbuddy.ai`, both endpoints probe-verified) — a `global:`-realm key (WorkBuddy AI / international) searches the same way as CN. The plugin itself is realm-agnostic: it follows whatever model route the conversation uses. | International accounts participate in the same account-pool rotation and 15001 quota cooldown as CN. |
33
43
 
34
44
  Quick self-check per component:
35
45
 
36
46
  ```bash
37
- # manager: route exists and accepts the wbk_ key (405/401 → wrong manager version)
47
+ # manager: route exists and accepts the wbk_ key (405/401 → wrong manager version);
48
+ # full-parameter body must be forwarded verbatim (200; 400 invalid_search_params → old route)
38
49
  curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:7864/v1/tools/search \
39
50
  -H "Authorization: Bearer <wbk_ key>" -H 'content-type: application/json' \
40
- -d '{"query":"ping"}'
51
+ -d '{"query":"ping","type":"text2text","max_results":3,"allowed_domains":["go.dev"],"blocked_domains":["reddit.com"],"freshness":"d1"}'
41
52
 
42
53
  # gateway (bypassing manager): 401 with the gateway's own api_key configured means alive
43
54
  curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:7863/v1/tools/search \
@@ -63,8 +74,17 @@ installed this way; `@deepseek-ai/schemastery` ships as a direct dependency.
63
74
  - insert:
64
75
  - id: web-search-workbuddy
65
76
  name: dsh-web-search-workbuddy
66
- # No baseURL / apiKeyEnv needed: both derive from the conversation's own
67
- # model-provider route (its apiKeyEnv credential + baseURL with /v1/ stripped).
77
+ # No config needed: baseURL + apiKeyEnv derive from the conversation's
78
+ # model-provider route automatically. Optional search defaults (v0.4.0):
79
+ # config:
80
+ # type: text2text # agenttool 请求类型(固定)
81
+ # maxResults: 5 # 1..20;请求级 maxResults 优先
82
+ # allowedDomains: [go.dev] # 只返回这些域
83
+ # blockedDomains: [reddit.com] # 网关拼成 " -site:reddit.com"
84
+ # freshness: d1 # d1 | m1 | y1
85
+ # modelControlled: true # v0.4.1:模型自主控制过滤参数
86
+ # modelMaxQueries: 10 # 一次调用最多几条 query
87
+ # modelSummaryMaxChars: 800 # 每条来源摘要上限
68
88
  - id: web
69
89
  name: '@deepseek-ai/dsh-web'
70
90
  config:
@@ -72,12 +92,46 @@ installed this way; `@deepseek-ai/schemastery` ships as a direct dependency.
72
92
  searchProvider: workbuddy-gateway # ← pin this provider
73
93
  - id: tool-web
74
94
  name: '@deepseek-ai/dsh-tool-web'
95
+ # Default mode (modelControlled: false): keep search: true in EVERY preset.
75
96
  config: { fetch: true, search: true, searchTimeoutMs: 60000 }
76
97
  # also set search: true in every agent preset's tool-web entry
77
98
  ```
78
99
 
100
+ ### Model-controlled mode (v0.4.1)
101
+
102
+ With `modelControlled: true`, this plugin registers a replacement `web_search`
103
+ tool whose schema exposes:
104
+
105
+ ```json
106
+ {
107
+ "queries": ["go generics"],
108
+ "allowedDomains": ["go.dev"],
109
+ "blockedDomains": ["reddit.com"],
110
+ "freshness": "d1",
111
+ "maxResults": 5
112
+ }
113
+ ```
114
+
115
+ The tool forwards those extras into `ctx.web.search()`'s request object; the
116
+ seam passes it through unchanged and the provider maps them onto the gateway
117
+ body (request values win over the config defaults above). No DSH framework
118
+ file is modified. Because `ctx.tools.register()` rejects duplicate names,
119
+ assembly **must** set `search: false` on every `@deepseek-ai/dsh-tool-web`
120
+ entry (the global one and all agent presets); `web_fetch` stays enabled:
121
+
122
+ ```yaml
123
+ - id: tool-web
124
+ name: '@deepseek-ai/dsh-tool-web'
125
+ config: { fetch: true, search: false, searchTimeoutMs: 60000 }
126
+ ```
127
+
128
+ If any preset still has `search: true`, startup reports a duplicate
129
+ `web_search`; either disable it or set `modelControlled: false` to keep the
130
+ official tool. A system-prompt section teaches the model when to use the four
131
+ optional filters.
132
+
79
133
  Fully restart `dsh web` afterwards (patch changes do not HMR). The model's tool
80
- catalog gains `web_search` in new sessions.
134
+ catalog gains the extended `web_search` in new sessions.
81
135
 
82
136
  ### Zero-config credential derivation
83
137
 
@@ -99,9 +153,43 @@ the search route.
99
153
  ```json
100
154
  POST {baseURL}/v1/tools/search
101
155
  Authorization: Bearer <wbk_ key>
102
- { "query": "...", "max_results": 5, "blocked_domains": [...], "freshness": "d1|m1|y1" }
156
+ {
157
+ "query": "...",
158
+ "type": "text2text",
159
+ "max_results": 5,
160
+ "allowed_domains": ["go.dev"],
161
+ "blocked_domains": ["reddit.com"],
162
+ "freshness": "d1"
163
+ }
103
164
  ```
104
165
 
166
+ Every parameter the upstream `workbuddy.cn/agenttool/v1/search` accepts is
167
+ covered. The manager route validates the known optional fields and forwards
168
+ the body verbatim; the 0057 gateway pins `type`, applies `max_results`,
169
+ passes `allowed_domains`/`freshness` upstream and appends `-site:<domain>`
170
+ for `blocked_domains` (official CLI semantics).
171
+
172
+ | agenttool parameter | Plugin config key | Values / default |
173
+ |---|---|---|
174
+ | `query` | (from the seam request) | required |
175
+ | `type` | `type` | `"text2text"` (default) |
176
+ | `max_results` | `maxResults` | 1..20, default `5`; seam request `maxResults` wins |
177
+ | `allowed_domains` | `allowedDomains` | string[]; scheme/path stripped, deduped; empty = omitted |
178
+ | `blocked_domains` | `blockedDomains` | string[]; same normalization; empty = omitted |
179
+ | `freshness` | `freshness` | `d1` \| `m1` \| `y1`; unset = omitted |
180
+
181
+ The DSH web seam's `WebSearchRequest` carries only `query` + `maxResults` in
182
+ its type, but `ctx.web.search()` passes the request object through untouched.
183
+ In default mode (v0.4.0) the other four parameters are deployment-level
184
+ defaults in this plugin's config. In `modelControlled: true` mode (v0.4.1) the
185
+ plugin-owned tool exposes them to the model per call. For direct callers each
186
+ one also accepts a **per-request override**, in camelCase or the upstream
187
+ snake_case spelling — `type`, `maxResults`/`max_results`,
188
+ `allowedDomains`/`allowed_domains`, `blockedDomains`/`blocked_domains`,
189
+ `freshness`. Request overrides win over config; invalid `freshness` fails
190
+ locally as `WEB_PROVIDER_ERROR` without spending an account-pool search quota.
191
+ Empty optional values are omitted from the wire body.
192
+
105
193
  Response is the upstream agenttool envelope passed through verbatim:
106
194
 
107
195
  ```json
@@ -120,6 +208,9 @@ sources; url-scheme filter + dedupe; `maxResults` truncation owned by the seam).
120
208
  | Manager unreachable / non-2xx / upstream business code ≠ 0 | `WEB_PROVIDER_ERROR` |
121
209
  | All-pool search quota exhausted (15001, gateway 429 `quota_web_search`) | `WEB_PROVIDER_ERROR` (message says quota) |
122
210
  | Caller cancellation | `WEB_ABORTED` |
211
+ | `timeoutMs` elapsed | `WEB_PROVIDER_ERROR` (message says timed out) |
212
+ | Invalid per-request `freshness` | `WEB_PROVIDER_ERROR` (no request sent) |
213
+ | Invalid config (`freshness` / array / `maxResults` bounds) | rejected by the Config schema at assembly |
123
214
 
124
215
  ## License
125
216
 
package/lib/index.js CHANGED
@@ -7,13 +7,64 @@
7
7
  * workbuddy-manager**:
8
8
  *
9
9
  * POST {baseURL}/v1/tools/search
10
- * body: {"query": "...", "max_results": 5, "blocked_domains": [...], "freshness": "d1|m1|y1"}
10
+ * body: {
11
+ * "query": "...",
12
+ * "type": "text2text",
13
+ * "max_results": 5,
14
+ * "allowed_domains": ["go.dev"],
15
+ * "blocked_domains": ["reddit.com"],
16
+ * "freshness": "d1|m1|y1"
17
+ * }
11
18
  * resp: {"code":0, "results":[{title,url,snippet}], ...} (agenttool envelope passthrough)
12
19
  * or {"error":"...", "code":"quota_web_search", ...} on 429 (all-pool 15001)
13
20
  *
21
+ * The manager route forwards the body verbatim (no rewriting), and the 0057
22
+ * gateway maps `allowed_domains`/`freshness`/`type` onto the upstream
23
+ * `workbuddy.cn/agenttool/v1/search` request and appends `blocked_domains` to
24
+ * the query text as `-site:<domain>` (official CLI semantics).
25
+ *
26
+ * ## Full parameter set (v0.4.0)
27
+ *
28
+ * The DSH web seam's `WebSearchRequest` only carries `query` + `maxResults`,
29
+ * so the remaining agenttool parameters are supplied by this plugin's config
30
+ * (deployment-level defaults). Every parameter also accepts a *per-request*
31
+ * override on the search request object, in either camelCase or the upstream
32
+ * snake_case spelling — this keeps the provider usable from a direct caller or
33
+ * a future seam that exposes the extra fields, without patching DSH core:
34
+ *
35
+ * | upstream /v1/tools/search | config key | request override(s) |
36
+ * |---------------------------|-----------------|----------------------------------------|
37
+ * | query | (request) | query |
38
+ * | type | type | type |
39
+ * | max_results | maxResults | maxResults / max_results |
40
+ * | allowed_domains | allowedDomains | allowedDomains / allowed_domains |
41
+ * | blocked_domains | blockedDomains | blockedDomains / blocked_domains |
42
+ * | freshness | freshness | freshness |
43
+ *
44
+ * Empty domain lists / an unset freshness are omitted from the wire body;
45
+ * `max_results` is clamped to 1..20 (the 0057 gateway's bound).
46
+ *
14
47
  * Provider id registers as "workbuddy-gateway"; pin it with
15
48
  * `web.searchProvider: workbuddy-gateway` in the profile patch.
16
49
  *
50
+ * ## Model-facing tool (v0.4.1, optional)
51
+ *
52
+ * The official `@deepseek-ai/dsh-tool-web` registers `web_search` with only
53
+ * `queries` and drops every other argument before calling `ctx.web.search()`.
54
+ * When `modelControlled: true`, this plugin registers its own `web_search`
55
+ * tool (same name) with the extra agenttool parameters exposed to the model:
56
+ *
57
+ * allowedDomains / blockedDomains / freshness / maxResults
58
+ *
59
+ * Assembly must disable the official registration in every `tool-web` entry
60
+ * (`search: false`) — `ctx.tools.register()` rejects duplicate names. The
61
+ * official `web_fetch` stays untouched. `ctx.web.search()` passes the request
62
+ * object through unchanged, so the provider's per-request overrides map the
63
+ * model's choices onto the gateway body without patching DSH core.
64
+ *
65
+ * When `modelControlled: false` (default), the plugin only registers the
66
+ * provider; the official tool keeps working with the config-level defaults.
67
+ *
17
68
  * ## Credential & endpoint resolution (zero-config by default)
18
69
  *
19
70
  * With no `baseURL`/`apiKeyEnv` in this plugin's config, both are **derived
@@ -44,12 +95,18 @@ const PROVIDER_ID = "workbuddy-gateway";
44
95
  /** Cordis plugin name used by loader diagnostics. */
45
96
  const name = "web-search-workbuddy";
46
97
 
47
- /** The web seam this provider registers into. */
98
+ /** The web seam this provider registers into (tools/systemPrompt are optional). */
48
99
  const inject = ["web"];
49
100
 
50
101
  /** Loader package that owns the pi-ai provider profiles. */
51
102
  const PI_AI_PACKAGE = "@deepseek-ai/dsh-llm-pi-ai";
52
103
 
104
+ /** agenttool `freshness` enum (d1 = day, m1 = month, y1 = year). */
105
+ const FRESHNESS_VALUES = ["d1", "m1", "y1"];
106
+
107
+ /** 0057 gateway / agenttool result-count bound. */
108
+ const MAX_RESULTS_CAP = 20;
109
+
53
110
  const Config = z.object({
54
111
  /**
55
112
  * Gateway base. Omit to derive it from the conversation's model-provider
@@ -65,6 +122,24 @@ const Config = z.object({
65
122
  timeoutMs: z.number().step(1).min(1000).default(30000).volatile(),
66
123
  /** Default max_results when the request omits maxResults. */
67
124
  maxResults: z.number().step(1).min(1).max(20).default(5).volatile(),
125
+ /** agenttool request type; the 0057 gateway pins "text2text" upstream. */
126
+ type: z.string().default("text2text").volatile(),
127
+ /** Only return results from these domains (agenttool allowed_domains). */
128
+ allowedDomains: z.array(z.string()).volatile(),
129
+ /** Exclude these domains; the gateway appends " -site:<domain>" to the query. */
130
+ blockedDomains: z.array(z.string()).volatile(),
131
+ /** Recency filter: d1 | m1 | y1. Omit to leave it unset. */
132
+ freshness: z.union(FRESHNESS_VALUES.map((value) => z.const(value))).volatile(),
133
+ /**
134
+ * Register the plugin-owned `web_search` tool with model-visible filter
135
+ * parameters. Requires `tool-web.search: false` in every preset. Default
136
+ * false = keep the official `@deepseek-ai/dsh-tool-web` tool.
137
+ */
138
+ modelControlled: z.boolean().default(false).volatile(),
139
+ /** Max queries accepted by one plugin-owned `web_search` call. */
140
+ modelMaxQueries: z.number().step(1).min(1).max(10).default(10).volatile(),
141
+ /** Per-source summary cap for the plugin-owned tool output. */
142
+ modelSummaryMaxChars: z.number().step(1).min(100).default(800).volatile(),
68
143
  });
69
144
 
70
145
  /**
@@ -196,6 +271,364 @@ async function searchConfigured(ctx, options, llmProvider) {
196
271
  return hasKey && hasURL;
197
272
  }
198
273
 
274
+ /** First defined value among the per-request overrides and the config default. */
275
+ function pick(...values) {
276
+ for (const value of values) if (value !== undefined && value !== null) return value;
277
+ return undefined;
278
+ }
279
+
280
+ /**
281
+ * Normalize an agenttool domain list: trim, strip scheme/path, drop blanks and
282
+ * case-insensitive duplicates. The gateway appends these to `-site:` (blocked)
283
+ * or forwards them as-is (allowed), so bare hostnames are required on the wire.
284
+ */
285
+ function cleanDomains(value) {
286
+ if (!Array.isArray(value)) return [];
287
+ const out = [];
288
+ const seen = new Set();
289
+ for (const raw of value) {
290
+ if (typeof raw !== "string") continue;
291
+ let domain = raw.trim();
292
+ if (domain.length === 0) continue;
293
+ domain = domain.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "");
294
+ const cut = domain.search(/[/?#]/);
295
+ if (cut >= 0) domain = domain.slice(0, cut);
296
+ domain = domain.replace(/^\./, "");
297
+ if (domain.length === 0) continue;
298
+ const key = domain.toLowerCase();
299
+ if (seen.has(key)) continue;
300
+ seen.add(key);
301
+ out.push(domain);
302
+ }
303
+ return out;
304
+ }
305
+
306
+ /** Clamp max_results into the 0057 gateway's 1..20 bound. */
307
+ function clampMaxResults(value, fallback) {
308
+ const n = Number(value);
309
+ if (!Number.isFinite(n) || n <= 0) return fallback;
310
+ return Math.min(MAX_RESULTS_CAP, Math.max(1, Math.trunc(n)));
311
+ }
312
+
313
+ /**
314
+ * Model-facing `web_search` arguments when `modelControlled` is enabled.
315
+ * `queries` is the official shape; the rest are extras this plugin forwards
316
+ * into `ctx.web.search()`'s request object (which the seam passes through).
317
+ */
318
+ const MODEL_PARAMETERS = {
319
+ type: "object",
320
+ properties: {
321
+ queries: {
322
+ type: "array",
323
+ items: { type: "string" },
324
+ description: "1–10 search queries; their results are merged.",
325
+ },
326
+ allowedDomains: {
327
+ type: "array",
328
+ items: { type: "string" },
329
+ description: "Only return results from these domains (e.g. [\"go.dev\"]).",
330
+ },
331
+ blockedDomains: {
332
+ type: "array",
333
+ items: { type: "string" },
334
+ description: "Exclude these domains (e.g. [\"reddit.com\"]).",
335
+ },
336
+ freshness: {
337
+ type: "string",
338
+ enum: ["d1", "m1", "y1"],
339
+ description: "Recency filter: d1 = past day, m1 = past month, y1 = past year.",
340
+ },
341
+ maxResults: {
342
+ type: "integer",
343
+ description: "Upper bound on sources returned (1..20). Defaults to the plugin config.",
344
+ },
345
+ },
346
+ required: ["queries"],
347
+ additionalProperties: false,
348
+ };
349
+
350
+ /** The canonical `web_search` output schema (same shape as the official tool). */
351
+ const MODEL_OUTPUT_SCHEMA = {
352
+ type: "object",
353
+ additionalProperties: false,
354
+ properties: {
355
+ content: { type: "string" },
356
+ sources: {
357
+ type: "array",
358
+ items: {
359
+ type: "object",
360
+ additionalProperties: false,
361
+ properties: {
362
+ url: { type: "string" },
363
+ title: { type: "string" },
364
+ snippet: { type: "string" },
365
+ summary: { type: "string" },
366
+ publishedAt: { type: "string" },
367
+ },
368
+ required: ["url"],
369
+ },
370
+ },
371
+ truncated: { type: "boolean" },
372
+ },
373
+ required: ["sources", "truncated"],
374
+ };
375
+
376
+ /** Collapse whitespace and cap one source summary, like the official tool. */
377
+ function boundSummary(summary, cap) {
378
+ const text = String(summary ?? "").replace(/\s+/gu, " ").trim();
379
+ if (text.length === 0) return undefined;
380
+ return text.length <= cap ? text : `${text.slice(0, Math.max(0, cap - 1))}…`;
381
+ }
382
+
383
+ /** Project one seam source into the model-facing (lossless JSON) shape. */
384
+ function modelSource(source, cap) {
385
+ const summary = boundSummary(source.summary, cap);
386
+ const snippet = typeof source.snippet === "string" ? source.snippet.slice(0, 200) : undefined;
387
+ return {
388
+ url: source.url,
389
+ ...(source.title !== undefined ? { title: source.title } : {}),
390
+ ...(snippet !== undefined && snippet.length > 0 ? { snippet } : {}),
391
+ ...(summary !== undefined ? { summary } : {}),
392
+ ...(source.publishedAt !== undefined ? { publishedAt: source.publishedAt } : {}),
393
+ };
394
+ }
395
+
396
+ /** Merge per-query seam results round-robin, dedupe by URL, cap at maxResults. */
397
+ function mergeModelResults(queries, results, maxResults) {
398
+ const seen = new Set();
399
+ const sources = [];
400
+ let ranks = 0;
401
+ for (const result of results) ranks = Math.max(ranks, result.sources.length);
402
+ let dropped = false;
403
+ merge: for (let rank = 0; rank < ranks; rank++) {
404
+ for (const result of results) {
405
+ const source = result.sources[rank];
406
+ if (source === undefined || seen.has(source.url)) continue;
407
+ seen.add(source.url);
408
+ if (sources.length === maxResults) { dropped = true; break merge; }
409
+ sources.push(source);
410
+ }
411
+ }
412
+ const contents = results.flatMap((result, index) =>
413
+ result.content !== undefined && result.content.length > 0
414
+ ? [`### ${queries[index]}\n\n${result.content}`] : []);
415
+ return {
416
+ ...(contents.length > 0 ? { content: contents.join("\n\n") } : {}),
417
+ sources,
418
+ truncated: results.some((result) => result.truncated) || dropped,
419
+ };
420
+ }
421
+
422
+ /** Self-contained fallback when the official renderer helpers are unavailable. */
423
+ function fallbackFormatSearchOutput(result) {
424
+ const parts = ["External web content follows."];
425
+ if (result.content !== undefined && result.content.length > 0) parts.push(result.content);
426
+ const sources = Array.isArray(result.sources) ? result.sources : [];
427
+ if (sources.length > 0) {
428
+ const lines = sources.map((source) => {
429
+ let label = typeof source.title === "string" && source.title.length > 0 ? source.title : undefined;
430
+ if (label === undefined) {
431
+ try { label = new URL(source.url).hostname; } catch { label = source.url; }
432
+ }
433
+ const excerpt = typeof source.summary === "string" && source.summary.length > 0
434
+ ? source.summary : (typeof source.snippet === "string" ? source.snippet : undefined);
435
+ const meta = [
436
+ ...(excerpt !== undefined && excerpt.length > 0 ? [excerpt] : []),
437
+ ...(typeof source.publishedAt === "string" && source.publishedAt.length > 0 ? [`(${source.publishedAt})`] : []),
438
+ ];
439
+ return `- [${label}](${source.url})${meta.length > 0 ? ` — ${meta.join(" ")}` : ""}`;
440
+ });
441
+ parts.push(`Sources:\n${lines.join("\n")}`);
442
+ } else if (result.content === undefined || result.content.length === 0) {
443
+ parts.push("No results found.");
444
+ }
445
+ if (result.truncated) parts.push(`(Showing the first ${sources.length} sources. Refine the query for more.)`);
446
+ parts.push("Cite the relevant URLs above as markdown links in your answer.");
447
+ return parts.join("\n\n");
448
+ }
449
+
450
+ /** Validate the plugin-owned tool's arguments; return an Error or undefined. */
451
+ function validateModelArgs(args, maxQueries) {
452
+ if (typeof args !== "object" || args === null || Array.isArray(args)) return new Error("web_search arguments must be an object");
453
+ const a = args;
454
+ if (!Array.isArray(a.queries)) return new Error("queries must be an array of strings");
455
+ if (a.queries.length === 0) return new Error("queries must contain at least one query");
456
+ if (a.queries.length > maxQueries) return new Error(`queries must contain at most ${maxQueries} queries`);
457
+ if (a.queries.some((q) => typeof q !== "string" || q.trim().length === 0)) return new Error("each query must be a non-empty string");
458
+ for (const key of ["allowedDomains", "blockedDomains"]) {
459
+ if (a[key] !== undefined && (!Array.isArray(a[key]) || a[key].some((d) => typeof d !== "string"))) {
460
+ return new Error(`${key} must be an array of strings`);
461
+ }
462
+ }
463
+ if (a.freshness !== undefined && !FRESHNESS_VALUES.includes(a.freshness)) {
464
+ return new Error(`freshness must be one of ${FRESHNESS_VALUES.join(", ")}`);
465
+ }
466
+ if (a.maxResults !== undefined && (!Number.isInteger(a.maxResults) || a.maxResults < 1 || a.maxResults > MAX_RESULTS_CAP)) {
467
+ return new Error(`maxResults must be an integer in 1..${MAX_RESULTS_CAP}`);
468
+ }
469
+ return undefined;
470
+ }
471
+
472
+ /**
473
+ * Replayable presentation meta for the plugin-owned tool, matching the
474
+ * official `WebSearchMeta` shape (structured sources, truncation, answer).
475
+ */
476
+ function modelSearchMeta(value) {
477
+ const sources = (Array.isArray(value?.sources) ? value.sources : []).map((source) => ({
478
+ url: source.url,
479
+ ...(typeof source.title === "string" ? { title: source.title } : {}),
480
+ ...(typeof source.snippet === "string" ? { snippet: source.snippet } : {}),
481
+ ...(typeof source.publishedAt === "string" ? { publishedAt: source.publishedAt } : {}),
482
+ }));
483
+ return {
484
+ sources,
485
+ truncated: value?.truncated === true,
486
+ ...(typeof value?.content === "string" ? { answer: value.content } : {}),
487
+ };
488
+ }
489
+
490
+ /** Pending-call card: same generic search card as the official tool. */
491
+ function modelPresentCall(args) {
492
+ const title = Array.isArray(args?.queries) ? args.queries.join(", ") : "";
493
+ return { card: "generic", title, kind: "search", rawInput: title };
494
+ }
495
+
496
+ /** Completed-call card: same `card: "web"` citation list as the official tool. */
497
+ function modelPresentResult(args, result) {
498
+ if (result.isError) return undefined;
499
+ const meta = result.meta;
500
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) return undefined;
501
+ if (!Array.isArray(meta.sources) || typeof meta.truncated !== "boolean") return undefined;
502
+ return {
503
+ card: "web",
504
+ kind: "search",
505
+ title: Array.isArray(args?.queries) ? args.queries.join(", ") : "",
506
+ sources: meta.sources,
507
+ truncated: meta.truncated,
508
+ ...(typeof meta.answer === "string" ? { answer: meta.answer } : {}),
509
+ };
510
+ }
511
+
512
+ /**
513
+ * Register the model-facing `web_search` tool. Requires the official tool-web
514
+ * `search` registration to be disabled in every preset; this plugin owns the
515
+ * duplicate name. The extras are passed to `ctx.web.search()` untouched,
516
+ * reaching the provider as per-request overrides (see `buildSearchBody`).
517
+ *
518
+ * Registration is deferred through `ctx.inject(['tools', 'systemPrompt'], …)`
519
+ * so the plugin does not require those services when `modelControlled` is off.
520
+ */
521
+ function registerModelTool(ctx, config) {
522
+ ctx.inject(["tools", "systemPrompt"], (child) => {
523
+ const tools = child.get("tools");
524
+ const systemPrompt = child.get("systemPrompt");
525
+ if (tools === undefined || systemPrompt === undefined) return;
526
+ const o = {
527
+ modelMaxQueries: config.modelMaxQueries.get(),
528
+ modelSummaryMaxChars: config.modelSummaryMaxChars.get(),
529
+ maxResults: config.maxResults.get(),
530
+ timeoutMs: config.timeoutMs.get(),
531
+ };
532
+
533
+ const disposeTool = tools.register({
534
+ name: "web_search",
535
+ description: "Search the web for current information. Optionally restrict domains, exclude sites, filter by recency, and cap the number of sources.",
536
+ parameters: MODEL_PARAMETERS,
537
+ output: {
538
+ schema: MODEL_OUTPUT_SCHEMA,
539
+ render: (_args, value) => [{ type: "text", text: fallbackFormatSearchOutput(value) }],
540
+ presentationMeta: (_args, value) => modelSearchMeta(value),
541
+ },
542
+ timeoutMs: o.timeoutMs,
543
+ isConcurrencySafe: () => true,
544
+ presentCall: modelPresentCall,
545
+ presentResult: modelPresentResult,
546
+ async execute(args, exec) {
547
+ const invalid = validateModelArgs(args, o.modelMaxQueries);
548
+ if (invalid !== undefined) throw invalid;
549
+ const { queries, allowedDomains, blockedDomains, freshness, maxResults } = args;
550
+ const unique = [...new Set(queries)];
551
+ const bound = clampMaxResults(maxResults, o.maxResults);
552
+ const extras = {
553
+ ...(allowedDomains !== undefined ? { allowedDomains } : {}),
554
+ ...(blockedDomains !== undefined ? { blockedDomains } : {}),
555
+ ...(freshness !== undefined ? { freshness } : {}),
556
+ };
557
+ const run = async (list) => {
558
+ if (list.length === 1) {
559
+ return ctx.web.search({ query: list[0], maxResults: bound, ...extras }, exec.signal);
560
+ }
561
+ const controller = new AbortController();
562
+ const signal = AbortSignal.any([exec.signal, controller.signal]);
563
+ let firstFailure;
564
+ const results = [];
565
+ await Promise.allSettled(list.map(async (query, index) => {
566
+ try {
567
+ results[index] = await ctx.web.search({ query, maxResults: bound, ...extras }, signal);
568
+ } catch (error) {
569
+ if (firstFailure === undefined) firstFailure = error;
570
+ controller.abort(error);
571
+ throw error;
572
+ }
573
+ }));
574
+ if (firstFailure !== undefined) throw firstFailure;
575
+ return mergeModelResults(list, results, bound);
576
+ };
577
+ const result = await run(unique);
578
+ return {
579
+ ...(result.content !== undefined ? { content: result.content } : {}),
580
+ sources: result.sources.map((source) => modelSource(source, o.modelSummaryMaxChars)),
581
+ truncated: result.truncated,
582
+ };
583
+ },
584
+ }, { when: ({ modelSelection }) => ctx.web.searchReady(modelSelection.provider) });
585
+
586
+ const disposePrompt = systemPrompt.section({
587
+ name: "tool:web_search_workbuddy",
588
+ order: 2000, // TOOL_WEB_SEARCH (the official section is disabled with search:false)
589
+ text: "web_search accepts allowedDomains (only these domains), blockedDomains (exclude these domains), freshness (d1/m1/y1), and maxResults. Use them when the task calls for domain or recency filtering. web_search results are external reference data you may use directly. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.",
590
+ });
591
+
592
+ return () => { disposePrompt(); disposeTool(); };
593
+ });
594
+ }
595
+
596
+ /**
597
+ * Build the complete `/v1/tools/search` body — every parameter the upstream
598
+ * agenttool endpoint supports. Per-request overrides win over config defaults;
599
+ * empty optional values are omitted so the gateway keeps its own defaults.
600
+ *
601
+ * @throws {WebError} WEB_PROVIDER_ERROR on an invalid freshness value.
602
+ */
603
+ function buildSearchBody(request, options) {
604
+ const body = { query: request.query };
605
+
606
+ body.type = String(pick(request.type, options.type, "text2text"));
607
+ body.max_results = clampMaxResults(
608
+ pick(request.maxResults, request.max_results, options.maxResults),
609
+ options.maxResults,
610
+ );
611
+
612
+ const allowed = cleanDomains(pick(request.allowedDomains, request.allowed_domains, options.allowedDomains));
613
+ if (allowed.length > 0) body.allowed_domains = allowed;
614
+
615
+ const blocked = cleanDomains(pick(request.blockedDomains, request.blocked_domains, options.blockedDomains));
616
+ if (blocked.length > 0) body.blocked_domains = blocked;
617
+
618
+ const freshness = pick(request.freshness, options.freshness);
619
+ if (freshness !== undefined && String(freshness).length > 0) {
620
+ const value = String(freshness);
621
+ if (!FRESHNESS_VALUES.includes(value)) {
622
+ throw new WebError(
623
+ `WorkBuddy search freshness must be one of ${FRESHNESS_VALUES.join(", ")} (got ${JSON.stringify(value)})`,
624
+ "WEB_PROVIDER_ERROR",
625
+ );
626
+ }
627
+ body.freshness = value;
628
+ }
629
+ return body;
630
+ }
631
+
199
632
  /** Map the agenttool envelope to the seam's normalized result. */
200
633
  function mapResponse(data) {
201
634
  const results = Array.isArray(data?.results) ? data.results : [];
@@ -217,9 +650,12 @@ function mapResponse(data) {
217
650
  return { sources, truncated: false };
218
651
  }
219
652
 
220
- /** One search against the gateway. Honors `signal` for cancellation. */
653
+ /** One search against the gateway. Honors `signal` and `timeoutMs`. */
221
654
  async function search(ctx, options, request, signal) {
222
655
  const { baseURL, apiKey } = await resolveTarget(ctx, options, signal);
656
+ const body = buildSearchBody(request, options);
657
+ const timeoutSignal = AbortSignal.timeout(options.timeoutMs ?? 30000);
658
+ const combinedSignal = signal !== undefined ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
223
659
 
224
660
  let response;
225
661
  try {
@@ -230,16 +666,20 @@ async function search(ctx, options, request, signal) {
230
666
  "content-type": "application/json",
231
667
  authorization: `Bearer ${apiKey}`,
232
668
  },
233
- body: JSON.stringify({
234
- query: request.query,
235
- max_results: request.maxResults ?? options.maxResults,
236
- }),
237
- ...(signal !== undefined ? { signal } : {}),
669
+ body: JSON.stringify(body),
670
+ signal: combinedSignal,
238
671
  });
239
672
  } catch (error) {
240
673
  if (signal?.aborted === true || (error instanceof DOMException && error.name === "AbortError")) {
241
674
  throw new WebError("WorkBuddy gateway search aborted", "WEB_ABORTED", { cause: signal?.reason ?? error });
242
675
  }
676
+ if (timeoutSignal.aborted) {
677
+ throw new WebError(
678
+ `WorkBuddy gateway search timed out after ${options.timeoutMs}ms`,
679
+ "WEB_PROVIDER_ERROR",
680
+ { cause: error },
681
+ );
682
+ }
243
683
  throw new WebError(
244
684
  `WorkBuddy gateway search request failed: ${String(error)}\n\nThe web request used endpoint ${JSON.stringify(`${baseURL}/v1/tools/search`)}. Check that workbuddy-manager (with the /v1/tools/search passthrough) is running and reachable.`,
245
685
  "WEB_PROVIDER_ERROR",
@@ -274,6 +714,9 @@ async function search(ctx, options, request, signal) {
274
714
  data = await response.json();
275
715
  } catch (error) {
276
716
  if (signal?.aborted === true) throw new WebError("WorkBuddy gateway search aborted", "WEB_ABORTED", { cause: signal.reason });
717
+ if (timeoutSignal.aborted) {
718
+ throw new WebError(`WorkBuddy gateway search timed out after ${options.timeoutMs}ms`, "WEB_PROVIDER_ERROR", { cause: error });
719
+ }
277
720
  throw new WebError(`WorkBuddy gateway returned an unprocessable response body: ${String(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
278
721
  }
279
722
 
@@ -292,7 +735,9 @@ async function search(ctx, options, request, signal) {
292
735
  /**
293
736
  * Register the gateway-backed search provider with ctx.web. Endpoint and
294
737
  * credential default to the conversation's own model-provider route; `ready()`
295
- * answers presence (tool-web uses it to admit `web_search` into a request).
738
+ * answers presence (the tool uses it to admit `web_search` into a request).
739
+ * When `modelControlled` is on, also register the plugin-owned model-facing
740
+ * `web_search` tool (official `tool-web.search` must be disabled).
296
741
  */
297
742
  function apply(ctx, config) {
298
743
  const options = () => ({
@@ -300,6 +745,10 @@ function apply(ctx, config) {
300
745
  apiKeyEnv: config.apiKeyEnv.get(),
301
746
  timeoutMs: config.timeoutMs.get(),
302
747
  maxResults: config.maxResults.get(),
748
+ type: config.type.get(),
749
+ allowedDomains: config.allowedDomains.get(),
750
+ blockedDomains: config.blockedDomains.get(),
751
+ freshness: config.freshness.get(),
303
752
  });
304
753
 
305
754
  ctx.web.registerSearchProvider({
@@ -308,6 +757,8 @@ function apply(ctx, config) {
308
757
  ready: (llmProvider) => searchConfigured(ctx, options(), llmProvider),
309
758
  search: (request, signal) => search(ctx, options(), request, signal),
310
759
  });
760
+
761
+ if (config.modelControlled.get() === true) registerModelTool(ctx, config);
311
762
  }
312
763
 
313
764
  export { Config, PROVIDER_ID, apply, inject, name };
@@ -1,7 +1,12 @@
1
1
  /**
2
2
  * dsh-web-search-workbuddy — WorkBuddy gateway-backed search provider
3
3
  * for the DSH web capability seam. See README.md and lib/index.js.
4
+ *
5
+ * v0.4.0: full agenttool/v1/search parameter set (type / max_results /
6
+ * allowed_domains / blocked_domains / freshness).
4
7
  */
8
+ /** Recency filter accepted by agenttool/v1/search. */
9
+ export type WebSearchFreshness = 'd1' | 'm1' | 'y1';
5
10
  export interface WebSearchWorkBuddyConfig {
6
11
  /** Gateway base (manager reverse-proxy or the wb2api-go port directly). */
7
12
  baseURL: string;
@@ -9,8 +14,37 @@ export interface WebSearchWorkBuddyConfig {
9
14
  apiKeyEnv: string;
10
15
  /** Single-request timeout in ms. */
11
16
  timeoutMs: number;
12
- /** Default max_results when the search request omits maxResults. */
17
+ /** Default max_results when the search request omits maxResults (1..20). */
13
18
  maxResults: number;
19
+ /** agenttool request type; fixed "text2text" upstream. Defaults to "text2text". */
20
+ type: string;
21
+ /** Only return results from these domains (agenttool allowed_domains). */
22
+ allowedDomains: string[];
23
+ /** Excluded domains; the 0057 gateway appends " -site:<domain>" to the query. */
24
+ blockedDomains: string[];
25
+ /** Recency filter; omitted = no freshness constraint. */
26
+ freshness: WebSearchFreshness;
27
+ /**
28
+ * v0.4.1: register a plugin-owned `web_search` tool exposing the filter
29
+ * parameters to the model. Requires `tool-web.search: false` in every preset.
30
+ */
31
+ modelControlled: boolean;
32
+ /** Upper bound on queries in one plugin-owned `web_search` call. */
33
+ modelMaxQueries: number;
34
+ /** Per-source summary cap in the plugin-owned tool's output. */
35
+ modelSummaryMaxChars: number;
36
+ }
37
+ /**
38
+ * Optional per-request overrides accepted by the provider's `search()` in
39
+ * addition to the seam's `query` / `maxResults`. camelCase and upstream
40
+ * snake_case spellings are equivalent; request values win over config.
41
+ */
42
+ export interface WebSearchWorkBuddyRequestOverrides {
43
+ type?: string;
44
+ max_results?: number;
45
+ allowed_domains?: string[];
46
+ blocked_domains?: string[];
47
+ freshness?: WebSearchFreshness | string;
14
48
  }
15
49
  /** Stable provider id this plugin registers under. */
16
50
  export declare const PROVIDER_ID: "workbuddy-gateway";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-web-search-workbuddy",
3
3
  "description": "WorkBuddy gateway-backed search provider (agenttool /v1/tools/search passthrough via the account-pool gateway) for the DeepSeek Harness web capability seam (ctx.web)",
4
- "version": "0.3.0",
4
+ "version": "0.4.1",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/types/index.d.ts",