@zeldrisho/pi-web-search 0.15.2 → 0.15.3

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/CHANGELOG.md CHANGED
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.15.3] - 2026-12-01
11
+
12
+ ### Security
13
+
14
+ - Create private cache temporary files exclusively so a write cannot overwrite or remove an existing temporary file.
15
+
10
16
  ## [0.15.2] - 2026-11-20
11
17
 
12
18
  ### Changed
@@ -231,7 +237,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
231
237
 
232
238
  - Add bounded Brave web search ([cbc9491](https://github.com/zeldrisho/pi-packages/commit/cbc9491dce36555ab91b6bef203ec8b380596a89))
233
239
 
234
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-search-v0.15.2...HEAD
240
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-search-v0.15.3...HEAD
241
+ [0.15.3]: https://github.com/zeldrisho/pi-packages/compare/pi-web-search-v0.15.2...pi-web-search-v0.15.3
235
242
  [0.15.2]: https://github.com/zeldrisho/pi-packages/compare/pi-web-search-v0.15.1...pi-web-search-v0.15.2
236
243
  [0.15.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-search-v0.15.0...pi-web-search-v0.15.1
237
244
  [0.15.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-search-v0.14.6...pi-web-search-v0.15.0
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @zeldrisho/pi-web-search
1
+ # pi-web-search
2
2
 
3
3
  Search the public web with [Brave Search](https://brave.com/search/api/) from Pi.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-search",
3
- "version": "0.15.2",
3
+ "version": "0.15.3",
4
4
  "description": "Pi extension for bounded Brave web search with generated-answer fallback",
5
5
  "keywords": [
6
6
  "brave-search",
@@ -30,12 +30,12 @@
30
30
  "access": "public"
31
31
  },
32
32
  "devDependencies": {
33
- "@earendil-works/pi-coding-agent": "^1.5.0",
34
- "@earendil-works/pi-tui": "^1.4.0",
35
- "typebox": "^1.4.3",
33
+ "@earendil-works/pi-coding-agent": "^1.6.0",
34
+ "@earendil-works/pi-tui": "^1.6.0",
35
+ "typebox": "^1.4.7",
36
36
  "typescript": "^7.0.2",
37
- "vite": "npm:@voidzero-dev/vite-plus-core@1.5.0",
38
- "vite-plus": "1.5.0"
37
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
38
+ "vite-plus": "1.7.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@earendil-works/pi-coding-agent": ">=0.99.0",
@@ -46,8 +46,5 @@
46
46
  "extensions": [
47
47
  "./src/index.ts"
48
48
  ]
49
- },
50
- "scripts": {
51
- "test": "vp test"
52
49
  }
53
50
  }
package/src/answers.ts CHANGED
@@ -37,7 +37,7 @@ export function parseAnswerStream(body: string): BraveAnswer {
37
37
  const chunks: string[] = [];
38
38
  let completed = false;
39
39
 
40
- for (const event of body.replace(/\r\n/g, "\n").split("\n\n")) {
40
+ for (const event of body.replaceAll("\r\n", "\n").split("\n\n")) {
41
41
  const data = event
42
42
  .split("\n")
43
43
  .filter((line) => line.startsWith("data:"))
@@ -53,8 +53,9 @@ export function parseAnswerStream(body: string): BraveAnswer {
53
53
 
54
54
  const parsed: unknown = JSON.parse(data);
55
55
 
56
- if (!Check(eventSchema, parsed) || parsed.error !== undefined)
56
+ if (!Check(eventSchema, parsed) || parsed.error !== undefined) {
57
57
  throw new Error("Brave Answers returned an invalid stream event.");
58
+ }
58
59
  const choice = parsed.choices?.[0];
59
60
 
60
61
  if (choice?.finish_reason && choice.finish_reason !== "stop") {
@@ -74,40 +75,47 @@ export function parseAnswerStream(body: string): BraveAnswer {
74
75
 
75
76
  const text = chunks
76
77
  .join("")
77
- .replace(/<(citation|usage)>([\s\S]*?)<\/\1>/g, (_tag: string, kind: string, json: string) => {
78
- const parsed: unknown = JSON.parse(json);
79
-
80
- if (kind === "usage") {
81
- if (!Check(usageSchema, parsed))
82
- throw new Error("Brave Answers returned invalid usage metadata.");
83
- usage = parsed;
84
-
85
- return "";
86
- }
87
-
88
- if (!Check(citationSchema, parsed))
89
- throw new Error("Brave Answers returned invalid citation metadata.");
90
- const url = normalizeUrl(parsed.url);
91
-
92
- if (!url) return "";
93
- const key = `${parsed.number}:${url}`;
94
-
95
- if (!seen.has(key)) {
96
- citations.push({ number: parsed.number, url });
97
- seen.add(key);
98
- }
99
-
100
- return `[${parsed.number}]`;
101
- })
78
+ .replaceAll(
79
+ /<(citation|usage)>([\s\S]*?)<\/\1>/g,
80
+ (_tag: string, kind: string, json: string) => {
81
+ const parsed: unknown = JSON.parse(json);
82
+
83
+ if (kind === "usage") {
84
+ if (!Check(usageSchema, parsed)) {
85
+ throw new Error("Brave Answers returned invalid usage metadata.");
86
+ }
87
+ usage = parsed;
88
+
89
+ return "";
90
+ }
91
+
92
+ if (!Check(citationSchema, parsed)) {
93
+ throw new Error("Brave Answers returned invalid citation metadata.");
94
+ }
95
+ const url = normalizeUrl(parsed.url);
96
+
97
+ if (!url) return "";
98
+ const key = `${parsed.number}:${url}`;
99
+
100
+ if (!seen.has(key)) {
101
+ citations.push({ number: parsed.number, url });
102
+ seen.add(key);
103
+ }
104
+
105
+ return `[${parsed.number}]`;
106
+ },
107
+ )
102
108
  .trim();
103
109
 
104
- if (/<\/?(?:citation|usage)\b/i.test(text))
110
+ if (/<\/?(?:citation|usage)\b/i.test(text)) {
105
111
  throw new Error("Brave Answers returned incomplete metadata tags.");
112
+ }
106
113
 
107
- if (!text)
114
+ if (!text) {
108
115
  throw new Error(
109
116
  'Brave Answers returned no answer content. Try mode: "web" for sources; no answer does not prove absence.',
110
117
  );
118
+ }
111
119
 
112
120
  return { text, citations, usage };
113
121
  }
package/src/brave.ts CHANGED
@@ -52,17 +52,21 @@ export function parseQueryMeta(query: BraveQuery | undefined): BraveQueryMeta {
52
52
 
53
53
  if (query.show_strict_warning !== undefined) meta.showStrictWarning = query.show_strict_warning;
54
54
 
55
- if (query.more_results_available !== undefined)
55
+ if (query.more_results_available !== undefined) {
56
56
  meta.moreResultsAvailable = query.more_results_available;
57
+ }
57
58
 
58
- if (query.search_operators?.applied !== undefined)
59
+ if (query.search_operators?.applied !== undefined) {
59
60
  meta.operatorsApplied = query.search_operators.applied;
61
+ }
60
62
 
61
- if (query.search_operators?.cleaned_query)
63
+ if (query.search_operators?.cleaned_query) {
62
64
  meta.cleanedQuery = query.search_operators.cleaned_query;
65
+ }
63
66
 
64
- if (Array.isArray(query.search_operators?.sites))
67
+ if (Array.isArray(query.search_operators?.sites)) {
65
68
  meta.operatorSites = [...query.search_operators.sites];
69
+ }
66
70
 
67
71
  return meta;
68
72
  }
@@ -77,12 +81,12 @@ export interface SearchResult {
77
81
 
78
82
  interface BraveWebResponse {
79
83
  web?: {
80
- results?: Array<{
84
+ results?: {
81
85
  title?: string;
82
86
  url?: string;
83
87
  description?: string;
84
88
  extra_snippets?: string[];
85
- }>;
89
+ }[];
86
90
  };
87
91
  query?: BraveQuery;
88
92
  }
@@ -146,8 +150,9 @@ export async function searchBraveWeb(
146
150
 
147
151
  if (extras.operators !== undefined) url.searchParams.set("operators", String(extras.operators));
148
152
 
149
- if (extras.resultFilter)
153
+ if (extras.resultFilter) {
150
154
  url.searchParams.set("result_filter", normalizeResultFilter(extras.resultFilter));
155
+ }
151
156
 
152
157
  if (extras.goggles) url.searchParams.set("goggles", extras.goggles);
153
158
 
@@ -176,8 +181,9 @@ export async function searchBraveWeb(
176
181
  .map((value) => normalizeText(value ?? "", 300))
177
182
  .filter(Boolean);
178
183
 
179
- if (additional.length)
184
+ if (additional.length) {
180
185
  snippet = normalizeText([snippet, ...additional].filter(Boolean).join("\n\n"), 2000);
186
+ }
181
187
  }
182
188
 
183
189
  return {
package/src/cache.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  chmodSync,
3
3
  closeSync,
4
+ fchmodSync,
4
5
  mkdirSync,
5
6
  openSync,
6
7
  readFileSync,
@@ -12,7 +13,7 @@ import {
12
13
  writeFileSync,
13
14
  } from "node:fs";
14
15
  import { resolve, sep } from "node:path";
15
- import { createHash } from "node:crypto";
16
+ import { createHash, randomUUID } from "node:crypto";
16
17
 
17
18
  interface ExpiringCacheEntry<V> {
18
19
  expiresAt: number;
@@ -40,11 +41,8 @@ export function stableKeyHash(key: string): string {
40
41
  }
41
42
 
42
43
  /** Hash canonical JSON, sorting object keys recursively while preserving array order. */
43
- // oxlint-disable-next-line anti-slop/no-unknown-parameters -- JSON serialization defines the accepted values.
44
44
  export function canonicalKey(value: unknown): string {
45
- // oxlint-disable-next-line anti-slop/no-unknown-parameters -- JSON replacer receives arbitrary JSON values.
46
45
  const json = JSON.stringify(value, (_key, entry: unknown) => {
47
- // oxlint-disable-next-line anti-slop/no-runtime-typeof -- recursively sort JSON objects.
48
46
  if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
49
47
  return Object.fromEntries(
50
48
  Object.entries(entry).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
@@ -76,6 +74,30 @@ export function resolveCachePath(directory: string, keyPath: string): string {
76
74
  return full;
77
75
  }
78
76
 
77
+ /** Publishes a cache file atomically using a temporary path in the same directory. */
78
+ export function writeCacheFile(path: string, temp: string, bytes: Uint8Array): void {
79
+ const descriptor = openSync(temp, "wx", 0o600);
80
+
81
+ try {
82
+ try {
83
+ writeFileSync(descriptor, bytes);
84
+ fchmodSync(descriptor, 0o600);
85
+ } finally {
86
+ closeSync(descriptor);
87
+ }
88
+
89
+ renameSync(temp, path);
90
+ } catch (error) {
91
+ try {
92
+ unlinkSync(temp);
93
+ } catch {
94
+ // Best-effort cleanup must not hide the write or rename failure.
95
+ }
96
+
97
+ throw error;
98
+ }
99
+ }
100
+
79
101
  /**
80
102
  * Encodes an expiration timestamp as an 8-byte big-endian buffer.
81
103
  *
@@ -233,8 +255,9 @@ export class ExpiringLruCache<K, V> {
233
255
 
234
256
  const size = this.sizeOf(value);
235
257
 
236
- if (!Number.isFinite(size) || size < 0 || size > this.maxBytes)
258
+ if (!Number.isFinite(size) || size < 0 || size > this.maxBytes) {
237
259
  throw new Error("oversized cache entry");
260
+ }
238
261
  entry = { expiresAt, size, value };
239
262
  } catch {
240
263
  this.#removeFromDisk(key);
@@ -262,22 +285,12 @@ export class ExpiringLruCache<K, V> {
262
285
  chmodSync(directory, 0o700);
263
286
  const payload = this.persistence!.serialize(value);
264
287
 
265
- if (payload.byteLength > this.maxBytes * 2 + 65_536)
288
+ if (payload.byteLength > this.maxBytes * 2 + 65_536) {
266
289
  throw new Error("oversized cache payload");
267
- const path = resolveCachePath(directory, this.persistence!.keyToPath(key));
268
- const temp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
269
-
270
- try {
271
- writeFileSync(temp, Buffer.concat([encodeExpiresAt(expiresAt), payload]), { mode: 0o600 });
272
- chmodSync(temp, 0o600);
273
- renameSync(temp, path);
274
- } finally {
275
- try {
276
- unlinkSync(temp);
277
- } catch {
278
- // The rename may already have removed the temporary path.
279
- }
280
290
  }
291
+ const path = resolveCachePath(directory, this.persistence!.keyToPath(key));
292
+ const temp = `${path}.${randomUUID()}.tmp`;
293
+ writeCacheFile(path, temp, Buffer.concat([encodeExpiresAt(expiresAt), payload]));
281
294
  } catch {
282
295
  // Best-effort persistence: a failed disk write never fails the caller.
283
296
  }
@@ -296,7 +309,7 @@ export class ExpiringLruCache<K, V> {
296
309
 
297
310
  try {
298
311
  const files = readdirSync(persistence.directory);
299
- const candidates: Array<{ path: string; size: number; mtime: number }> = [];
312
+ const candidates: { path: string; size: number; mtime: number }[] = [];
300
313
 
301
314
  for (const file of files) {
302
315
  const path = resolveCachePath(persistence.directory, file);
package/src/provider.ts CHANGED
@@ -13,8 +13,8 @@ export function normalizeText(value: string, maxLength: number): string {
13
13
  if (maxLength <= 0) return "";
14
14
 
15
15
  const text = value
16
- .replace(/<[^>]*>/g, " ")
17
- .replace(/\s+/g, " ")
16
+ .replaceAll(/<[^>]*>/g, " ")
17
+ .replaceAll(/\s+/g, " ")
18
18
  .trim();
19
19
 
20
20
  return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}…`;
package/src/render.ts CHANGED
@@ -12,7 +12,7 @@ export function renderCollapsibleOutput(
12
12
  warning?: string,
13
13
  expandHint = "Ctrl+O to expand",
14
14
  ): Container {
15
- const lines = output.replace(/\r\n/g, "\n").split("\n");
15
+ const lines = output.replaceAll("\r\n", "\n").split("\n");
16
16
 
17
17
  while (lines.at(-1) === "") lines.pop();
18
18
  const visible = expanded ? lines : lines.slice(0, COLLAPSED_LINES);
@@ -22,8 +22,9 @@ export function validateProviderRequest(
22
22
  mode: SearchMode,
23
23
  extras?: ProviderRequestExtras,
24
24
  ): void {
25
- if (mode !== "web" && mode !== "answers")
25
+ if (mode !== "web" && mode !== "answers") {
26
26
  throw new Error('Search mode must be "web" or "answers".');
27
+ }
27
28
 
28
29
  if (
29
30
  mode === "answers" &&
package/src/search.ts CHANGED
@@ -26,11 +26,11 @@ import { InflightCoalescer } from "./inflight";
26
26
  import { SEARCH_DEFAULT_RESULT_COUNT } from "./limits";
27
27
  import { answerSchema, searchBraveAnswers, type BraveAnswer } from "./answers";
28
28
 
29
- const CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
29
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
30
30
 
31
31
  const CACHE_MAX_ENTRIES = 100;
32
32
 
33
- const CACHE_MAX_RESULT_BYTES = 20 * 1_024 * 1_024;
33
+ const CACHE_MAX_RESULT_BYTES = 20 * 1024 * 1024;
34
34
 
35
35
  const MAX_INFLIGHT_REQUESTS = 100;
36
36
 
@@ -152,7 +152,7 @@ export interface SearchDetails {
152
152
  }
153
153
 
154
154
  function escapeMarkdownLinkText(value: string): string {
155
- return value.replace(/([\\[\]])/g, "\\$1");
155
+ return value.replaceAll(/([\\[\]])/g, "\\$1");
156
156
  }
157
157
 
158
158
  /** Formats bounded provider results as untrusted Markdown for the tool response. */
@@ -264,7 +264,7 @@ function formatAnswer(answer: BraveAnswer, fallback: boolean): string {
264
264
  }
265
265
 
266
266
  interface SearchUpdate {
267
- content: Array<{ type: "text"; text: string }>;
267
+ content: { type: "text"; text: string }[];
268
268
  details: Record<string, never>;
269
269
  }
270
270
 
@@ -541,8 +541,9 @@ export class SearchRuntime {
541
541
 
542
542
  if (meta.showStrictWarning !== undefined) evidence.showStrictWarning = meta.showStrictWarning;
543
543
 
544
- if (meta.moreResultsAvailable !== undefined)
544
+ if (meta.moreResultsAvailable !== undefined) {
545
545
  evidence.moreResultsAvailable = meta.moreResultsAvailable;
546
+ }
546
547
 
547
548
  if (meta.operatorsApplied !== undefined) evidence.operatorsApplied = meta.operatorsApplied;
548
549
 
@@ -566,7 +567,7 @@ export class SearchRuntime {
566
567
  // Never use it to bypass the tool's output limits or private overflow storage.
567
568
  if (
568
569
  truncation.truncated ||
569
- encoder.encode(JSON.stringify(structured)).byteLength > DEFAULT_MAX_BYTES - 2_048
570
+ encoder.encode(JSON.stringify(structured)).byteLength > DEFAULT_MAX_BYTES - 2048
570
571
  ) {
571
572
  structured.results = [];
572
573
  delete structured.answer;
@@ -603,6 +604,7 @@ export class SearchRuntime {
603
604
 
604
605
  // SAFETY: the bounded result DTO contains JSON data only; serialization removes
605
606
  // optional undefined properties before exposing it to programmatic callers.
607
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- preserve output's JSON representation
606
608
  const structuredContent = JSON.parse(JSON.stringify(structured)) as NonNullable<
607
609
  AgentToolResult["structuredContent"]
608
610
  >;