@herbertgao/pi-extensions 2026.10.14 → 2026.10.15

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 (41) hide show
  1. package/README.md +8 -6
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/node_modules/@narumitw/pi-btw/README.md +1 -1
  4. package/node_modules/@narumitw/pi-btw/dist/index.ts +77 -64
  5. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
  6. package/node_modules/@narumitw/pi-btw/docs/core-alignment.md +10 -2
  7. package/node_modules/@narumitw/pi-btw/package.json +5 -5
  8. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +83 -63
  9. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  10. package/node_modules/pi-web-access/CHANGELOG.md +40 -0
  11. package/node_modules/pi-web-access/README.md +96 -22
  12. package/node_modules/pi-web-access/brave-rate-limit.ts +2 -2
  13. package/node_modules/pi-web-access/curator-page.ts +3 -1
  14. package/node_modules/pi-web-access/curator-server.ts +1 -0
  15. package/node_modules/pi-web-access/dist/index.js +2607 -1674
  16. package/node_modules/pi-web-access/dist/mcp-cli.js +1119 -327
  17. package/node_modules/pi-web-access/duckduckgo-rate-limit.ts +95 -0
  18. package/node_modules/pi-web-access/duckduckgo.ts +51 -45
  19. package/node_modules/pi-web-access/exa.ts +48 -6
  20. package/node_modules/pi-web-access/extract.ts +2 -2
  21. package/node_modules/pi-web-access/fetch-params.ts +5 -4
  22. package/node_modules/pi-web-access/field-extract.ts +347 -0
  23. package/node_modules/pi-web-access/gemini-search.ts +151 -13
  24. package/node_modules/pi-web-access/index.ts +128 -125
  25. package/node_modules/pi-web-access/mistral-search.ts +1 -1
  26. package/node_modules/pi-web-access/ninerouter.ts +92 -0
  27. package/node_modules/pi-web-access/offtopic-judge.ts +72 -0
  28. package/node_modules/pi-web-access/openai-search.ts +36 -10
  29. package/node_modules/pi-web-access/package.json +1 -1
  30. package/node_modules/pi-web-access/perplexity.ts +1 -0
  31. package/node_modules/pi-web-access/query-rewrite.ts +39 -13
  32. package/node_modules/pi-web-access/source-check.ts +31 -15
  33. package/node_modules/pi-web-access/summary-model-scope.ts +19 -1
  34. package/node_modules/pi-web-access/summary-review.ts +13 -20
  35. package/node_modules/pi-web-access/tool-arguments.ts +1 -1
  36. package/node_modules/pi-web-access/upgrade-notice.ts +47 -0
  37. package/node_modules/pi-web-access/utils.ts +26 -1
  38. package/node_modules/pi-web-access/web-tool-contract.ts +4 -1
  39. package/node_modules/pi-web-access/web-tool-core.ts +99 -19
  40. package/node_modules/pi-web-access/xai-search.ts +3 -3
  41. package/package.json +6 -6
