@abhishek944/pi-web-access 0.0.0-stage → 0.1.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.
- package/ASTACK.md +23 -0
- package/CHANGELOG.md +1289 -0
- package/LICENSE +21 -0
- package/README.md +1215 -2
- package/SECURITY.md +5 -0
- package/abortable.ts +17 -0
- package/activity.ts +101 -0
- package/anysearch.ts +188 -0
- package/auth-fetch.ts +152 -0
- package/baizhi.ts +124 -0
- package/banner.png +0 -0
- package/bocha.ts +203 -0
- package/brave-rate-limit.ts +176 -0
- package/brave.ts +247 -0
- package/brightdata-unlocker.ts +272 -0
- package/ceramic.ts +220 -0
- package/chrome-cookies.ts +752 -0
- package/cloudflare-search.ts +237 -0
- package/content-find.ts +255 -0
- package/crawl4ai.ts +196 -0
- package/credential-source.ts +242 -0
- package/curator-page.ts +3607 -0
- package/curator-run.ts +45 -0
- package/curator-server.ts +761 -0
- package/custom-search.ts +226 -0
- package/data-uri-sanitize.ts +406 -0
- package/datalab-pdf-extract.ts +568 -0
- package/declared-web-links.ts +173 -0
- package/deepseek.ts +377 -0
- package/degoog.ts +323 -0
- package/dist/index.js +28286 -0
- package/dist/mcp-cli.js +29186 -0
- package/dist/pi-mcp.js +20855 -0
- package/dist/types/abortable.d.ts +2 -0
- package/dist/types/activity.d.ts +33 -0
- package/dist/types/anysearch.d.ts +7 -0
- package/dist/types/auth-fetch.d.ts +14 -0
- package/dist/types/baizhi.d.ts +3 -0
- package/dist/types/bocha.d.ts +3 -0
- package/dist/types/brave-rate-limit.d.ts +35 -0
- package/dist/types/brave.d.ts +3 -0
- package/dist/types/brightdata-unlocker.d.ts +11 -0
- package/dist/types/ceramic.d.ts +3 -0
- package/dist/types/chrome-cookies.d.ts +44 -0
- package/dist/types/cloudflare-search.d.ts +4 -0
- package/dist/types/content-find.d.ts +10 -0
- package/dist/types/crawl4ai.d.ts +8 -0
- package/dist/types/credential-source.d.ts +29 -0
- package/dist/types/curator-page.d.ts +5 -0
- package/dist/types/curator-run.d.ts +10 -0
- package/dist/types/curator-server.d.ts +72 -0
- package/dist/types/custom-search.d.ts +22 -0
- package/dist/types/data-uri-sanitize.d.ts +20 -0
- package/dist/types/datalab-pdf-extract.d.ts +59 -0
- package/dist/types/declared-web-links.d.ts +7 -0
- package/dist/types/deepseek.d.ts +13 -0
- package/dist/types/degoog.d.ts +3 -0
- package/dist/types/domain-filter-normalization.d.ts +9 -0
- package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
- package/dist/types/duckduckgo.d.ts +6 -0
- package/dist/types/endpoint-pdf-extract.d.ts +22 -0
- package/dist/types/exa.d.ts +17 -0
- package/dist/types/extract.d.ts +70 -0
- package/dist/types/feature-config.d.ts +2 -0
- package/dist/types/fetch-params.d.ts +39 -0
- package/dist/types/field-extract.d.ts +37 -0
- package/dist/types/firecrawl.d.ts +18 -0
- package/dist/types/gemini-adc.d.ts +9 -0
- package/dist/types/gemini-api.d.ts +37 -0
- package/dist/types/gemini-pdf-extract.d.ts +8 -0
- package/dist/types/gemini-search.d.ts +76 -0
- package/dist/types/gemini-url-context.d.ts +3 -0
- package/dist/types/gemini-web-config.d.ts +25 -0
- package/dist/types/gemini-web.d.ts +31 -0
- package/dist/types/github-api.d.ts +6 -0
- package/dist/types/github-extract.d.ts +19 -0
- package/dist/types/github-issue-pr.d.ts +28 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/jina-search.d.ts +7 -0
- package/dist/types/kagi.d.ts +14 -0
- package/dist/types/keenable.d.ts +3 -0
- package/dist/types/kimi-search.d.ts +4 -0
- package/dist/types/linkup.d.ts +5 -0
- package/dist/types/mcp-cli.d.ts +2 -0
- package/dist/types/mcp-server.d.ts +10 -0
- package/dist/types/mcp-tool-definitions.d.ts +16 -0
- package/dist/types/mistral-search.d.ts +3 -0
- package/dist/types/ninerouter.d.ts +3 -0
- package/dist/types/offtopic-judge.d.ts +26 -0
- package/dist/types/ollama.d.ts +14 -0
- package/dist/types/openai-search.d.ts +23 -0
- package/dist/types/page-query.d.ts +22 -0
- package/dist/types/parallel-mcp.d.ts +10 -0
- package/dist/types/parallel.d.ts +13 -0
- package/dist/types/pdf-extract.d.ts +44 -0
- package/dist/types/perplexity.d.ts +26 -0
- package/dist/types/pi-mcp.d.ts +56 -0
- package/dist/types/pi-session-results.d.ts +8 -0
- package/dist/types/querit.d.ts +9 -0
- package/dist/types/query-rewrite.d.ts +2 -0
- package/dist/types/render-search-error.d.ts +56 -0
- package/dist/types/retrieval-only.d.ts +78 -0
- package/dist/types/rsc-extract.d.ts +11 -0
- package/dist/types/search-answer-formatting.d.ts +7 -0
- package/dist/types/search-result-count-normalization.d.ts +1 -0
- package/dist/types/searchinfinity.d.ts +7 -0
- package/dist/types/searxng.d.ts +3 -0
- package/dist/types/source-check.d.ts +102 -0
- package/dist/types/ssrf-protection.d.ts +66 -0
- package/dist/types/storage.d.ts +69 -0
- package/dist/types/summary-model-scope.d.ts +33 -0
- package/dist/types/summary-review.d.ts +30 -0
- package/dist/types/tabstack.d.ts +5 -0
- package/dist/types/tavily.d.ts +7 -0
- package/dist/types/tinyfish.d.ts +10 -0
- package/dist/types/tool-activation.d.ts +7 -0
- package/dist/types/tool-arguments.d.ts +1 -0
- package/dist/types/upgrade-notice.d.ts +6 -0
- package/dist/types/utils.d.ts +55 -0
- package/dist/types/valyu.d.ts +5 -0
- package/dist/types/video-extract.d.ts +15 -0
- package/dist/types/web-tool-contract.d.ts +98 -0
- package/dist/types/web-tool-core.d.ts +227 -0
- package/dist/types/xai-search.d.ts +12 -0
- package/dist/types/you.d.ts +3 -0
- package/dist/types/youtube-extract.d.ts +29 -0
- package/dist/types/zai.d.ts +3 -0
- package/docs/pi-mcp.md +41 -0
- package/domain-filter-normalization.ts +44 -0
- package/duckduckgo-rate-limit.ts +205 -0
- package/duckduckgo.ts +123 -0
- package/endpoint-pdf-extract.ts +225 -0
- package/exa.ts +620 -0
- package/extract.ts +1721 -0
- package/feature-config.ts +29 -0
- package/fetch-params.ts +147 -0
- package/field-extract.ts +347 -0
- package/firecrawl.ts +476 -0
- package/gemini-adc.ts +345 -0
- package/gemini-api.ts +368 -0
- package/gemini-pdf-extract.ts +108 -0
- package/gemini-search.ts +1162 -0
- package/gemini-url-context.ts +128 -0
- package/gemini-web-config.ts +131 -0
- package/gemini-web.ts +527 -0
- package/github-api.ts +197 -0
- package/github-extract.ts +1064 -0
- package/github-issue-pr.ts +717 -0
- package/index.ts +2819 -0
- package/jina-search.ts +275 -0
- package/kagi.ts +257 -0
- package/keenable.ts +222 -0
- package/kimi-search.ts +209 -0
- package/linkup.ts +170 -0
- package/mcp-cli.ts +40 -0
- package/mcp-server.ts +84 -0
- package/mcp-tool-definitions.ts +143 -0
- package/mistral-search.ts +268 -0
- package/ninerouter.ts +92 -0
- package/offtopic-judge.ts +72 -0
- package/ollama.ts +237 -0
- package/openai-search.ts +855 -0
- package/package.json +108 -4
- package/page-query.ts +185 -0
- package/parallel-mcp.ts +255 -0
- package/parallel.ts +373 -0
- package/pdf-extract.ts +447 -0
- package/perplexity.ts +245 -0
- package/pi-mcp.ts +139 -0
- package/pi-session-results.ts +40 -0
- package/pi-web-fetch-demo.mp4 +0 -0
- package/promise-try.d.ts +7 -0
- package/querit.ts +394 -0
- package/query-rewrite.ts +84 -0
- package/render-search-error.ts +170 -0
- package/retrieval-only.ts +102 -0
- package/rsc-extract.ts +338 -0
- package/search-answer-formatting.ts +11 -0
- package/search-result-count-normalization.ts +4 -0
- package/searchinfinity.ts +246 -0
- package/searxng.ts +236 -0
- package/source-check.ts +269 -0
- package/ssrf-protection.ts +602 -0
- package/storage.ts +547 -0
- package/summary-model-scope.ts +72 -0
- package/summary-review.ts +476 -0
- package/tabstack.ts +289 -0
- package/tavily.ts +257 -0
- package/tinyfish.ts +373 -0
- package/tool-activation.ts +169 -0
- package/tool-arguments.ts +23 -0
- package/upgrade-notice.ts +47 -0
- package/utils.ts +693 -0
- package/valyu.ts +177 -0
- package/video-extract.ts +398 -0
- package/web-tool-contract.ts +93 -0
- package/web-tool-core.ts +1810 -0
- package/xai-search.ts +443 -0
- package/you.ts +165 -0
- package/youtube-extract.ts +336 -0
- package/zai.ts +161 -0
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
import type { ModelThinkingLevel, ThinkingLevel } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { complete, Api, Message, Model } from "@earendil-works/pi-ai/compat";
|
|
3
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { findModelWithProviderRouting, isModelInScope, resolveHelperModelSelector, type SummaryThinkingLevel } from "./summary-model-scope.ts";
|
|
5
|
+
import type { QueryResultData } from "./storage.ts";
|
|
6
|
+
|
|
7
|
+
type ProviderHeaders = Record<string, string | null>;
|
|
8
|
+
type CompleteFunction = typeof complete;
|
|
9
|
+
type SummaryModelRegistry = SummaryGenerationContext["modelRegistry"] & { complete?: CompleteFunction };
|
|
10
|
+
|
|
11
|
+
const PREFERRED_SUMMARY_MODELS = [
|
|
12
|
+
{ provider: "anthropic", id: "claude-haiku-4-5" },
|
|
13
|
+
{ provider: "openai-codex", id: "gpt-5.6-luna" },
|
|
14
|
+
{ provider: "openai-codex", id: "gpt-5.6-terra" },
|
|
15
|
+
{ provider: "google", id: "gemini-3.6-flash" },
|
|
16
|
+
{ provider: "openai", id: "gpt-5-mini" },
|
|
17
|
+
{ provider: "deepseek", id: "deepseek-v4-flash" },
|
|
18
|
+
] as const;
|
|
19
|
+
|
|
20
|
+
export const SUMMARY_GENERATION_DEADLINE_MS = 30_000;
|
|
21
|
+
|
|
22
|
+
export interface SummaryMeta {
|
|
23
|
+
model: string | null;
|
|
24
|
+
durationMs: number;
|
|
25
|
+
tokenEstimate: number;
|
|
26
|
+
fallbackUsed: boolean;
|
|
27
|
+
fallbackReason?: string;
|
|
28
|
+
phase?: "summary-model" | "deterministic-fallback";
|
|
29
|
+
edited?: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type SummaryGenerationContext = Pick<ExtensionContext, "model" | "modelRegistry" | "sessionManager" | "scopedModels">;
|
|
33
|
+
|
|
34
|
+
type SummaryModelFailure = { model: string; reason: string; message: string };
|
|
35
|
+
|
|
36
|
+
function estimateTokens(text: string): number {
|
|
37
|
+
const trimmed = text.trim();
|
|
38
|
+
if (trimmed.length === 0) return 0;
|
|
39
|
+
return Math.max(1, Math.ceil(trimmed.length / 4));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function summarizeQueryResult(result: QueryResultData): string {
|
|
43
|
+
if (result.error) {
|
|
44
|
+
return `Query: ${result.query}\nStatus: Error\nError: ${result.error}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const lines = [
|
|
48
|
+
`Query: ${result.query}`,
|
|
49
|
+
`Provider: ${result.provider ?? "unknown"}`,
|
|
50
|
+
`Answer: ${result.answer || "(no answer text returned)"}`,
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
if (result.results.length === 0) {
|
|
54
|
+
lines.push("Sources: none");
|
|
55
|
+
return lines.join("\n");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
lines.push("Sources:");
|
|
59
|
+
// Snippets are the only evidence when there is no answer, so they get a larger
|
|
60
|
+
// budget; uncapped, they would overrun the summary deadline.
|
|
61
|
+
const [perSource, perQuery] = result.answer?.trim() ? [200, 3_000] : [600, 12_000];
|
|
62
|
+
let budgetLeft = perQuery;
|
|
63
|
+
for (let i = 0; i < result.results.length; i++) {
|
|
64
|
+
const source = result.results[i];
|
|
65
|
+
lines.push(`${i + 1}. ${source.title} — ${source.url}`);
|
|
66
|
+
const text = (source.snippet ?? "").replace(/\s+/g, " ").trim();
|
|
67
|
+
const limit = Math.min(perSource, budgetLeft);
|
|
68
|
+
if (!text || limit <= 0) continue;
|
|
69
|
+
const snippet = text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;
|
|
70
|
+
budgetLeft -= snippet.length;
|
|
71
|
+
lines.push(` ${snippet}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return lines.join("\n");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function buildSummaryPrompt(results: QueryResultData[], feedback?: string, instructions?: string): string {
|
|
78
|
+
const sections = [
|
|
79
|
+
"You are writing the final web search summary for a coding assistant.",
|
|
80
|
+
"Write a concise, factual summary using only the provided search results.",
|
|
81
|
+
"Requirements:",
|
|
82
|
+
"- Keep it readable and skimmable.",
|
|
83
|
+
"- Include key findings and caveats.",
|
|
84
|
+
"- Do not invent sources or claims.",
|
|
85
|
+
"- If evidence is weak or conflicting, say so explicitly.",
|
|
86
|
+
"- End with a short \"Sources\" section listing the most relevant URLs.",
|
|
87
|
+
];
|
|
88
|
+
|
|
89
|
+
const extraInstructions = typeof instructions === "string" ? instructions.trim() : "";
|
|
90
|
+
if (extraInstructions) {
|
|
91
|
+
sections.push(extraInstructions);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (feedback) {
|
|
95
|
+
sections.push("- Incorporate the user feedback provided below into the summary.");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
sections.push("");
|
|
99
|
+
sections.push("<search_results>");
|
|
100
|
+
|
|
101
|
+
for (let i = 0; i < results.length; i++) {
|
|
102
|
+
sections.push(`\n[Result ${i + 1}]`);
|
|
103
|
+
sections.push(summarizeQueryResult(results[i]));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
sections.push("\n</search_results>");
|
|
107
|
+
|
|
108
|
+
if (feedback) {
|
|
109
|
+
sections.push("");
|
|
110
|
+
sections.push("<user_feedback>");
|
|
111
|
+
sections.push(feedback);
|
|
112
|
+
sections.push("</user_feedback>");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return sections.join("\n");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function buildDeterministicAnswerPreview(answer: string): string {
|
|
119
|
+
let text = answer.replace(/\s+/g, " ").trim();
|
|
120
|
+
if (text.length === 0) return "";
|
|
121
|
+
|
|
122
|
+
const sourceMarker = text.search(/\bSources?\s*:/i);
|
|
123
|
+
if (sourceMarker >= 0) text = text.slice(0, sourceMarker).trim();
|
|
124
|
+
if (text.length === 0) return "";
|
|
125
|
+
|
|
126
|
+
return text.length > 240 ? `${text.slice(0, 237)}...` : text;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function buildDeterministicSummaryLines(results: QueryResultData[]): string[] {
|
|
130
|
+
if (results.length === 0) {
|
|
131
|
+
return [
|
|
132
|
+
"No completed search results were available when the curator session finished.",
|
|
133
|
+
"",
|
|
134
|
+
"Sources",
|
|
135
|
+
"- None",
|
|
136
|
+
];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const lines: string[] = [
|
|
140
|
+
"Summary based on the currently selected search results.",
|
|
141
|
+
"",
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
const sourceUrls: string[] = [];
|
|
145
|
+
let successful = 0;
|
|
146
|
+
let failed = 0;
|
|
147
|
+
|
|
148
|
+
for (const result of results) {
|
|
149
|
+
if (result.error) {
|
|
150
|
+
failed += 1;
|
|
151
|
+
lines.push(`- ${result.query}: failed (${result.error})`);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
successful += 1;
|
|
156
|
+
const preview = buildDeterministicAnswerPreview(result.answer);
|
|
157
|
+
if (preview.length > 0) {
|
|
158
|
+
lines.push(`- ${result.query}: ${preview}`);
|
|
159
|
+
} else {
|
|
160
|
+
lines.push(`- ${result.query}: returned ${result.results.length} source${result.results.length === 1 ? "" : "s"} without answer text.`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
for (const source of result.results) {
|
|
164
|
+
if (!sourceUrls.includes(source.url)) {
|
|
165
|
+
sourceUrls.push(source.url);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
lines.push("");
|
|
171
|
+
lines.push(`Completed queries: ${results.length}`);
|
|
172
|
+
lines.push(`Successful: ${successful}`);
|
|
173
|
+
lines.push(`Failed: ${failed}`);
|
|
174
|
+
lines.push("");
|
|
175
|
+
lines.push("Sources");
|
|
176
|
+
|
|
177
|
+
if (sourceUrls.length === 0) {
|
|
178
|
+
lines.push("- None");
|
|
179
|
+
} else {
|
|
180
|
+
for (const url of sourceUrls.slice(0, 12)) {
|
|
181
|
+
lines.push(`- ${url}`);
|
|
182
|
+
}
|
|
183
|
+
if (sourceUrls.length > 12) {
|
|
184
|
+
lines.push(`- ... and ${sourceUrls.length - 12} more`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return lines;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function buildDeterministicSummary(results: QueryResultData[]): { summary: string; meta: SummaryMeta } {
|
|
192
|
+
const summary = buildDeterministicSummaryLines(results).join("\n").trim();
|
|
193
|
+
const nonEmptySummary = summary.length > 0
|
|
194
|
+
? summary
|
|
195
|
+
: "No completed search results were available when the curator session finished.\n\nSources\n- None";
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
summary: nonEmptySummary,
|
|
199
|
+
meta: {
|
|
200
|
+
model: null,
|
|
201
|
+
durationMs: 0,
|
|
202
|
+
tokenEstimate: estimateTokens(nonEmptySummary),
|
|
203
|
+
fallbackUsed: true,
|
|
204
|
+
fallbackReason: "deterministic-submit-fallback",
|
|
205
|
+
phase: "deterministic-fallback",
|
|
206
|
+
edited: false,
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function resolveThinkingLevel(model: Model<Api>, requested?: SummaryThinkingLevel): Promise<ModelThinkingLevel | undefined> {
|
|
212
|
+
if (!requested) return undefined;
|
|
213
|
+
const { clampThinkingLevel } = await import("@earendil-works/pi-ai");
|
|
214
|
+
return clampThinkingLevel(model, requested as ModelThinkingLevel);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function resolveSummaryModelCandidates(
|
|
218
|
+
ctx: SummaryGenerationContext,
|
|
219
|
+
modelOverride: string | undefined,
|
|
220
|
+
preferredFallback: boolean,
|
|
221
|
+
): Promise<{ candidates: Array<{ model: Model<Api>; apiKey?: string; headers?: ProviderHeaders; thinkingLevel?: SummaryThinkingLevel }>; failures: SummaryModelFailure[] }> {
|
|
222
|
+
const specs: Array<{ provider: string; id: string; thinkingLevel?: SummaryThinkingLevel }> = [];
|
|
223
|
+
const failures: SummaryModelFailure[] = [];
|
|
224
|
+
const normalizedOverride = typeof modelOverride === "string" ? modelOverride.trim() : "";
|
|
225
|
+
if (normalizedOverride.length > 0) {
|
|
226
|
+
const spec = resolveHelperModelSelector(normalizedOverride, "summary model", ctx.model);
|
|
227
|
+
if (spec) specs.push(spec);
|
|
228
|
+
else failures.push({ model: normalizedOverride, reason: "no active Pi session model", message: `Summary model not found: ${normalizedOverride} (no active Pi session model)` });
|
|
229
|
+
}
|
|
230
|
+
if (preferredFallback) specs.push(...PREFERRED_SUMMARY_MODELS);
|
|
231
|
+
|
|
232
|
+
const candidates: Array<{ model: Model<Api>; apiKey?: string; headers?: ProviderHeaders; thinkingLevel?: SummaryThinkingLevel }> = [];
|
|
233
|
+
const seen = new Set<string>();
|
|
234
|
+
for (const spec of specs) {
|
|
235
|
+
const value = `${spec.provider}/${spec.id}`;
|
|
236
|
+
if (seen.has(value)) continue;
|
|
237
|
+
seen.add(value);
|
|
238
|
+
|
|
239
|
+
const model = findModelWithProviderRouting(ctx.modelRegistry, spec.provider, spec.id);
|
|
240
|
+
if (!model) {
|
|
241
|
+
failures.push({ model: value, reason: "not found", message: `Summary model not found: ${value}` });
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (!isModelInScope(model, ctx.scopedModels)) {
|
|
245
|
+
failures.push({ model: value, reason: "not enabled", message: `Summary model is not enabled: ${value}` });
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
249
|
+
if (!auth.ok) {
|
|
250
|
+
failures.push({ model: value, reason: "no API key", message: `No API key available for summary model ${value}` });
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
candidates.push({ model, apiKey: auth.apiKey, headers: auth.headers, thinkingLevel: spec.thinkingLevel });
|
|
254
|
+
}
|
|
255
|
+
return { candidates, failures };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function summaryUnavailableReason(failures: SummaryModelFailure[], preferredFallback: boolean): string {
|
|
259
|
+
if (failures.length === 0) return "summary-model-unavailable";
|
|
260
|
+
if (failures.length === 1) return `summary-model-unavailable: ${failures[0].message}`;
|
|
261
|
+
const list = failures.map(failure => `${failure.model} (${failure.reason})`).join(", ");
|
|
262
|
+
const hint = preferredFallback ? "; set summaryModel in web-search.json to a model you can use" : "";
|
|
263
|
+
return `summary-model-unavailable: none of the ${failures.length} summary models could be used: ${list}${hint}`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function buildFallbackSummary(
|
|
267
|
+
results: QueryResultData[],
|
|
268
|
+
fallbackReason: string,
|
|
269
|
+
durationMs = 0,
|
|
270
|
+
): { summary: string; meta: SummaryMeta } {
|
|
271
|
+
const deterministic = buildDeterministicSummary(results);
|
|
272
|
+
return {
|
|
273
|
+
summary: deterministic.summary,
|
|
274
|
+
meta: {
|
|
275
|
+
...deterministic.meta,
|
|
276
|
+
durationMs,
|
|
277
|
+
fallbackReason,
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function isAbortError(err: unknown): boolean {
|
|
283
|
+
if (!err || typeof err !== "object") return false;
|
|
284
|
+
const name = (err as { name?: unknown }).name;
|
|
285
|
+
const message = (err as { message?: unknown }).message;
|
|
286
|
+
return name === "AbortError" || (typeof message === "string" && message.toLowerCase().includes("abort"));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function getTextFromContentPart(part: unknown): string {
|
|
290
|
+
if (!part || typeof part !== "object") return "";
|
|
291
|
+
const value = part as Record<string, unknown>;
|
|
292
|
+
if (typeof value.text === "string") return value.text;
|
|
293
|
+
if (typeof value.refusal === "string") return value.refusal;
|
|
294
|
+
return "";
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function getContentPartType(part: unknown): string {
|
|
298
|
+
if (!part || typeof part !== "object") return "unknown";
|
|
299
|
+
const value = part as Record<string, unknown>;
|
|
300
|
+
return typeof value.type === "string" ? value.type : "unknown";
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export async function generateSummaryDraft(
|
|
304
|
+
results: QueryResultData[],
|
|
305
|
+
ctx: SummaryGenerationContext,
|
|
306
|
+
signal?: AbortSignal,
|
|
307
|
+
modelOverride?: string,
|
|
308
|
+
feedback?: string,
|
|
309
|
+
completeFn?: CompleteFunction,
|
|
310
|
+
deadlineMs = SUMMARY_GENERATION_DEADLINE_MS,
|
|
311
|
+
instructions?: string,
|
|
312
|
+
options: { preferredFallback?: boolean } = {},
|
|
313
|
+
): Promise<{ summary: string; meta: SummaryMeta }> {
|
|
314
|
+
if (!ctx || !ctx.modelRegistry) {
|
|
315
|
+
throw new Error("Summary generation context unavailable");
|
|
316
|
+
}
|
|
317
|
+
if (signal?.aborted) throw new Error("Aborted");
|
|
318
|
+
|
|
319
|
+
const registry = ctx.modelRegistry as SummaryModelRegistry;
|
|
320
|
+
const customCompleteFn = completeFn !== undefined;
|
|
321
|
+
// streamSimple is Pi's provider-neutral path and routes virtual models; complete() does not (#574).
|
|
322
|
+
const usesRegistryStreamSimple = !customCompleteFn && typeof registry.streamSimple === "function";
|
|
323
|
+
const usesRegistryComplete = !customCompleteFn && !usesRegistryStreamSimple && typeof registry.complete === "function";
|
|
324
|
+
let piAiCompat: typeof import("@earendil-works/pi-ai/compat") | undefined;
|
|
325
|
+
|
|
326
|
+
const generationStartedAt = Date.now();
|
|
327
|
+
const deadlineController = new AbortController();
|
|
328
|
+
const deadlineMarker = Symbol("summary-generation-deadline");
|
|
329
|
+
let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
|
|
330
|
+
const deadlinePromise = new Promise<typeof deadlineMarker>(resolve => {
|
|
331
|
+
deadlineTimer = setTimeout(() => {
|
|
332
|
+
deadlineController.abort();
|
|
333
|
+
resolve(deadlineMarker);
|
|
334
|
+
}, deadlineMs);
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
let callerAbortListener: (() => void) | undefined;
|
|
338
|
+
const callerAbortPromise = signal
|
|
339
|
+
? new Promise<never>((_, reject) => {
|
|
340
|
+
callerAbortListener = () => reject(new Error("Aborted"));
|
|
341
|
+
if (signal.aborted) callerAbortListener();
|
|
342
|
+
else signal.addEventListener("abort", callerAbortListener, { once: true });
|
|
343
|
+
})
|
|
344
|
+
: undefined;
|
|
345
|
+
const completionSignal = signal
|
|
346
|
+
? AbortSignal.any([signal, deadlineController.signal])
|
|
347
|
+
: deadlineController.signal;
|
|
348
|
+
|
|
349
|
+
function checkSummaryDeadline(): void {
|
|
350
|
+
if (signal?.aborted) throw new Error("Aborted");
|
|
351
|
+
// Imports or synchronous providers can finish before an overdue timer runs.
|
|
352
|
+
if (deadlineController.signal.aborted || Date.now() - generationStartedAt >= deadlineMs) {
|
|
353
|
+
deadlineController.abort();
|
|
354
|
+
throw deadlineMarker;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async function raceSummaryOperation<T>(operation: Promise<T>): Promise<T> {
|
|
359
|
+
// A provider may ignore AbortSignal and never settle; observe it before racing so
|
|
360
|
+
// its eventual rejection cannot become an unhandled promise rejection.
|
|
361
|
+
void operation.then(() => undefined, () => undefined);
|
|
362
|
+
checkSummaryDeadline();
|
|
363
|
+
const contenders: Promise<unknown>[] = [operation, deadlinePromise];
|
|
364
|
+
if (callerAbortPromise) contenders.push(callerAbortPromise);
|
|
365
|
+
const result = await Promise.race(contenders);
|
|
366
|
+
checkSummaryDeadline();
|
|
367
|
+
return result as T;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
try {
|
|
371
|
+
if (signal?.aborted) throw new Error("Aborted");
|
|
372
|
+
const prompt = buildSummaryPrompt(results, feedback, instructions);
|
|
373
|
+
let resolved: Awaited<ReturnType<typeof resolveSummaryModelCandidates>>;
|
|
374
|
+
try {
|
|
375
|
+
checkSummaryDeadline();
|
|
376
|
+
if (!customCompleteFn && !usesRegistryStreamSimple && !usesRegistryComplete) {
|
|
377
|
+
piAiCompat = await raceSummaryOperation(import("@earendil-works/pi-ai/compat"));
|
|
378
|
+
}
|
|
379
|
+
if (!usesRegistryStreamSimple) completeFn ??= usesRegistryComplete ? registry.complete!.bind(registry) as CompleteFunction : piAiCompat!.complete;
|
|
380
|
+
resolved = await raceSummaryOperation(resolveSummaryModelCandidates(ctx, modelOverride, options.preferredFallback ?? true));
|
|
381
|
+
} catch (err) {
|
|
382
|
+
checkSummaryDeadline();
|
|
383
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
384
|
+
return buildFallbackSummary(results, `summary-model-settings-error: ${message}`, Date.now() - generationStartedAt);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const failures = resolved.failures;
|
|
388
|
+
for (const { model, apiKey, headers, thinkingLevel } of resolved.candidates) {
|
|
389
|
+
const startedAt = Date.now();
|
|
390
|
+
try {
|
|
391
|
+
// sessionId lets pi-ai's OpenCode providers add x-opencode-session. cacheRetention "none" keeps this
|
|
392
|
+
// one-off call out of the session's prompt cache and Codex continuation, as Pi does for compaction.
|
|
393
|
+
const sessionId = ctx.sessionManager?.getSessionId?.();
|
|
394
|
+
const userMessage: Message = {
|
|
395
|
+
role: "user",
|
|
396
|
+
content: [{ type: "text", text: prompt }],
|
|
397
|
+
timestamp: Date.now(),
|
|
398
|
+
};
|
|
399
|
+
const requestedThinkingLevel = await raceSummaryOperation(resolveThinkingLevel(model, thinkingLevel));
|
|
400
|
+
const enabledThinkingLevel = requestedThinkingLevel && requestedThinkingLevel !== "off"
|
|
401
|
+
? requestedThinkingLevel as ThinkingLevel
|
|
402
|
+
: undefined;
|
|
403
|
+
const simpleOptions = {
|
|
404
|
+
sessionId,
|
|
405
|
+
cacheRetention: "none" as const,
|
|
406
|
+
signal: completionSignal,
|
|
407
|
+
...(enabledThinkingLevel ? { reasoning: enabledThinkingLevel } : {}),
|
|
408
|
+
};
|
|
409
|
+
const completionOptions = {
|
|
410
|
+
...(usesRegistryComplete ? {} : { apiKey, headers }),
|
|
411
|
+
sessionId,
|
|
412
|
+
cacheRetention: "none" as const,
|
|
413
|
+
signal: completionSignal,
|
|
414
|
+
...(requestedThinkingLevel ? { reasoning: requestedThinkingLevel } : {}),
|
|
415
|
+
...(enabledThinkingLevel ? { reasoningEffort: enabledThinkingLevel } : {}),
|
|
416
|
+
};
|
|
417
|
+
checkSummaryDeadline();
|
|
418
|
+
const completion = usesRegistryStreamSimple
|
|
419
|
+
? registry.streamSimple(model, { messages: [userMessage] }, simpleOptions).result()
|
|
420
|
+
: thinkingLevel !== undefined && !customCompleteFn && !usesRegistryComplete
|
|
421
|
+
? piAiCompat!.completeSimple(model, { messages: [userMessage] }, { apiKey, headers, ...simpleOptions })
|
|
422
|
+
: completeFn!(model, { messages: [userMessage] }, completionOptions);
|
|
423
|
+
|
|
424
|
+
const response = await raceSummaryOperation(Promise.resolve(completion));
|
|
425
|
+
if (response.stopReason === "aborted") {
|
|
426
|
+
throw new Error("Aborted");
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const contentParts = Array.isArray(response.content) ? response.content : [];
|
|
430
|
+
const summary = contentParts
|
|
431
|
+
.map((part: unknown) => getTextFromContentPart(part))
|
|
432
|
+
.filter((text: string) => text.trim().length > 0)
|
|
433
|
+
.join("\n")
|
|
434
|
+
.trim();
|
|
435
|
+
|
|
436
|
+
if (summary.length === 0) {
|
|
437
|
+
const partTypes = contentParts.map((part: unknown) => getContentPartType(part));
|
|
438
|
+
const typesLabel = partTypes.length > 0 ? partTypes.join(", ") : "none";
|
|
439
|
+
throw new Error(`Summary model returned empty response (content parts: ${typesLabel})`);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return {
|
|
443
|
+
summary,
|
|
444
|
+
meta: {
|
|
445
|
+
model: `${model.provider}/${model.id}`,
|
|
446
|
+
durationMs: Math.max(0, Date.now() - startedAt),
|
|
447
|
+
tokenEstimate: estimateTokens(summary),
|
|
448
|
+
fallbackUsed: false,
|
|
449
|
+
phase: "summary-model",
|
|
450
|
+
edited: false,
|
|
451
|
+
},
|
|
452
|
+
};
|
|
453
|
+
} catch (err) {
|
|
454
|
+
checkSummaryDeadline();
|
|
455
|
+
if (isAbortError(err)) throw err;
|
|
456
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
457
|
+
failures.push({ model: `${model.provider}/${model.id}`, reason: message, message });
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
return buildFallbackSummary(
|
|
462
|
+
results,
|
|
463
|
+
summaryUnavailableReason(failures, options.preferredFallback ?? true),
|
|
464
|
+
Date.now() - generationStartedAt,
|
|
465
|
+
);
|
|
466
|
+
} catch (err) {
|
|
467
|
+
if (signal?.aborted) throw new Error("Aborted");
|
|
468
|
+
if (err === deadlineMarker) {
|
|
469
|
+
return buildFallbackSummary(results, "summary-generation-timeout", Date.now() - generationStartedAt);
|
|
470
|
+
}
|
|
471
|
+
throw err;
|
|
472
|
+
} finally {
|
|
473
|
+
if (deadlineTimer) clearTimeout(deadlineTimer);
|
|
474
|
+
if (signal && callerAbortListener) signal.removeEventListener("abort", callerAbortListener);
|
|
475
|
+
}
|
|
476
|
+
}
|