@demigodmode/pi-web-agent 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +19 -4
  3. package/dist/backends/config.d.ts +40 -0
  4. package/dist/backends/config.js +140 -1
  5. package/dist/backends/factory.d.ts +17 -1
  6. package/dist/backends/factory.js +170 -85
  7. package/dist/backends/failure.d.ts +11 -0
  8. package/dist/backends/failure.js +34 -0
  9. package/dist/backends/fallback-policy.d.ts +33 -0
  10. package/dist/backends/fallback-policy.js +239 -0
  11. package/dist/backends/provider-failure.d.ts +21 -0
  12. package/dist/backends/provider-failure.js +111 -0
  13. package/dist/backends/provider-health.d.ts +29 -0
  14. package/dist/backends/provider-health.js +49 -0
  15. package/dist/commands/web-agent-config.d.ts +17 -1
  16. package/dist/commands/web-agent-config.js +131 -7
  17. package/dist/extension.d.ts +1 -0
  18. package/dist/extension.js +49 -3
  19. package/dist/fetch/destination-policy.d.ts +32 -0
  20. package/dist/fetch/destination-policy.js +24 -0
  21. package/dist/fetch/firecrawl-fetch.js +64 -45
  22. package/dist/fetch/guard-proxy-fetch.d.ts +17 -0
  23. package/dist/fetch/guard-proxy-fetch.js +82 -0
  24. package/dist/fetch/guard-proxy.d.ts +58 -0
  25. package/dist/fetch/guard-proxy.js +420 -0
  26. package/dist/fetch/guarded-fetch.d.ts +7 -0
  27. package/dist/fetch/guarded-fetch.js +75 -0
  28. package/dist/fetch/headless-fetch.d.ts +17 -2
  29. package/dist/fetch/headless-fetch.js +181 -9
  30. package/dist/fetch/http-fetch.js +16 -1
  31. package/dist/fetch/network-guard.d.ts +82 -0
  32. package/dist/fetch/network-guard.js +275 -0
  33. package/dist/fetch/proxy-fetch.d.ts +22 -0
  34. package/dist/fetch/proxy-fetch.js +46 -0
  35. package/dist/jiti-compat-run.d.ts +1 -0
  36. package/dist/jiti-compat-run.js +9 -0
  37. package/dist/jiti-compat.d.ts +32 -0
  38. package/dist/jiti-compat.js +215 -0
  39. package/dist/orchestration/answer-synthesizer.js +2 -0
  40. package/dist/orchestration/evidence-quality.d.ts +3 -2
  41. package/dist/orchestration/evidence-quality.js +2 -1
  42. package/dist/orchestration/index.d.ts +23 -0
  43. package/dist/orchestration/index.js +9 -2
  44. package/dist/orchestration/research-orchestrator.d.ts +21 -1
  45. package/dist/orchestration/research-orchestrator.js +40 -7
  46. package/dist/orchestration/research-types.d.ts +13 -1
  47. package/dist/orchestration/research-worker.js +38 -3
  48. package/dist/orchestration/stop-decider.js +3 -1
  49. package/dist/presentation/config-store.js +10 -0
  50. package/dist/presentation/explore-presentation.js +3 -1
  51. package/dist/presentation/fetch-presentation.js +16 -9
  52. package/dist/presentation/search-presentation.d.ts +2 -1
  53. package/dist/presentation/search-presentation.js +13 -1
  54. package/dist/readers/youtube-reader.d.ts +3 -1
  55. package/dist/readers/youtube-reader.js +11 -3
  56. package/dist/search/brave.d.ts +1 -2
  57. package/dist/search/brave.js +23 -80
  58. package/dist/search/duckduckgo.d.ts +7 -3
  59. package/dist/search/duckduckgo.js +17 -18
  60. package/dist/search/exa.d.ts +1 -2
  61. package/dist/search/exa.js +15 -76
  62. package/dist/search/fanout.d.ts +12 -0
  63. package/dist/search/fanout.js +86 -47
  64. package/dist/search/json-provider.d.ts +32 -0
  65. package/dist/search/json-provider.js +76 -0
  66. package/dist/search/searxng.d.ts +1 -2
  67. package/dist/search/searxng.js +15 -57
  68. package/dist/search/tavily.d.ts +1 -2
  69. package/dist/search/tavily.js +17 -74
  70. package/dist/search/youcom.d.ts +1 -2
  71. package/dist/search/youcom.js +15 -76
  72. package/dist/tools/web-explore.d.ts +9 -0
  73. package/dist/tools/web-explore.js +16 -2
  74. package/dist/tools/web-search.js +41 -103
  75. package/dist/types.d.ts +40 -0
  76. package/package.json +4 -3
  77. package/scripts/patch-jiti-compat.mjs +52 -8