@@ -0,0 +1,72 @@
1
+ // Asks a classifier model from Pi's catalog whether a search response addresses its query, for the
2
+ // searchRouting "off-topic" fallback (#619). eval/offtopic-judge.mjs measured the thresholds.
3
+ import type { ClassifierContext } from "@earendil-works/pi-ai";
4
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
5
+ import { isRecord } from "./utils.ts";
6
+
7
+ const LABELS = ["addresses", "off_topic"] as const;
8
+ type Label = typeof LABELS[number];
9
+
10
+ // Frozen after calibration (docs/offtopic-judge.md); change it only after re-measuring.
11
+ const INSTRUCTIONS = "A search engine returned this answer and these results for the query. addresses: the answer or at least one result is about what the query asks for, even if incomplete or outdated. off_topic: nothing is about what the query asks for, including results that only share words with it, a different meaning of the same word, or a different product.";
12
+
13
+ /** The only Pi classifier references accepted, each with its measured off_topic threshold (docs/offtopic-judge.md). */
14
+ export const OFFTOPIC_JUDGE_MODELS = {
15
+ "cloudflare-workers-ai/@cf/cloudflare/clef": 0.85,
16
+ "typesafe/jev-latest": 0.85,
17
+ "cloudflare-workers-ai/typesafe/jev-1.14.0": 0.85,
18
+ } as const;
19
+ export type OffTopicJudgeModel = keyof typeof OFFTOPIC_JUDGE_MODELS;
20
+
21
+ export type OffTopicResult = { title: string; url: string; snippet: string };
22
+ export type OffTopicJudgment = { probabilities: Record<Label, number> } | { error: string };
23
+
24
+ const TIMEOUT_MS = 10_000;
25
+ const MAX_RESULTS = 10;
26
+ const MAX_ANSWER_CHARS = 4_000;
27
+ const MAX_SNIPPET_CHARS = 500;
28
+ const PROBABILITY_SUM_TOLERANCE = 0.02;
29
+
30
+ /** Returns the model's probabilities for "addresses" and "off_topic"; every model failure is an error, a caller abort is rethrown. */
31
+ export async function judgeOffTopic(
32
+ model: OffTopicJudgeModel,
33
+ query: string,
34
+ response: { answer: string; results: OffTopicResult[] },
35
+ modelRegistry: Pick<ModelRegistry, "findOfType" | "classify">,
36
+ signal?: AbortSignal,
37
+ ): Promise<OffTopicJudgment> {
38
+ if (typeof modelRegistry.findOfType !== "function" || typeof modelRegistry.classify !== "function") return { error: "this Pi version cannot run classifier models; update Pi" };
39
+ const slash = model.indexOf("/");
40
+ const classifier = modelRegistry.findOfType("classifier", model.slice(0, slash), model.slice(slash + 1));
41
+ if (!classifier) return { error: `${model} is not in this Pi's classifier catalog` };
42
+ const context: ClassifierContext = {
43
+ state: {
44
+ query,
45
+ answer: response.answer.slice(0, MAX_ANSWER_CHARS),
46
+ results: response.results.slice(0, MAX_RESULTS).map(({ title, url, snippet }) => ({ title, url, snippet: snippet.slice(0, MAX_SNIPPET_CHARS) })),
47
+ },
48
+ // Null criteria: empty strings changed Clef's answers.
49
+ questions: { relevance: { type: "choice", instructions: INSTRUCTIONS, criteria: { addresses: null, off_topic: null } as unknown as Record<string, string> } },
50
+ };
51
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
52
+ try {
53
+ const result = await modelRegistry.classify(classifier, context, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
54
+ signal?.throwIfAborted();
55
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1000} s` };
56
+ if (result.stopReason !== "stop") return { error: result.errorMessage || `the model stopped with ${result.stopReason}` };
57
+ const answer: unknown = result.answers?.relevance;
58
+ const probabilities = isRecord(answer) ? answer.probabilities : undefined;
59
+ if (!isRecord(answer) || !LABELS.includes(answer.choice as Label) || !isRecord(probabilities)) return { error: "the response is invalid: relevance choice is not one of its labels" };
60
+ const keys = Object.keys(probabilities);
61
+ const values = LABELS.map((label) => probabilities[label]);
62
+ if (keys.length !== LABELS.length || !values.every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1)) {
63
+ return { error: "the response is invalid: relevance probabilities do not match the labels" };
64
+ }
65
+ if (Math.abs((values as number[]).reduce((total, value) => total + value, 0) - 1) > PROBABILITY_SUM_TOLERANCE) return { error: "the response is invalid: relevance probabilities do not sum to 1" };
66
+ return { probabilities: probabilities as Record<Label, number> };
67
+ } catch (err) {
68
+ signal?.throwIfAborted();
69
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1000} s` };
70
+ return { error: err instanceof Error ? err.message : String(err) };
71
+ }
72
+ }
@@ -69,6 +69,12 @@ interface CurrentModelSearchTarget {
69
69
  useCodexEndpoint: boolean;
70
70
  }
71
71
 
72
+ function isAzureResponsesUrl(url: URL): boolean {
73
+ return url.protocol === "https:" &&
74
+ [".openai.azure.com", ".cognitiveservices.azure.com", ".services.ai.azure.com"].some((suffix) => url.hostname.endsWith(suffix)) &&
75
+ /^\/openai\/v1(?:\/responses)?\/?$/u.test(url.pathname);
76
+ }
77
+
72
78
  function resolveCurrentModelSearchTarget(model: CurrentModel): CurrentModelSearchTarget {
73
79
  const url = new URL(model.baseUrl);
74
80
  if (url.protocol !== "https:") throw new Error("Current model base URL must use HTTPS");
@@ -88,7 +94,12 @@ function resolveCurrentModelSearchTarget(model: CurrentModel): CurrentModelSearc
88
94
  return { responsesUrl: CODEX_RESPONSES_URL, useCodexEndpoint: true };
89
95
  }
90
96
 
91
- throw new Error("Current model is not backed by an official OpenAI Responses endpoint");
97
+ if ((model.api === "openai-responses" || model.api === "azure-openai-responses") && isAzureResponsesUrl(url)) {
98
+ url.pathname = "/openai/v1/responses";
99
+ return { responsesUrl: url.toString(), useCodexEndpoint: false };
100
+ }
101
+
102
+ throw new Error("Current model is not backed by an official OpenAI or Azure Responses endpoint");
92
103
  }
93
104
 
94
105
  // The active model draws on a ChatGPT subscription: openai-codex, or openai signed in
