digdig 0.1.2 → 0.1.4

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 (107) hide show
  1. package/README.md +31 -34
  2. package/digdig.config.example.json +6 -0
  3. package/dist/claims/deterministic-checks.d.ts.map +1 -1
  4. package/dist/claims/deterministic-checks.js +35 -13
  5. package/dist/claims/deterministic-checks.js.map +1 -1
  6. package/dist/commands/doc-search.d.ts.map +1 -1
  7. package/dist/commands/doc-search.js +3 -0
  8. package/dist/commands/doc-search.js.map +1 -1
  9. package/dist/commands/evidence.js +2 -2
  10. package/dist/commands/evidence.js.map +1 -1
  11. package/dist/commands/extract.d.ts.map +1 -1
  12. package/dist/commands/extract.js +18 -5
  13. package/dist/commands/extract.js.map +1 -1
  14. package/dist/commands/results-add.d.ts +1 -0
  15. package/dist/commands/results-add.d.ts.map +1 -1
  16. package/dist/commands/results-add.js +19 -0
  17. package/dist/commands/results-add.js.map +1 -1
  18. package/dist/commands/review.d.ts.map +1 -1
  19. package/dist/commands/review.js +2 -1
  20. package/dist/commands/review.js.map +1 -1
  21. package/dist/config.d.ts +17 -15
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/config.js +59 -101
  24. package/dist/config.js.map +1 -1
  25. package/dist/deep/dedupe.d.ts +16 -12
  26. package/dist/deep/dedupe.d.ts.map +1 -1
  27. package/dist/deep/dedupe.js +27 -27
  28. package/dist/deep/dedupe.js.map +1 -1
  29. package/dist/deep/degree-utils.d.ts +0 -27
  30. package/dist/deep/degree-utils.d.ts.map +1 -1
  31. package/dist/deep/degree-utils.js +0 -30
  32. package/dist/deep/degree-utils.js.map +1 -1
  33. package/dist/deep/fuse.d.ts +2 -1
  34. package/dist/deep/fuse.d.ts.map +1 -1
  35. package/dist/deep/fuse.js +10 -11
  36. package/dist/deep/fuse.js.map +1 -1
  37. package/dist/deep/graph.d.ts +3 -1
  38. package/dist/deep/graph.d.ts.map +1 -1
  39. package/dist/deep/graph.js +6 -5
  40. package/dist/deep/graph.js.map +1 -1
  41. package/dist/deep/installed-firecrawl.d.ts +2 -1
  42. package/dist/deep/installed-firecrawl.d.ts.map +1 -1
  43. package/dist/deep/installed-firecrawl.js +8 -9
  44. package/dist/deep/installed-firecrawl.js.map +1 -1
  45. package/dist/deep/installed-tavily.d.ts +2 -1
  46. package/dist/deep/installed-tavily.d.ts.map +1 -1
  47. package/dist/deep/installed-tavily.js +6 -4
  48. package/dist/deep/installed-tavily.js.map +1 -1
  49. package/dist/deep/local-doc/indexer.d.ts +13 -3
  50. package/dist/deep/local-doc/indexer.d.ts.map +1 -1
  51. package/dist/deep/local-doc/indexer.js +28 -19
  52. package/dist/deep/local-doc/indexer.js.map +1 -1
  53. package/dist/deep/local-doc/scanner.js +1 -1
  54. package/dist/deep/local-doc/scanner.js.map +1 -1
  55. package/dist/deep/local-doc/searcher.d.ts +1 -0
  56. package/dist/deep/local-doc/searcher.d.ts.map +1 -1
  57. package/dist/deep/local-doc/searcher.js +29 -22
  58. package/dist/deep/local-doc/searcher.js.map +1 -1
  59. package/dist/deep/local-doc/types.d.ts +2 -0
  60. package/dist/deep/local-doc/types.d.ts.map +1 -1
  61. package/dist/deep/local-doc/types.js.map +1 -1
  62. package/dist/deep/session.d.ts +5 -1
  63. package/dist/deep/session.d.ts.map +1 -1
  64. package/dist/deep/session.js +38 -20
  65. package/dist/deep/session.js.map +1 -1
  66. package/dist/entry.d.ts.map +1 -1
  67. package/dist/entry.js +6 -0
  68. package/dist/entry.js.map +1 -1
  69. package/dist/errors.d.ts +1 -0
  70. package/dist/errors.d.ts.map +1 -1
  71. package/dist/errors.js +5 -19
  72. package/dist/errors.js.map +1 -1
  73. package/dist/external-search.d.ts +3 -1
  74. package/dist/external-search.d.ts.map +1 -1
  75. package/dist/external-search.js +41 -16
  76. package/dist/external-search.js.map +1 -1
  77. package/dist/feedback-log.d.ts.map +1 -1
  78. package/dist/feedback-log.js +2 -1
  79. package/dist/feedback-log.js.map +1 -1
  80. package/dist/firecrawl-results.d.ts +3 -0
  81. package/dist/firecrawl-results.d.ts.map +1 -0
  82. package/dist/firecrawl-results.js +27 -0
  83. package/dist/firecrawl-results.js.map +1 -0
  84. package/dist/init.d.ts +1 -11
  85. package/dist/init.d.ts.map +1 -1
  86. package/dist/init.js +67 -51
  87. package/dist/init.js.map +1 -1
  88. package/dist/legacy.d.ts +1 -23
  89. package/dist/legacy.d.ts.map +1 -1
  90. package/dist/legacy.js +2 -57
  91. package/dist/legacy.js.map +1 -1
  92. package/dist/protocol.d.ts +1 -1
  93. package/dist/protocol.d.ts.map +1 -1
  94. package/dist/protocol.js +2 -0
  95. package/dist/protocol.js.map +1 -1
  96. package/dist/runCli.d.ts.map +1 -1
  97. package/dist/runCli.js +126 -79
  98. package/dist/runCli.js.map +1 -1
  99. package/dist/search-filters.d.ts +13 -0
  100. package/dist/search-filters.d.ts.map +1 -0
  101. package/dist/search-filters.js +59 -0
  102. package/dist/search-filters.js.map +1 -0
  103. package/dist/service.d.ts +11 -1
  104. package/dist/service.d.ts.map +1 -1
  105. package/dist/service.js +50 -11
  106. package/dist/service.js.map +1 -1
  107. package/package.json +1 -1
