dsh-web-search-workbuddy 0.4.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,11 @@ 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
+
9
14
  **v0.4.0**: forwards every parameter `workbuddy.cn/agenttool/v1/search`
10
15
  supports (`type`, `max_results`, `allowed_domains`, `blocked_domains`,
11
16
  `freshness`) — see [Protocol](#protocol).
@@ -77,6 +82,9 @@ installed this way; `@deepseek-ai/schemastery` ships as a direct dependency.
77
82
  # allowedDomains: [go.dev] # 只返回这些域
78
83
  # blockedDomains: [reddit.com] # 网关拼成 " -site:reddit.com"
79
84
  # freshness: d1 # d1 | m1 | y1
85
+ # modelControlled: true # v0.4.1:模型自主控制过滤参数
86
+ # modelMaxQueries: 10 # 一次调用最多几条 query
87
+ # modelSummaryMaxChars: 800 # 每条来源摘要上限
80
88
  - id: web
81
89
  name: '@deepseek-ai/dsh-web'
82
90
  config:
@@ -84,12 +92,46 @@ installed this way; `@deepseek-ai/schemastery` ships as a direct dependency.
84
92
  searchProvider: workbuddy-gateway # ← pin this provider
85
93
  - id: tool-web
86
94
  name: '@deepseek-ai/dsh-tool-web'
95
+ # Default mode (modelControlled: false): keep search: true in EVERY preset.
87
96
  config: { fetch: true, search: true, searchTimeoutMs: 60000 }
88
97
  # also set search: true in every agent preset's tool-web entry
89
98
  ```
90
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
+
91
133
  Fully restart `dsh web` afterwards (patch changes do not HMR). The model's tool
92
- catalog gains `web_search` in new sessions.
134
+ catalog gains the extended `web_search` in new sessions.
93
135
 
94
136
  ### Zero-config credential derivation
95
137
 
@@ -136,10 +178,12 @@ for `blocked_domains` (official CLI semantics).
136
178
  | `blocked_domains` | `blockedDomains` | string[]; same normalization; empty = omitted |
137
179
  | `freshness` | `freshness` | `d1` \| `m1` \| `y1`; unset = omitted |
138
180
 
139
- The DSH web seam's `WebSearchRequest` carries only `query` + `maxResults`, so
140
- the other four parameters are deployment-level defaults in this plugin's
141
- config. For direct callers (or a future seam exposing more fields) each one
142
- also accepts a **per-request override**, in camelCase or the upstream
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
143
187
  snake_case spelling — `type`, `maxResults`/`max_results`,
144
188
  `allowedDomains`/`allowed_domains`, `blockedDomains`/`blocked_domains`,
145
189
  `freshness`. Request overrides win over config; invalid `freshness` fails
package/lib/index.js CHANGED
@@ -47,6 +47,24 @@
47
47
  * Provider id registers as "workbuddy-gateway"; pin it with
48
48
  * `web.searchProvider: workbuddy-gateway` in the profile patch.
49
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
+ *
50
68
  * ## Credential & endpoint resolution (zero-config by default)
51
69
  *
52
70
  * With no `baseURL`/`apiKeyEnv` in this plugin's config, both are **derived
@@ -77,7 +95,7 @@ const PROVIDER_ID = "workbuddy-gateway";
77
95
  /** Cordis plugin name used by loader diagnostics. */
78
96
  const name = "web-search-workbuddy";
79
97
 
80
- /** The web seam this provider registers into. */
98
+ /** The web seam this provider registers into (tools/systemPrompt are optional). */
81
99
  const inject = ["web"];
82
100
 
83
101
  /** Loader package that owns the pi-ai provider profiles. */
@@ -112,6 +130,16 @@ const Config = z.object({
112
130
  blockedDomains: z.array(z.string()).volatile(),
113
131
  /** Recency filter: d1 | m1 | y1. Omit to leave it unset. */
114
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(),
115
143
  });
116
144
 
117
145
  /**
@@ -282,6 +310,289 @@ function clampMaxResults(value, fallback) {
282
310
  return Math.min(MAX_RESULTS_CAP, Math.max(1, Math.trunc(n)));
283
311
  }
284
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
+
285
596
  /**
286
597
  * Build the complete `/v1/tools/search` body — every parameter the upstream
287
598
  * agenttool endpoint supports. Per-request overrides win over config defaults;
@@ -424,7 +735,9 @@ async function search(ctx, options, request, signal) {
424
735
  /**
425
736
  * Register the gateway-backed search provider with ctx.web. Endpoint and
426
737
  * credential default to the conversation's own model-provider route; `ready()`
427
- * 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).
428
741
  */
429
742
  function apply(ctx, config) {
430
743
  const options = () => ({
@@ -444,6 +757,8 @@ function apply(ctx, config) {
444
757
  ready: (llmProvider) => searchConfigured(ctx, options(), llmProvider),
445
758
  search: (request, signal) => search(ctx, options(), request, signal),
446
759
  });
760
+
761
+ if (config.modelControlled.get() === true) registerModelTool(ctx, config);
447
762
  }
448
763
 
449
764
  export { Config, PROVIDER_ID, apply, inject, name };
@@ -24,6 +24,15 @@ export interface WebSearchWorkBuddyConfig {
24
24
  blockedDomains: string[];
25
25
  /** Recency filter; omitted = no freshness constraint. */
26
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;
27
36
  }
28
37
  /**
29
38
  * Optional per-request overrides accepted by the provider's `search()` in
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.4.0",
4
+ "version": "0.4.1",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/types/index.d.ts",