@@ -101,10 +112,11 @@ export function isOpenAISubscriptionModelSelected(ctx?: Pick<ExtensionContext, "
101
112
 
102
113
  export function isCurrentModelHostedSearchEligible(ctx?: Pick<ExtensionContext, "model">): boolean {
103
114
  const model = ctx?.model;
104
- if (!model || !/^gpt-/iu.test(model.id)) return false;
115
+ if (!model) return false;
105
116
  try {
106
117
  resolveCurrentModelSearchTarget(model);
107
- return true;
118
+ // Azure model IDs are deployment names, which need not use a GPT prefix.
119
+ return /^gpt-/iu.test(model.id) || isAzureResponsesUrl(new URL(model.baseUrl));
108
120
  } catch {
109
121
  return false;
110
122
  }
@@ -330,11 +342,11 @@ async function resolvePiAuth(ctx: ExtensionContext, responsesUrl: string, provid
330
342
  return undefined;
331
343
  }
332
344
 
333
- export async function resolveOpenAIAuth(ctx?: ExtensionContext, signal?: AbortSignal): Promise<OpenAIAuth | undefined> {
345
+ export async function resolveOpenAIAuth(ctx?: ExtensionContext, signal?: AbortSignal, model?: string): Promise<OpenAIAuth | undefined> {
334
346
  const config = loadConfig();
335
347
  const responsesUrl = resolveConfiguredResponsesUrl(config.openaiResponsesUrl);
336
348
  const useProviderBaseUrl = resolveUseProviderBaseUrl(config);
337
- const modelOverride = resolveConfiguredSearchModel(config.openaiSearchModel);
349
+ const modelOverride = model ?? resolveConfiguredSearchModel(config.openaiSearchModel);
338
350
  const providers = resolveConfiguredSearchProviders(config.openaiSearchProviders);
339
351
  if (ctx) {
340
352
  const auth = await resolvePiAuth(ctx, responsesUrl, providers, modelOverride, config.openaiResponsesUrl !== undefined, useProviderBaseUrl);
@@ -383,13 +395,14 @@ export async function isOpenAISearchAvailable(ctx?: ExtensionContext): Promise<b
383
395
  async function resolveCurrentModelAuth(ctx: ExtensionContext, signal?: AbortSignal): Promise<OpenAIAuth> {
384
396
  const model = ctx.model;
385
397
  if (!model || !isCurrentModelHostedSearchEligible(ctx)) {
386
- throw new Error("Current model is not eligible for official OpenAI Hosted web search");
398
+ throw new Error("Current model is not eligible for OpenAI or Azure hosted web search");
387
399
  }
388
- const target = resolveCurrentModelSearchTarget(model);
389
400
  const resolved = await ctx.modelRegistry.getApiKeyAndHeaders(model);
390
401
  if (signal?.aborted) signal.throwIfAborted();
391
402
  if (!resolved.ok) throw new Error(`OpenAI current model authentication failed: ${resolved.error}`);
392
403
  if (!resolved.apiKey) throw new Error("OpenAI current model authentication failed: API key unavailable");
404
+ // Resolve the destination together with credentials; auth may override baseUrl.
405
+ const target = resolveCurrentModelSearchTarget({ ...model, baseUrl: resolved.baseUrl ?? model.baseUrl });
393
406
  return {
394
407
  provider: "openai",
395
408
  apiKey: resolved.apiKey,
@@ -715,9 +728,13 @@ async function runOpenAISearch(
715
728
  ctx?: Pick<ExtensionContext, "sessionManager">,
716
729
  ): Promise<SearchResponse> {
717
730
  const useAlphaSearch = isAlphaSearchEnabled();
718
- if (useAlphaSearch) options.signal?.throwIfAborted();
719
731
  const useCodexEndpoint = auth.useCodexEndpoint ?? (auth.provider === "openai-codex" || isCodexJwt(auth.apiKey));
720
732
  const responsesUrl = useCodexEndpoint && !auth.useProviderBaseUrl ? CODEX_RESPONSES_URL : auth.responsesUrl;
733
+ const isAzure = isAzureResponsesUrl(new URL(responsesUrl));
734
+ if (isAzure && useAlphaSearch) {
735
+ throw new OpenAIAlphaSearchUnsupportedError("Azure OpenAI does not support Codex alpha/search; disable openaiUseAlphaSearch to use hosted web_search");
736
+ }
737
+ if (useAlphaSearch) options.signal?.throwIfAborted();
721
738
  const requestUrl = useAlphaSearch ? resolveAlphaSearchUrl(responsesUrl) : responsesUrl;
722
739
  const body = useAlphaSearch ? buildAlphaSearchBody(query, options, auth.model) : {
723
740
  model: auth.model,
@@ -748,6 +765,15 @@ async function runOpenAISearch(
748
765
  ctx,
749
766
  );
750
767
 
768
+ if (isAzure) {
769
+ for (const name of ["Authorization", "api-key", "OpenAI-Beta", "chatgpt-account-id", "originator"]) requestHeaders.delete(name);
770
+ if (decodeJwtPayload(auth.apiKey)) {
771
+ requestHeaders.set("Authorization", `Bearer ${auth.apiKey}`);
772
+ } else {
773
+ requestHeaders.set("api-key", auth.apiKey);
774
+ }
775
+ }
776
+
751
777
  try {
752
778
  const response = await fetchWithCredentialRedirects(requestUrl, {
753
779
  method: "POST",
@@ -756,7 +782,7 @@ async function runOpenAISearch(
756
782
  signal: options.signal
757
783
  ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])
758
784
  : AbortSignal.timeout(SEARCH_TIMEOUT_MS),
759
- }, ["Authorization", "x-opencode-session", "x-opencode-client", "chatgpt-account-id", ...Object.keys(auth.headers)]);
785
+ }, ["Authorization", "api-key", "x-opencode-session", "x-opencode-client", "chatgpt-account-id", ...Object.keys(auth.headers)]);
760
786
 
761
787
  if (!response.ok) {
762
788
  activityMonitor.logError(activityId, `HTTP ${response.status}`);
@@ -804,7 +830,7 @@ export async function searchWithOpenAI(
804
830
  options: SearchOptions = {},
805
831
  ctx?: ExtensionContext,
806
832
  ): Promise<SearchResponse> {
807
- const auth = await resolveOpenAIAuth(ctx, options.signal);
833
+ const auth = await resolveOpenAIAuth(ctx, options.signal, options.model);
808
834
  if (!auth) {
809
835
  throw new Error(
810
836
  "OpenAI web search unavailable. Either:\n" +
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-access",
3
- "version": "0.44.0",
3
+ "version": "0.45.0",
4
4
  "description": "Web search, URL fetching, GitHub repo cloning, PDF extraction, YouTube video understanding, and local video analysis for Pi coding agent. Supports OpenAI, Brave, Parallel, TinyFish, Search1API, Searchinfinity, Querit, Tavily, Firecrawl, Crawl4AI, Jina, SERPdive, Kagi, Ollama, AnySearch, Bright Data SERP, SerpBase, SerpApi, Serply, You.com, SearXNG, degoog, Exa, Perplexity, Gemini, Kimi, and Mistral.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -30,6 +30,7 @@ export interface SearchResponse {
30
30
  }
31
31
 
32
32
  export interface SearchOptions {
33
+ model?: string;
33
34
  numResults?: number;
34
35
  recencyFilter?: "day" | "week" | "month" | "year";
35
36
  domainFilter?: string[];
@@ -1,7 +1,7 @@
1
1
  import type { complete, Api, Model, ProviderHeaders } from "@earendil-works/pi-ai/compat";
2
- import type { SummaryGenerationContext } from "./summary-review.ts";
2
+ import { resolveThinkingLevel, type SummaryGenerationContext } from "./summary-review.ts";
3
3
  import { awaitWithAbort } from "./abortable.ts";
4
- import { findModelWithProviderRouting, isModelInScope } from "./summary-model-scope.ts";
4
+ import { findModelWithProviderRouting, isModelInScope, resolveHelperModelSelector, type SummaryThinkingLevel } from "./summary-model-scope.ts";
5
5
 
6
6
  async function resolveFirstAvailableModel(
7
7
  ctx: SummaryGenerationContext,
@@ -16,25 +16,43 @@ async function resolveFirstAvailableModel(
16
16
  throw new Error(`No enabled model available: ${candidates.map(candidate => `${candidate.provider}/${candidate.id}`).join(", ")}`);
17
17
  }
18
18
 
19
+ async function resolveConfiguredModel(
20
+ ctx: SummaryGenerationContext,
21
+ selector: string,
22
+ ): Promise<{ model: Model<Api>; apiKey?: string; headers?: ProviderHeaders; thinkingLevel?: SummaryThinkingLevel }> {
23
+ const spec = resolveHelperModelSelector(selector, "query rewrite model", ctx.model);
24
+ if (!spec) throw new Error(`Query rewrite model not found: ${selector} (no active Pi session model)`);
25
+ const model = findModelWithProviderRouting(ctx.modelRegistry, spec.provider, spec.id);
26
+ if (!model) throw new Error(`Query rewrite model not found: ${selector}`);
27
+ const value = `${model.provider}/${model.id}`;
28
+ if (!isModelInScope(model, ctx.scopedModels)) throw new Error(`Query rewrite model is not enabled: ${value}`);
29
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
30
+ if (!auth.ok) throw new Error(`No API key available for query rewrite model ${value}`);
31
+ return { model, apiKey: auth.apiKey, headers: auth.headers, thinkingLevel: spec.thinkingLevel };
32
+ }
33
+
19
34
  export async function rewriteSearchQuery(
20
35
  query: string,
21
36
  ctx: SummaryGenerationContext,
22
37
  signal: AbortSignal,
38
+ modelSelector?: string,
23
39
  ): Promise<string> {
24
- const { model, apiKey, headers } = await resolveFirstAvailableModel(ctx, [
25
- { provider: "anthropic", id: "claude-haiku-4-5" },
26
- { provider: "google", id: "gemini-3.6-flash" },
27
- { provider: "openai", id: "gpt-5-mini" },
28
- ]);
40
+ const { model, apiKey, headers, thinkingLevel }: Awaited<ReturnType<typeof resolveConfiguredModel>> = modelSelector === undefined
41
+ ? await resolveFirstAvailableModel(ctx, [
42
+ { provider: "anthropic", id: "claude-haiku-4-5" },
43
+ { provider: "google", id: "gemini-3.6-flash" },
44
+ { provider: "openai", id: "gpt-5-mini" },
45
+ ])
46
+ : await resolveConfiguredModel(ctx, modelSelector);
29
47
  const registry = ctx.modelRegistry as typeof ctx.modelRegistry & { complete?: typeof complete };
30
48
  // streamSimple is Pi's provider-neutral path and routes virtual models; complete() does not (#574).
31
49
  const usesRegistryStreamSimple = typeof registry.streamSimple === "function";
32
50
  const usesRegistryComplete = !usesRegistryStreamSimple && typeof registry.complete === "function";
33
51
  if (signal.aborted) throw new Error("Aborted");
34
- const completeFn = usesRegistryStreamSimple
35
- ? undefined
36
- : usesRegistryComplete ? registry.complete!.bind(registry) : (await awaitWithAbort(import("@earendil-works/pi-ai/compat"), signal)).complete;
52
+ const compat = usesRegistryStreamSimple || usesRegistryComplete ? undefined : await awaitWithAbort(import("@earendil-works/pi-ai/compat"), signal);
37
53
  if (signal.aborted) throw new Error("Aborted");
54
+ const requestedThinkingLevel = await awaitWithAbort(resolveThinkingLevel(model, thinkingLevel), signal);
55
+ const reasoning = requestedThinkingLevel !== "off" ? requestedThinkingLevel : undefined;
38
56
  const context = {
39
57
  messages: [{
40
58
  role: "user" as const,
@@ -42,9 +60,17 @@ export async function rewriteSearchQuery(
42
60
  timestamp: Date.now(),
43
61
  }],
44
62
  };
45
- const response = completeFn
46
- ? await completeFn(model, context, usesRegistryComplete ? { signal } : { apiKey, headers, signal })
47
- : await registry.streamSimple(model, context, { signal }).result();
63
+ const response = usesRegistryStreamSimple
64
+ ? await registry.streamSimple(model, context, { signal, ...(reasoning ? { reasoning } : {}) }).result()
65
+ : usesRegistryComplete
66
+ ? await registry.complete!(model, context, {
67
+ signal,
68
+ ...(requestedThinkingLevel ? { reasoning: requestedThinkingLevel } : {}),
69
+ ...(reasoning ? { reasoningEffort: reasoning } : {}),
70
+ })
71
+ : thinkingLevel
72
+ ? await compat!.completeSimple(model, context, { apiKey, headers, signal, ...(reasoning ? { reasoning } : {}) })
73
+ : await compat!.complete(model, context, { apiKey, headers, signal });
48
74
  if (response.stopReason === "aborted") throw new Error("Aborted");
49
75
  const contentParts = Array.isArray(response.content) ? response.content : [];
50
76
  const text = contentParts
@@ -100,26 +100,43 @@ export function hashContent(text: string): string {
100
100
  interface Span { text: string; start: number; end: number }
101
101
 
102
102
  function tokenize(value: string): string[] {
103
- return [...new Set(value.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length > 3))];
103
+ // Short words are mostly noise ("the", "for"), but short acronyms and numbers ("API", "TLS", "429") carry meaning.
104
+ return [...new Set(value.split(/[^A-Za-z0-9]+/)
105
+ .filter((term) => term.length > 3 || (term.length > 1 && /^[A-Z0-9]+$/.test(term)))
106
+ .map((term) => term.length > 3 ? term.toLowerCase() : term))];
104
107
  }
105
108
 
106
- function extractRelevantSpans(content: string, hint: string): Span[] {
109
+ /** Long terms match inside words in any case ("stream" in "Streaming"); short acronyms only as whole words in the same case, so "API" skips "rapid" and "US" skips "us". */
110
+ function countMatches(terms: string[], text: string): number {
111
+ const lower = text.toLowerCase();
112
+ const words = new Set(text.split(/[^A-Za-z0-9]+/));
113
+ return terms.filter((term) => term.length > 3 ? lower.includes(term) : words.has(term)).length;
114
+ }
115
+
116
+ function extractRelevantSpans(content: string, claim: string, snippet: string): Span[] {
107
117
  const sentences: Span[] = [];
108
- const sentencePattern = /[^.!?]+(?:[.!?]+(?=\s|$)|$)/g;
109
- for (const match of content.matchAll(sentencePattern)) {
110
- const raw = match[0];
118
+ // A sentence ends at punctuation (plus closing quotes, brackets, emphasis or a [n] citation) followed by
119
+ // whitespace or the end, so "example.com" stays inside its sentence. The lookbehind starts each attempt only at
120
+ // the beginning of a punctuation run, which keeps the scan linear on long runs such as "!!!…x".
121
+ const boundary = /(?<![.!?])[.!?]+(?:["'”’)\]*_]|\[\d+\])*(?=\s|$)/g;
122
+ let segmentStart = 0;
123
+ const addSentence = (end: number) => {
124
+ const raw = content.slice(segmentStart, end);
111
125
  const text = raw.trim();
112
126
  if (text.length > 0 && text.length <= 400) {
113
- const start = (match.index ?? 0) + raw.indexOf(text);
127
+ const start = segmentStart + raw.indexOf(text);
114
128
  sentences.push({ text, start, end: start + text.length });
115
129
  }
116
- }
117
- const terms = tokenize(hint);
118
- if (terms.length === 0) return [];
130
+ segmentStart = end;
131
+ };
132
+ for (const match of content.matchAll(boundary)) addSentence(match.index + match[0].length);
133
+ addSentence(content.length);
134
+ const claimTerms = tokenize(claim);
135
+ const snippetTerms = tokenize(snippet);
119
136
  return sentences
120
- .map((sentence, index) => ({ sentence, index, score: terms.filter((term) => sentence.text.toLowerCase().includes(term)).length }))
121
- .filter((item) => item.score > 0)
122
- .sort((a, b) => b.score - a.score || a.index - b.index)
137
+ .map((sentence, index) => ({ sentence, index, claim: countMatches(claimTerms, sentence.text), snippet: countMatches(snippetTerms, sentence.text) }))
138
+ .filter((item) => item.claim + item.snippet > 0)
139
+ .sort((a, b) => b.claim - a.claim || b.snippet - a.snippet || a.index - b.index)
123
140
  .slice(0, 3)
124
141
  .map(({ sentence }) => sentence);
125
142
  }
@@ -128,7 +145,7 @@ function passageId(sourceRank: number, index: number): string {
128
145
  return `p-${sourceRank}-${index}`;
129
146
  }
130
147
 
131
- export function buildPassages(sources: ResearchSource[], fetched: ExtractedContent[] = [], hint = ""): ResearchPassage[] {
148
+ export function buildPassages(sources: ResearchSource[], fetched: ExtractedContent[] = [], claim = ""): ResearchPassage[] {
132
149
  const passages: ResearchPassage[] = [];
133
150
  const fetchedByUrl = new Map(fetched.map((item) => [item.url, item]));
134
151
  for (const source of sources) {
@@ -143,8 +160,7 @@ export function buildPassages(sources: ResearchSource[], fetched: ExtractedConte
143
160
  }
144
161
  const page = fetchedByUrl.get(source.url);
145
162
  if (page && !page.error && page.content) {
146
- const passageHint = source.snippet?.trim() || hint;
147
- for (const [index, span] of extractRelevantSpans(page.content, passageHint).entries()) {
163
+ for (const [index, span] of extractRelevantSpans(page.content, claim, source.snippet ?? "").entries()) {
148
164
  passages.push({
149
165
  passage_id: passageId(source.rank, index + 1),
150
166
  source_url: source.url,
@@ -44,7 +44,7 @@ export function isModelInScope(model: ModelLike, scopedModels: ReadonlyArray<{ m
44
44
  return scopedModels.length === 0 || scopedModels.some(scoped => scoped.model.provider === model.provider && scoped.model.id === model.id);
45
45
  }
46
46
 
47
- export function splitThinkingSuffix(value: string): { value: string; thinkingLevel?: SummaryThinkingLevel } {
47
+ function splitThinkingSuffix(value: string): { value: string; thinkingLevel?: SummaryThinkingLevel } {
48
48
  const index = value.lastIndexOf(":");
49
49
  if (index < 0) return { value };
50
50
  const suffix = value.slice(index + 1);
@@ -52,3 +52,21 @@ export function splitThinkingSuffix(value: string): { value: string; thinkingLev
52
52
  ? { value: value.slice(0, index), thinkingLevel: suffix as SummaryThinkingLevel }
53
53
  : { value };
54
54
  }
55
+
56
+ /**
57
+ * Parse `current[:level]` or `provider/model-id[:level]`; `current` names the active Pi session model and
58
+ * resolves to undefined when there is none. Throws for any other value.
59
+ */
60
+ export function resolveHelperModelSelector(
61
+ value: string,
62
+ label: string,
63
+ currentModel?: ModelLike,
64
+ ): { provider: string; id: string; thinkingLevel?: SummaryThinkingLevel } | undefined {
65
+ const { value: selector, thinkingLevel } = splitThinkingSuffix(value.trim());
66
+ if (selector === "current") return currentModel ? { provider: currentModel.provider, id: currentModel.id, thinkingLevel } : undefined;
67
+ const slashIndex = selector.indexOf("/");
68
+ if (slashIndex <= 0 || slashIndex >= selector.length - 1) {
69
+ throw new Error(`Invalid ${label}: ${value}. Use provider/model-id or current.`);
70
+ }
71
+ return { provider: selector.slice(0, slashIndex), id: selector.slice(slashIndex + 1), thinkingLevel };
72
+ }
@@ -1,7 +1,7 @@
1
1
  import type { ModelThinkingLevel, ThinkingLevel } from "@earendil-works/pi-ai";
2
2
  import type { complete, Api, Message, Model } from "@earendil-works/pi-ai/compat";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
- import { findModelWithProviderRouting, isModelInScope, splitThinkingSuffix, type SummaryThinkingLevel } from "./summary-model-scope.ts";
4
+ import { findModelWithProviderRouting, isModelInScope, resolveHelperModelSelector, type SummaryThinkingLevel } from "./summary-model-scope.ts";
5
5
  import type { QueryResultData } from "./storage.ts";
6
6
 
7
7
  type ProviderHeaders = Record<string, string | null>;
@@ -206,20 +206,7 @@ export function buildDeterministicSummary(results: QueryResultData[]): { summary
206
206
  };
207
207
  }
208
208
 
209
- function parseModelSelector(value: string): { provider: string; id: string; thinkingLevel?: SummaryThinkingLevel } {
210
- const selector = splitThinkingSuffix(value);
211
- const slashIndex = selector.value.indexOf("/");
212
- if (slashIndex <= 0 || slashIndex >= selector.value.length - 1) {
213
- throw new Error(`Invalid summary model: ${value}. Use provider/model-id.`);
214
- }
215
- return {
216
- provider: selector.value.slice(0, slashIndex),
217
- id: selector.value.slice(slashIndex + 1),
218
- thinkingLevel: selector.thinkingLevel,
219
- };
220
- }
221
-
222
- async function resolveThinkingLevel(model: Model<Api>, requested?: SummaryThinkingLevel): Promise<ModelThinkingLevel | undefined> {
209
+ export async function resolveThinkingLevel(model: Model<Api>, requested?: SummaryThinkingLevel): Promise<ModelThinkingLevel | undefined> {
223
210
  if (!requested) return undefined;
224
211
  const { clampThinkingLevel } = await import("@earendil-works/pi-ai");
225
212
  return clampThinkingLevel(model, requested as ModelThinkingLevel);
@@ -227,15 +214,20 @@ async function resolveThinkingLevel(model: Model<Api>, requested?: SummaryThinki
227
214
 
228
215
  async function resolveSummaryModelCandidates(
229
216
  ctx: SummaryGenerationContext,
230
- modelOverride?: string,
217
+ modelOverride: string | undefined,
218
+ preferredFallback: boolean,
231
219
  ): Promise<{ candidates: Array<{ model: Model<Api>; apiKey?: string; headers?: ProviderHeaders; thinkingLevel?: SummaryThinkingLevel }>; errors: string[] }> {
232
220
  const specs: Array<{ provider: string; id: string; thinkingLevel?: SummaryThinkingLevel }> = [];
221
+ const errors: string[] = [];
233
222
  const normalizedOverride = typeof modelOverride === "string" ? modelOverride.trim() : "";
234
- if (normalizedOverride.length > 0) specs.push(parseModelSelector(normalizedOverride));
235
- specs.push(...PREFERRED_SUMMARY_MODELS);
223
+ if (normalizedOverride.length > 0) {
224
+ const spec = resolveHelperModelSelector(normalizedOverride, "summary model", ctx.model);
225
+ if (spec) specs.push(spec);
226
+ else errors.push(`Summary model not found: ${normalizedOverride} (no active Pi session model)`);
227
+ }
228
+ if (preferredFallback) specs.push(...PREFERRED_SUMMARY_MODELS);
236
229
 
237
230
  const candidates: Array<{ model: Model<Api>; apiKey?: string; headers?: ProviderHeaders; thinkingLevel?: SummaryThinkingLevel }> = [];
238
- const errors: string[] = [];
239
231
  const seen = new Set<string>();
240
232
  for (const spec of specs) {
241
233
  const value = `${spec.provider}/${spec.id}`;
@@ -307,6 +299,7 @@ export async function generateSummaryDraft(
307
299
  completeFn?: CompleteFunction,
308
300
  deadlineMs = SUMMARY_GENERATION_DEADLINE_MS,
309
301
  instructions?: string,
302
+ options: { preferredFallback?: boolean } = {},
310
303
  ): Promise<{ summary: string; meta: SummaryMeta }> {
311
304
  if (!ctx || !ctx.modelRegistry) {
312
305
  throw new Error("Summary generation context unavailable");
@@ -374,7 +367,7 @@ export async function generateSummaryDraft(
374
367
  piAiCompat = await raceSummaryOperation(import("@earendil-works/pi-ai/compat"));
375
368
  }
376
369
  if (!usesRegistryStreamSimple) completeFn ??= usesRegistryComplete ? registry.complete!.bind(registry) as CompleteFunction : piAiCompat!.complete;
377
- resolved = await raceSummaryOperation(resolveSummaryModelCandidates(ctx, modelOverride));
370
+ resolved = await raceSummaryOperation(resolveSummaryModelCandidates(ctx, modelOverride, options.preferredFallback ?? true));
378
371
  } catch (err) {
379
372
  checkSummaryDeadline();
380
373
  const message = err instanceof Error ? err.message : String(err);
@@ -1,5 +1,5 @@
1
1
  // Some models send array arguments as a JSON string, for example
2
- // `provider: "[\"parallel-mcp\"]"`, which fails schema validation before the tool
2
+ // `queries: "[\"a\", \"b\"]"`, which fails schema validation before the tool
3
3
  // runs. Parse such strings back into arrays of strings, reject strings that start
4
4
  // with "[" but are not valid JSON, and leave anything else as is.
5
5
  export function parseStringifiedArrays(args: unknown, keys: readonly string[]): unknown {
@@ -0,0 +1,47 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import packageJson from "./package.json" with { type: "json" };
7
+
8
+ // major.minor.patch as one comparable number; undefined for anything else.
9
+ const versionNumber = (version: unknown) => typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version)
10
+ ? version.split(".").reduce((total, part) => total * 1e6 + Number(part), 0)
11
+ : undefined;
12
+
13
+ export async function showUpgradeNotice(
14
+ ctx: { hasUI: boolean; ui: { notify(message: string, type: "info"): void } },
15
+ stateDir = join(getAgentDir(), "pi-web-access"),
16
+ // npm installs run the bundle in dist/, a checkout runs this file from the package root.
17
+ changelogPath = fileURLToPath(new URL(/\/dist\/[^/]+$/.test(import.meta.url) ? "../CHANGELOG.md" : "./CHANGELOG.md", import.meta.url)),
18
+ version = packageJson.version,
19
+ ): Promise<void> {
20
+ if (!ctx.hasUI) return;
21
+ const statePath = join(stateDir, "last-seen-version.json");
22
+ const lastSeen = await readFile(statePath, "utf-8").then((raw) => JSON.parse(raw).version).catch(() => undefined);
23
+ const previous = versionNumber(lastSeen);
24
+ const current = versionNumber(version);
25
+ if (current === undefined || previous === current) return;
26
+ try {
27
+ mkdirSync(stateDir, { recursive: true });
28
+ writeFileSync(statePath, JSON.stringify({ version }));
29
+ } catch {
30
+ // Read-only installs cannot record the seen version. Without it the notice would repeat on every start, so skip it.
31
+ return;
32
+ }
33
+ if (previous === undefined || previous > current) return;
34
+
35
+ const bullets = (await readFile(changelogPath, "utf-8")).split(/^## /m).flatMap((section) => {
36
+ const released = versionNumber(/^\[([^\]]+)\]/.exec(section)?.[1]);
37
+ if (released === undefined || released <= previous || released > current) return [];
38
+ const highlights = section.split(/^### /m).find((part) => part.startsWith("Highlights")) ?? "";
39
+ return (highlights.match(/^- .*/gm) ?? []).map((bullet) => bullet.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim());
40
+ });
41
+ ctx.ui.notify([
42
+ `pi-web-access updated from ${lastSeen} to ${version}`,
43
+ ...bullets.slice(0, 5),
44
+ ...(bullets.length > 5 ? [`...and ${bullets.length - 5} more`] : []),
45
+ "Changelog: https://github.com/nicobailon/pi-web-access/blob/main/CHANGELOG.md",
46
+ ].join("\n"), "info");
47
+ }
@@ -51,6 +51,31 @@ export function isLoopbackHostname(hostnameValue: string): boolean {
51
51
  || (isIP(normalized) === 4 && normalized.split(".", 1)[0] === "127");
52
52
  }
53
53
 
54
+ export function isRecord(value: unknown): value is Record<string, unknown> {
55
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56
+ }
57
+
58
+ function allowsHttpBaseUrls(): boolean {
59
+ const environmentValue = process.env.PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS;
60
+ if (environmentValue !== undefined) {
61
+ const value = environmentValue.trim().toLowerCase();
62
+ if (value === "true" || value === "1") return true;
63
+ if (value === "false" || value === "0") return false;
64
+ throw new Error("Invalid configuration: PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS must be true, false, 1, or 0");
65
+ }
66
+ const path = getWebSearchConfigPath();
67
+ if (!existsSync(path)) return false;
68
+ let raw: unknown;
69
+ try {
70
+ raw = JSON.parse(readFileSync(path, "utf-8"));
71
+ } catch (err) {
72
+ throw new Error(`Failed to parse ${path}: ${err instanceof Error ? err.message : String(err)}`);
73
+ }
74
+ const value = isRecord(raw) ? raw.allowHttpBaseUrls : undefined;
75
+ if (value !== undefined && typeof value !== "boolean") throw new Error(`allowHttpBaseUrls in ${path} must be a boolean`);
76
+ return value === true;
77
+ }
78
+
54
79
  export function resolveApiBaseUrl(options: ApiBaseUrlOptions): string {
55
80
  const fromEnvironment = options.environmentValue !== undefined;
56
81
  const value = fromEnvironment ? options.environmentValue : options.configuredValue;
@@ -69,7 +94,7 @@ export function resolveApiBaseUrl(options: ApiBaseUrlOptions): string {
69
94
  } catch {
70
95
  throw new Error(`${source} must be an absolute HTTP(S) URL`);
71
96
  }
72
- if (url.protocol !== "https:" && (url.protocol !== "http:" || !isLoopbackHostname(url.hostname))) {
97
+ if (url.protocol !== "https:" && (url.protocol !== "http:" || (!isLoopbackHostname(url.hostname) && !allowsHttpBaseUrls()))) {
73
98
  throw new Error(`${source} must be an absolute HTTPS URL`);
74
99
  }
75
100
  if (url.username || url.password) {
@@ -3,6 +3,7 @@
3
3
  // behavior lives in one place; each host keeps its own schemas and transport.
4
4
 
5
5
  import type { FindMode } from "./content-find.ts";
6
+ import type { PageExtraction } from "./field-extract.ts";
6
7
  import type { RecencyFilter } from "./source-check.ts";
7
8
 
8
9
  export type WebToolContent =
@@ -32,10 +33,12 @@ export type WebSearchStructuredContent = {
32
33
 
33
34
  export type FetchContentStructuredContent = {
34
35
  responseId: string | null;
35
- urls: Array<{ url: string; title: string; content: string; error: string | null; mimeType?: string; status?: number; duration?: number }>;
36
+ /** In extract mode, each fetched URL also has its `extraction`: typed fields per name, or why extraction failed. */
37
+ urls: Array<{ url: string; title: string; content: string; error: string | null; mimeType?: string; status?: number; duration?: number; extraction?: PageExtraction }>;
36
38
  };
37
39
 
38
40
  export interface WebSearchCallParams {
41
+ model?: string;
39
42
  query?: string;
40
43
  queries?: string[];
41
44
  numResults?: number;