package/dist/runCli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { installedFirecrawlStatus, installedFirecrawlSearch } from './deep/installed-firecrawl.js';
2
2
  import { installedTavilySearch, installedTavilyStatus } from './deep/installed-tavily.js';
3
- import { externalSearch } from './external-search.js';
3
+ import { directFilters, isTimeRange } from './search-filters.js';
4
+ import { externalSearch, searchLimits } from './external-search.js';
4
5
  import { feedbackLog, feedbackError } from './feedback-log.js';
5
6
  /**
6
7
  * SearXNG CLI - CLI Runner (Commander-based)
@@ -15,13 +16,13 @@ import { assertSearXNGConfig } from './service.js';
15
16
  import { SessionStateError } from './deep/session-lock.js';
16
17
  import { createSuccessEnvelope, createErrorEnvelope } from './protocol.js';
17
18
  import { SearchError } from './errors.js';
18
- import { config } from './config.js';
19
+ import { config, EXTERNAL_PROVIDERS } from './config.js';
19
20
  import { OllamaService, MAX_RESULTS as OLLAMA_MAX_RESULTS } from './ollama-service.js';
20
21
  import { DeepSeekService, MAX_RESULTS as DEEPSEEK_MAX_RESULTS } from './deepseek-service.js';
21
22
  import { initConfig } from './init.js';
22
23
  import { runExtract } from './commands/extract.js';
23
24
  import { runGraphAdd } from './commands/graph-add.js';
24
- import { runResultsAdd } from './commands/results-add.js';
25
+ import { runResultsAdd, runResultsPending } from './commands/results-add.js';
25
26
  import { runDocIndex } from './commands/doc-index.js';
26
27
  import { runDocSearch } from './commands/doc-search.js';
27
28
  import { runGraphObfuscateCommand } from './commands/graph-obfuscate.js';
@@ -74,28 +75,56 @@ function agreementLabel(votes) {
74
75
  const parts = votes.map(vote => `${vote.engine} #${vote.position}`);
75
76
  return ` [${votes.length} engines: ${parts.join(', ')}]`;
76
77
  }
77
- /**
78
- * Says so when a filter was asked for but no per-engine confirmation exists.
79
- *
80
- * `--time` and `--lang` go to SearXNG as one request parameter, and which
81
- * engines honour them is the server's business — the payload never reports
82
- * per-engine filter support. Printing a filtered-looking result set without this
83
- * note would let a caller assume the constraint held everywhere.
84
- */
85
- function filterScopeNote(data) {
86
- const requested = [];
87
- if (data.timeRange)
88
- requested.push(`time=${data.timeRange}`);
89
- if (data.language)
90
- requested.push(`lang=${data.language}`);
91
- if (requested.length === 0)
78
+ function searchFilterScope(options, attempts) {
79
+ const requested = {
80
+ ...(options.timeRange && { timeRange: options.timeRange }),
81
+ ...(options.language && { language: options.language }),
82
+ ...(options.page !== undefined && { page: options.page }),
83
+ ...(options.categories?.length && { categories: options.categories }),
84
+ };
85
+ const keys = Object.keys(requested);
86
+ if (!keys.length || !attempts.length)
87
+ return {};
88
+ const providers = {};
89
+ for (const attempt of attempts) {
90
+ // All queries in a batch use the same filters. A successful response
91
+ // confirms this route even when another query on the same route failed.
92
+ if (attempt.status === 'error' && providers[attempt.provider])
93
+ continue;
94
+ const mapped = attempt.provider === 'searxng' ? keys : attempt.mapped ?? [];
95
+ providers[attempt.provider] = {
96
+ forwarded: attempt.status === 'ok' ? mapped : [],
97
+ notForwarded: keys.filter(key => !mapped.includes(key)),
98
+ ...(attempt.status === 'error' && mapped.length && { unconfirmed: mapped }),
99
+ };
100
+ }
101
+ return { filterScope: { requested, providers } };
102
+ }
103
+ function filterScopeNote(scope) {
104
+ if (!scope)
92
105
  return '';
93
- return `*Filter (${requested.join(', ')}) was sent as one request parameter; whether every engine applied it is not reported.*`;
106
+ const lines = [];
107
+ for (const [name, route] of Object.entries(scope.providers)) {
108
+ const values = (keys) => keys.map(key => `${key}=${scope.requested[key]}`).join(', ');
109
+ if (route.forwarded.length)
110
+ lines.push(`${name} forwarded ${values(route.forwarded)}.`);
111
+ if (route.notForwarded.length)
112
+ lines.push(`${name} did not forward ${values(route.notForwarded)}.`);
113
+ if (route.unconfirmed?.length)
114
+ lines.push(`${name} request failed, forwarding unconfirmed for ${values(route.unconfirmed)}.`);
115
+ }
116
+ return lines.join('\n');
94
117
  }
95
118
  function formatAsMarkdown(data) {
96
119
  const lines = [];
97
120
  lines.push(`## Search: ${data.query || 'Unknown'}`);
98
121
  lines.push('');
122
+ const answers = (data.answers ?? []).map((answer) => typeof answer === 'string' ? answer : answer?.answer ?? JSON.stringify(answer)).filter(Boolean);
123
+ if (answers.length) {
124
+ lines.push('**Direct answers**', '');
125
+ for (const answer of answers)
126
+ lines.push(answer, '');
127
+ }
99
128
  const results = data.results || [];
100
129
  if (results.length > 0) {
101
130
  lines.push(`**${results.length}** results`);
@@ -108,6 +137,8 @@ function formatAsMarkdown(data) {
108
137
  }
109
138
  lines.push(`### ${i + 1}. [${r.title || 'No Title'}](${r.url || '#'})${scoreIndicator}${agreementLabel(r.votes)}`);
110
139
  lines.push('');
140
+ if (r.imageUrl)
141
+ lines.push(`[Image](${r.imageUrl})`, '');
111
142
  if (displayText(r)) {
112
143
  lines.push(displayText(r));
113
144
  lines.push('');
@@ -130,11 +161,15 @@ function formatAsMarkdown(data) {
130
161
  lines.push('');
131
162
  }
132
163
  }
133
- else {
164
+ else if (!answers.length) {
134
165
  lines.push('No results found.');
135
166
  lines.push('');
136
167
  }
137
168
  if (data.providerResults?.length) {
169
+ for (const item of data.providerResults) {
170
+ if (item.paginationError)
171
+ lines.push(`Partial ${item.provider} results: page ${item.paginationError.page} failed (${item.paginationError.code}).`, '');
172
+ }
138
173
  lines.push('**Search providers:** ' + data.providerResults.map((item) => `${item.provider} (${item.query}): ${item.status}${item.error ? ` (${item.error})` : ''}, received ${item.received}, returned ${item.returned}`).join(' · '));
139
174
  lines.push('');
140
175
  }
@@ -149,7 +184,7 @@ function formatAsMarkdown(data) {
149
184
  lines.push(`*Unresponsive: ${unresponsive}*`);
150
185
  lines.push('');
151
186
  }
152
- const note = filterScopeNote(data);
187
+ const note = filterScopeNote(data.filterScope);
153
188
  if (note) {
154
189
  lines.push(note);
155
190
  lines.push('');
@@ -300,25 +335,23 @@ function formatSessionReportAsMarkdown(data) {
300
335
  * Search providers reachable through `--engines` magic words. Each is selected
301
336
  * by placing its name in the engine list; every other name goes to SearXNG.
302
337
  */
303
- const EXTERNAL_PROVIDERS = ['ollama', 'deepseek', 'exa', 'tavily', 'firecrawl', 'jina'];
304
338
  const PROVIDER_IMPLS = {
305
339
  ollama: {
306
- configured: () => Boolean(config.ollamaApiKey),
307
340
  maxResults: OLLAMA_MAX_RESULTS,
308
341
  search: (query, limit) => new OllamaService({ apiKey: config.ollamaApiKey }).search({ query, limit }),
309
342
  },
310
343
  deepseek: {
311
- configured: () => Boolean(config.deepseekApiKey),
312
344
  maxResults: DEEPSEEK_MAX_RESULTS,
313
345
  search: (query, limit) => new DeepSeekService({ apiKey: config.deepseekApiKey }).search({ query, limit }),
314
346
  },
315
- exa: { configured: () => Boolean(process.env.EXA_API_KEY), maxResults: 100, search: (query, limit) => externalSearch('exa', process.env.EXA_API_KEY, query, limit) },
316
- tavily: { configured: () => Boolean(process.env.TAVILY_API_KEY), maxResults: 20, search: (query, limit) => externalSearch('tavily', process.env.TAVILY_API_KEY, query, limit) },
317
- firecrawl: { configured: () => Boolean(process.env.FIRECRAWL_API_KEY), maxResults: 100, search: (query, limit) => externalSearch('firecrawl', process.env.FIRECRAWL_API_KEY, query, limit) },
318
- jina: { configured: () => Boolean(process.env.JINA_API_KEY), maxResults: 5, search: (query, limit) => externalSearch('jina', process.env.JINA_API_KEY, query, limit) },
347
+ exa: { maxResults: searchLimits.exa, search: (query, limit, params) => externalSearch('exa', config.exaApiKey, query, limit, params) },
348
+ tavily: { maxResults: searchLimits.tavily, search: (query, limit, params) => externalSearch('tavily', config.tavilyApiKey, query, limit, params) },
349
+ firecrawl: { maxResults: searchLimits.firecrawl, search: (query, limit, params) => externalSearch('firecrawl', config.firecrawlApiKey, query, limit, params) },
350
+ jina: { maxResults: searchLimits.jina, search: (query, limit, params) => externalSearch('jina', config.jinaApiKey, query, limit, params) },
319
351
  };
352
+ const hostSearchHint = 'If your Agent host offers the requested source, call its search tool. To save those results, pipe them to dg results-add <session> --kind search --tool <tool> --query "<query>" --data-stdin.';
320
353
  async function configuredExternalProviders() {
321
- const providers = EXTERNAL_PROVIDERS.filter(p => PROVIDER_IMPLS[p].configured());
354
+ const providers = EXTERNAL_PROVIDERS.filter(p => config[`${p}ApiKey`]);
322
355
  const tavilyCli = await installedTavilyStatus();
323
356
  const firecrawlCli = await installedFirecrawlStatus();
324
357
  if (!providers.includes('firecrawl') && firecrawlCli === 'authenticated')
@@ -334,6 +367,7 @@ async function configuredExternalProviders() {
334
367
  function summarizeAttempts(attempts, returnedKeys) {
335
368
  return attempts.map(attempt => attempt.status === 'ok' ? {
336
369
  query: attempt.query, provider: attempt.provider, status: 'ok', received: attempt.response.results.length,
370
+ ...(attempt.response.paginationError && { paginationError: attempt.response.paginationError }),
337
371
  returned: new Set(attempt.response.results.map(result => resultUrlKey(result)).filter(key => returnedKeys.has(key))).size,
338
372
  } : {
339
373
  query: attempt.query, provider: attempt.provider, status: 'error', received: 0, returned: 0,
@@ -343,10 +377,11 @@ function summarizeAttempts(attempts, returnedKeys) {
343
377
  }
344
378
  function planProviderSearch(engines, tavilyCli = false, firecrawlCli = false) {
345
379
  const selected = EXTERNAL_PROVIDERS.filter(p => engines.includes(p));
380
+ const usable = selected.filter(p => config[`${p}ApiKey`] || (p === 'tavily' && tavilyCli) || (p === 'firecrawl' && firecrawlCli));
346
381
  return {
347
382
  tavilyCli, firecrawlCli,
348
- usable: selected.filter(p => PROVIDER_IMPLS[p].configured() || ((p === 'tavily' && tavilyCli) || (p === 'firecrawl' && firecrawlCli))),
349
- unconfigured: selected.filter(p => !PROVIDER_IMPLS[p].configured() && !((p === 'tavily' && tavilyCli) || (p === 'firecrawl' && firecrawlCli))),
383
+ usable,
384
+ unconfigured: selected.filter(p => !usable.includes(p)),
350
385
  sxngEngines: engines.filter(e => !EXTERNAL_PROVIDERS.includes(e)),
351
386
  };
352
387
  }
@@ -363,13 +398,14 @@ async function searchOneQuery(service, plan, searchOptions, limit) {
363
398
  const attempts = [];
364
399
  const limitNotes = [];
365
400
  for (const provider of plan.usable) {
401
+ const { params, forwarded } = directFilters(provider, searchOptions);
366
402
  const started = Date.now();
367
403
  feedbackLog('provider', 'start', { provider });
368
404
  try {
369
405
  const response = provider === 'tavily' && plan.tavilyCli
370
- ? await installedTavilySearch(searchOptions.query, limit)
371
- : provider === 'firecrawl' && plan.firecrawlCli ? await installedFirecrawlSearch(searchOptions.query, limit)
372
- : await PROVIDER_IMPLS[provider].search(searchOptions.query, limit);
406
+ ? await installedTavilySearch(searchOptions.query, limit, params)
407
+ : provider === 'firecrawl' && plan.firecrawlCli ? await installedFirecrawlSearch(searchOptions.query, limit, params)
408
+ : await PROVIDER_IMPLS[provider].search(searchOptions.query, limit, params);
373
409
  feedbackLog('provider', 'ok', { provider, durationMs: Date.now() - started, count: response.results.length });
374
410
  // The provider caps the count itself, so compare against its ceiling
375
411
  // rather than against what came back: a provider may also return
@@ -379,11 +415,11 @@ async function searchOneQuery(service, plan, searchOptions, limit) {
379
415
  if (limit > applied)
380
416
  limitNotes.push({ provider, requested: limit, applied });
381
417
  providerResponses.push(response);
382
- attempts.push({ provider, query: searchOptions.query, status: 'ok', response });
418
+ attempts.push({ provider, query: searchOptions.query, mapped: forwarded, status: 'ok', response });
383
419
  }
384
420
  catch (error) {
385
421
  feedbackLog('provider', 'error', { provider, durationMs: Date.now() - started, error: feedbackError(error) });
386
- attempts.push({ provider, query: searchOptions.query, status: 'error', error });
422
+ attempts.push({ provider, query: searchOptions.query, mapped: forwarded, status: 'error', error });
387
423
  }
388
424
  }
389
425
  let sxngResponse = null;
@@ -416,7 +452,17 @@ async function runSearchInner(service, options) {
416
452
  console.log(JSON.stringify(createErrorEnvelope('INVALID_LIMIT', 'Limit must be a positive safe integer'), null, 2));
417
453
  return 1;
418
454
  }
419
- const queries = options.queries || (options.query ? [options.query] : []);
455
+ if (options.page !== undefined && (!Number.isSafeInteger(options.page) || options.page <= 0)) {
456
+ console.log(JSON.stringify(createErrorEnvelope('INVALID_PAGE', 'Page must be a positive safe integer'), null, 2));
457
+ return 1;
458
+ }
459
+ const timeRange = options.timeRange;
460
+ if (timeRange !== undefined && !isTimeRange(timeRange)) {
461
+ console.log(JSON.stringify(createErrorEnvelope('INVALID_TIME_RANGE', 'Time range must be day, week, month, year or all'), null, 2));
462
+ return 1;
463
+ }
464
+ const filters = { timeRange, language: options.language, page: options.page, categories: options.categories };
465
+ let queries = options.queries ? [...new Set(options.queries)] : (options.query ? [options.query] : []);
420
466
  if (queries.length === 0) {
421
467
  feedbackLog('validation', 'error', { error: 'MISSING_QUERY' });
422
468
  const envelope = createErrorEnvelope('MISSING_QUERY', 'No search query provided', { hint: 'Use: dg "your search query" or dg --queries "q1,q2,q3"' });
@@ -439,7 +485,7 @@ async function runSearchInner(service, options) {
439
485
  }
440
486
  }
441
487
  const tavilyStatus = engines.includes('tavily') ? await installedTavilyStatus() : 'not_installed';
442
- const tavilyCli = tavilyStatus === 'authenticated' || (tavilyStatus === 'keyless' && !process.env.TAVILY_API_KEY);
488
+ const tavilyCli = tavilyStatus === 'authenticated' || (tavilyStatus === 'keyless' && !config.tavilyApiKey);
443
489
  const firecrawlCli = engines.includes('firecrawl') && await installedFirecrawlStatus() === 'authenticated';
444
490
  // A selected provider without its API key cannot run. Failing loudly beats
445
491
  // silently answering from SearXNG, which would make the provider look active.
@@ -447,10 +493,15 @@ async function runSearchInner(service, options) {
447
493
  const unconfigured = planProviderSearch(engines, tavilyCli, firecrawlCli).unconfigured;
448
494
  if (unconfigured.length > 0) {
449
495
  feedbackLog('validation', 'error', { error: 'PROVIDER_NOT_CONFIGURED' });
450
- const envelope = createErrorEnvelope('PROVIDER_NOT_CONFIGURED', `Provider selected but no API key configured: ${unconfigured.join(', ')}`, { hint: unconfigured.map(p => p === 'ollama'
451
- ? 'Set OLLAMA_API_KEY or add "ollamaApiKey" to digdig.config.json'
452
- : p === 'deepseek' ? 'Set DEEPSEEK_API_KEY or add "deepseekApiKey" to digdig.config.json'
453
- : `Set ${p.toUpperCase()}_API_KEY`).join('; ') });
496
+ const directHints = unconfigured.map(provider => {
497
+ const keyHint = `Run dg init or set "${provider}ApiKey" in digdig.config.json.`;
498
+ if (provider === 'tavily')
499
+ return `${keyHint} The tvly CLI is also supported.`;
500
+ if (provider === 'firecrawl')
501
+ return `${keyHint} An authenticated official firecrawl CLI is also supported.`;
502
+ return keyHint;
503
+ });
504
+ const envelope = createErrorEnvelope('PROVIDER_NOT_CONFIGURED', `Search provider unavailable to the dg CLI: ${unconfigured.join(', ')}`, { hint: [...directHints, hostSearchHint].join(' ') });
454
505
  console.log(JSON.stringify(envelope, null, 2));
455
506
  return 1;
456
507
  }
@@ -559,8 +610,7 @@ async function runSearchInner(service, options) {
559
610
  }
560
611
  feedbackLog('redundancy', 'ok', { count: adjustedQueries.length, failed: skippedQueries.length });
561
612
  // Replace queries with adjusted ones (skipped ones removed)
562
- queries.length = 0;
563
- queries.push(...adjustedQueries);
613
+ queries = [...new Set(adjustedQueries)];
564
614
  }
565
615
  const attempts = [];
566
616
  try {
@@ -592,11 +642,8 @@ async function runSearchInner(service, options) {
592
642
  const searchOptions = {
593
643
  query,
594
644
  engines,
595
- categories: options.categories,
645
+ ...filters,
596
646
  limit,
597
- page: options.page,
598
- language: options.language,
599
- timeRange: options.timeRange,
600
647
  };
601
648
  const { providerResponses, sxngResponse, limitNotes: notes, attempts: queryAttempts } = await searchOneQuery(service, plan, searchOptions, limit);
602
649
  attempts.push(...queryAttempts);
@@ -643,20 +690,13 @@ async function runSearchInner(service, options) {
643
690
  console.error(`[session] ${pendingCount} pending results awaiting Agent review. Run --quality to list them.`);
644
691
  }
645
692
  }
646
- const meta = mergeEnvelopeMetadata(responses, null);
647
- for (const suggestion of mergeMeta.suggestions ?? []) {
648
- if (!meta.suggestions.includes(suggestion))
649
- meta.suggestions.push(suggestion);
650
- }
651
- for (const answer of mergeMeta.answers ?? []) {
652
- if (!meta.answers.includes(answer))
653
- meta.answers.push(answer);
654
- }
693
+ const meta = mergeEnvelopeMetadata(responses, mergeMeta);
655
694
  const outputFormat = (options.format || config.defaultFormat);
656
695
  const returnedKeys = new Set(fusion.display.map(result => resultUrlKey(result)));
657
696
  const providerResults = summarizeAttempts(attempts, returnedKeys);
658
697
  const displayData = {
659
698
  providerResults,
699
+ ...searchFilterScope(filters, attempts),
660
700
  query: queries.length > 1 ? queries.join(' · ') : queries[0],
661
701
  queries,
662
702
  // The deduplicated candidate pool, not a sum of provider self-reports
@@ -666,9 +706,7 @@ async function runSearchInner(service, options) {
666
706
  answers: meta.answers,
667
707
  suggestions: meta.suggestions,
668
708
  unresponsiveEngines: meta.unresponsiveEngines,
669
- // Carried so the display layer can say the filter's reach is
670
- // unconfirmed. Not part of the result ranking — it describes the
671
- // request, not any individual result.
709
+ // Original request values. filterScope reports forwarding by provider.
672
710
  ...(options.timeRange ? { timeRange: options.timeRange } : {}),
673
711
  ...(options.language ? { language: options.language } : {}),
674
712
  // Absent when nothing was capped, so a request the providers could
@@ -698,6 +736,7 @@ async function runSearchInner(service, options) {
698
736
  const partialResults = attempts.flatMap(attempt => attempt.status === 'ok' ? attempt.response.results : []);
699
737
  const details = attempts.length ? {
700
738
  providerResults: summarizeAttempts(attempts, new Set(partialResults.map(result => resultUrlKey(result)))),
739
+ ...searchFilterScope(filters, attempts),
701
740
  partialResults, sessionWrite: 'unconfirmed',
702
741
  } : undefined;
703
742
  console.log(JSON.stringify(createErrorEnvelope(error.code, error.message, { retryable: error.code === 'SESSION_BUSY', details }), null, 2));
@@ -711,13 +750,13 @@ async function runSearchInner(service, options) {
711
750
  if (error instanceof SearchError) {
712
751
  const envelope = createErrorEnvelope(error.code, error.message, {
713
752
  retryable: error.retryable,
714
- hint: error.hint,
715
- details: { provider: error.provider, ...(error.status === undefined ? {} : { status: error.status }), ...(attempts.length ? { providerResults: summarizeAttempts(attempts, new Set()) } : {}) },
753
+ hint: error.code === 'CONFIG_MISSING' ? `${error.hint} ${hostSearchHint}` : error.hint,
754
+ details: { provider: error.provider, ...(error.status === undefined ? {} : { status: error.status }), ...(attempts.length ? { providerResults: summarizeAttempts(attempts, new Set()) } : {}), ...searchFilterScope(filters, attempts) },
716
755
  });
717
756
  console.log(JSON.stringify(envelope, null, 2));
718
757
  return 1;
719
758
  }
720
- const envelope = createErrorEnvelope('SEARCH_FAILED', attempts.length ? 'Search request failed' : error instanceof Error ? error.message : 'Search request failed', attempts.length ? { details: { providerResults: summarizeAttempts(attempts, new Set()) } } : {});
759
+ const envelope = createErrorEnvelope('SEARCH_FAILED', attempts.length ? 'Search request failed' : error instanceof Error ? error.message : 'Search request failed', attempts.length ? { details: { providerResults: summarizeAttempts(attempts, new Set()), ...searchFilterScope(filters, attempts) } } : {});
721
760
  console.log(JSON.stringify(envelope, null, 2));
722
761
  return 1;
723
762
  }
@@ -742,7 +781,7 @@ function reportEmptySession(count) {
742
781
  if (count)
743
782
  return false;
744
783
  console.log(JSON.stringify(createErrorEnvelope('EMPTY_SESSION', 'This session has no stored results to report on', {
745
- retryable: false, hint: 'Run a search with --session before reporting on this session',
784
+ retryable: false, hint: 'Add host search results with dg results-add or run a dg search with --session before reporting on this session',
746
785
  }), null, 2));
747
786
  process.exitCode = 1;
748
787
  return true;
@@ -757,7 +796,7 @@ export function createProgram(argv = []) {
757
796
  .option('-e, --engines <engines>', `Comma-separated list of search engines; "${EXTERNAL_PROVIDERS.join('"/"')}" route to non-SearXNG providers`)
758
797
  .option('-c, --categories <cats>', 'Comma-separated list of categories')
759
798
  .option('-l, --limit <n>', 'Maximum number of results', parseLimit)
760
- .option('-p, --page <n>', 'Page number for pagination', val => parseInt(val, 10))
799
+ .option('-p, --page <n>', 'Page number (SearXNG starts here and fetches more if needed)', parseLimit)
761
800
  .option('--lang <code>', 'Language code (e.g., en, zh, ja)')
762
801
  .option('--time <range>', 'Time range: day, week, month, year, all')
763
802
  .option('-f, --format <fmt>', 'Output format: md (default), json')
@@ -775,7 +814,7 @@ export function createProgram(argv = []) {
775
814
  .option('--skip-stdin', 'Read the skip array from stdin')
776
815
  .option('--unskip-stdin', 'Read the restore array from stdin')
777
816
  .option('--health', 'Check the SearXNG backend health (Ollama/DeepSeek have no health endpoint)')
778
- .option('--engines-list', 'List available search engines')
817
+ .option('--engines-list', 'List CLI search engines and provider configuration')
779
818
  .option('--categories-list', 'List available categories')
780
819
  .allowUnknownOption(false);
781
820
  program
@@ -800,12 +839,12 @@ export function createProgram(argv = []) {
800
839
  obscuraPath: opts.obscuraPath,
801
840
  obscuraDumpFormat: opts.obscuraDump === 'markdown' ? 'markdown' : 'html',
802
841
  jina: opts.jina ?? false,
803
- jinaApiKey: process.env.JINA_API_KEY,
842
+ jinaApiKey: config.jinaApiKey,
804
843
  useInstalledTavily: true,
805
844
  useInstalledFirecrawl: true,
806
845
  externalKeys: {
807
- exa: process.env.EXA_API_KEY, tavily: process.env.TAVILY_API_KEY,
808
- firecrawl: process.env.FIRECRAWL_API_KEY,
846
+ exa: config.exaApiKey, tavily: config.tavilyApiKey,
847
+ firecrawl: config.firecrawlApiKey,
809
848
  ollama: config.ollamaApiKey,
810
849
  deepseek: config.deepseekApiKey,
811
850
  },
@@ -860,6 +899,14 @@ Search imports await extraction; extracted imports await approval.`)
860
899
  });
861
900
  process.exitCode = code;
862
901
  });
902
+ program
903
+ .command('results-pending')
904
+ .argument('<session>', 'Session directory or name')
905
+ .description('List candidates awaiting extraction as JSON')
906
+ .option('--limit <n>', 'Maximum candidates to display (default: 20)', parseLimit)
907
+ .action((session, opts, command) => {
908
+ process.exitCode = runResultsPending(session, opts.limit ?? command.parent?.opts().limit ?? 20);
909
+ });
863
910
  program
864
911
  .command('doc-index')
865
912
  .argument('<path>', 'Document path to index')
@@ -1194,7 +1241,7 @@ Examples:
1194
1241
  .argument('<session>', 'Session directory or name')
1195
1242
  .description('Confirm evidence + submit stance + optional auto-policy')
1196
1243
  .requiredOption('--claim-id <id>', 'Claim ID')
1197
- .requiredOption('--evidence-file <path>', 'UTF-8 JSON file with evidence object under this session agent-inputs directory')
1244
+ .option('--evidence-file <path>', 'UTF-8 JSON file with evidence object under this session agent-inputs directory')
1198
1245
  .option('--evidence-stdin', 'Read the same JSON from stdin instead of a file')
1199
1246
  .requiredOption('--stance <s>', 'Stance: support, refute, insufficient')
1200
1247
  .requiredOption('--reason <text>', 'Judgement rationale')
@@ -1322,7 +1369,9 @@ export async function runCli(args, service) {
1322
1369
  }
1323
1370
  const sessionDir = resolveSessionPath(opts.session);
1324
1371
  const sessionResults = loadSessionResults(sessionDir);
1325
- if (!opts.skipFile && !opts.unskipFile && !opts.approveFile && reportEmptySession(sessionResults.length))
1372
+ const approving = Boolean(opts.approveFile || opts.approveStdin);
1373
+ const changingSkip = Boolean(opts.skipFile || opts.skipStdin || opts.unskipFile || opts.unskipStdin);
1374
+ if (!approving && !changingSkip && reportEmptySession(sessionResults.length))
1326
1375
  return;
1327
1376
  const sessionGraph = loadSessionGraph(sessionDir);
1328
1377
  const readSelections = (option, file, stdin) => {
@@ -1348,7 +1397,7 @@ export async function runCli(args, service) {
1348
1397
  console.log(JSON.stringify(createSuccessEnvelope({ changed: result.changed, skipped, results: result.results.map(item => ({ id: item.id, revision: item.revision, skippedAt: item.skippedAt })) }), null, 2));
1349
1398
  return true;
1350
1399
  };
1351
- if (opts.skipFile || opts.unskipFile || opts.skipStdin || opts.unskipStdin) {
1400
+ if (changingSkip) {
1352
1401
  if ((opts.skipFile || opts.skipStdin) && (opts.unskipFile || opts.unskipStdin)) {
1353
1402
  console.log(JSON.stringify(createErrorEnvelope('MULTIPLE_SKIP_ACTIONS', 'Use only one of --skip-file, --skip-stdin, --unskip-file or --unskip-stdin'), null, 2));
1354
1403
  process.exitCode = 1;
@@ -1359,12 +1408,7 @@ export async function runCli(args, service) {
1359
1408
  process.exitCode = applySkip(option, opts.skipFile ?? opts.unskipFile, skipping ? opts.skipStdin : opts.unskipStdin, skipping) ? 0 : 1;
1360
1409
  return;
1361
1410
  }
1362
- // Get pending results for Agent review
1363
- const pending = getPendingResults(sessionDir);
1364
- const facts = buildPendingReport(sessionResults, pending);
1365
- // Approval is allowed only after reporting what is waiting and how
1366
- // much of it carries a body.
1367
- if (opts.approveFile) {
1411
+ if (approving) {
1368
1412
  const selections = readSelections('--approve-file', opts.approveFile, opts.approveStdin);
1369
1413
  if (!selections) {
1370
1414
  process.exitCode = 1;
@@ -1376,6 +1420,7 @@ export async function runCli(args, service) {
1376
1420
  .map(result => describeResult(result));
1377
1421
  const { approval, injectInfo } = approveAndInjectResults(sessionDir, selections);
1378
1422
  if (approval.error) {
1423
+ const facts = buildPendingReport(sessionResults, getPendingResults(sessionDir));
1379
1424
  console.log(JSON.stringify(createErrorEnvelope(approval.error.code, approval.error.message, {
1380
1425
  details: { facts, selectedResults, error: approval.error },
1381
1426
  hint: 'Run dg extract --session <session> for unverified results, then review and approve again.',
@@ -1386,15 +1431,17 @@ export async function runCli(args, service) {
1386
1431
  console.log(JSON.stringify(createSuccessEnvelope({
1387
1432
  approved: approval.approved,
1388
1433
  total: approval.total,
1434
+ totalPending: approval.totalPending,
1389
1435
  nodesAdded: injectInfo.nodesAdded,
1390
1436
  edgesAdded: injectInfo.edgesAdded,
1391
- facts,
1392
1437
  selectedResults,
1393
1438
  message: `Approved ${approval.approved} results, injected into graph (+${injectInfo.nodesAdded} nodes, +${injectInfo.edgesAdded} edges)`,
1394
1439
  }), null, 2));
1395
1440
  process.exitCode = 0;
1396
1441
  return;
1397
1442
  }
1443
+ const pending = getPendingResults(sessionDir);
1444
+ const facts = buildPendingReport(sessionResults, pending);
1398
1445
  if (pending.length === 0) {
1399
1446
  // Nothing to approve: the counts still describe the session.
1400
1447
  const outputFormat = (opts.format || config.defaultFormat);