@@ -1,25 +1,9 @@
1
1
  import { createCacheKey, createTtlCache } from '../cache/ttl-cache.js';
2
2
  import { buildSearchPresentation } from '../presentation/search-presentation.js';
3
- import { fetchDuckDuckGoHtml, parseDuckDuckGoResults } from '../search/duckduckgo.js';
4
- function classifySearchFailure(error) {
5
- const rawMessage = error instanceof Error ? error.message : 'Unknown search failure.';
6
- const normalized = rawMessage.toLowerCase();
7
- if (normalized.includes('blocked') ||
8
- normalized.includes('rate limit') ||
9
- normalized.includes('rate-limit') ||
10
- normalized.includes('403') ||
11
- normalized.includes('429') ||
12
- normalized.includes('captcha') ||
13
- normalized.includes('challenge')) {
14
- return {
15
- code: 'BLOCKED',
16
- message: 'DuckDuckGo search appears to be blocked or rate limited.'
17
- };
18
- }
19
- return {
20
- code: 'FETCH_FAILED',
21
- message: `DuckDuckGo search request failed: ${rawMessage}`
22
- };
3
+ import { classifyHttpFailure } from '../backends/provider-failure.js';
4
+ import { DuckDuckGoHttpError, fetchDuckDuckGoHtml, parseDuckDuckGoResults } from '../search/duckduckgo.js';
5
+ function respond(result) {
6
+ return { ...result, presentation: buildSearchPresentation(result) };
23
7
  }
24
8
  function htmlLooksBlocked(html) {
25
9
  const normalized = html.toLowerCase();
@@ -37,107 +21,61 @@ export function createWebSearchTool({ searchHtml = fetchDuckDuckGoHtml, cache =
37
21
  return async function webSearch({ query }) {
38
22
  const normalizedQuery = query.trim();
39
23
  if (!normalizedQuery) {
40
- const result = {
24
+ return respond({
41
25
  status: 'error',
42
26
  results: [],
43
27
  metadata: { backend: 'duckduckgo', cacheHit: false },
44
- error: { code: 'INVALID_QUERY', message: 'Query must not be empty.' }
45
- };
46
- return {
47
- ...result,
48
- presentation: buildSearchPresentation(result)
49
- };
28
+ error: { code: 'INVALID_QUERY', message: 'Query must not be empty.', failure: { kind: 'bad_request' } }
29
+ });
50
30
  }
51
31
  const cacheKey = createCacheKey(['web_search', normalizedQuery]);
52
32
  const cached = cache.get(cacheKey);
53
33
  if (cached) {
54
- const result = {
55
- ...cached,
56
- metadata: { ...cached.metadata, cacheHit: true }
57
- };
58
- return {
59
- ...result,
60
- presentation: buildSearchPresentation(result)
61
- };
34
+ return respond({ ...cached, metadata: { ...cached.metadata, cacheHit: true } });
62
35
  }
36
+ let html;
63
37
  try {
64
- let html = await searchHtml(normalizedQuery);
65
- let parsed = parseDuckDuckGoResults(html);
66
- // A 200-OK bot-wall reads as a successful fetch, so the fetch-layer retry never sees it.
67
- // Give a page that looks blocked one more shot here before we classify it.
68
- if (parsed.results.length === 0 && htmlLooksBlocked(html)) {
69
- html = await searchHtml(normalizedQuery);
70
- parsed = parseDuckDuckGoResults(html);
71
- }
72
- if (parsed.results.length > 0) {
73
- const result = {
74
- status: 'ok',
75
- results: parsed.results,
76
- metadata: { backend: 'duckduckgo', cacheHit: false }
77
- };
78
- cache.set(cacheKey, result);
79
- return {
80
- ...result,
81
- presentation: buildSearchPresentation(result)
82
- };
83
- }
84
- // Check for a bot-wall before "no results": a page can carry both markers, and BLOCKED is
85
- // the honest call since it routes to the fallback instead of a dead end.
86
- if (htmlLooksBlocked(html)) {
87
- const result = {
88
- status: 'error',
89
- results: [],
90
- metadata: { backend: 'duckduckgo', cacheHit: false },
91
- error: {
92
- code: 'BLOCKED',
93
- message: 'DuckDuckGo search appears to be blocked or rate limited.'
94
- }
95
- };
96
- return {
97
- ...result,
98
- presentation: buildSearchPresentation(result)
99
- };
100
- }
101
- if (parsed.noResults) {
102
- const result = {
103
- status: 'error',
104
- results: [],
105
- metadata: { backend: 'duckduckgo', cacheHit: false },
106
- error: {
107
- code: 'NO_RESULTS',
108
- message: 'DuckDuckGo returned no usable results for this query.'
109
- }
110
- };
111
- return {
112
- ...result,
113
- presentation: buildSearchPresentation(result)
114
- };
115
- }
116
- const result = {
38
+ html = await searchHtml(normalizedQuery);
39
+ }
40
+ catch (error) {
41
+ const failure = error instanceof DuckDuckGoHttpError
42
+ ? classifyHttpFailure('duckduckgo', { status: error.status, headers: error.headers })
43
+ : { kind: 'transient' };
44
+ const blockedLike = failure.kind === 'blocked' || failure.kind === 'rate_limited';
45
+ return respond({
117
46
  status: 'error',
118
47
  results: [],
119
48
  metadata: { backend: 'duckduckgo', cacheHit: false },
120
49
  error: {
121
- code: 'PARSE_FAILED',
122
- message: 'DuckDuckGo returned a page, but it did not match the expected results format.'
50
+ code: blockedLike ? 'BLOCKED' : 'FETCH_FAILED',
51
+ message: blockedLike
52
+ ? 'DuckDuckGo search appears to be blocked or rate limited.'
53
+ : `DuckDuckGo search request failed: ${error instanceof Error ? error.message : String(error)}`,
54
+ failure
123
55
  }
124
- };
125
- return {
126
- ...result,
127
- presentation: buildSearchPresentation(result)
128
- };
56
+ });
129
57
  }
130
- catch (error) {
131
- const result = {
58
+ const parsed = parseDuckDuckGoResults(html);
59
+ if (parsed.results.length > 0) {
60
+ const result = { status: 'ok', results: parsed.results, metadata: { backend: 'duckduckgo', cacheHit: false } };
61
+ cache.set(cacheKey, result);
62
+ return respond(result);
63
+ }
64
+ // Bot-wall check first: a page can carry both markers, and blocked routes to fallback.
65
+ const walled = htmlLooksBlocked(html) || (!parsed.hasResultContainers && !parsed.noResults);
66
+ if (walled) {
67
+ return respond({
132
68
  status: 'error',
133
69
  results: [],
134
70
  metadata: { backend: 'duckduckgo', cacheHit: false },
135
- error: classifySearchFailure(error)
136
- };
137
- return {
138
- ...result,
139
- presentation: buildSearchPresentation(result)
140
- };
71
+ error: {
72
+ code: 'BLOCKED',
73
+ message: 'DuckDuckGo search appears to be blocked or rate limited.',
74
+ failure: { kind: 'blocked' }
75
+ }
76
+ });
141
77
  }
78
+ // DuckDuckGo said there are no results, or every result was filtered out: a valid empty search.
79
+ return respond({ status: 'ok', results: [], metadata: { backend: 'duckduckgo', cacheHit: false } });
142
80
  };
143
81
  }
package/dist/types.d.ts CHANGED
@@ -12,10 +12,44 @@ export type FanoutMetadata = {
12
12
  mode: Exclude<FanoutMode, 'off'>;
13
13
  providers: SearchProviderName[];
14
14
  skipped?: SearchProviderName[];
15
+ outcomes?: FanoutOutcome[];
16
+ };
17
+ export type FailureKind = 'rate_limited' | 'quota_exhausted' | 'auth_failed' | 'not_configured' | 'transient' | 'blocked' | 'bad_response' | 'bad_request' | 'config_global' | 'guard_refused';
18
+ export type FailureInfo = {
19
+ kind: FailureKind;
20
+ httpStatus?: number;
21
+ /** Documented provider body code or tag, e.g. Exa `NO_MORE_CREDITS`. */
22
+ providerCode?: string;
23
+ /** Exactly what the provider reported, uncapped. */
24
+ providerRetryAfterMs?: number;
25
+ };
26
+ export type Attempt = {
27
+ backend: string;
28
+ outcome: 'results' | 'empty' | 'failed' | 'skipped' | 'retried';
29
+ failure?: FailureInfo;
30
+ skipReason?: 'cooling_down' | 'disabled';
31
+ cooldownUntil?: number;
32
+ /** The provider's own message for a user-fixable failure, e.g. a missing key or base URL. */
33
+ detail?: string;
34
+ };
35
+ export type SearchCoverage = {
36
+ partial: true;
37
+ unavailable: Array<{
38
+ provider: string;
39
+ kind: FailureKind;
40
+ }>;
41
+ };
42
+ export type FanoutOutcome = {
43
+ provider: SearchProviderName;
44
+ outcome: 'results' | 'empty' | 'failed' | 'skipped';
45
+ count?: number;
46
+ failure?: FailureInfo;
47
+ skipReason?: 'cooling_down' | 'disabled';
15
48
  };
16
49
  export type ToolError = {
17
50
  code: string;
18
51
  message: string;
52
+ failure?: FailureInfo;
19
53
  };
20
54
  export type SearchMetadata = {
21
55
  backend: 'duckduckgo' | 'searxng' | 'brave' | 'youcom' | 'exa' | 'tavily';
@@ -23,6 +57,8 @@ export type SearchMetadata = {
23
57
  fallbackFrom?: 'searxng' | 'brave' | 'youcom' | 'exa' | 'tavily' | 'duckduckgo';
24
58
  fallbackReason?: string;
25
59
  fanout?: FanoutMetadata;
60
+ attempts?: Attempt[];
61
+ coverage?: SearchCoverage;
26
62
  };
27
63
  export type FetchMethod = 'http' | 'headless' | 'firecrawl' | 'github' | 'pdf' | 'youtube';
28
64
  export type FetchMetadata = {
@@ -34,6 +70,9 @@ export type FetchMetadata = {
34
70
  truncated?: boolean;
35
71
  browser?: 'configured' | 'chrome' | 'edge' | 'brave' | 'chromium';
36
72
  navigationMs?: number;
73
+ /** Headless only: browser requests refused by the private-address guard (#53). */
74
+ blockedSubresources?: number;
75
+ attempts?: Attempt[];
37
76
  };
38
77
  export type ExtractedContent = {
39
78
  title?: string;
@@ -80,6 +119,7 @@ export type WebExploreResponse = {
80
119
  caveatReasons?: string[];
81
120
  fanoutProviders?: SearchProviderName[];
82
121
  fanoutSkipped?: SearchProviderName[];
122
+ attempts?: Attempt[];
83
123
  };
84
124
  presentation?: PresentationEnvelope;
85
125
  error?: ToolError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@demigodmode/pi-web-agent",
3
- "version": "1.10.0",
3
+ "version": "1.12.0",
4
4
  "description": "Pi package for reliable web access with explicit search, fetch, and headless boundaries.",
5
5
  "type": "module",
6
6
  "main": "./dist/extension.js",
@@ -68,6 +68,7 @@
68
68
  "jsdom": "^26.0.0",
69
69
  "playwright": "^1.60.0",
70
70
  "typebox": "^1.1.37",
71
+ "undici": "^8.10.2",
71
72
  "unpdf": "^1.8.1",
72
73
  "youtube-caption-extractor": "^1.10.2"
73
74
  },
@@ -76,10 +77,10 @@
76
77
  "@earendil-works/pi-tui": "^0.80.10",
77
78
  "@types/jsdom": "^21.1.7",
78
79
  "@types/node": "^24.0.0",
79
- "@vitest/coverage-v8": "^3.2.6",
80
+ "@vitest/coverage-v8": "^4.1.11",
80
81
  "typescript": "^5.8.0",
81
82
  "vitepress": "^1.6.4",
82
- "vitest": "^3.2.6"
83
+ "vitest": "^4.1.11"
83
84
  },
84
85
  "peerDependencies": {
85
86
  "@earendil-works/pi-coding-agent": "*",
@@ -10,19 +10,63 @@
10
10
  // when this package is installed as a pi extension via `pi install npm:...`.
11
11
  // Safe to run multiple times and safe to no-op if the target files or
12
12
  // patterns are missing (e.g. a future dependency bump changes the shape).
13
- import { readFileSync, writeFileSync, existsSync } from "node:fs";
13
+ //
14
+ // src/jiti-compat.ts does the same two patches at extension load time, because
15
+ // the shared ~/.pi/agent/npm tree means another extension's install can revert
16
+ // them long after this hook ran (#34). The logic is deliberately duplicated
17
+ // rather than shared: postinstall runs before `npm run build` in CI and in a
18
+ // fresh clone, so this file cannot depend on dist/. Keep the two in sync.
19
+ import { readFileSync, writeFileSync, existsSync, renameSync, unlinkSync } from "node:fs";
14
20
  import { createRequire } from "node:module";
15
21
  import { dirname, join, relative, sep } from "node:path";
16
22
 
17
- const resolveFromHere = createRequire(import.meta.url).resolve;
23
+ const requireFromHere = createRequire(import.meta.url);
24
+ const resolveFromHere = requireFromHere.resolve;
25
+
26
+ // Resolve the copies jsdom actually loads. The shared ~/.pi/agent/npm tree
27
+ // often holds a second, nested copy of a package when extensions disagree on
28
+ // versions, and patching a hoisted copy jsdom never requires would fix
29
+ // nothing. Mirrors resolveFromJsdom in src/jiti-compat.ts.
30
+ function resolveFromJsdom(specifier, via) {
31
+ try {
32
+ const jsdomEntry = resolveFromHere("jsdom");
33
+ const importer = via ? createRequire(jsdomEntry).resolve(via) : jsdomEntry;
34
+ return createRequire(importer).resolve(specifier);
35
+ } catch {
36
+ return resolveFromHere(specifier);
37
+ }
38
+ }
39
+
40
+ // Temp file + rename, not an in-place write. `writeFileSync` truncates first,
41
+ // so an interrupted write would leave a half-patched file that still contains
42
+ // the marker comment and would be skipped as "already patched" forever.
43
+ // Mirrors writeFileAtomic in src/jiti-compat.ts.
44
+ function writeFileAtomic(path, contents) {
45
+ const temp = `${path}.pi-web-agent-${process.pid}.tmp`;
46
+ try {
47
+ writeFileSync(temp, contents);
48
+ renameSync(temp, path);
49
+ } catch (err) {
50
+ try {
51
+ if (existsSync(temp)) unlinkSync(temp);
52
+ } catch {
53
+ // Best effort.
54
+ }
55
+ throw err;
56
+ }
57
+ }
18
58
 
19
59
  function findPackageRoot(entryFile, packageName) {
20
60
  let directory = dirname(entryFile);
21
61
  while (true) {
22
62
  const manifestFile = join(directory, "package.json");
23
63
  if (existsSync(manifestFile)) {
24
- const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
25
- if (manifest.name === packageName) return directory;
64
+ try {
65
+ const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
66
+ if (manifest.name === packageName) return directory;
67
+ } catch {
68
+ // Malformed package.json on the way up. Keep walking.
69
+ }
26
70
  }
27
71
 
28
72
  const parent = dirname(directory);
@@ -34,7 +78,7 @@ function findPackageRoot(entryFile, packageName) {
34
78
  }
35
79
 
36
80
  function patchTr46() {
37
- const file = resolveFromHere("tr46");
81
+ const file = resolveFromJsdom("tr46", "whatwg-url");
38
82
  if (!existsSync(file)) {
39
83
  console.debug("patch-jiti-compat: tr46/index.js not found, skipping");
40
84
  return;
@@ -44,7 +88,7 @@ function patchTr46() {
44
88
  console.debug("patch-jiti-compat: tr46/index.js does not match expected pattern, skipping");
45
89
  return;
46
90
  }
47
- writeFileSync(
91
+ writeFileAtomic(
48
92
  file,
49
93
  contents.replaceAll('require("punycode/")', 'require("punycode/punycode.js")'),
50
94
  );
@@ -61,7 +105,7 @@ module.exports[Symbol.iterator] = Set.prototype[Symbol.iterator].bind(module.exp
61
105
  `;
62
106
 
63
107
  function patchCssstyleSetExports() {
64
- const packageRoot = findPackageRoot(resolveFromHere("cssstyle"), "cssstyle");
108
+ const packageRoot = findPackageRoot(resolveFromJsdom("cssstyle"), "cssstyle");
65
109
  const files = [
66
110
  join(packageRoot, "lib", "allExtraProperties.js"),
67
111
  join(packageRoot, "lib", "generated", "allProperties.js"),
@@ -79,7 +123,7 @@ function patchCssstyleSetExports() {
79
123
  console.debug(`patch-jiti-compat: ${label} does not match expected pattern, skipping`);
80
124
  continue;
81
125
  }
82
- writeFileSync(file, contents + SET_SHIM);
126
+ writeFileAtomic(file, contents + SET_SHIM);
83
127
  console.log(`patch-jiti-compat: patched ${label}`);
84
128
  }
85
129
  }