@canonry/canonry 7.51.5 → 7.51.6
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/dist/ads-ABAT3K4K.js +544 -0
- package/dist/agent-5G4DRLYX.js +70 -0
- package/dist/agent-ask-UDVCZRO7.js +139 -0
- package/dist/agent-conversations-5E4JP2QZ.js +52 -0
- package/dist/agent-memory-7IIJ4HGZ.js +92 -0
- package/dist/agent-providers-BOXPUXZ4.js +55 -0
- package/dist/agent-transcript-4O56G6PQ.js +77 -0
- package/dist/analytics-PKMWX5XL.js +240 -0
- package/dist/apply-OK4XEBDA.js +175 -0
- package/dist/backfill-2OT56CX2.js +41 -0
- package/dist/backlinks-547WCHND.js +303 -0
- package/dist/bing-ZVBV4ZD5.js +418 -0
- package/dist/bootstrap-HUB7XQ73.js +326 -0
- package/dist/cdp-KQKQ4PWJ.js +162 -0
- package/dist/chunk-2G6IP3MO.js +517 -0
- package/dist/chunk-42D2LE2B.js +1273 -0
- package/dist/chunk-4MJYGB56.js +124 -0
- package/dist/chunk-63ISSSGX.js +9150 -0
- package/dist/{chunk-PLYJX67A.js → chunk-6G6FTDWC.js} +8080 -13939
- package/dist/chunk-6GO5VVAC.js +15 -0
- package/dist/{chunk-4YCGZGA3.js → chunk-73P65KPW.js} +2 -2
- package/dist/chunk-7B2Q4NJE.js +133 -0
- package/dist/{chunk-JBZZEIM2.js → chunk-7WZ2FPB4.js} +2 -13
- package/dist/chunk-AOJU5LKX.js +8 -0
- package/dist/chunk-B2FR2ZQ4.js +420 -0
- package/dist/{chunk-HAHXPJQ5.js → chunk-B5J675KK.js} +16 -1684
- package/dist/{chunk-SFMWHPMX.js → chunk-D6COIM3U.js} +17128 -17143
- package/dist/{chunk-A3WSAAQS.js → chunk-DGVUTH7W.js} +9086 -34522
- package/dist/chunk-ELCLGWUT.js +83 -0
- package/dist/chunk-GO2J7SYT.js +1034 -0
- package/dist/chunk-HACZUMGM.js +145 -0
- package/dist/chunk-HM4NNKLG.js +94 -0
- package/dist/chunk-I3A56PFP.js +58 -0
- package/dist/chunk-I77PLCWG.js +961 -0
- package/dist/chunk-ISOQPVPY.js +232 -0
- package/dist/chunk-KFT5LOP2.js +610 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-MMEO22MF.js +38 -0
- package/dist/chunk-NHQ2U5I4.js +78 -0
- package/dist/chunk-PCXRFT3N.js +530 -0
- package/dist/chunk-PITHTCAX.js +15376 -0
- package/dist/chunk-QWKPSFGL.js +30 -0
- package/dist/chunk-RKIXES2B.js +609 -0
- package/dist/chunk-TSENU4GG.js +18 -0
- package/dist/{chunk-HLVEB5TB.js → chunk-TUTKNUMV.js} +7 -5
- package/dist/chunk-U3AHE2RT.js +1160 -0
- package/dist/chunk-UQ3MOZGC.js +644 -0
- package/dist/{chunk-AZFPA7JV.js → chunk-VBCE4CLX.js} +6 -4
- package/dist/chunk-VJWDBFSL.js +69 -0
- package/dist/chunk-VYMZ3QXG.js +8264 -0
- package/dist/chunk-WAULJDKO.js +2686 -0
- package/dist/chunk-WDFI5YMD.js +204 -0
- package/dist/chunk-XEBKF4N5.js +8 -0
- package/dist/chunk-Z7IUAJOF.js +13 -0
- package/dist/{chunk-KEATAHXH.js → chunk-ZWJRY5UI.js} +358 -581
- package/dist/chunk-ZXUAWVWM.js +15 -0
- package/dist/citations-UYB2RU5U.js +106 -0
- package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-F6FI7NB2.js} +5 -3
- package/dist/cli-commands-ZG5ILKDA.js +19 -0
- package/dist/cli.js +35 -29
- package/dist/competitor-EKP4R7YY.js +561 -0
- package/dist/content-DREE6JF3.js +257 -0
- package/dist/dashboard-ZALEOLLU.js +71 -0
- package/dist/demo-JG4Y22O4.js +75 -0
- package/dist/{demo-server-GIWDJGJX.js → demo-server-3A4J2C65.js} +22 -9
- package/dist/discover-W6GMD2HS.js +372 -0
- package/dist/discover-eval-CKFZHRBW.js +282 -0
- package/dist/doctor-TNGBSUMA.js +152 -0
- package/dist/evidence-3H2GFQBZ.js +57 -0
- package/dist/export-cmd-WUIKU5GK.js +49 -0
- package/dist/ga-JI6REFO4.js +911 -0
- package/dist/gbp-4ENDM5NS.js +370 -0
- package/dist/google-HKQSCLOC.js +946 -0
- package/dist/google-marketing-KQR5J2S4.js +403 -0
- package/dist/health-cmd-TS7EMMCS.js +64 -0
- package/dist/history-MSD5DK6K.js +90 -0
- package/dist/index.d.ts +47 -47
- package/dist/index.js +29 -6
- package/dist/init-L6WAEOWX.js +432 -0
- package/dist/insights-RTZ3IZTD.js +63 -0
- package/dist/intelligence-service-TH52PCNJ.js +15 -0
- package/dist/keys-625DZBRM.js +116 -0
- package/dist/keyword-CW46RNRR.js +164 -0
- package/dist/logs-V33SHBIW.js +30 -0
- package/dist/mcp-DFEDPSEG.js +14 -0
- package/dist/mcp.js +14 -5
- package/dist/measurement-plan-6W37RUOP.js +42 -0
- package/dist/notify-DSUOT7WO.js +125 -0
- package/dist/organic-evidence-BMN6L4OB.js +53 -0
- package/dist/overview-WRRMBZ6S.js +213 -0
- package/dist/project-2GJIU3FE.js +460 -0
- package/dist/query-3XPMGJUA.js +211 -0
- package/dist/research-V433CKJ4.js +200 -0
- package/dist/results-export-RGBU7QQQ.js +27 -0
- package/dist/run-NIAC6OJN.js +31 -0
- package/dist/schedule-KDWXRIE7.js +177 -0
- package/dist/search-626MPUJN.js +42 -0
- package/dist/serve-73SMMASI.js +557 -0
- package/dist/session-7WWOETZB.js +47 -0
- package/dist/settings-VKFQO6F2.js +107 -0
- package/dist/skills-5HC5H7TE.js +33 -0
- package/dist/snapshot-BSJUHFBC.js +538 -0
- package/dist/src-F6HM73TN.js +316 -0
- package/dist/status-V4OWP7LZ.js +126 -0
- package/dist/support-ARF4HER7.js +24 -0
- package/dist/technical-aeo-TG7CGU3F.js +625 -0
- package/dist/telemetry-O2IUNUBW.js +118 -0
- package/dist/tools-2GJIDKND.js +41 -0
- package/dist/traffic-XV4I3UPH.js +1295 -0
- package/dist/users-VGBLDL5K.js +170 -0
- package/dist/visibility-stats-UKJYJ6PP.js +241 -0
- package/dist/wordpress-JZA7CGC6.js +600 -0
- package/package.json +1 -1
- package/dist/chunk-4QQYYRHV.js +0 -23082
- package/dist/cli-commands-FOJR3HHU.js +0 -15
- package/dist/intelligence-service-XQCNWAPL.js +0 -9
|
@@ -0,0 +1,2686 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseJsonColumn
|
|
3
|
+
} from "./chunk-63ISSSGX.js";
|
|
4
|
+
import {
|
|
5
|
+
AI_ENGINE_DOMAINS,
|
|
6
|
+
AI_ENGINE_SELF_DOMAINS,
|
|
7
|
+
AnchoredSpanSources,
|
|
8
|
+
ProviderBatchSubmitError,
|
|
9
|
+
ProviderNames,
|
|
10
|
+
RetrievalContracts,
|
|
11
|
+
RetrievalStatuses,
|
|
12
|
+
VERTEX_AI_SEARCH_PROXY_DOMAIN,
|
|
13
|
+
asRecord,
|
|
14
|
+
describeError,
|
|
15
|
+
hostMatchesAnyDomain,
|
|
16
|
+
hostOf,
|
|
17
|
+
isRetryableHttpError,
|
|
18
|
+
normalizeServedModel,
|
|
19
|
+
registrableDomain,
|
|
20
|
+
resolveProviderModel,
|
|
21
|
+
retryAfterDelayMs,
|
|
22
|
+
usageCount,
|
|
23
|
+
withRetry
|
|
24
|
+
} from "./chunk-D6COIM3U.js";
|
|
25
|
+
|
|
26
|
+
// ../provider-openai/src/normalize.ts
|
|
27
|
+
import OpenAI from "openai";
|
|
28
|
+
|
|
29
|
+
// ../provider-openai/src/utils.ts
|
|
30
|
+
async function withRetry2(fn, options = {}) {
|
|
31
|
+
return withRetry(fn, {
|
|
32
|
+
maxRetries: options.maxRetries ?? 3,
|
|
33
|
+
baseDelayMs: options.initialDelay ?? 1e3,
|
|
34
|
+
// Jitter off preserves the historical deterministic backoff that every
|
|
35
|
+
// provider has shipped to date (1000, 2000, 4000ms). Enable per-caller
|
|
36
|
+
// if you need it.
|
|
37
|
+
jitter: false,
|
|
38
|
+
isRetryable: isRetryableHttpError,
|
|
39
|
+
onRetry: ({ attempt, err, delayMs }) => {
|
|
40
|
+
console.warn(
|
|
41
|
+
`[provider] Attempt ${attempt + 1} failed, retrying in ${delayMs}ms...`,
|
|
42
|
+
describeError(err)
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ../provider-openai/src/normalize.ts
|
|
49
|
+
var DEFAULT_MODEL = "gpt-5.4";
|
|
50
|
+
var OPENAI_RETRIEVAL_CONTRACT = RetrievalContracts["search-required-v1"];
|
|
51
|
+
function createClient(config) {
|
|
52
|
+
return new OpenAI({
|
|
53
|
+
apiKey: config.apiKey,
|
|
54
|
+
...config.baseUrl ? { baseURL: config.baseUrl } : {}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function validateConfig(config) {
|
|
58
|
+
if (!config.apiKey || config.apiKey.length === 0) {
|
|
59
|
+
return { ok: false, provider: "openai", message: "missing api key" };
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
ok: true,
|
|
63
|
+
provider: "openai",
|
|
64
|
+
message: "config valid",
|
|
65
|
+
model: config.model ?? DEFAULT_MODEL
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
async function healthcheck(config) {
|
|
69
|
+
const validation = validateConfig(config);
|
|
70
|
+
if (!validation.ok) return validation;
|
|
71
|
+
try {
|
|
72
|
+
const client = createClient(config);
|
|
73
|
+
const response = await withRetry2(
|
|
74
|
+
() => client.responses.create({
|
|
75
|
+
model: config.model ?? DEFAULT_MODEL,
|
|
76
|
+
input: 'Say "ok"'
|
|
77
|
+
})
|
|
78
|
+
);
|
|
79
|
+
const text = extractResponseText(response);
|
|
80
|
+
return {
|
|
81
|
+
ok: text.length > 0,
|
|
82
|
+
provider: "openai",
|
|
83
|
+
message: text.length > 0 ? "openai api key verified" : "empty response from openai",
|
|
84
|
+
model: config.model ?? DEFAULT_MODEL
|
|
85
|
+
};
|
|
86
|
+
} catch (err) {
|
|
87
|
+
return {
|
|
88
|
+
ok: false,
|
|
89
|
+
provider: "openai",
|
|
90
|
+
message: describeError(err),
|
|
91
|
+
model: config.model ?? DEFAULT_MODEL
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
var OPENAI_RESPONSES_ENDPOINT = "/v1/responses";
|
|
96
|
+
function buildTrackedQueryRequest(input) {
|
|
97
|
+
const webSearchTool = { type: "web_search" };
|
|
98
|
+
if (input.location) {
|
|
99
|
+
webSearchTool.user_location = {
|
|
100
|
+
type: "approximate",
|
|
101
|
+
city: input.location.city,
|
|
102
|
+
region: input.location.region,
|
|
103
|
+
country: input.location.country,
|
|
104
|
+
...input.location.timezone ? { timezone: input.location.timezone } : {}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const body = {
|
|
108
|
+
model: input.config.model ?? DEFAULT_MODEL,
|
|
109
|
+
tools: [webSearchTool],
|
|
110
|
+
// search-required-v1: web_search is the only tool, so requiring a tool
|
|
111
|
+
// call requires a search. See OPENAI_RETRIEVAL_CONTRACT.
|
|
112
|
+
tool_choice: "required",
|
|
113
|
+
input: input.query
|
|
114
|
+
};
|
|
115
|
+
return { endpoint: OPENAI_RESPONSES_ENDPOINT, body };
|
|
116
|
+
}
|
|
117
|
+
async function executeTrackedQuery(input) {
|
|
118
|
+
const model = input.config.model ?? DEFAULT_MODEL;
|
|
119
|
+
const params = buildTrackedQueryRequest(input).body;
|
|
120
|
+
const client = createClient(input.config);
|
|
121
|
+
let response;
|
|
122
|
+
try {
|
|
123
|
+
response = await withRetry2(() => client.responses.create(params));
|
|
124
|
+
} catch (err) {
|
|
125
|
+
const msg = describeError(err);
|
|
126
|
+
throw new Error(`[provider-openai] ${msg}`);
|
|
127
|
+
}
|
|
128
|
+
return parseTrackedQueryResponse(response, model);
|
|
129
|
+
}
|
|
130
|
+
function parseTrackedQueryResponse(body, model) {
|
|
131
|
+
const rawResponse = responseToRecord(body);
|
|
132
|
+
const parsed = reparseStoredResult(rawResponse);
|
|
133
|
+
return {
|
|
134
|
+
provider: "openai",
|
|
135
|
+
rawResponse,
|
|
136
|
+
model,
|
|
137
|
+
servedModel: normalizeServedModel(rawResponse.model),
|
|
138
|
+
groundingSources: parsed.groundingSources,
|
|
139
|
+
searchQueries: parsed.searchQueries,
|
|
140
|
+
retrievalStatus: parsed.retrievalStatus,
|
|
141
|
+
retrievalContract: OPENAI_RETRIEVAL_CONTRACT,
|
|
142
|
+
usage: extractUsageFromRaw(rawResponse),
|
|
143
|
+
stopReason: extractStopReasonFromRaw(rawResponse)
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function normalizeResult(raw) {
|
|
147
|
+
const parsed = reparseStoredResult(raw.rawResponse);
|
|
148
|
+
const useParsed = hasParsedResponseContent(raw.rawResponse);
|
|
149
|
+
const groundingSources = useParsed ? parsed.groundingSources : raw.groundingSources;
|
|
150
|
+
const searchQueries = useParsed ? parsed.searchQueries : raw.searchQueries;
|
|
151
|
+
const citedDomains = extractCitedDomainsFromSources(groundingSources);
|
|
152
|
+
return {
|
|
153
|
+
provider: "openai",
|
|
154
|
+
answerText: parsed.answerText,
|
|
155
|
+
citedDomains,
|
|
156
|
+
groundingSources,
|
|
157
|
+
searchQueries,
|
|
158
|
+
retrievalStatus: useParsed ? parsed.retrievalStatus : raw.retrievalStatus
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
function hasParsedResponseContent(rawResponse) {
|
|
162
|
+
return Array.isArray(rawResponse.output) && rawResponse.output.length > 0;
|
|
163
|
+
}
|
|
164
|
+
function reparseStoredResult(rawResponse) {
|
|
165
|
+
const groundingSources = extractGroundingSourcesFromRaw(rawResponse);
|
|
166
|
+
const searchQueries = extractSearchQueriesFromRaw(rawResponse);
|
|
167
|
+
return {
|
|
168
|
+
provider: "openai",
|
|
169
|
+
answerText: extractAnswerTextFromRaw(rawResponse),
|
|
170
|
+
citedDomains: extractCitedDomainsFromSources(groundingSources),
|
|
171
|
+
groundingSources,
|
|
172
|
+
searchQueries,
|
|
173
|
+
retrievalStatus: extractRetrievalStatusFromRaw(rawResponse)
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function extractRetrievalStatusFromRaw(rawResponse) {
|
|
177
|
+
const output = rawResponse.output;
|
|
178
|
+
if (!Array.isArray(output) || output.length === 0) return RetrievalStatuses.unknown;
|
|
179
|
+
const searched = output.some(
|
|
180
|
+
(item) => item !== null && typeof item === "object" && item.type === "web_search_call"
|
|
181
|
+
);
|
|
182
|
+
if (searched) return RetrievalStatuses.used;
|
|
183
|
+
if (typeof rawResponse.status === "string" && rawResponse.status !== "completed") {
|
|
184
|
+
return RetrievalStatuses.unknown;
|
|
185
|
+
}
|
|
186
|
+
return RetrievalStatuses["not-used"];
|
|
187
|
+
}
|
|
188
|
+
function extractResponseText(response) {
|
|
189
|
+
try {
|
|
190
|
+
const parts = [];
|
|
191
|
+
for (const item of response.output) {
|
|
192
|
+
if (item.type === "message") {
|
|
193
|
+
for (const content of item.content) {
|
|
194
|
+
if (content.type === "output_text") {
|
|
195
|
+
parts.push(content.text);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return parts.join("");
|
|
201
|
+
} catch {
|
|
202
|
+
return "";
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function extractGroundingSourcesFromRaw(rawResponse) {
|
|
206
|
+
const sources = [];
|
|
207
|
+
const seen = /* @__PURE__ */ new Set();
|
|
208
|
+
try {
|
|
209
|
+
const output = rawResponse.output;
|
|
210
|
+
if (!output) return [];
|
|
211
|
+
for (const item of output) {
|
|
212
|
+
if (item.type === "message") {
|
|
213
|
+
for (const content of item.content ?? []) {
|
|
214
|
+
if (content.type === "output_text" && content.annotations) {
|
|
215
|
+
for (const annotation of content.annotations) {
|
|
216
|
+
if (annotation.type === "url_citation" && typeof annotation.url === "string" && !seen.has(annotation.url)) {
|
|
217
|
+
seen.add(annotation.url);
|
|
218
|
+
sources.push({
|
|
219
|
+
uri: annotation.url,
|
|
220
|
+
title: annotation.title ?? ""
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
} catch {
|
|
229
|
+
}
|
|
230
|
+
return sources;
|
|
231
|
+
}
|
|
232
|
+
function extractSearchQueriesFromRaw(rawResponse) {
|
|
233
|
+
const queries = /* @__PURE__ */ new Set();
|
|
234
|
+
try {
|
|
235
|
+
const output = rawResponse.output;
|
|
236
|
+
if (!output) return [];
|
|
237
|
+
for (const item of output) {
|
|
238
|
+
if (item.type !== "web_search_call" || !item.action) continue;
|
|
239
|
+
const action = item.action;
|
|
240
|
+
if (typeof action.query === "string" && action.query.length > 0) {
|
|
241
|
+
queries.add(action.query);
|
|
242
|
+
}
|
|
243
|
+
if (Array.isArray(action.queries)) {
|
|
244
|
+
for (const query of action.queries) {
|
|
245
|
+
if (typeof query === "string" && query.length > 0) {
|
|
246
|
+
queries.add(query);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
} catch {
|
|
252
|
+
}
|
|
253
|
+
return [...queries];
|
|
254
|
+
}
|
|
255
|
+
function extractAnswerTextFromRaw(rawResponse) {
|
|
256
|
+
try {
|
|
257
|
+
const output = rawResponse.output;
|
|
258
|
+
if (!output) return "";
|
|
259
|
+
const parts = [];
|
|
260
|
+
for (const item of output) {
|
|
261
|
+
if (item.type === "message" && item.content) {
|
|
262
|
+
for (const content of item.content) {
|
|
263
|
+
if (content.type === "output_text" && content.text) {
|
|
264
|
+
parts.push(content.text);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return parts.join("");
|
|
270
|
+
} catch {
|
|
271
|
+
return "";
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function extractUsageFromRaw(rawResponse) {
|
|
275
|
+
const usage = rawResponse.usage;
|
|
276
|
+
if (usage === null || typeof usage !== "object") return void 0;
|
|
277
|
+
const inputTokens = usageCount(usage.input_tokens);
|
|
278
|
+
const cachedInputTokens = usageCount(usage.input_tokens_details?.cached_tokens);
|
|
279
|
+
const output = Array.isArray(rawResponse.output) ? rawResponse.output : [];
|
|
280
|
+
return {
|
|
281
|
+
inputTokens: Math.max(0, inputTokens - cachedInputTokens),
|
|
282
|
+
cachedInputTokens,
|
|
283
|
+
cacheWriteTokens: 0,
|
|
284
|
+
outputTokens: usageCount(usage.output_tokens),
|
|
285
|
+
searchCount: output.filter((item) => item?.type === "web_search_call").length
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function extractStopReasonFromRaw(rawResponse) {
|
|
289
|
+
const incomplete = rawResponse.incomplete_details;
|
|
290
|
+
const reason = incomplete !== null && typeof incomplete === "object" ? incomplete.reason : void 0;
|
|
291
|
+
if (typeof reason === "string" && reason.length > 0) return reason;
|
|
292
|
+
const status = rawResponse.status;
|
|
293
|
+
return typeof status === "string" && status.length > 0 ? status : void 0;
|
|
294
|
+
}
|
|
295
|
+
function extractCitedDomainsFromSources(groundingSources) {
|
|
296
|
+
const domains = /* @__PURE__ */ new Set();
|
|
297
|
+
for (const source of groundingSources) {
|
|
298
|
+
const domain = extractDomainFromUri(source.uri);
|
|
299
|
+
if (domain) domains.add(domain);
|
|
300
|
+
}
|
|
301
|
+
return [...domains];
|
|
302
|
+
}
|
|
303
|
+
function extractDomainFromUri(uri) {
|
|
304
|
+
const hostname = hostOf(uri);
|
|
305
|
+
if (!hostname || !registrableDomain(hostname) || hostMatchesAnyDomain(hostname, AI_ENGINE_SELF_DOMAINS.chatgpt)) return null;
|
|
306
|
+
return hostname;
|
|
307
|
+
}
|
|
308
|
+
async function generateText(prompt, config) {
|
|
309
|
+
const model = config.model ?? DEFAULT_MODEL;
|
|
310
|
+
const client = createClient(config);
|
|
311
|
+
const response = await withRetry2(
|
|
312
|
+
() => client.responses.create({
|
|
313
|
+
model,
|
|
314
|
+
input: prompt
|
|
315
|
+
})
|
|
316
|
+
);
|
|
317
|
+
return extractResponseText(response);
|
|
318
|
+
}
|
|
319
|
+
function responseToRecord(response) {
|
|
320
|
+
try {
|
|
321
|
+
return JSON.parse(JSON.stringify(response));
|
|
322
|
+
} catch {
|
|
323
|
+
return { error: "failed to serialize response" };
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ../provider-openai/src/list-models.ts
|
|
328
|
+
import OpenAI2 from "openai";
|
|
329
|
+
function listModels(config, signal) {
|
|
330
|
+
return withRetry(async () => {
|
|
331
|
+
signal.throwIfAborted();
|
|
332
|
+
const client = new OpenAI2({ apiKey: config.apiKey, baseURL: config.baseUrl, maxRetries: 0, timeout: 2500 });
|
|
333
|
+
const models = [];
|
|
334
|
+
const page = client.models.list({ signal });
|
|
335
|
+
let seen = 0;
|
|
336
|
+
for await (const model of page) {
|
|
337
|
+
signal.throwIfAborted();
|
|
338
|
+
if (++seen > 1e3) throw new Error("Model catalog exceeded the discovery limit");
|
|
339
|
+
if (!/^(?:gpt-|o\d|chat-)/.test(model.id) || /audio|realtime|transcrib|tts|image|codex|search|instruct/.test(model.id)) continue;
|
|
340
|
+
if (/^gpt-(?:3\.5|4)(?:-|$)/.test(model.id)) continue;
|
|
341
|
+
models.push({ id: model.id, displayName: model.id, tier: "standard" });
|
|
342
|
+
}
|
|
343
|
+
return models;
|
|
344
|
+
}, {
|
|
345
|
+
maxRetries: 1,
|
|
346
|
+
baseDelayMs: 200,
|
|
347
|
+
isRetryable: (error) => !signal.aborted && isRetryableHttpError(error),
|
|
348
|
+
computeDelayMs: (_attempt, error, delay) => {
|
|
349
|
+
const retryDelay = retryAfterDelayMs(error) ?? delay;
|
|
350
|
+
if (retryDelay >= 2500) throw error;
|
|
351
|
+
return retryDelay;
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ../provider-openai/src/adapter.ts
|
|
357
|
+
function toOpenAIConfig(config) {
|
|
358
|
+
return {
|
|
359
|
+
apiKey: config.apiKey ?? "",
|
|
360
|
+
model: config.model,
|
|
361
|
+
baseUrl: config.baseUrl,
|
|
362
|
+
quotaPolicy: config.quotaPolicy
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
function toOpenAIInput(input, config) {
|
|
366
|
+
return {
|
|
367
|
+
query: input.query,
|
|
368
|
+
canonicalDomains: input.canonicalDomains,
|
|
369
|
+
competitorDomains: input.competitorDomains,
|
|
370
|
+
config: toOpenAIConfig(config),
|
|
371
|
+
location: input.location
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
function toRawQueryResult(raw) {
|
|
375
|
+
return {
|
|
376
|
+
provider: "openai",
|
|
377
|
+
rawResponse: raw.rawResponse,
|
|
378
|
+
model: raw.model,
|
|
379
|
+
servedModel: raw.servedModel,
|
|
380
|
+
groundingSources: raw.groundingSources,
|
|
381
|
+
searchQueries: raw.searchQueries,
|
|
382
|
+
// Read from the response's `web_search_call` items. Under forced search
|
|
383
|
+
// nearly every row reads `used`; that is the contract holding, and a
|
|
384
|
+
// `not-used` row is the visible breach, so the observation still
|
|
385
|
+
// discriminates. The contract declares how the request was built.
|
|
386
|
+
retrievalStatus: raw.retrievalStatus,
|
|
387
|
+
retrievalContract: raw.retrievalContract,
|
|
388
|
+
usage: raw.usage,
|
|
389
|
+
stopReason: raw.stopReason
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
var openaiAdapter = {
|
|
393
|
+
name: "openai",
|
|
394
|
+
displayName: "OpenAI",
|
|
395
|
+
mode: "api",
|
|
396
|
+
// normalize.ts sets `user_location` on the web_search tool.
|
|
397
|
+
supportsLocationContext: true,
|
|
398
|
+
keyUrl: "https://platform.openai.com/api-keys",
|
|
399
|
+
// Upstream model list: https://platform.openai.com/docs/models
|
|
400
|
+
modelRegistry: {
|
|
401
|
+
defaultModel: "gpt-5.4",
|
|
402
|
+
validationPattern: /./,
|
|
403
|
+
validationHint: "any valid OpenAI model name (e.g. gpt-5.4, o3, chatgpt-4o-latest)",
|
|
404
|
+
knownModels: [
|
|
405
|
+
{ id: "gpt-5.4", displayName: "GPT-5.4", tier: "flagship" },
|
|
406
|
+
{ id: "gpt-5.4-pro", displayName: "GPT-5.4 Pro", tier: "flagship" },
|
|
407
|
+
{ id: "gpt-5-mini", displayName: "GPT-5 Mini", tier: "fast" },
|
|
408
|
+
{ id: "gpt-5-nano", displayName: "GPT-5 Nano", tier: "economy" },
|
|
409
|
+
{ id: "gpt-5", displayName: "GPT-5", tier: "standard" },
|
|
410
|
+
{ id: "gpt-4.1", displayName: "GPT-4.1", tier: "standard" }
|
|
411
|
+
]
|
|
412
|
+
},
|
|
413
|
+
listModels,
|
|
414
|
+
validateConfig(config) {
|
|
415
|
+
const result = validateConfig(toOpenAIConfig(config));
|
|
416
|
+
return {
|
|
417
|
+
ok: result.ok,
|
|
418
|
+
provider: "openai",
|
|
419
|
+
message: result.message,
|
|
420
|
+
model: result.model
|
|
421
|
+
};
|
|
422
|
+
},
|
|
423
|
+
async healthcheck(config) {
|
|
424
|
+
const result = await healthcheck(toOpenAIConfig(config));
|
|
425
|
+
return {
|
|
426
|
+
ok: result.ok,
|
|
427
|
+
provider: "openai",
|
|
428
|
+
message: result.message,
|
|
429
|
+
model: result.model
|
|
430
|
+
};
|
|
431
|
+
},
|
|
432
|
+
buildTrackedQueryRequest(input, config) {
|
|
433
|
+
return buildTrackedQueryRequest(toOpenAIInput(input, config));
|
|
434
|
+
},
|
|
435
|
+
async executeTrackedQuery(input, config) {
|
|
436
|
+
return toRawQueryResult(await executeTrackedQuery(toOpenAIInput(input, config)));
|
|
437
|
+
},
|
|
438
|
+
parseTrackedQueryResponse(body, model) {
|
|
439
|
+
return toRawQueryResult(parseTrackedQueryResponse(body, model));
|
|
440
|
+
},
|
|
441
|
+
normalizeResult(raw) {
|
|
442
|
+
const openaiRaw = {
|
|
443
|
+
provider: "openai",
|
|
444
|
+
rawResponse: raw.rawResponse,
|
|
445
|
+
model: raw.model,
|
|
446
|
+
groundingSources: raw.groundingSources,
|
|
447
|
+
searchQueries: raw.searchQueries,
|
|
448
|
+
// A reconstruction that predates the field falls back to `unknown`
|
|
449
|
+
// rather than asserting an absence.
|
|
450
|
+
retrievalStatus: raw.retrievalStatus ?? RetrievalStatuses.unknown,
|
|
451
|
+
retrievalContract: raw.retrievalContract ?? OPENAI_RETRIEVAL_CONTRACT
|
|
452
|
+
};
|
|
453
|
+
const normalized = normalizeResult(openaiRaw);
|
|
454
|
+
return {
|
|
455
|
+
provider: "openai",
|
|
456
|
+
answerText: normalized.answerText,
|
|
457
|
+
citedDomains: normalized.citedDomains,
|
|
458
|
+
groundingSources: normalized.groundingSources,
|
|
459
|
+
searchQueries: normalized.searchQueries,
|
|
460
|
+
retrievalStatus: normalized.retrievalStatus
|
|
461
|
+
};
|
|
462
|
+
},
|
|
463
|
+
async generateText(prompt, config) {
|
|
464
|
+
return generateText(prompt, toOpenAIConfig(config));
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
// ../provider-openai/src/anchored-spans.ts
|
|
469
|
+
function isRecord(value) {
|
|
470
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
471
|
+
}
|
|
472
|
+
function extractAnchoredSpans(rawResponse) {
|
|
473
|
+
const spans = [];
|
|
474
|
+
const output = Array.isArray(rawResponse.output) ? rawResponse.output : [];
|
|
475
|
+
for (const item of output) {
|
|
476
|
+
if (!isRecord(item) || item.type !== "message" || !Array.isArray(item.content)) continue;
|
|
477
|
+
for (const part of item.content) {
|
|
478
|
+
if (!isRecord(part) || part.type !== "output_text" || typeof part.text !== "string") continue;
|
|
479
|
+
const text = part.text;
|
|
480
|
+
const citations = (Array.isArray(part.annotations) ? part.annotations : []).flatMap((annotation) => {
|
|
481
|
+
if (!isRecord(annotation) || annotation.type !== "url_citation" || typeof annotation.url !== "string") return [];
|
|
482
|
+
const start = annotation.start_index;
|
|
483
|
+
const end = annotation.end_index;
|
|
484
|
+
if (typeof start !== "number" || typeof end !== "number" || !Number.isInteger(start) || !Number.isInteger(end)) return [];
|
|
485
|
+
if (start < 0 || end < start || end > text.length) return [];
|
|
486
|
+
return [{ start, end, url: annotation.url }];
|
|
487
|
+
}).sort((a, b) => a.start - b.start);
|
|
488
|
+
let previousEnd = 0;
|
|
489
|
+
for (const citation of citations) {
|
|
490
|
+
const lineStart = citation.start === 0 ? 0 : text.lastIndexOf("\n", citation.start - 1) + 1;
|
|
491
|
+
const from = Math.max(lineStart, previousEnd);
|
|
492
|
+
if (citation.start > from) {
|
|
493
|
+
spans.push({ text: text.slice(from, citation.start), source: citation.url, kind: "window", via: AnchoredSpanSources["openai-annotation"] });
|
|
494
|
+
}
|
|
495
|
+
previousEnd = Math.max(previousEnd, citation.end);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return spans;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// ../provider-claude/src/normalize.ts
|
|
503
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
504
|
+
|
|
505
|
+
// ../provider-claude/src/utils.ts
|
|
506
|
+
async function withRetry3(fn, options = {}) {
|
|
507
|
+
return withRetry(fn, {
|
|
508
|
+
maxRetries: options.maxRetries ?? 3,
|
|
509
|
+
baseDelayMs: options.initialDelay ?? 1e3,
|
|
510
|
+
// Jitter off preserves the historical deterministic backoff that every
|
|
511
|
+
// provider has shipped to date (1000, 2000, 4000ms). Enable per-caller
|
|
512
|
+
// if you need it.
|
|
513
|
+
jitter: false,
|
|
514
|
+
isRetryable: options.isRetryable ?? isRetryableHttpError,
|
|
515
|
+
computeDelayMs: options.computeDelayMs,
|
|
516
|
+
onRetry: ({ attempt, err, delayMs }) => {
|
|
517
|
+
console.warn(
|
|
518
|
+
`[provider] Attempt ${attempt + 1} failed, retrying in ${delayMs}ms...`,
|
|
519
|
+
describeError(err)
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ../provider-claude/src/normalize.ts
|
|
526
|
+
var DEFAULT_MODEL2 = "claude-sonnet-4-6";
|
|
527
|
+
var VALIDATION_PATTERN = /^claude-/;
|
|
528
|
+
var CLAUDE_RETRIEVAL_CONTRACT = RetrievalContracts["search-required-v1"];
|
|
529
|
+
var CLAUDE_MODELS_REJECTING_FORCED_TOOL_CHOICE = /* @__PURE__ */ new Set(["claude-opus-5-5", "claude-fable-5-1", "claude-mythos-5-1"]);
|
|
530
|
+
function claudeModelRejectsForcedToolChoice(model) {
|
|
531
|
+
return CLAUDE_MODELS_REJECTING_FORCED_TOOL_CHOICE.has(
|
|
532
|
+
model.trim().toLowerCase()
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
function claudeRetrievalContractForModel(model) {
|
|
536
|
+
return claudeModelRejectsForcedToolChoice(model) ? RetrievalContracts["native-auto-v1"] : CLAUDE_RETRIEVAL_CONTRACT;
|
|
537
|
+
}
|
|
538
|
+
var CLAUDE_TOOL_CHOICE_BY_CONTRACT = {
|
|
539
|
+
[RetrievalContracts["search-required-v1"]]: {
|
|
540
|
+
type: "tool",
|
|
541
|
+
name: "web_search"
|
|
542
|
+
},
|
|
543
|
+
[RetrievalContracts["native-auto-v1"]]: { type: "auto" }
|
|
544
|
+
};
|
|
545
|
+
function resolveModel(config) {
|
|
546
|
+
const m = config.model;
|
|
547
|
+
if (!m) return DEFAULT_MODEL2;
|
|
548
|
+
if (VALIDATION_PATTERN.test(m)) return m;
|
|
549
|
+
console.warn(
|
|
550
|
+
`[provider-claude] Invalid model name "${m}" \u2014 this provider uses the Anthropic API which only accepts "claude-*" model names. Falling back to ${DEFAULT_MODEL2}.`
|
|
551
|
+
);
|
|
552
|
+
return DEFAULT_MODEL2;
|
|
553
|
+
}
|
|
554
|
+
function validateConfig2(config) {
|
|
555
|
+
if (!config.apiKey || config.apiKey.length === 0) {
|
|
556
|
+
return { ok: false, provider: "claude", message: "missing api key" };
|
|
557
|
+
}
|
|
558
|
+
const model = resolveModel(config);
|
|
559
|
+
const warning = config.model && !VALIDATION_PATTERN.test(config.model) ? ` (invalid model "${config.model}" replaced with default)` : claudeModelRejectsForcedToolChoice(model) ? ` (${model} rejects forced tool_choice, so tracked queries run under ${claudeRetrievalContractForModel(model)}: web_search is offered but retrieval is not guaranteed)` : "";
|
|
560
|
+
return {
|
|
561
|
+
ok: true,
|
|
562
|
+
provider: "claude",
|
|
563
|
+
message: `config valid${warning}`,
|
|
564
|
+
model
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
async function healthcheck2(config) {
|
|
568
|
+
const validation = validateConfig2(config);
|
|
569
|
+
if (!validation.ok) return validation;
|
|
570
|
+
try {
|
|
571
|
+
const model = resolveModel(config);
|
|
572
|
+
const client = new Anthropic({ apiKey: config.apiKey });
|
|
573
|
+
const response = await withRetry3(
|
|
574
|
+
() => client.messages.create({
|
|
575
|
+
model,
|
|
576
|
+
max_tokens: 32,
|
|
577
|
+
messages: [{ role: "user", content: 'Say "ok"' }]
|
|
578
|
+
})
|
|
579
|
+
);
|
|
580
|
+
const text = extractTextFromResponse(response);
|
|
581
|
+
return {
|
|
582
|
+
ok: text.length > 0,
|
|
583
|
+
provider: "claude",
|
|
584
|
+
message: text.length > 0 ? "claude api key verified" : "empty response from claude",
|
|
585
|
+
model
|
|
586
|
+
};
|
|
587
|
+
} catch (err) {
|
|
588
|
+
return {
|
|
589
|
+
ok: false,
|
|
590
|
+
provider: "claude",
|
|
591
|
+
message: describeError(err),
|
|
592
|
+
model: resolveModel(config)
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
var CLAUDE_MESSAGES_ENDPOINT = "/v1/messages";
|
|
597
|
+
function buildTrackedQueryRequest2(input) {
|
|
598
|
+
const webSearchTool = {
|
|
599
|
+
type: "web_search_20250305",
|
|
600
|
+
name: "web_search",
|
|
601
|
+
max_uses: 5
|
|
602
|
+
};
|
|
603
|
+
if (input.location) {
|
|
604
|
+
webSearchTool.user_location = {
|
|
605
|
+
type: "approximate",
|
|
606
|
+
city: input.location.city,
|
|
607
|
+
region: input.location.region,
|
|
608
|
+
country: input.location.country,
|
|
609
|
+
...input.location.timezone ? { timezone: input.location.timezone } : {}
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
const model = resolveModel(input.config);
|
|
613
|
+
const retrievalContract = claudeRetrievalContractForModel(model);
|
|
614
|
+
const body = {
|
|
615
|
+
model,
|
|
616
|
+
max_tokens: 4096,
|
|
617
|
+
tools: [webSearchTool],
|
|
618
|
+
// search-required-v1 forces web_search, so retrieval is guaranteed by the
|
|
619
|
+
// API control and the query text and answer substance stay untouched.
|
|
620
|
+
// native-auto-v1 (models that reject forcing) leaves the search to
|
|
621
|
+
// Claude. See claudeRetrievalContractForModel.
|
|
622
|
+
tool_choice: CLAUDE_TOOL_CHOICE_BY_CONTRACT[retrievalContract],
|
|
623
|
+
messages: [{ role: "user", content: input.query }]
|
|
624
|
+
};
|
|
625
|
+
return { endpoint: CLAUDE_MESSAGES_ENDPOINT, body };
|
|
626
|
+
}
|
|
627
|
+
async function executeTrackedQuery2(input) {
|
|
628
|
+
const params = buildTrackedQueryRequest2(input).body;
|
|
629
|
+
const client = new Anthropic({ apiKey: input.config.apiKey });
|
|
630
|
+
let response;
|
|
631
|
+
try {
|
|
632
|
+
response = await withRetry3(() => client.messages.create(params));
|
|
633
|
+
} catch (err) {
|
|
634
|
+
const msg = describeError(err);
|
|
635
|
+
throw new Error(`[provider-claude] ${msg}`);
|
|
636
|
+
}
|
|
637
|
+
return parseTrackedQueryResponse2(response, params.model);
|
|
638
|
+
}
|
|
639
|
+
function parseTrackedQueryResponse2(body, model) {
|
|
640
|
+
const rawResponse = responseToRecord2(body);
|
|
641
|
+
const parsed = reparseStoredResult2(rawResponse);
|
|
642
|
+
if (parsed.providerError) {
|
|
643
|
+
throw new Error(`[provider-claude] ${parsed.providerError}`);
|
|
644
|
+
}
|
|
645
|
+
return {
|
|
646
|
+
provider: "claude",
|
|
647
|
+
rawResponse,
|
|
648
|
+
model,
|
|
649
|
+
servedModel: extractServedModel(rawResponse),
|
|
650
|
+
groundingSources: parsed.groundingSources,
|
|
651
|
+
searchQueries: parsed.searchQueries,
|
|
652
|
+
retrievalStatus: parsed.retrievalStatus,
|
|
653
|
+
// The contract is decided by the model the request was built for, the
|
|
654
|
+
// same way buildTrackedQueryRequest chose its tool_choice.
|
|
655
|
+
retrievalContract: claudeRetrievalContractForModel(model),
|
|
656
|
+
usage: extractUsageFromRaw2(rawResponse),
|
|
657
|
+
stopReason: extractStopReasonFromRaw2(rawResponse)
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
function normalizeResult2(raw) {
|
|
661
|
+
const parsed = reparseStoredResult2(raw.rawResponse);
|
|
662
|
+
const useParsed = hasParsedResponseContent2(raw.rawResponse);
|
|
663
|
+
const groundingSources = useParsed ? parsed.groundingSources : raw.groundingSources;
|
|
664
|
+
const searchQueries = useParsed ? parsed.searchQueries : raw.searchQueries;
|
|
665
|
+
const citedDomains = extractCitedDomainsFromSources2(groundingSources);
|
|
666
|
+
return {
|
|
667
|
+
provider: "claude",
|
|
668
|
+
answerText: parsed.answerText,
|
|
669
|
+
citedDomains,
|
|
670
|
+
groundingSources,
|
|
671
|
+
searchQueries,
|
|
672
|
+
retrievalStatus: useParsed ? parsed.retrievalStatus : raw.retrievalStatus
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
function hasParsedResponseContent2(rawResponse) {
|
|
676
|
+
return Array.isArray(rawResponse.content) && rawResponse.content.length > 0;
|
|
677
|
+
}
|
|
678
|
+
function extractServedModel(rawResponse) {
|
|
679
|
+
return normalizeServedModel(rawResponse.model);
|
|
680
|
+
}
|
|
681
|
+
function reparseStoredResult2(rawResponse) {
|
|
682
|
+
const groundingSources = extractGroundingSourcesFromRaw2(rawResponse);
|
|
683
|
+
const searchQueries = extractSearchQueriesFromRaw2(rawResponse);
|
|
684
|
+
const providerErrors = extractWebSearchToolErrors(rawResponse);
|
|
685
|
+
return {
|
|
686
|
+
provider: "claude",
|
|
687
|
+
answerText: extractAnswerTextFromRaw2(rawResponse),
|
|
688
|
+
citedDomains: extractCitedDomainsFromSources2(groundingSources),
|
|
689
|
+
groundingSources,
|
|
690
|
+
searchQueries,
|
|
691
|
+
retrievalStatus: extractRetrievalStatusFromRaw2(rawResponse),
|
|
692
|
+
...providerErrors.length > 0 ? { providerError: `web_search tool error: ${providerErrors.join(", ")}` } : {}
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
function extractTextFromResponse(response) {
|
|
696
|
+
try {
|
|
697
|
+
const parts = [];
|
|
698
|
+
for (const block of response.content) {
|
|
699
|
+
if (block.type === "text") {
|
|
700
|
+
parts.push(block.text);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return parts.join("");
|
|
704
|
+
} catch {
|
|
705
|
+
return "";
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
function extractGroundingSourcesFromRaw2(rawResponse) {
|
|
709
|
+
const sources = [];
|
|
710
|
+
const seen = /* @__PURE__ */ new Set();
|
|
711
|
+
try {
|
|
712
|
+
const content = rawResponse.content;
|
|
713
|
+
if (!content) return [];
|
|
714
|
+
for (const block of content) {
|
|
715
|
+
if (block.type === "text" && Array.isArray(block.citations)) {
|
|
716
|
+
for (const citation of block.citations) {
|
|
717
|
+
if (citation.type === "web_search_result_location" && typeof citation.url === "string" && !seen.has(citation.url)) {
|
|
718
|
+
seen.add(citation.url);
|
|
719
|
+
sources.push({
|
|
720
|
+
uri: citation.url,
|
|
721
|
+
title: citation.title ?? ""
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
} catch {
|
|
728
|
+
}
|
|
729
|
+
return sources;
|
|
730
|
+
}
|
|
731
|
+
function extractRetrievalStatusFromRaw2(rawResponse) {
|
|
732
|
+
try {
|
|
733
|
+
const content = rawResponse.content;
|
|
734
|
+
if (!Array.isArray(content) || content.length === 0) return "unknown";
|
|
735
|
+
return content.some(
|
|
736
|
+
(block) => block.type === "server_tool_use" && block.name === "web_search"
|
|
737
|
+
) ? "used" : "not-used";
|
|
738
|
+
} catch {
|
|
739
|
+
return "unknown";
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
function extractSearchQueriesFromRaw2(rawResponse) {
|
|
743
|
+
const queries = /* @__PURE__ */ new Set();
|
|
744
|
+
try {
|
|
745
|
+
const content = rawResponse.content;
|
|
746
|
+
if (!content) return [];
|
|
747
|
+
for (const block of content) {
|
|
748
|
+
if (block.type === "server_tool_use" && block.name === "web_search") {
|
|
749
|
+
if (typeof block.input?.query === "string" && block.input.query.length > 0) {
|
|
750
|
+
queries.add(block.input.query);
|
|
751
|
+
}
|
|
752
|
+
if (Array.isArray(block.input?.queries)) {
|
|
753
|
+
for (const query of block.input.queries) {
|
|
754
|
+
if (typeof query === "string" && query.length > 0) {
|
|
755
|
+
queries.add(query);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
} catch {
|
|
762
|
+
}
|
|
763
|
+
return [...queries];
|
|
764
|
+
}
|
|
765
|
+
function extractAnswerTextFromRaw2(rawResponse) {
|
|
766
|
+
try {
|
|
767
|
+
const content = rawResponse.content;
|
|
768
|
+
if (!content) return "";
|
|
769
|
+
const parts = [];
|
|
770
|
+
for (const block of content) {
|
|
771
|
+
if (block.type === "text" && block.text) {
|
|
772
|
+
parts.push(block.text);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return parts.join("");
|
|
776
|
+
} catch {
|
|
777
|
+
return "";
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
function extractWebSearchToolErrors(rawResponse) {
|
|
781
|
+
const errors = /* @__PURE__ */ new Set();
|
|
782
|
+
try {
|
|
783
|
+
const content = rawResponse.content;
|
|
784
|
+
if (!content) return [];
|
|
785
|
+
for (const block of content) {
|
|
786
|
+
if (block.type !== "web_search_tool_result") continue;
|
|
787
|
+
if (block.content === null || typeof block.content !== "object" || Array.isArray(block.content))
|
|
788
|
+
continue;
|
|
789
|
+
const errorCode = block.content.error_code;
|
|
790
|
+
if (typeof errorCode === "string" && errorCode.length > 0) {
|
|
791
|
+
errors.add(errorCode);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
} catch {
|
|
795
|
+
}
|
|
796
|
+
return [...errors];
|
|
797
|
+
}
|
|
798
|
+
function extractUsageFromRaw2(rawResponse) {
|
|
799
|
+
const usage = rawResponse.usage;
|
|
800
|
+
if (usage === null || typeof usage !== "object") return void 0;
|
|
801
|
+
return {
|
|
802
|
+
inputTokens: usageCount(usage.input_tokens),
|
|
803
|
+
cachedInputTokens: usageCount(usage.cache_read_input_tokens),
|
|
804
|
+
cacheWriteTokens: usageCount(usage.cache_creation_input_tokens),
|
|
805
|
+
outputTokens: usageCount(usage.output_tokens),
|
|
806
|
+
searchCount: usageCount(usage.server_tool_use?.web_search_requests)
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
function extractStopReasonFromRaw2(rawResponse) {
|
|
810
|
+
const stopReason = rawResponse.stop_reason;
|
|
811
|
+
return typeof stopReason === "string" && stopReason.length > 0 ? stopReason : void 0;
|
|
812
|
+
}
|
|
813
|
+
function extractCitedDomainsFromSources2(groundingSources) {
|
|
814
|
+
const domains = /* @__PURE__ */ new Set();
|
|
815
|
+
for (const source of groundingSources) {
|
|
816
|
+
const domain = extractDomainFromUri2(source.uri);
|
|
817
|
+
if (domain) domains.add(domain);
|
|
818
|
+
}
|
|
819
|
+
return [...domains];
|
|
820
|
+
}
|
|
821
|
+
function extractDomainFromUri2(uri) {
|
|
822
|
+
const hostname = hostOf(uri);
|
|
823
|
+
if (!hostname || !registrableDomain(hostname) || hostMatchesAnyDomain(hostname, AI_ENGINE_SELF_DOMAINS.claude)) {
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
return hostname;
|
|
827
|
+
}
|
|
828
|
+
async function generateText2(prompt, config) {
|
|
829
|
+
const model = resolveModel(config);
|
|
830
|
+
const client = new Anthropic({ apiKey: config.apiKey });
|
|
831
|
+
const response = await withRetry3(
|
|
832
|
+
() => client.messages.create({
|
|
833
|
+
model,
|
|
834
|
+
max_tokens: 2048,
|
|
835
|
+
messages: [{ role: "user", content: prompt }]
|
|
836
|
+
})
|
|
837
|
+
);
|
|
838
|
+
return extractTextFromResponse(response);
|
|
839
|
+
}
|
|
840
|
+
function responseToRecord2(response) {
|
|
841
|
+
try {
|
|
842
|
+
return JSON.parse(JSON.stringify(response));
|
|
843
|
+
} catch {
|
|
844
|
+
return { error: "failed to serialize response" };
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// ../provider-claude/src/list-models.ts
|
|
849
|
+
import Anthropic2 from "@anthropic-ai/sdk";
|
|
850
|
+
function listModels2(config, signal) {
|
|
851
|
+
return withRetry(async () => {
|
|
852
|
+
signal.throwIfAborted();
|
|
853
|
+
const client = new Anthropic2({ apiKey: config.apiKey, baseURL: config.baseUrl, maxRetries: 0, timeout: 2500 });
|
|
854
|
+
const models = [];
|
|
855
|
+
const page = client.models.list({ limit: 100 }, { signal });
|
|
856
|
+
let seen = 0;
|
|
857
|
+
for await (const model of page) {
|
|
858
|
+
signal.throwIfAborted();
|
|
859
|
+
if (++seen > 1e3) throw new Error("Model catalog exceeded the discovery limit");
|
|
860
|
+
models.push({ id: model.id, displayName: model.display_name, tier: "standard" });
|
|
861
|
+
}
|
|
862
|
+
return models;
|
|
863
|
+
}, {
|
|
864
|
+
maxRetries: 1,
|
|
865
|
+
baseDelayMs: 200,
|
|
866
|
+
isRetryable: (error) => !signal.aborted && isRetryableHttpError(error),
|
|
867
|
+
computeDelayMs: (_attempt, error, delay) => {
|
|
868
|
+
const retryDelay = retryAfterDelayMs(error) ?? delay;
|
|
869
|
+
if (retryDelay >= 2500) throw error;
|
|
870
|
+
return retryDelay;
|
|
871
|
+
}
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// ../provider-claude/src/batch.ts
|
|
876
|
+
import Anthropic3, { APIError } from "@anthropic-ai/sdk";
|
|
877
|
+
var AMBIGUOUS_CLIENT_ERROR_STATUSES = /* @__PURE__ */ new Set([408, 409]);
|
|
878
|
+
var CANCEL_SETTLED_STATUSES = /* @__PURE__ */ new Set(["canceling", "ended"]);
|
|
879
|
+
function isDefiniteRejection(err) {
|
|
880
|
+
if (!(err instanceof APIError) || typeof err.status !== "number") return false;
|
|
881
|
+
return err.status >= 400 && err.status < 500 && !AMBIGUOUS_CLIENT_ERROR_STATUSES.has(err.status);
|
|
882
|
+
}
|
|
883
|
+
function isRateLimitRejection(err) {
|
|
884
|
+
return err instanceof APIError && err.status === 429;
|
|
885
|
+
}
|
|
886
|
+
function isRetryableBatchCall(err) {
|
|
887
|
+
return err instanceof APIError && isRetryableHttpError(err);
|
|
888
|
+
}
|
|
889
|
+
function honourRetryAfter(_attempt, err, defaultMs) {
|
|
890
|
+
return retryAfterDelayMs(err) ?? defaultMs;
|
|
891
|
+
}
|
|
892
|
+
function createBatchClient(config, onSend) {
|
|
893
|
+
return new Anthropic3({
|
|
894
|
+
apiKey: config.apiKey ?? "",
|
|
895
|
+
maxRetries: 0,
|
|
896
|
+
...onSend ? {
|
|
897
|
+
fetch: (input, init) => {
|
|
898
|
+
onSend();
|
|
899
|
+
return globalThis.fetch(input, init);
|
|
900
|
+
}
|
|
901
|
+
} : {}
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
function toPollResult(batch) {
|
|
905
|
+
const counts = batch.request_counts;
|
|
906
|
+
return {
|
|
907
|
+
status: batch.processing_status,
|
|
908
|
+
requestCounts: {
|
|
909
|
+
processing: counts.processing,
|
|
910
|
+
succeeded: counts.succeeded,
|
|
911
|
+
errored: counts.errored,
|
|
912
|
+
canceled: counts.canceled,
|
|
913
|
+
expired: counts.expired
|
|
914
|
+
},
|
|
915
|
+
...batch.ended_at ? { endedAt: batch.ended_at } : {},
|
|
916
|
+
// `expires_at` is the processing deadline (24h after creation), not the
|
|
917
|
+
// results' lifetime. The API states when results became unavailable only
|
|
918
|
+
// once it happens, as `archived_at`.
|
|
919
|
+
...batch.archived_at ? { resultsExpireAt: batch.archived_at } : {}
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
function describeErroredResult(result) {
|
|
923
|
+
const inner = result.error?.error;
|
|
924
|
+
return inner ? `${inner.type}: ${inner.message}` : describeError(result.error);
|
|
925
|
+
}
|
|
926
|
+
function toResultLine(line) {
|
|
927
|
+
const customId = line.custom_id;
|
|
928
|
+
const result = line.result;
|
|
929
|
+
switch (result.type) {
|
|
930
|
+
case "succeeded":
|
|
931
|
+
return { customId, type: "succeeded", body: responseToRecord2(result.message) };
|
|
932
|
+
case "errored":
|
|
933
|
+
return { customId, type: "errored", error: `[provider-claude] ${describeErroredResult(result)}` };
|
|
934
|
+
case "canceled":
|
|
935
|
+
return { customId, type: "canceled", error: "[provider-claude] the batch was canceled before this request was processed" };
|
|
936
|
+
case "expired":
|
|
937
|
+
return { customId, type: "expired", error: "[provider-claude] the batch expired before this request was processed" };
|
|
938
|
+
default: {
|
|
939
|
+
const unrecognized = result;
|
|
940
|
+
return { customId, type: "errored", error: `[provider-claude] unrecognized batch result: ${describeError(unrecognized)}` };
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
function createClaudeBatchCapability(options = {}) {
|
|
945
|
+
const initialDelay = options.retryBaseDelayMs;
|
|
946
|
+
return {
|
|
947
|
+
maxRequestsPerBatch: 1e5,
|
|
948
|
+
maxBytesPerBatch: 256 * 1024 * 1024,
|
|
949
|
+
defaultDeadlineHours: 24,
|
|
950
|
+
async submit(requests, config) {
|
|
951
|
+
if (requests.length === 0) {
|
|
952
|
+
throw new ProviderBatchSubmitError("[provider-claude] a batch needs at least one request", { definite: true });
|
|
953
|
+
}
|
|
954
|
+
const foreign = requests.find((r) => r.request.endpoint !== CLAUDE_MESSAGES_ENDPOINT);
|
|
955
|
+
if (foreign) {
|
|
956
|
+
throw new ProviderBatchSubmitError(
|
|
957
|
+
`[provider-claude] batch request ${foreign.customId} targets ${foreign.request.endpoint}, not ${CLAUDE_MESSAGES_ENDPOINT}`,
|
|
958
|
+
{ definite: true }
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
const params = {
|
|
962
|
+
requests: requests.map((r) => ({
|
|
963
|
+
custom_id: r.customId,
|
|
964
|
+
params: r.request.body
|
|
965
|
+
}))
|
|
966
|
+
};
|
|
967
|
+
let sent = false;
|
|
968
|
+
const client = createBatchClient(config, () => {
|
|
969
|
+
sent = true;
|
|
970
|
+
});
|
|
971
|
+
try {
|
|
972
|
+
const batch = await withRetry3(
|
|
973
|
+
() => {
|
|
974
|
+
sent = false;
|
|
975
|
+
return client.messages.batches.create(params);
|
|
976
|
+
},
|
|
977
|
+
{ initialDelay, isRetryable: isRateLimitRejection, computeDelayMs: honourRetryAfter }
|
|
978
|
+
);
|
|
979
|
+
return { providerBatchId: batch.id, expiresAt: batch.expires_at };
|
|
980
|
+
} catch (err) {
|
|
981
|
+
throw new ProviderBatchSubmitError(`[provider-claude] batch submit failed: ${describeError(err)}`, {
|
|
982
|
+
definite: !sent || isDefiniteRejection(err),
|
|
983
|
+
cause: err
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
},
|
|
987
|
+
async poll(providerBatchId, config) {
|
|
988
|
+
const client = createBatchClient(config);
|
|
989
|
+
try {
|
|
990
|
+
const batch = await withRetry3(() => client.messages.batches.retrieve(providerBatchId), {
|
|
991
|
+
initialDelay,
|
|
992
|
+
isRetryable: isRetryableBatchCall,
|
|
993
|
+
computeDelayMs: honourRetryAfter
|
|
994
|
+
});
|
|
995
|
+
return toPollResult(batch);
|
|
996
|
+
} catch (err) {
|
|
997
|
+
throw new Error(`[provider-claude] batch poll failed: ${describeError(err)}`, { cause: err });
|
|
998
|
+
}
|
|
999
|
+
},
|
|
1000
|
+
async *results(providerBatchId, config) {
|
|
1001
|
+
const client = createBatchClient(config);
|
|
1002
|
+
try {
|
|
1003
|
+
const lines = await withRetry3(() => client.messages.batches.results(providerBatchId), {
|
|
1004
|
+
initialDelay,
|
|
1005
|
+
isRetryable: isRetryableBatchCall,
|
|
1006
|
+
computeDelayMs: honourRetryAfter
|
|
1007
|
+
});
|
|
1008
|
+
for await (const line of lines) {
|
|
1009
|
+
yield toResultLine(line);
|
|
1010
|
+
}
|
|
1011
|
+
} catch (err) {
|
|
1012
|
+
throw new Error(`[provider-claude] batch results failed: ${describeError(err)}`, { cause: err });
|
|
1013
|
+
}
|
|
1014
|
+
},
|
|
1015
|
+
async cancel(providerBatchId, config) {
|
|
1016
|
+
const client = createBatchClient(config);
|
|
1017
|
+
const retryOptions = { initialDelay, isRetryable: isRetryableBatchCall, computeDelayMs: honourRetryAfter };
|
|
1018
|
+
try {
|
|
1019
|
+
await withRetry3(() => client.messages.batches.cancel(providerBatchId), retryOptions);
|
|
1020
|
+
} catch (err) {
|
|
1021
|
+
const current = await withRetry3(() => client.messages.batches.retrieve(providerBatchId), retryOptions).catch(() => null);
|
|
1022
|
+
if (current && CANCEL_SETTLED_STATUSES.has(current.processing_status)) return;
|
|
1023
|
+
throw new Error(`[provider-claude] batch cancel failed: ${describeError(err)}`, { cause: err });
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
var claudeBatch = createClaudeBatchCapability();
|
|
1029
|
+
|
|
1030
|
+
// ../provider-claude/src/adapter.ts
|
|
1031
|
+
function toClaudeConfig(config) {
|
|
1032
|
+
return {
|
|
1033
|
+
apiKey: config.apiKey ?? "",
|
|
1034
|
+
model: config.model,
|
|
1035
|
+
quotaPolicy: config.quotaPolicy
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
function toClaudeInput(input, config) {
|
|
1039
|
+
return {
|
|
1040
|
+
query: input.query,
|
|
1041
|
+
canonicalDomains: input.canonicalDomains,
|
|
1042
|
+
competitorDomains: input.competitorDomains,
|
|
1043
|
+
config: toClaudeConfig(config),
|
|
1044
|
+
location: input.location
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
function toRawQueryResult2(raw) {
|
|
1048
|
+
return {
|
|
1049
|
+
provider: "claude",
|
|
1050
|
+
rawResponse: raw.rawResponse,
|
|
1051
|
+
model: raw.model,
|
|
1052
|
+
servedModel: raw.servedModel,
|
|
1053
|
+
groundingSources: raw.groundingSources,
|
|
1054
|
+
searchQueries: raw.searchQueries,
|
|
1055
|
+
retrievalStatus: raw.retrievalStatus,
|
|
1056
|
+
retrievalContract: raw.retrievalContract,
|
|
1057
|
+
usage: raw.usage,
|
|
1058
|
+
stopReason: raw.stopReason
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
var claudeAdapter = {
|
|
1062
|
+
name: "claude",
|
|
1063
|
+
displayName: "Claude",
|
|
1064
|
+
mode: "api",
|
|
1065
|
+
// normalize.ts sets `user_location` on the web_search tool.
|
|
1066
|
+
supportsLocationContext: true,
|
|
1067
|
+
keyUrl: "https://platform.claude.com/settings/keys",
|
|
1068
|
+
// Upstream model list: https://platform.claude.com/docs/en/about-claude/models/overview
|
|
1069
|
+
modelRegistry: {
|
|
1070
|
+
defaultModel: "claude-sonnet-4-6",
|
|
1071
|
+
validationPattern: /^claude-/,
|
|
1072
|
+
validationHint: 'model name must start with "claude-" (e.g. claude-sonnet-4-6)',
|
|
1073
|
+
knownModels: [
|
|
1074
|
+
{ id: "claude-opus-4-6", displayName: "Claude Opus 4.6", tier: "flagship" },
|
|
1075
|
+
{ id: "claude-sonnet-4-6", displayName: "Claude Sonnet 4.6", tier: "standard" },
|
|
1076
|
+
{ id: "claude-haiku-4-5", displayName: "Claude Haiku 4.5", tier: "fast" }
|
|
1077
|
+
]
|
|
1078
|
+
},
|
|
1079
|
+
listModels: listModels2,
|
|
1080
|
+
validateConfig(config) {
|
|
1081
|
+
const result = validateConfig2(toClaudeConfig(config));
|
|
1082
|
+
return {
|
|
1083
|
+
ok: result.ok,
|
|
1084
|
+
provider: "claude",
|
|
1085
|
+
message: result.message,
|
|
1086
|
+
model: result.model
|
|
1087
|
+
};
|
|
1088
|
+
},
|
|
1089
|
+
async healthcheck(config) {
|
|
1090
|
+
const result = await healthcheck2(toClaudeConfig(config));
|
|
1091
|
+
return {
|
|
1092
|
+
ok: result.ok,
|
|
1093
|
+
provider: "claude",
|
|
1094
|
+
message: result.message,
|
|
1095
|
+
model: result.model
|
|
1096
|
+
};
|
|
1097
|
+
},
|
|
1098
|
+
buildTrackedQueryRequest(input, config) {
|
|
1099
|
+
return buildTrackedQueryRequest2(toClaudeInput(input, config));
|
|
1100
|
+
},
|
|
1101
|
+
async executeTrackedQuery(input, config) {
|
|
1102
|
+
return toRawQueryResult2(await executeTrackedQuery2(toClaudeInput(input, config)));
|
|
1103
|
+
},
|
|
1104
|
+
parseTrackedQueryResponse(body, model) {
|
|
1105
|
+
return toRawQueryResult2(parseTrackedQueryResponse2(body, model));
|
|
1106
|
+
},
|
|
1107
|
+
// Message Batches: the same request bodies at half the token price. See batch.ts.
|
|
1108
|
+
batch: claudeBatch,
|
|
1109
|
+
normalizeResult(raw) {
|
|
1110
|
+
const claudeRaw = {
|
|
1111
|
+
provider: "claude",
|
|
1112
|
+
rawResponse: raw.rawResponse,
|
|
1113
|
+
model: raw.model,
|
|
1114
|
+
groundingSources: raw.groundingSources,
|
|
1115
|
+
searchQueries: raw.searchQueries,
|
|
1116
|
+
// The shared RawQueryResult now carries retrieval, so nothing is lost
|
|
1117
|
+
// across this boundary. A reconstruction that predates the field falls
|
|
1118
|
+
// back to `unknown` rather than asserting an absence.
|
|
1119
|
+
retrievalStatus: raw.retrievalStatus ?? "unknown",
|
|
1120
|
+
// The contract is decided by the model the request was built for.
|
|
1121
|
+
retrievalContract: raw.retrievalContract ?? claudeRetrievalContractForModel(raw.model)
|
|
1122
|
+
};
|
|
1123
|
+
const normalized = normalizeResult2(claudeRaw);
|
|
1124
|
+
return {
|
|
1125
|
+
provider: "claude",
|
|
1126
|
+
answerText: normalized.answerText,
|
|
1127
|
+
citedDomains: normalized.citedDomains,
|
|
1128
|
+
groundingSources: normalized.groundingSources,
|
|
1129
|
+
searchQueries: normalized.searchQueries,
|
|
1130
|
+
retrievalStatus: normalized.retrievalStatus
|
|
1131
|
+
};
|
|
1132
|
+
},
|
|
1133
|
+
async generateText(prompt, config) {
|
|
1134
|
+
return generateText2(prompt, toClaudeConfig(config));
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
|
|
1138
|
+
// ../provider-claude/src/anchored-spans.ts
|
|
1139
|
+
function isRecord2(value) {
|
|
1140
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1141
|
+
}
|
|
1142
|
+
function leadIn(text) {
|
|
1143
|
+
const end = text.trimEnd().length;
|
|
1144
|
+
if (end === 0) return "";
|
|
1145
|
+
return text.slice(text.lastIndexOf("\n", end - 1) + 1);
|
|
1146
|
+
}
|
|
1147
|
+
function extractAnchoredSpans2(rawResponse) {
|
|
1148
|
+
const spans = [];
|
|
1149
|
+
const content = Array.isArray(rawResponse.content) ? rawResponse.content : [];
|
|
1150
|
+
let previousUncited = null;
|
|
1151
|
+
for (const block of content) {
|
|
1152
|
+
if (!isRecord2(block) || block.type !== "text" || typeof block.text !== "string") continue;
|
|
1153
|
+
const urls = /* @__PURE__ */ new Set();
|
|
1154
|
+
for (const citation of Array.isArray(block.citations) ? block.citations : []) {
|
|
1155
|
+
if (isRecord2(citation) && citation.type === "web_search_result_location" && typeof citation.url === "string") {
|
|
1156
|
+
urls.add(citation.url);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
if (urls.size === 0) {
|
|
1160
|
+
previousUncited = block.text;
|
|
1161
|
+
continue;
|
|
1162
|
+
}
|
|
1163
|
+
const window = (previousUncited === null ? "" : leadIn(previousUncited)) + block.text;
|
|
1164
|
+
for (const url of urls) {
|
|
1165
|
+
spans.push({ text: window, source: url, kind: "window", via: AnchoredSpanSources["claude-citation"] });
|
|
1166
|
+
}
|
|
1167
|
+
previousUncited = null;
|
|
1168
|
+
}
|
|
1169
|
+
return spans;
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// ../provider-gemini/src/normalize.ts
|
|
1173
|
+
import { GoogleGenAI } from "@google/genai";
|
|
1174
|
+
|
|
1175
|
+
// ../provider-gemini/src/utils.ts
|
|
1176
|
+
var GEMINI_MAX_RATE_LIMIT_WAIT_MS = 65e3;
|
|
1177
|
+
function geminiRetryDelayMs(err) {
|
|
1178
|
+
const match = /"retryDelay"\s*:\s*"(\d+(?:\.\d+)?)s"/.exec(describeError(err));
|
|
1179
|
+
return match ? Math.round(Number(match[1]) * 1e3) : null;
|
|
1180
|
+
}
|
|
1181
|
+
function isGeminiDailyQuotaError(err) {
|
|
1182
|
+
return /"quotaId"\s*:\s*"[^"]*PerDay/i.test(describeError(err));
|
|
1183
|
+
}
|
|
1184
|
+
function isGeminiRetryable(err) {
|
|
1185
|
+
if (!isRetryableHttpError(err) || isGeminiDailyQuotaError(err)) return false;
|
|
1186
|
+
const asked = geminiRetryDelayMs(err);
|
|
1187
|
+
return asked === null || asked <= GEMINI_MAX_RATE_LIMIT_WAIT_MS;
|
|
1188
|
+
}
|
|
1189
|
+
async function withRetry4(fn, options = {}) {
|
|
1190
|
+
return withRetry(fn, {
|
|
1191
|
+
maxRetries: options.maxRetries ?? 3,
|
|
1192
|
+
baseDelayMs: options.initialDelay ?? 1e3,
|
|
1193
|
+
// Jitter off preserves the historical deterministic backoff that every
|
|
1194
|
+
// provider has shipped to date (1000, 2000, 4000ms). Enable per-caller
|
|
1195
|
+
// if you need it.
|
|
1196
|
+
jitter: false,
|
|
1197
|
+
isRetryable: isGeminiRetryable,
|
|
1198
|
+
computeDelayMs: (_attempt, err, defaultMs) => {
|
|
1199
|
+
const asked = geminiRetryDelayMs(err);
|
|
1200
|
+
return asked === null ? defaultMs : asked + 500;
|
|
1201
|
+
},
|
|
1202
|
+
...options.sleep ? { sleep: options.sleep } : {},
|
|
1203
|
+
onRetry: ({ attempt, err, delayMs }) => {
|
|
1204
|
+
console.warn(
|
|
1205
|
+
`[provider] Attempt ${attempt + 1} failed, retrying in ${delayMs}ms...`,
|
|
1206
|
+
describeError(err)
|
|
1207
|
+
);
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// ../provider-gemini/src/normalize.ts
|
|
1213
|
+
var DEFAULT_MODEL3 = "gemini-flash-latest";
|
|
1214
|
+
function isVertexConfig(config) {
|
|
1215
|
+
return !!config.vertexProject;
|
|
1216
|
+
}
|
|
1217
|
+
function resolveModel2(config) {
|
|
1218
|
+
return config.model || DEFAULT_MODEL3;
|
|
1219
|
+
}
|
|
1220
|
+
function createClient2(config) {
|
|
1221
|
+
const httpOptions = config.baseUrl ? { httpOptions: { baseUrl: config.baseUrl } } : {};
|
|
1222
|
+
if (isVertexConfig(config)) {
|
|
1223
|
+
return new GoogleGenAI({
|
|
1224
|
+
vertexai: true,
|
|
1225
|
+
project: config.vertexProject,
|
|
1226
|
+
location: config.vertexRegion || "us-central1",
|
|
1227
|
+
...config.vertexCredentials ? { googleAuthOptions: { keyFilename: config.vertexCredentials } } : {},
|
|
1228
|
+
...httpOptions
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
return new GoogleGenAI({ apiKey: config.apiKey, ...httpOptions });
|
|
1232
|
+
}
|
|
1233
|
+
function validateConfig3(config) {
|
|
1234
|
+
if ("vertexProject" in config && config.vertexProject !== void 0 && config.vertexProject.trim().length === 0) {
|
|
1235
|
+
return { ok: false, provider: "gemini", message: "missing Vertex AI project ID" };
|
|
1236
|
+
}
|
|
1237
|
+
if (isVertexConfig(config)) {
|
|
1238
|
+
const model2 = resolveModel2(config);
|
|
1239
|
+
return {
|
|
1240
|
+
ok: true,
|
|
1241
|
+
provider: "gemini",
|
|
1242
|
+
message: "config valid (Vertex AI)",
|
|
1243
|
+
model: model2
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
if (!config.apiKey || config.apiKey.length === 0) {
|
|
1247
|
+
return { ok: false, provider: "gemini", message: "missing api key" };
|
|
1248
|
+
}
|
|
1249
|
+
const model = resolveModel2(config);
|
|
1250
|
+
return {
|
|
1251
|
+
ok: true,
|
|
1252
|
+
provider: "gemini",
|
|
1253
|
+
message: "config valid",
|
|
1254
|
+
model
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
async function healthcheck3(config) {
|
|
1258
|
+
const validation = validateConfig3(config);
|
|
1259
|
+
if (!validation.ok) return validation;
|
|
1260
|
+
try {
|
|
1261
|
+
const model = resolveModel2(config);
|
|
1262
|
+
const client = createClient2(config);
|
|
1263
|
+
const result = await withRetry4(
|
|
1264
|
+
() => client.models.generateContent({
|
|
1265
|
+
model,
|
|
1266
|
+
contents: 'Say "ok"'
|
|
1267
|
+
})
|
|
1268
|
+
);
|
|
1269
|
+
const text = result.text ?? "";
|
|
1270
|
+
const backend = isVertexConfig(config) ? "vertex ai" : "api key";
|
|
1271
|
+
return {
|
|
1272
|
+
ok: text.length > 0,
|
|
1273
|
+
provider: "gemini",
|
|
1274
|
+
message: text.length > 0 ? `gemini ${backend} verified` : `empty response from gemini ${backend}`,
|
|
1275
|
+
model
|
|
1276
|
+
};
|
|
1277
|
+
} catch (err) {
|
|
1278
|
+
return {
|
|
1279
|
+
ok: false,
|
|
1280
|
+
provider: "gemini",
|
|
1281
|
+
message: describeError(err),
|
|
1282
|
+
model: config.model ?? DEFAULT_MODEL3
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
function buildTrackedQueryRequest3(input) {
|
|
1287
|
+
const model = resolveModel2(input.config);
|
|
1288
|
+
const endpoint = isVertexConfig(input.config) ? `/v1beta1/projects/${input.config.vertexProject}/locations/${input.config.vertexRegion || "us-central1"}/publishers/google/models/${model}:generateContent` : `/v1beta/models/${model}:generateContent`;
|
|
1289
|
+
const body = {
|
|
1290
|
+
contents: [{ parts: [{ text: buildPrompt(input.query, input.location) }], role: "user" }],
|
|
1291
|
+
tools: [{ googleSearch: {} }],
|
|
1292
|
+
generationConfig: {}
|
|
1293
|
+
};
|
|
1294
|
+
return { endpoint, body };
|
|
1295
|
+
}
|
|
1296
|
+
async function executeTrackedQuery3(input) {
|
|
1297
|
+
const model = resolveModel2(input.config);
|
|
1298
|
+
const request = buildTrackedQueryRequest3(input).body;
|
|
1299
|
+
const client = createClient2(input.config);
|
|
1300
|
+
let result;
|
|
1301
|
+
try {
|
|
1302
|
+
result = await withRetry4(
|
|
1303
|
+
() => client.models.generateContent({
|
|
1304
|
+
model,
|
|
1305
|
+
contents: request.contents,
|
|
1306
|
+
config: {
|
|
1307
|
+
tools: request.tools
|
|
1308
|
+
}
|
|
1309
|
+
})
|
|
1310
|
+
);
|
|
1311
|
+
} catch (err) {
|
|
1312
|
+
const msg = describeError(err);
|
|
1313
|
+
throw new Error(`[provider-gemini] ${msg}`);
|
|
1314
|
+
}
|
|
1315
|
+
return parseTrackedQueryResponse3(result, model);
|
|
1316
|
+
}
|
|
1317
|
+
function parseTrackedQueryResponse3(body, model) {
|
|
1318
|
+
const rawResponse = responseToRecord3(body);
|
|
1319
|
+
const parsed = reparseStoredResult3(rawResponse);
|
|
1320
|
+
return {
|
|
1321
|
+
provider: "gemini",
|
|
1322
|
+
rawResponse,
|
|
1323
|
+
model,
|
|
1324
|
+
servedModel: normalizeServedModel(rawResponse.modelVersion),
|
|
1325
|
+
groundingSources: parsed.groundingSources,
|
|
1326
|
+
searchQueries: parsed.searchQueries,
|
|
1327
|
+
usage: extractUsageFromRaw3(rawResponse),
|
|
1328
|
+
stopReason: extractStopReasonFromRaw3(rawResponse)
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
function normalizeResult3(raw) {
|
|
1332
|
+
const parsed = reparseStoredResult3(raw.rawResponse);
|
|
1333
|
+
const useParsed = hasParsedResponseContent3(raw.rawResponse);
|
|
1334
|
+
const groundingSources = useParsed ? parsed.groundingSources : raw.groundingSources;
|
|
1335
|
+
const searchQueries = useParsed ? parsed.searchQueries : raw.searchQueries;
|
|
1336
|
+
const citedDomains = extractCitedDomainsFromSources3(groundingSources);
|
|
1337
|
+
return {
|
|
1338
|
+
provider: "gemini",
|
|
1339
|
+
answerText: parsed.answerText,
|
|
1340
|
+
citedDomains,
|
|
1341
|
+
groundingSources,
|
|
1342
|
+
searchQueries
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
function hasParsedResponseContent3(rawResponse) {
|
|
1346
|
+
return Array.isArray(rawResponse.candidates) && rawResponse.candidates.length > 0;
|
|
1347
|
+
}
|
|
1348
|
+
function reparseStoredResult3(rawResponse) {
|
|
1349
|
+
const groundingSources = extractGroundingMetadataFromRaw(rawResponse);
|
|
1350
|
+
const searchQueries = extractSearchQueriesFromRaw3(rawResponse);
|
|
1351
|
+
return {
|
|
1352
|
+
provider: "gemini",
|
|
1353
|
+
answerText: extractAnswerText(rawResponse),
|
|
1354
|
+
citedDomains: extractCitedDomainsFromSources3(groundingSources),
|
|
1355
|
+
groundingSources,
|
|
1356
|
+
searchQueries
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1359
|
+
function buildPrompt(query, location) {
|
|
1360
|
+
if (location) {
|
|
1361
|
+
return `${query} (searching from ${location.city}, ${location.region}, ${location.country})`;
|
|
1362
|
+
}
|
|
1363
|
+
return query;
|
|
1364
|
+
}
|
|
1365
|
+
function extractAnswerText(rawResponse) {
|
|
1366
|
+
try {
|
|
1367
|
+
const candidates = rawResponse.candidates;
|
|
1368
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1369
|
+
const parts = candidates[0]?.content?.parts;
|
|
1370
|
+
if (!parts || parts.length === 0) return "";
|
|
1371
|
+
return parts.map((p) => p.text ?? "").join("");
|
|
1372
|
+
} catch {
|
|
1373
|
+
return "";
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
function extractGroundingMetadataFromRaw(rawResponse) {
|
|
1377
|
+
try {
|
|
1378
|
+
const candidates = rawResponse.candidates;
|
|
1379
|
+
const candidate = candidates?.[0];
|
|
1380
|
+
if (!candidate) return [];
|
|
1381
|
+
const metadata = candidate.groundingMetadata;
|
|
1382
|
+
if (!metadata) return [];
|
|
1383
|
+
const chunks = metadata.groundingChunks;
|
|
1384
|
+
if (!chunks) return [];
|
|
1385
|
+
const indices = /* @__PURE__ */ new Set();
|
|
1386
|
+
for (const support of metadata.groundingSupports ?? []) {
|
|
1387
|
+
for (const index of support.groundingChunkIndices ?? []) {
|
|
1388
|
+
if (Number.isInteger(index) && index >= 0 && index < chunks.length) {
|
|
1389
|
+
indices.add(index);
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
const selectedChunks = indices.size > 0 ? [...indices].map((index) => chunks[index]).filter(Boolean) : chunks;
|
|
1394
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1395
|
+
const sources = [];
|
|
1396
|
+
for (const chunk of selectedChunks) {
|
|
1397
|
+
if (!chunk.web?.uri || seen.has(chunk.web.uri)) continue;
|
|
1398
|
+
seen.add(chunk.web.uri);
|
|
1399
|
+
sources.push({
|
|
1400
|
+
uri: chunk.web.uri,
|
|
1401
|
+
title: chunk.web.title ?? ""
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
return sources;
|
|
1405
|
+
} catch {
|
|
1406
|
+
return [];
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
function extractSearchQueriesFromRaw3(rawResponse) {
|
|
1410
|
+
try {
|
|
1411
|
+
const candidates = rawResponse.candidates;
|
|
1412
|
+
const candidate = candidates?.[0];
|
|
1413
|
+
return candidate?.groundingMetadata?.webSearchQueries ?? [];
|
|
1414
|
+
} catch {
|
|
1415
|
+
return [];
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
function extractUsageFromRaw3(rawResponse) {
|
|
1419
|
+
const usage = rawResponse.usageMetadata;
|
|
1420
|
+
if (usage === null || typeof usage !== "object") return void 0;
|
|
1421
|
+
const promptTokens = usageCount(usage.promptTokenCount);
|
|
1422
|
+
const cachedInputTokens = usageCount(usage.cachedContentTokenCount);
|
|
1423
|
+
const searchQueries = extractSearchQueriesFromRaw3(rawResponse);
|
|
1424
|
+
return {
|
|
1425
|
+
inputTokens: Math.max(0, promptTokens - cachedInputTokens),
|
|
1426
|
+
cachedInputTokens,
|
|
1427
|
+
cacheWriteTokens: 0,
|
|
1428
|
+
outputTokens: usageCount(usage.candidatesTokenCount) + usageCount(usage.thoughtsTokenCount),
|
|
1429
|
+
searchCount: Array.isArray(searchQueries) ? searchQueries.length : 0
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
function extractStopReasonFromRaw3(rawResponse) {
|
|
1433
|
+
const candidates = rawResponse.candidates;
|
|
1434
|
+
const finishReason = Array.isArray(candidates) ? candidates[0]?.finishReason : void 0;
|
|
1435
|
+
return typeof finishReason === "string" && finishReason.length > 0 ? finishReason : void 0;
|
|
1436
|
+
}
|
|
1437
|
+
function extractCitedDomainsFromSources3(groundingSources) {
|
|
1438
|
+
const domains = /* @__PURE__ */ new Set();
|
|
1439
|
+
for (const source of groundingSources) {
|
|
1440
|
+
const domain = extractDomainFromUri3(source.uri);
|
|
1441
|
+
if (domain) {
|
|
1442
|
+
domains.add(domain);
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
if (source.title) {
|
|
1446
|
+
const titleDomain = extractDomainFromTitle(source.title);
|
|
1447
|
+
if (titleDomain) {
|
|
1448
|
+
domains.add(titleDomain);
|
|
1449
|
+
continue;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
return [...domains];
|
|
1454
|
+
}
|
|
1455
|
+
function extractDomainFromTitle(title) {
|
|
1456
|
+
const trimmed = title.trim();
|
|
1457
|
+
return registrableDomain(trimmed) ? hostOf(trimmed) : null;
|
|
1458
|
+
}
|
|
1459
|
+
function extractDomainFromUri3(uri) {
|
|
1460
|
+
try {
|
|
1461
|
+
const url = new URL(uri);
|
|
1462
|
+
const hostname = hostOf(uri);
|
|
1463
|
+
if (!hostname || !registrableDomain(hostname)) return null;
|
|
1464
|
+
if (hostMatchesAnyDomain(hostname, AI_ENGINE_SELF_DOMAINS.gemini)) {
|
|
1465
|
+
return null;
|
|
1466
|
+
}
|
|
1467
|
+
if (hostname === VERTEX_AI_SEARCH_PROXY_DOMAIN) {
|
|
1468
|
+
const redirectPath = url.pathname.replace(/^\/grounding-api-redirect\//, "");
|
|
1469
|
+
if (redirectPath && redirectPath !== url.pathname) {
|
|
1470
|
+
try {
|
|
1471
|
+
const decoded = decodeURIComponent(redirectPath);
|
|
1472
|
+
if (decoded.startsWith("http")) {
|
|
1473
|
+
return hostOf(decoded);
|
|
1474
|
+
}
|
|
1475
|
+
} catch {
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
return null;
|
|
1479
|
+
}
|
|
1480
|
+
return hostname;
|
|
1481
|
+
} catch {
|
|
1482
|
+
return null;
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
async function generateText3(prompt, config) {
|
|
1486
|
+
const model = resolveModel2(config);
|
|
1487
|
+
const client = createClient2(config);
|
|
1488
|
+
const result = await withRetry4(
|
|
1489
|
+
() => client.models.generateContent({
|
|
1490
|
+
model,
|
|
1491
|
+
contents: prompt
|
|
1492
|
+
})
|
|
1493
|
+
);
|
|
1494
|
+
return result.text ?? "";
|
|
1495
|
+
}
|
|
1496
|
+
function responseToRecord3(body) {
|
|
1497
|
+
const response = body;
|
|
1498
|
+
try {
|
|
1499
|
+
const candidates = response.candidates?.map((c) => ({
|
|
1500
|
+
content: c.content,
|
|
1501
|
+
finishReason: c.finishReason,
|
|
1502
|
+
groundingMetadata: c.groundingMetadata ? {
|
|
1503
|
+
webSearchQueries: c.groundingMetadata.webSearchQueries,
|
|
1504
|
+
groundingChunks: c.groundingMetadata.groundingChunks,
|
|
1505
|
+
// Preserve support-to-chunk mappings so stored snapshots can be reparsed using
|
|
1506
|
+
// Google's documented citation model.
|
|
1507
|
+
// Docs: https://ai.google.dev/gemini-api/docs/google-search
|
|
1508
|
+
groundingSupports: c.groundingMetadata.groundingSupports
|
|
1509
|
+
} : void 0
|
|
1510
|
+
}));
|
|
1511
|
+
return {
|
|
1512
|
+
candidates: candidates ?? [],
|
|
1513
|
+
usageMetadata: response.usageMetadata ?? null,
|
|
1514
|
+
// Gemini reports the identity it actually served here — the only place it
|
|
1515
|
+
// appears. Preserved so `servedModel` can be read back off a stored snapshot.
|
|
1516
|
+
modelVersion: response.modelVersion ?? null,
|
|
1517
|
+
responseId: response.responseId ?? null
|
|
1518
|
+
};
|
|
1519
|
+
} catch {
|
|
1520
|
+
return { error: "failed to serialize response" };
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
// ../provider-gemini/src/embeddings.ts
|
|
1525
|
+
import { GoogleGenAI as GoogleGenAI2 } from "@google/genai";
|
|
1526
|
+
var DEFAULT_EMBED_MODEL = "gemini-embedding-001";
|
|
1527
|
+
var DEFAULT_OUTPUT_DIMENSIONALITY = 768;
|
|
1528
|
+
var CLUSTERING_TASK_TYPE = "CLUSTERING";
|
|
1529
|
+
async function embedQueries(queries, options) {
|
|
1530
|
+
if (queries.length === 0) return [];
|
|
1531
|
+
if (!options.apiKey) throw new Error("embedQueries: missing apiKey");
|
|
1532
|
+
const genai = new GoogleGenAI2({ apiKey: options.apiKey, ...options.baseUrl ? { httpOptions: { baseUrl: options.baseUrl } } : {} });
|
|
1533
|
+
const response = await genai.models.embedContent({
|
|
1534
|
+
model: options.model ?? DEFAULT_EMBED_MODEL,
|
|
1535
|
+
contents: queries,
|
|
1536
|
+
config: { taskType: CLUSTERING_TASK_TYPE, outputDimensionality: options.outputDimensionality ?? DEFAULT_OUTPUT_DIMENSIONALITY }
|
|
1537
|
+
});
|
|
1538
|
+
return extractEmbeddingVectors(response, queries.length);
|
|
1539
|
+
}
|
|
1540
|
+
function extractEmbeddingVectors(response, expectedLength) {
|
|
1541
|
+
const embeddings = response?.embeddings ?? [];
|
|
1542
|
+
if (embeddings.length !== expectedLength) {
|
|
1543
|
+
throw new Error(`embedQueries: expected ${expectedLength} embeddings, got ${embeddings.length}`);
|
|
1544
|
+
}
|
|
1545
|
+
return embeddings.map((e, i) => {
|
|
1546
|
+
if (!e.values || e.values.length === 0) throw new Error(`embedQueries: missing values for query at index ${i}`);
|
|
1547
|
+
return e.values;
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
// ../provider-gemini/src/list-models.ts
|
|
1552
|
+
function listModels3(config, signal) {
|
|
1553
|
+
return withRetry(async () => {
|
|
1554
|
+
signal.throwIfAborted();
|
|
1555
|
+
const client = createClient2(config);
|
|
1556
|
+
const page = await client.models.list({ config: { pageSize: 100, queryBase: true, abortSignal: signal, httpOptions: { timeout: 2500 } } });
|
|
1557
|
+
const models = [];
|
|
1558
|
+
let seen = 0;
|
|
1559
|
+
for await (const model of page) {
|
|
1560
|
+
signal.throwIfAborted();
|
|
1561
|
+
if (++seen > 1e3) throw new Error("Model catalog exceeded the discovery limit");
|
|
1562
|
+
const id = model.name?.replace(/^(?:publishers\/google\/)?models\//, "");
|
|
1563
|
+
if (!id?.startsWith("gemini-") || /image|tts|audio|live|embedding/.test(id)) continue;
|
|
1564
|
+
if (model.supportedActions && !model.supportedActions.includes("generateContent")) continue;
|
|
1565
|
+
models.push({ id, displayName: model.displayName || id, tier: "standard" });
|
|
1566
|
+
}
|
|
1567
|
+
return models;
|
|
1568
|
+
}, {
|
|
1569
|
+
maxRetries: 1,
|
|
1570
|
+
baseDelayMs: 200,
|
|
1571
|
+
isRetryable: (error) => !signal.aborted && isRetryableHttpError(error),
|
|
1572
|
+
computeDelayMs: (_attempt, error, delay) => {
|
|
1573
|
+
const retryDelay = retryAfterDelayMs(error) ?? delay;
|
|
1574
|
+
if (retryDelay >= 2500) throw error;
|
|
1575
|
+
return retryDelay;
|
|
1576
|
+
}
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
// ../provider-gemini/src/adapter.ts
|
|
1581
|
+
import { FinishReason } from "@google/genai";
|
|
1582
|
+
function toGeminiConfig(config) {
|
|
1583
|
+
return {
|
|
1584
|
+
apiKey: config.apiKey ?? "",
|
|
1585
|
+
model: config.model,
|
|
1586
|
+
baseUrl: config.baseUrl,
|
|
1587
|
+
quotaPolicy: config.quotaPolicy,
|
|
1588
|
+
vertexProject: config.vertexProject,
|
|
1589
|
+
vertexRegion: config.vertexRegion,
|
|
1590
|
+
vertexCredentials: config.vertexCredentials
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
function toGeminiInput(input, config) {
|
|
1594
|
+
return {
|
|
1595
|
+
query: input.query,
|
|
1596
|
+
canonicalDomains: input.canonicalDomains,
|
|
1597
|
+
competitorDomains: input.competitorDomains,
|
|
1598
|
+
config: toGeminiConfig(config),
|
|
1599
|
+
location: input.location
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
function toRawQueryResult3(raw) {
|
|
1603
|
+
return {
|
|
1604
|
+
provider: "gemini",
|
|
1605
|
+
rawResponse: raw.rawResponse,
|
|
1606
|
+
model: raw.model,
|
|
1607
|
+
servedModel: raw.servedModel,
|
|
1608
|
+
groundingSources: raw.groundingSources,
|
|
1609
|
+
searchQueries: raw.searchQueries,
|
|
1610
|
+
retrievalStatus: readRetrievalStatus(raw.rawResponse),
|
|
1611
|
+
retrievalContract: "native-auto-v1",
|
|
1612
|
+
usage: raw.usage,
|
|
1613
|
+
stopReason: raw.stopReason
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
function readRetrievalStatus(rawResponse) {
|
|
1617
|
+
const response = rawResponse;
|
|
1618
|
+
if (usageCount(response.usageMetadata?.toolUsePromptTokenCount) > 0) return RetrievalStatuses.used;
|
|
1619
|
+
const candidate = Array.isArray(response.candidates) ? response.candidates[0] : void 0;
|
|
1620
|
+
if (!candidate) return RetrievalStatuses.unknown;
|
|
1621
|
+
const metadata = candidate.groundingMetadata;
|
|
1622
|
+
const queries = metadata?.webSearchQueries;
|
|
1623
|
+
const chunks = metadata?.groundingChunks;
|
|
1624
|
+
if (Array.isArray(queries) && queries.some((query) => typeof query === "string" && query.trim().length > 0) || Array.isArray(chunks) && chunks.some((chunk) => typeof chunk.web?.uri === "string" && chunk.web.uri.trim().length > 0)) {
|
|
1625
|
+
return RetrievalStatuses.used;
|
|
1626
|
+
}
|
|
1627
|
+
const parts = candidate.content?.parts;
|
|
1628
|
+
const hasAnswer = Array.isArray(parts) && parts.some((part) => !part.thought && typeof part.text === "string" && part.text.trim().length > 0);
|
|
1629
|
+
return candidate.finishReason === FinishReason.STOP && hasAnswer ? RetrievalStatuses["not-used"] : RetrievalStatuses.unknown;
|
|
1630
|
+
}
|
|
1631
|
+
var geminiAdapter = {
|
|
1632
|
+
name: "gemini",
|
|
1633
|
+
displayName: "Gemini",
|
|
1634
|
+
mode: "api",
|
|
1635
|
+
// normalize.ts folds the location into the prompt the model receives.
|
|
1636
|
+
supportsLocationContext: true,
|
|
1637
|
+
keyUrl: "https://aistudio.google.com/apikey",
|
|
1638
|
+
// Upstream model list: https://ai.google.dev/gemini-api/docs/models
|
|
1639
|
+
modelRegistry: {
|
|
1640
|
+
defaultModel: "gemini-flash-latest",
|
|
1641
|
+
validationPattern: /./,
|
|
1642
|
+
validationHint: "any valid Google model name (e.g. gemini-flash-latest, gemini-3.8-flash)",
|
|
1643
|
+
knownModels: [
|
|
1644
|
+
// Google's moving aliases: always the newest Flash / Flash-Lite, with
|
|
1645
|
+
// 2 weeks' email notice before a breaking change. The model actually
|
|
1646
|
+
// served is recorded per snapshot (`servedModel`), so trends still show
|
|
1647
|
+
// when the model behind an alias changed.
|
|
1648
|
+
{ id: "gemini-flash-latest", displayName: "Gemini Flash (latest)", tier: "standard" },
|
|
1649
|
+
{ id: "gemini-flash-lite-latest", displayName: "Gemini Flash-Lite (latest)", tier: "economy" },
|
|
1650
|
+
{ id: "gemini-3.8-flash", displayName: "Gemini 3.8 Flash", tier: "standard" },
|
|
1651
|
+
{ id: "gemini-3.5-flash-lite", displayName: "Gemini 3.5 Flash-Lite", tier: "economy" },
|
|
1652
|
+
// Google limits the 2.5 models to projects that already used them, so a
|
|
1653
|
+
// new key may be refused. Listed for installs that still pin them.
|
|
1654
|
+
{ id: "gemini-2.5-pro", displayName: "Gemini 2.5 Pro", tier: "flagship" },
|
|
1655
|
+
{ id: "gemini-2.5-flash", displayName: "Gemini 2.5 Flash", tier: "standard" },
|
|
1656
|
+
{ id: "gemini-2.5-flash-lite", displayName: "Gemini 2.5 Flash-Lite", tier: "economy" },
|
|
1657
|
+
{ id: "gemini-2.0-flash", displayName: "Gemini 2.0 Flash", tier: "standard" }
|
|
1658
|
+
]
|
|
1659
|
+
},
|
|
1660
|
+
listModels: (config, signal) => listModels3(toGeminiConfig(config), signal),
|
|
1661
|
+
validateConfig(config) {
|
|
1662
|
+
const result = validateConfig3(toGeminiConfig(config));
|
|
1663
|
+
return {
|
|
1664
|
+
ok: result.ok,
|
|
1665
|
+
provider: "gemini",
|
|
1666
|
+
message: result.message,
|
|
1667
|
+
model: result.model
|
|
1668
|
+
};
|
|
1669
|
+
},
|
|
1670
|
+
async healthcheck(config) {
|
|
1671
|
+
const result = await healthcheck3(toGeminiConfig(config));
|
|
1672
|
+
return {
|
|
1673
|
+
ok: result.ok,
|
|
1674
|
+
provider: "gemini",
|
|
1675
|
+
message: result.message,
|
|
1676
|
+
model: result.model
|
|
1677
|
+
};
|
|
1678
|
+
},
|
|
1679
|
+
buildTrackedQueryRequest(input, config) {
|
|
1680
|
+
return buildTrackedQueryRequest3(toGeminiInput(input, config));
|
|
1681
|
+
},
|
|
1682
|
+
async executeTrackedQuery(input, config) {
|
|
1683
|
+
return toRawQueryResult3(await executeTrackedQuery3(toGeminiInput(input, config)));
|
|
1684
|
+
},
|
|
1685
|
+
parseTrackedQueryResponse(body, model) {
|
|
1686
|
+
return toRawQueryResult3(parseTrackedQueryResponse3(body, model));
|
|
1687
|
+
},
|
|
1688
|
+
normalizeResult(raw) {
|
|
1689
|
+
const geminiRaw = {
|
|
1690
|
+
provider: "gemini",
|
|
1691
|
+
rawResponse: raw.rawResponse,
|
|
1692
|
+
model: raw.model,
|
|
1693
|
+
groundingSources: raw.groundingSources,
|
|
1694
|
+
searchQueries: raw.searchQueries
|
|
1695
|
+
};
|
|
1696
|
+
const normalized = normalizeResult3(geminiRaw);
|
|
1697
|
+
return {
|
|
1698
|
+
provider: "gemini",
|
|
1699
|
+
answerText: normalized.answerText,
|
|
1700
|
+
citedDomains: normalized.citedDomains,
|
|
1701
|
+
groundingSources: normalized.groundingSources,
|
|
1702
|
+
searchQueries: normalized.searchQueries,
|
|
1703
|
+
retrievalStatus: readRetrievalStatus(raw.rawResponse)
|
|
1704
|
+
};
|
|
1705
|
+
},
|
|
1706
|
+
async generateText(prompt, config) {
|
|
1707
|
+
return generateText3(prompt, toGeminiConfig(config));
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
1710
|
+
|
|
1711
|
+
// ../provider-gemini/src/anchored-spans.ts
|
|
1712
|
+
function isRecord3(value) {
|
|
1713
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1714
|
+
}
|
|
1715
|
+
function chunkSource(chunk) {
|
|
1716
|
+
if (!isRecord3(chunk) || !isRecord3(chunk.web)) return null;
|
|
1717
|
+
const uri = typeof chunk.web.uri === "string" ? chunk.web.uri : "";
|
|
1718
|
+
const uriHost = hostOf(uri);
|
|
1719
|
+
if (uriHost && uriHost !== VERTEX_AI_SEARCH_PROXY_DOMAIN && registrableDomain(uriHost)) return uri;
|
|
1720
|
+
const title = typeof chunk.web.title === "string" ? chunk.web.title.trim() : "";
|
|
1721
|
+
return title && registrableDomain(title) ? title : null;
|
|
1722
|
+
}
|
|
1723
|
+
function extractAnchoredSpans3(rawResponse) {
|
|
1724
|
+
const candidates = Array.isArray(rawResponse.candidates) ? rawResponse.candidates : [];
|
|
1725
|
+
const candidate = candidates[0];
|
|
1726
|
+
if (!isRecord3(candidate) || !isRecord3(candidate.groundingMetadata)) return [];
|
|
1727
|
+
const metadata = candidate.groundingMetadata;
|
|
1728
|
+
const chunks = Array.isArray(metadata.groundingChunks) ? metadata.groundingChunks : [];
|
|
1729
|
+
const spans = [];
|
|
1730
|
+
for (const support of Array.isArray(metadata.groundingSupports) ? metadata.groundingSupports : []) {
|
|
1731
|
+
if (!isRecord3(support) || !isRecord3(support.segment)) continue;
|
|
1732
|
+
const text = support.segment.text;
|
|
1733
|
+
if (typeof text !== "string" || !text.trim()) continue;
|
|
1734
|
+
const sources = /* @__PURE__ */ new Set();
|
|
1735
|
+
for (const index of Array.isArray(support.groundingChunkIndices) ? support.groundingChunkIndices : []) {
|
|
1736
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= chunks.length) continue;
|
|
1737
|
+
const source = chunkSource(chunks[index]);
|
|
1738
|
+
if (source) sources.add(source);
|
|
1739
|
+
}
|
|
1740
|
+
for (const source of sources) {
|
|
1741
|
+
spans.push({ text, source, kind: "window", via: AnchoredSpanSources["gemini-support"] });
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
return spans;
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
// ../provider-perplexity/src/normalize.ts
|
|
1748
|
+
import OpenAI3 from "openai";
|
|
1749
|
+
|
|
1750
|
+
// ../provider-perplexity/src/utils.ts
|
|
1751
|
+
async function withRetry5(fn, options = {}) {
|
|
1752
|
+
return withRetry(fn, {
|
|
1753
|
+
maxRetries: options.maxRetries ?? 3,
|
|
1754
|
+
baseDelayMs: options.initialDelay ?? 1e3,
|
|
1755
|
+
// Jitter off preserves the historical deterministic backoff that every
|
|
1756
|
+
// provider has shipped to date (1000, 2000, 4000ms). Enable per-caller
|
|
1757
|
+
// if you need it.
|
|
1758
|
+
jitter: false,
|
|
1759
|
+
isRetryable: isRetryableHttpError,
|
|
1760
|
+
onRetry: ({ attempt, err, delayMs }) => {
|
|
1761
|
+
console.warn(
|
|
1762
|
+
`[provider] Attempt ${attempt + 1} failed, retrying in ${delayMs}ms...`,
|
|
1763
|
+
describeError(err)
|
|
1764
|
+
);
|
|
1765
|
+
}
|
|
1766
|
+
});
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
// ../provider-perplexity/src/normalize.ts
|
|
1770
|
+
var DEFAULT_MODEL4 = "fast";
|
|
1771
|
+
var BASE_URL = "https://api.perplexity.ai/v1";
|
|
1772
|
+
var AGENT_PATH = "/agent";
|
|
1773
|
+
var PERPLEXITY_AGENT_ENDPOINT = "/v1/agent";
|
|
1774
|
+
var PERPLEXITY_RETRIEVAL_CONTRACT = "search-required-v1";
|
|
1775
|
+
var RETRIEVAL_OUTPUT_TYPES = /* @__PURE__ */ new Set(["search_results", "fetch_url_results"]);
|
|
1776
|
+
function resolveModel3(model) {
|
|
1777
|
+
const trimmed = model?.trim();
|
|
1778
|
+
return resolveProviderModel("perplexity", trimmed ? trimmed : DEFAULT_MODEL4);
|
|
1779
|
+
}
|
|
1780
|
+
var ANTHROPIC_MAX_OUTPUT_TOKENS = 4096;
|
|
1781
|
+
function agentSelection(model) {
|
|
1782
|
+
if (!model.includes("/")) return { preset: model };
|
|
1783
|
+
return model.startsWith("anthropic/") ? { model, max_output_tokens: ANTHROPIC_MAX_OUTPUT_TOKENS } : { model };
|
|
1784
|
+
}
|
|
1785
|
+
function buildAgentRequest(query, model, location) {
|
|
1786
|
+
const webSearch = { type: "web_search" };
|
|
1787
|
+
if (location) {
|
|
1788
|
+
webSearch.user_location = {
|
|
1789
|
+
city: location.city,
|
|
1790
|
+
region: location.region,
|
|
1791
|
+
country: location.country
|
|
1792
|
+
};
|
|
1793
|
+
}
|
|
1794
|
+
return {
|
|
1795
|
+
...agentSelection(model),
|
|
1796
|
+
input: query,
|
|
1797
|
+
tools: [webSearch],
|
|
1798
|
+
tool_choice: { type: "web_search" }
|
|
1799
|
+
};
|
|
1800
|
+
}
|
|
1801
|
+
function validateConfig4(config) {
|
|
1802
|
+
if (!config.apiKey || config.apiKey.length === 0) {
|
|
1803
|
+
return { ok: false, provider: "perplexity", message: "missing api key" };
|
|
1804
|
+
}
|
|
1805
|
+
return {
|
|
1806
|
+
ok: true,
|
|
1807
|
+
provider: "perplexity",
|
|
1808
|
+
message: "config valid",
|
|
1809
|
+
model: resolveModel3(config.model)
|
|
1810
|
+
};
|
|
1811
|
+
}
|
|
1812
|
+
async function healthcheck4(config) {
|
|
1813
|
+
const validation = validateConfig4(config);
|
|
1814
|
+
if (!validation.ok) return validation;
|
|
1815
|
+
const model = resolveModel3(config.model);
|
|
1816
|
+
try {
|
|
1817
|
+
const client = createClient3(config.apiKey);
|
|
1818
|
+
const response = await withRetry5(
|
|
1819
|
+
() => postAgent(client, { ...agentSelection(model), input: 'Say "ok"' })
|
|
1820
|
+
);
|
|
1821
|
+
assertUsableResponse(response);
|
|
1822
|
+
const text = extractAgentAnswerText(response);
|
|
1823
|
+
return {
|
|
1824
|
+
ok: text.length > 0,
|
|
1825
|
+
provider: "perplexity",
|
|
1826
|
+
message: text.length > 0 ? "perplexity api key verified" : "empty response from perplexity",
|
|
1827
|
+
model
|
|
1828
|
+
};
|
|
1829
|
+
} catch (err) {
|
|
1830
|
+
return {
|
|
1831
|
+
ok: false,
|
|
1832
|
+
provider: "perplexity",
|
|
1833
|
+
message: describeError(err),
|
|
1834
|
+
model
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
function buildTrackedQueryRequest4(input) {
|
|
1839
|
+
return {
|
|
1840
|
+
endpoint: PERPLEXITY_AGENT_ENDPOINT,
|
|
1841
|
+
body: buildAgentRequest(input.query, resolveModel3(input.config.model), input.location)
|
|
1842
|
+
};
|
|
1843
|
+
}
|
|
1844
|
+
async function executeTrackedQuery4(input) {
|
|
1845
|
+
const model = resolveModel3(input.config.model);
|
|
1846
|
+
const client = createClient3(input.config.apiKey);
|
|
1847
|
+
const { body } = buildTrackedQueryRequest4(input);
|
|
1848
|
+
try {
|
|
1849
|
+
const rawResponse = await withRetry5(() => postAgent(client, body));
|
|
1850
|
+
return parseTrackedQueryResponse4(rawResponse, model);
|
|
1851
|
+
} catch (err) {
|
|
1852
|
+
const msg = describeError(err);
|
|
1853
|
+
throw new Error(`[provider-perplexity] ${msg}`);
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
function parseTrackedQueryResponse4(body, model) {
|
|
1857
|
+
assertUsableResponse(body);
|
|
1858
|
+
const parsed = reparseStoredResult4(body);
|
|
1859
|
+
return {
|
|
1860
|
+
provider: "perplexity",
|
|
1861
|
+
rawResponse: body,
|
|
1862
|
+
model: resolveModel3(model),
|
|
1863
|
+
servedModel: normalizeServedModel(body.model),
|
|
1864
|
+
groundingSources: parsed.groundingSources,
|
|
1865
|
+
searchQueries: parsed.searchQueries,
|
|
1866
|
+
retrievalStatus: parsed.retrievalStatus,
|
|
1867
|
+
usage: extractAgentUsage(body),
|
|
1868
|
+
stopReason: extractAgentStopReason(body)
|
|
1869
|
+
};
|
|
1870
|
+
}
|
|
1871
|
+
function normalizeResult4(raw) {
|
|
1872
|
+
const parsed = reparseStoredResult4(raw.rawResponse);
|
|
1873
|
+
const useParsed = hasParsedResponseContent4(raw.rawResponse);
|
|
1874
|
+
const groundingSources = useParsed ? parsed.groundingSources : raw.groundingSources;
|
|
1875
|
+
const searchQueries = useParsed ? parsed.searchQueries : raw.searchQueries;
|
|
1876
|
+
const citedDomains = extractCitedDomains(groundingSources);
|
|
1877
|
+
return {
|
|
1878
|
+
provider: "perplexity",
|
|
1879
|
+
answerText: parsed.answerText,
|
|
1880
|
+
citedDomains,
|
|
1881
|
+
groundingSources,
|
|
1882
|
+
searchQueries,
|
|
1883
|
+
retrievalStatus: useParsed ? parsed.retrievalStatus : raw.retrievalStatus ?? "unknown"
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
function hasParsedResponseContent4(rawResponse) {
|
|
1887
|
+
const agent = agentResponseOf(rawResponse);
|
|
1888
|
+
if (agent) return agentOutput(agent).length > 0;
|
|
1889
|
+
if (Array.isArray(rawResponse.choices) && rawResponse.choices.length > 0) return true;
|
|
1890
|
+
if (Array.isArray(rawResponse.search_results) && rawResponse.search_results.length > 0) return true;
|
|
1891
|
+
if (Array.isArray(rawResponse.citations) && rawResponse.citations.length > 0) return true;
|
|
1892
|
+
const nestedResponse = extractNestedApiResponse(rawResponse);
|
|
1893
|
+
if (!nestedResponse) return false;
|
|
1894
|
+
return Array.isArray(nestedResponse.choices) && nestedResponse.choices.length > 0 || Array.isArray(nestedResponse.search_results) && nestedResponse.search_results.length > 0 || Array.isArray(nestedResponse.citations) && nestedResponse.citations.length > 0;
|
|
1895
|
+
}
|
|
1896
|
+
function reparseStoredResult4(rawResponse) {
|
|
1897
|
+
const agent = agentResponseOf(rawResponse);
|
|
1898
|
+
if (agent) return parseAgentResponse(agent);
|
|
1899
|
+
return parseSonarResponse(rawResponse);
|
|
1900
|
+
}
|
|
1901
|
+
function extractAnchoredSpans4(rawResponse) {
|
|
1902
|
+
const agent = agentResponseOf(rawResponse);
|
|
1903
|
+
let text;
|
|
1904
|
+
let sourceFor;
|
|
1905
|
+
if (agent) {
|
|
1906
|
+
text = extractAgentAnswerText(agent);
|
|
1907
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1908
|
+
for (const item of agentOutput(agent)) {
|
|
1909
|
+
if (item.type !== "search_results" || !Array.isArray(item.results)) continue;
|
|
1910
|
+
for (const result of item.results) {
|
|
1911
|
+
if (!isRecord4(result) || typeof result.id !== "number" || typeof result.url !== "string" || !result.url) continue;
|
|
1912
|
+
if (!byId.has(result.id)) byId.set(result.id, result.url);
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
sourceFor = (marker) => byId.get(marker);
|
|
1916
|
+
} else {
|
|
1917
|
+
text = extractAnswerText2(rawResponse);
|
|
1918
|
+
const citations = extractCitations(rawResponse);
|
|
1919
|
+
sourceFor = (marker) => citations[marker - 1];
|
|
1920
|
+
}
|
|
1921
|
+
const spans = [];
|
|
1922
|
+
if (!text.includes("[")) return spans;
|
|
1923
|
+
let groupStart = -1;
|
|
1924
|
+
let groupEnd = -1;
|
|
1925
|
+
let previousEnd = 0;
|
|
1926
|
+
let markers = [];
|
|
1927
|
+
const flush = () => {
|
|
1928
|
+
if (markers.length === 0) return;
|
|
1929
|
+
const lineStart = groupStart === 0 ? 0 : text.lastIndexOf("\n", groupStart - 1) + 1;
|
|
1930
|
+
const from = Math.max(lineStart, previousEnd);
|
|
1931
|
+
const window = text.slice(from, groupStart);
|
|
1932
|
+
if (window.trim()) {
|
|
1933
|
+
for (const source of new Set(markers.map(sourceFor).filter((url) => typeof url === "string" && url.length > 0))) {
|
|
1934
|
+
spans.push({ text: window, source, kind: "window", via: AnchoredSpanSources["perplexity-marker"] });
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
previousEnd = groupEnd;
|
|
1938
|
+
markers = [];
|
|
1939
|
+
};
|
|
1940
|
+
for (const match of text.matchAll(/\[(\d{1,3})\]/g)) {
|
|
1941
|
+
if (markers.length > 0 && match.index !== groupEnd) flush();
|
|
1942
|
+
if (markers.length === 0) groupStart = match.index;
|
|
1943
|
+
markers.push(Number(match[1]));
|
|
1944
|
+
groupEnd = match.index + match[0].length;
|
|
1945
|
+
}
|
|
1946
|
+
flush();
|
|
1947
|
+
return spans;
|
|
1948
|
+
}
|
|
1949
|
+
function createClient3(apiKey) {
|
|
1950
|
+
return new OpenAI3({ apiKey, baseURL: BASE_URL });
|
|
1951
|
+
}
|
|
1952
|
+
function postAgent(client, body) {
|
|
1953
|
+
return client.post(AGENT_PATH, { body });
|
|
1954
|
+
}
|
|
1955
|
+
function assertUsableResponse(response) {
|
|
1956
|
+
const status = response.status;
|
|
1957
|
+
if (status === void 0 || status === "completed") return;
|
|
1958
|
+
if (status === "incomplete") {
|
|
1959
|
+
if (extractAgentAnswerText(response).trim().length > 0) return;
|
|
1960
|
+
const details = isRecord4(response.incomplete_details) ? response.incomplete_details : void 0;
|
|
1961
|
+
const reason = typeof details?.reason === "string" && details.reason.length > 0 ? details.reason : "no reason given";
|
|
1962
|
+
throw new Error(`agent response incomplete with no answer: ${reason}`);
|
|
1963
|
+
}
|
|
1964
|
+
const error = isRecord4(response.error) ? response.error : void 0;
|
|
1965
|
+
const message = typeof error?.message === "string" && error.message.length > 0 ? error.message : "no error detail";
|
|
1966
|
+
const type = typeof error?.type === "string" && error.type.length > 0 ? ` (${error.type})` : "";
|
|
1967
|
+
throw new Error(`agent response ${typeof status === "string" ? status : describeError(status)}: ${message}${type}`);
|
|
1968
|
+
}
|
|
1969
|
+
function agentResponseOf(rawResponse) {
|
|
1970
|
+
if (Array.isArray(rawResponse.output)) return rawResponse;
|
|
1971
|
+
const nested = extractNestedApiResponse(rawResponse);
|
|
1972
|
+
return nested && Array.isArray(nested.output) ? nested : null;
|
|
1973
|
+
}
|
|
1974
|
+
function agentOutput(response) {
|
|
1975
|
+
return Array.isArray(response.output) ? response.output.filter(isRecord4) : [];
|
|
1976
|
+
}
|
|
1977
|
+
function parseAgentResponse(response) {
|
|
1978
|
+
const groundingSources = extractAgentGroundingSources(response);
|
|
1979
|
+
return {
|
|
1980
|
+
provider: "perplexity",
|
|
1981
|
+
answerText: extractAgentAnswerText(response),
|
|
1982
|
+
citedDomains: extractCitedDomains(groundingSources),
|
|
1983
|
+
groundingSources,
|
|
1984
|
+
searchQueries: extractAgentSearchQueries(response),
|
|
1985
|
+
retrievalStatus: extractAgentRetrievalStatus(response)
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
function extractAgentAnswerText(response) {
|
|
1989
|
+
const parts = [];
|
|
1990
|
+
for (const item of agentOutput(response)) {
|
|
1991
|
+
if (item.type !== "message" || !Array.isArray(item.content)) continue;
|
|
1992
|
+
for (const part of item.content) {
|
|
1993
|
+
if (isRecord4(part) && part.type === "output_text" && typeof part.text === "string") parts.push(part.text);
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
return parts.join("");
|
|
1997
|
+
}
|
|
1998
|
+
function extractAgentGroundingSources(response) {
|
|
1999
|
+
const sources = [];
|
|
2000
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2001
|
+
const add = (entry) => {
|
|
2002
|
+
if (!isRecord4(entry) || typeof entry.url !== "string" || entry.url.length === 0) return;
|
|
2003
|
+
if (seen.has(entry.url)) return;
|
|
2004
|
+
seen.add(entry.url);
|
|
2005
|
+
sources.push({ uri: entry.url, title: typeof entry.title === "string" ? entry.title : "" });
|
|
2006
|
+
};
|
|
2007
|
+
for (const item of agentOutput(response)) {
|
|
2008
|
+
if (item.type === "search_results" && Array.isArray(item.results)) {
|
|
2009
|
+
item.results.forEach(add);
|
|
2010
|
+
} else if (item.type === "fetch_url_results" && Array.isArray(item.contents)) {
|
|
2011
|
+
item.contents.forEach(add);
|
|
2012
|
+
} else if (item.type === "message" && Array.isArray(item.content)) {
|
|
2013
|
+
for (const part of item.content) {
|
|
2014
|
+
if (isRecord4(part) && Array.isArray(part.annotations)) part.annotations.forEach(add);
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
return sources;
|
|
2019
|
+
}
|
|
2020
|
+
function extractAgentSearchQueries(response) {
|
|
2021
|
+
const queries = /* @__PURE__ */ new Set();
|
|
2022
|
+
for (const item of agentOutput(response)) {
|
|
2023
|
+
if (item.type !== "search_results" || !Array.isArray(item.queries)) continue;
|
|
2024
|
+
for (const query of item.queries) {
|
|
2025
|
+
if (typeof query === "string" && query.trim().length > 0) queries.add(query);
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
return [...queries];
|
|
2029
|
+
}
|
|
2030
|
+
function extractAgentUsage(response) {
|
|
2031
|
+
const usage = isRecord4(response.usage) ? response.usage : void 0;
|
|
2032
|
+
if (!usage) return void 0;
|
|
2033
|
+
const details = isRecord4(usage.input_tokens_details) ? usage.input_tokens_details : void 0;
|
|
2034
|
+
const cachedInputTokens = usageCount(details?.cache_read_input_tokens);
|
|
2035
|
+
const cacheWriteTokens = usageCount(details?.cache_creation_input_tokens);
|
|
2036
|
+
const toolCalls = isRecord4(usage.tool_calls_details) ? usage.tool_calls_details : void 0;
|
|
2037
|
+
const webSearch = isRecord4(toolCalls?.web_search) ? toolCalls.web_search : void 0;
|
|
2038
|
+
const searchCount = typeof webSearch?.invocation === "number" ? usageCount(webSearch.invocation) : agentOutput(response).filter((item) => item.type === "search_results").length;
|
|
2039
|
+
return {
|
|
2040
|
+
inputTokens: Math.max(0, usageCount(usage.input_tokens) - cachedInputTokens - cacheWriteTokens),
|
|
2041
|
+
cachedInputTokens,
|
|
2042
|
+
cacheWriteTokens,
|
|
2043
|
+
outputTokens: usageCount(usage.output_tokens),
|
|
2044
|
+
searchCount
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
function extractAgentStopReason(response) {
|
|
2048
|
+
const details = isRecord4(response.incomplete_details) ? response.incomplete_details : void 0;
|
|
2049
|
+
if (typeof details?.reason === "string" && details.reason.length > 0) return details.reason;
|
|
2050
|
+
return typeof response.status === "string" && response.status.length > 0 ? response.status : void 0;
|
|
2051
|
+
}
|
|
2052
|
+
function extractAgentRetrievalStatus(response) {
|
|
2053
|
+
const output = agentOutput(response);
|
|
2054
|
+
if (output.some((item) => typeof item.type === "string" && RETRIEVAL_OUTPUT_TYPES.has(item.type))) return "used";
|
|
2055
|
+
if (output.some((item) => item.type === "message")) return "not-used";
|
|
2056
|
+
return "unknown";
|
|
2057
|
+
}
|
|
2058
|
+
function parseSonarResponse(rawResponse) {
|
|
2059
|
+
const groundingSources = extractGroundingSources(rawResponse);
|
|
2060
|
+
return {
|
|
2061
|
+
provider: "perplexity",
|
|
2062
|
+
answerText: extractAnswerText2(rawResponse),
|
|
2063
|
+
citedDomains: extractCitedDomains(groundingSources),
|
|
2064
|
+
groundingSources,
|
|
2065
|
+
// Sonar documented `search_results` and `citations` on the response but no
|
|
2066
|
+
// returned search-query telemetry, so Canonry does not synthesize it.
|
|
2067
|
+
// Docs: https://docs.perplexity.ai/docs/sonar/openai-compatibility
|
|
2068
|
+
searchQueries: [],
|
|
2069
|
+
// Sonar's only retrieval marker was present on every stored row, so it
|
|
2070
|
+
// never discriminated a non-retrieving answer. `unknown` is what we know.
|
|
2071
|
+
retrievalStatus: "unknown"
|
|
2072
|
+
};
|
|
2073
|
+
}
|
|
2074
|
+
function extractCitations(rawResponse) {
|
|
2075
|
+
if (Array.isArray(rawResponse.citations)) {
|
|
2076
|
+
return rawResponse.citations.filter((c) => typeof c === "string");
|
|
2077
|
+
}
|
|
2078
|
+
const nestedResponse = extractNestedApiResponse(rawResponse);
|
|
2079
|
+
if (nestedResponse) {
|
|
2080
|
+
const nested = nestedResponse.citations;
|
|
2081
|
+
if (Array.isArray(nested)) {
|
|
2082
|
+
return nested.filter((c) => typeof c === "string");
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
return [];
|
|
2086
|
+
}
|
|
2087
|
+
function extractGroundingSources(rawResponse) {
|
|
2088
|
+
const searchResults = extractSearchResults(rawResponse);
|
|
2089
|
+
if (searchResults.length > 0) {
|
|
2090
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2091
|
+
const sources = [];
|
|
2092
|
+
for (const result of searchResults) {
|
|
2093
|
+
if (seen.has(result.uri)) continue;
|
|
2094
|
+
seen.add(result.uri);
|
|
2095
|
+
sources.push(result);
|
|
2096
|
+
}
|
|
2097
|
+
return sources;
|
|
2098
|
+
}
|
|
2099
|
+
return extractCitations(rawResponse).map((url) => ({
|
|
2100
|
+
uri: url,
|
|
2101
|
+
title: ""
|
|
2102
|
+
}));
|
|
2103
|
+
}
|
|
2104
|
+
function extractSearchResults(rawResponse) {
|
|
2105
|
+
const direct = parseSearchResultsArray(rawResponse.search_results);
|
|
2106
|
+
if (direct.length > 0) return direct;
|
|
2107
|
+
const nestedResponse = extractNestedApiResponse(rawResponse);
|
|
2108
|
+
if (nestedResponse) {
|
|
2109
|
+
return parseSearchResultsArray(nestedResponse.search_results);
|
|
2110
|
+
}
|
|
2111
|
+
return [];
|
|
2112
|
+
}
|
|
2113
|
+
function parseSearchResultsArray(value) {
|
|
2114
|
+
if (!Array.isArray(value)) return [];
|
|
2115
|
+
return value.flatMap((result) => {
|
|
2116
|
+
if (!isRecord4(result)) return [];
|
|
2117
|
+
const url = result.url;
|
|
2118
|
+
if (typeof url !== "string" || url.length === 0) {
|
|
2119
|
+
return [];
|
|
2120
|
+
}
|
|
2121
|
+
const title = result.title;
|
|
2122
|
+
return [{
|
|
2123
|
+
uri: url,
|
|
2124
|
+
title: typeof title === "string" ? title : ""
|
|
2125
|
+
}];
|
|
2126
|
+
});
|
|
2127
|
+
}
|
|
2128
|
+
function extractAnswerText2(rawResponse) {
|
|
2129
|
+
try {
|
|
2130
|
+
const directChoices = rawResponse.choices;
|
|
2131
|
+
if (directChoices?.length) {
|
|
2132
|
+
return directChoices[0].message?.content ?? "";
|
|
2133
|
+
}
|
|
2134
|
+
const nestedResponse = extractNestedApiResponse(rawResponse);
|
|
2135
|
+
const nestedChoices = nestedResponse?.choices;
|
|
2136
|
+
if (!nestedChoices?.length) return "";
|
|
2137
|
+
return nestedChoices[0].message?.content ?? "";
|
|
2138
|
+
} catch {
|
|
2139
|
+
return "";
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
function extractNestedApiResponse(rawResponse) {
|
|
2143
|
+
return isRecord4(rawResponse.apiResponse) ? rawResponse.apiResponse : null;
|
|
2144
|
+
}
|
|
2145
|
+
function isRecord4(value) {
|
|
2146
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2147
|
+
}
|
|
2148
|
+
function extractCitedDomains(groundingSources) {
|
|
2149
|
+
const domains = /* @__PURE__ */ new Set();
|
|
2150
|
+
for (const source of groundingSources) {
|
|
2151
|
+
const domain = extractDomainFromUri4(source.uri);
|
|
2152
|
+
if (domain) domains.add(domain);
|
|
2153
|
+
}
|
|
2154
|
+
return [...domains];
|
|
2155
|
+
}
|
|
2156
|
+
function extractDomainFromUri4(uri) {
|
|
2157
|
+
const hostname = hostOf(uri);
|
|
2158
|
+
if (!hostname || !registrableDomain(hostname) || hostMatchesAnyDomain(hostname, AI_ENGINE_SELF_DOMAINS.perplexity)) return null;
|
|
2159
|
+
return hostname;
|
|
2160
|
+
}
|
|
2161
|
+
async function generateText4(prompt, config) {
|
|
2162
|
+
const model = resolveModel3(config.model);
|
|
2163
|
+
const client = createClient3(config.apiKey);
|
|
2164
|
+
const response = await withRetry5(() => postAgent(client, { ...agentSelection(model), input: prompt }));
|
|
2165
|
+
assertUsableResponse(response);
|
|
2166
|
+
return extractAgentAnswerText(response);
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
// ../provider-perplexity/src/adapter.ts
|
|
2170
|
+
function toPerplexityConfig(config) {
|
|
2171
|
+
return {
|
|
2172
|
+
apiKey: config.apiKey ?? "",
|
|
2173
|
+
model: config.model,
|
|
2174
|
+
quotaPolicy: config.quotaPolicy
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
function toPerplexityInput(input, config) {
|
|
2178
|
+
return {
|
|
2179
|
+
query: input.query,
|
|
2180
|
+
canonicalDomains: input.canonicalDomains,
|
|
2181
|
+
competitorDomains: input.competitorDomains,
|
|
2182
|
+
config: toPerplexityConfig(config),
|
|
2183
|
+
location: input.location
|
|
2184
|
+
};
|
|
2185
|
+
}
|
|
2186
|
+
function toRawQueryResult4(raw) {
|
|
2187
|
+
return {
|
|
2188
|
+
provider: "perplexity",
|
|
2189
|
+
rawResponse: raw.rawResponse,
|
|
2190
|
+
model: raw.model,
|
|
2191
|
+
servedModel: raw.servedModel,
|
|
2192
|
+
groundingSources: raw.groundingSources,
|
|
2193
|
+
searchQueries: raw.searchQueries,
|
|
2194
|
+
// Read off the Agent API output: a `search_results` item is the retrieval
|
|
2195
|
+
// call. The contract is how we built the request, so it is always known.
|
|
2196
|
+
retrievalStatus: raw.retrievalStatus ?? "unknown",
|
|
2197
|
+
retrievalContract: PERPLEXITY_RETRIEVAL_CONTRACT,
|
|
2198
|
+
usage: raw.usage,
|
|
2199
|
+
stopReason: raw.stopReason
|
|
2200
|
+
};
|
|
2201
|
+
}
|
|
2202
|
+
var perplexityAdapter = {
|
|
2203
|
+
name: "perplexity",
|
|
2204
|
+
displayName: "Perplexity",
|
|
2205
|
+
mode: "api",
|
|
2206
|
+
// normalize.ts sends the location as `user_location` on the web_search tool.
|
|
2207
|
+
supportsLocationContext: true,
|
|
2208
|
+
keyUrl: "https://www.perplexity.ai/settings/api",
|
|
2209
|
+
// Agent API presets: https://docs.perplexity.ai/docs/agent-api/presets
|
|
2210
|
+
// Model slugs (GET https://api.perplexity.ai/v1/models): provider-prefixed, e.g. perplexity/sonar.
|
|
2211
|
+
modelRegistry: {
|
|
2212
|
+
defaultModel: DEFAULT_MODEL4,
|
|
2213
|
+
// Presets, `vendor/model` slugs, and the retired Sonar names and previous
|
|
2214
|
+
// preset names that PROVIDER_MODEL_ALIASES resolves (`sonar` → `fast`).
|
|
2215
|
+
validationPattern: /^(?:fast|low|medium|high|xhigh|fast-search|pro-search|deep-research|advanced-deep-research|sonar(?:-pro|-reasoning|-reasoning-pro|-deep-research)?|[a-z0-9][a-z0-9-]*\/[A-Za-z0-9][\w.:-]*)$/,
|
|
2216
|
+
validationHint: "expected an Agent API preset (fast, low, medium, high, xhigh) or a provider/model slug (e.g. perplexity/sonar)",
|
|
2217
|
+
knownModels: [
|
|
2218
|
+
{ id: "fast", displayName: "Fast preset", tier: "standard" },
|
|
2219
|
+
{ id: "low", displayName: "Low preset (pro search)", tier: "flagship" },
|
|
2220
|
+
{ id: "medium", displayName: "Medium preset (deep research)", tier: "flagship" },
|
|
2221
|
+
{ id: "perplexity/sonar", displayName: "Sonar model + web search", tier: "fast" }
|
|
2222
|
+
]
|
|
2223
|
+
},
|
|
2224
|
+
validateConfig(config) {
|
|
2225
|
+
const result = validateConfig4(toPerplexityConfig(config));
|
|
2226
|
+
return {
|
|
2227
|
+
ok: result.ok,
|
|
2228
|
+
provider: "perplexity",
|
|
2229
|
+
message: result.message,
|
|
2230
|
+
model: result.model
|
|
2231
|
+
};
|
|
2232
|
+
},
|
|
2233
|
+
async healthcheck(config) {
|
|
2234
|
+
const result = await healthcheck4(toPerplexityConfig(config));
|
|
2235
|
+
return {
|
|
2236
|
+
ok: result.ok,
|
|
2237
|
+
provider: "perplexity",
|
|
2238
|
+
message: result.message,
|
|
2239
|
+
model: result.model
|
|
2240
|
+
};
|
|
2241
|
+
},
|
|
2242
|
+
buildTrackedQueryRequest(input, config) {
|
|
2243
|
+
return buildTrackedQueryRequest4(toPerplexityInput(input, config));
|
|
2244
|
+
},
|
|
2245
|
+
async executeTrackedQuery(input, config) {
|
|
2246
|
+
return toRawQueryResult4(await executeTrackedQuery4(toPerplexityInput(input, config)));
|
|
2247
|
+
},
|
|
2248
|
+
parseTrackedQueryResponse(body, model) {
|
|
2249
|
+
return toRawQueryResult4(parseTrackedQueryResponse4(body, model));
|
|
2250
|
+
},
|
|
2251
|
+
normalizeResult(raw) {
|
|
2252
|
+
const perplexityRaw = {
|
|
2253
|
+
provider: "perplexity",
|
|
2254
|
+
rawResponse: raw.rawResponse,
|
|
2255
|
+
model: raw.model,
|
|
2256
|
+
groundingSources: raw.groundingSources,
|
|
2257
|
+
searchQueries: raw.searchQueries,
|
|
2258
|
+
retrievalStatus: raw.retrievalStatus
|
|
2259
|
+
};
|
|
2260
|
+
const normalized = normalizeResult4(perplexityRaw);
|
|
2261
|
+
return {
|
|
2262
|
+
provider: "perplexity",
|
|
2263
|
+
answerText: normalized.answerText,
|
|
2264
|
+
citedDomains: normalized.citedDomains,
|
|
2265
|
+
groundingSources: normalized.groundingSources,
|
|
2266
|
+
searchQueries: normalized.searchQueries,
|
|
2267
|
+
retrievalStatus: normalized.retrievalStatus
|
|
2268
|
+
};
|
|
2269
|
+
},
|
|
2270
|
+
async generateText(prompt, config) {
|
|
2271
|
+
return generateText4(prompt, toPerplexityConfig(config));
|
|
2272
|
+
}
|
|
2273
|
+
};
|
|
2274
|
+
|
|
2275
|
+
// ../provider-muse/src/normalize.ts
|
|
2276
|
+
import OpenAI4 from "openai";
|
|
2277
|
+
var MUSE_DEFAULT_MODEL = "muse-spark-1.3";
|
|
2278
|
+
var MUSE_BASE_URL = "https://api.meta.ai/v1";
|
|
2279
|
+
var MUSE_SPARK_MODEL = /^muse-spark-[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
|
|
2280
|
+
var MUSE_SELF_DOMAINS = [AI_ENGINE_DOMAINS.metaAi];
|
|
2281
|
+
var MAX_RETRY_AFTER_MS = 6e4;
|
|
2282
|
+
var RETRYABLE_RESPONSE_ERROR_CODES = /* @__PURE__ */ new Set(["rate_limit_exceeded", "server_error"]);
|
|
2283
|
+
function createClient4(config) {
|
|
2284
|
+
return new OpenAI4({
|
|
2285
|
+
apiKey: config.apiKey,
|
|
2286
|
+
baseURL: config.baseUrl || MUSE_BASE_URL,
|
|
2287
|
+
// Otherwise the SDK sends OPENAI_ORG_ID / OPENAI_PROJECT_ID to Meta.
|
|
2288
|
+
organization: null,
|
|
2289
|
+
project: null,
|
|
2290
|
+
maxRetries: 0
|
|
2291
|
+
});
|
|
2292
|
+
}
|
|
2293
|
+
function modelOf(config) {
|
|
2294
|
+
return config.model || MUSE_DEFAULT_MODEL;
|
|
2295
|
+
}
|
|
2296
|
+
function validateConfig5(config) {
|
|
2297
|
+
if (!config.apiKey.trim()) return { ok: false, provider: "muse", message: "missing api key" };
|
|
2298
|
+
const model = modelOf(config);
|
|
2299
|
+
if (!MUSE_SPARK_MODEL.test(model)) {
|
|
2300
|
+
return { ok: false, provider: "muse", message: "model must be a Muse Spark text model" };
|
|
2301
|
+
}
|
|
2302
|
+
return { ok: true, provider: "muse", message: "config valid", model };
|
|
2303
|
+
}
|
|
2304
|
+
var MuseResponseError = class extends Error {
|
|
2305
|
+
constructor(message, retryable) {
|
|
2306
|
+
super(message);
|
|
2307
|
+
this.retryable = retryable;
|
|
2308
|
+
this.name = "MuseResponseError";
|
|
2309
|
+
}
|
|
2310
|
+
retryable;
|
|
2311
|
+
};
|
|
2312
|
+
function retryRequest(fn) {
|
|
2313
|
+
return withRetry(fn, {
|
|
2314
|
+
maxRetries: 3,
|
|
2315
|
+
baseDelayMs: 1e3,
|
|
2316
|
+
isRetryable: (error) => error instanceof MuseResponseError ? error.retryable : isRetryableHttpError(error),
|
|
2317
|
+
computeDelayMs: (_attempt, error, delay) => {
|
|
2318
|
+
const retryDelay = retryAfterDelayMs(error) ?? delay;
|
|
2319
|
+
if (retryDelay > MAX_RETRY_AFTER_MS) throw error;
|
|
2320
|
+
return retryDelay;
|
|
2321
|
+
}
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
function statusMessage(rawResponse) {
|
|
2325
|
+
const status = typeof rawResponse.status === "string" ? rawResponse.status : "missing or invalid";
|
|
2326
|
+
const error = asRecord(rawResponse.error);
|
|
2327
|
+
const detail = [error?.code, error?.message, asRecord(rawResponse.incomplete_details)?.reason].filter((value) => typeof value === "string" && value.length > 0).join(": ");
|
|
2328
|
+
return `Meta Model API response status: ${status}${detail ? ` (${detail})` : ""}`;
|
|
2329
|
+
}
|
|
2330
|
+
function createResponse(config, body) {
|
|
2331
|
+
const client = createClient4(config);
|
|
2332
|
+
return retryRequest(async () => {
|
|
2333
|
+
const rawResponse = responseToRecord4(await client.responses.create(body));
|
|
2334
|
+
if (rawResponse.status !== "completed" && rawResponse.status !== "incomplete") {
|
|
2335
|
+
const code = asRecord(rawResponse.error)?.code;
|
|
2336
|
+
throw new MuseResponseError(
|
|
2337
|
+
statusMessage(rawResponse),
|
|
2338
|
+
typeof code === "string" && RETRYABLE_RESPONSE_ERROR_CODES.has(code)
|
|
2339
|
+
);
|
|
2340
|
+
}
|
|
2341
|
+
return rawResponse;
|
|
2342
|
+
});
|
|
2343
|
+
}
|
|
2344
|
+
async function healthcheck5(config) {
|
|
2345
|
+
const validation = validateConfig5(config);
|
|
2346
|
+
if (!validation.ok) return validation;
|
|
2347
|
+
try {
|
|
2348
|
+
const rawResponse = await createResponse(config, { model: modelOf(config), input: 'Say "ok"' });
|
|
2349
|
+
const answerText = reparseStoredResult5(rawResponse).answerText;
|
|
2350
|
+
return {
|
|
2351
|
+
ok: answerText.length > 0,
|
|
2352
|
+
provider: "muse",
|
|
2353
|
+
message: answerText.length > 0 ? "muse api key verified" : "empty response from muse",
|
|
2354
|
+
model: modelOf(config)
|
|
2355
|
+
};
|
|
2356
|
+
} catch (err) {
|
|
2357
|
+
return { ok: false, provider: "muse", message: describeError(err), model: modelOf(config) };
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
async function executeTrackedQuery5(input) {
|
|
2361
|
+
const validation = validateConfig5(input.config);
|
|
2362
|
+
if (!validation.ok) throw new Error(`[provider-muse] ${validation.message}`);
|
|
2363
|
+
const model = modelOf(input.config);
|
|
2364
|
+
const tool = { type: "web_search" };
|
|
2365
|
+
if (input.location) {
|
|
2366
|
+
tool.user_location = {
|
|
2367
|
+
type: "approximate",
|
|
2368
|
+
...input.location.city ? { city: input.location.city } : {},
|
|
2369
|
+
...input.location.region ? { region: input.location.region } : {},
|
|
2370
|
+
...input.location.country ? { country: input.location.country } : {},
|
|
2371
|
+
...input.location.timezone ? { timezone: input.location.timezone } : {}
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
try {
|
|
2375
|
+
const rawResponse = await createResponse(input.config, {
|
|
2376
|
+
model,
|
|
2377
|
+
input: input.query,
|
|
2378
|
+
tools: [tool],
|
|
2379
|
+
include: ["web_search_call.results"]
|
|
2380
|
+
});
|
|
2381
|
+
const parsed = parseResponse(rawResponse);
|
|
2382
|
+
if (!parsed) throw new Error("Meta Model API returned a malformed response");
|
|
2383
|
+
return {
|
|
2384
|
+
provider: "muse",
|
|
2385
|
+
rawResponse,
|
|
2386
|
+
model,
|
|
2387
|
+
servedModel: normalizeServedModel(rawResponse.model),
|
|
2388
|
+
groundingSources: parsed.groundingSources,
|
|
2389
|
+
searchQueries: parsed.searchQueries,
|
|
2390
|
+
retrievedSources: parsed.retrievedSources,
|
|
2391
|
+
retrievalStatus: parsed.retrievalStatus,
|
|
2392
|
+
usage: extractUsage(rawResponse),
|
|
2393
|
+
stopReason: extractStopReason(rawResponse)
|
|
2394
|
+
};
|
|
2395
|
+
} catch (err) {
|
|
2396
|
+
throw new Error(`[provider-muse] ${describeError(err)}`);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
function extractUsage(rawResponse) {
|
|
2400
|
+
const usage = asRecord(rawResponse.usage);
|
|
2401
|
+
if (!usage) return void 0;
|
|
2402
|
+
const inputTokens = usageCount(usage.input_tokens);
|
|
2403
|
+
const cachedInputTokens = usageCount(asRecord(usage.input_tokens_details)?.cached_tokens);
|
|
2404
|
+
const output = Array.isArray(rawResponse.output) ? rawResponse.output : [];
|
|
2405
|
+
return {
|
|
2406
|
+
inputTokens: Math.max(0, inputTokens - cachedInputTokens),
|
|
2407
|
+
cachedInputTokens,
|
|
2408
|
+
cacheWriteTokens: 0,
|
|
2409
|
+
outputTokens: usageCount(usage.output_tokens),
|
|
2410
|
+
searchCount: output.filter((item) => asRecord(item)?.type === "web_search_call").length
|
|
2411
|
+
};
|
|
2412
|
+
}
|
|
2413
|
+
function extractStopReason(rawResponse) {
|
|
2414
|
+
const reason = asRecord(rawResponse.incomplete_details)?.reason;
|
|
2415
|
+
if (typeof reason === "string" && reason.length > 0) return reason;
|
|
2416
|
+
const status = rawResponse.status;
|
|
2417
|
+
return typeof status === "string" && status.length > 0 ? status : void 0;
|
|
2418
|
+
}
|
|
2419
|
+
function normalizeResult5(raw) {
|
|
2420
|
+
return reparseStoredResult5(raw.rawResponse);
|
|
2421
|
+
}
|
|
2422
|
+
function validCitedUrl(value) {
|
|
2423
|
+
if (typeof value !== "string") return false;
|
|
2424
|
+
try {
|
|
2425
|
+
const url = new URL(value);
|
|
2426
|
+
return (url.protocol === "http:" || url.protocol === "https:") && Boolean(hostOf(value)) && Boolean(registrableDomain(value));
|
|
2427
|
+
} catch {
|
|
2428
|
+
return false;
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
function responseToRecord4(response) {
|
|
2432
|
+
return JSON.parse(JSON.stringify(response));
|
|
2433
|
+
}
|
|
2434
|
+
function reparseStoredResult5(rawResponse) {
|
|
2435
|
+
return parseResponse(rawResponse) ?? {
|
|
2436
|
+
provider: "muse",
|
|
2437
|
+
answerText: "",
|
|
2438
|
+
citedDomains: [],
|
|
2439
|
+
groundingSources: [],
|
|
2440
|
+
searchQueries: [],
|
|
2441
|
+
retrievedSources: null,
|
|
2442
|
+
retrievalStatus: "unknown"
|
|
2443
|
+
};
|
|
2444
|
+
}
|
|
2445
|
+
function parseResponse(rawResponse) {
|
|
2446
|
+
const output = Array.isArray(rawResponse.output) ? rawResponse.output : null;
|
|
2447
|
+
if (rawResponse.status !== "completed" && rawResponse.status !== "incomplete" || !output) return null;
|
|
2448
|
+
const messageTexts = [];
|
|
2449
|
+
const groundingSources = [];
|
|
2450
|
+
const citedDomains = /* @__PURE__ */ new Set();
|
|
2451
|
+
const searchQueries = /* @__PURE__ */ new Set();
|
|
2452
|
+
const seenUrls = /* @__PURE__ */ new Set();
|
|
2453
|
+
const retrievedSources = [];
|
|
2454
|
+
const seenRetrieved = /* @__PURE__ */ new Set();
|
|
2455
|
+
let retrievalReported = true;
|
|
2456
|
+
let completedSearch = false;
|
|
2457
|
+
let failedSearch = false;
|
|
2458
|
+
for (const itemValue of output) {
|
|
2459
|
+
const item = asRecord(itemValue);
|
|
2460
|
+
if (!item || typeof item.type !== "string") return null;
|
|
2461
|
+
if (item.type === "web_search_call") {
|
|
2462
|
+
if (item.status === "completed") completedSearch = true;
|
|
2463
|
+
else failedSearch = true;
|
|
2464
|
+
const action = asRecord(item.action);
|
|
2465
|
+
if (typeof action?.query === "string" && action.query) searchQueries.add(action.query);
|
|
2466
|
+
if (Array.isArray(action?.queries)) {
|
|
2467
|
+
for (const query of action.queries) {
|
|
2468
|
+
if (typeof query === "string" && query) searchQueries.add(query);
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
collectRetrieved(item, action, retrievedSources, seenRetrieved);
|
|
2472
|
+
if (action?.type !== "open_page" && item.status === "completed" && !Array.isArray(item.results)) retrievalReported = false;
|
|
2473
|
+
continue;
|
|
2474
|
+
}
|
|
2475
|
+
if (item.type !== "message" || item.phase === "commentary") continue;
|
|
2476
|
+
if (item.status !== void 0 && item.status !== "completed" && item.status !== "incomplete") return null;
|
|
2477
|
+
if (!Array.isArray(item.content)) return null;
|
|
2478
|
+
const blockTexts = [];
|
|
2479
|
+
for (const blockValue of item.content) {
|
|
2480
|
+
const block = asRecord(blockValue);
|
|
2481
|
+
if (!block || typeof block.type !== "string") return null;
|
|
2482
|
+
if (block.type !== "output_text") continue;
|
|
2483
|
+
if (typeof block.text !== "string") return null;
|
|
2484
|
+
blockTexts.push(block.text);
|
|
2485
|
+
if (!Array.isArray(block.annotations)) continue;
|
|
2486
|
+
for (const annotationValue of block.annotations) {
|
|
2487
|
+
const annotation = asRecord(annotationValue);
|
|
2488
|
+
if (annotation?.type !== "url_citation" || !validCitedUrl(annotation.url)) continue;
|
|
2489
|
+
if (seenUrls.has(annotation.url)) continue;
|
|
2490
|
+
seenUrls.add(annotation.url);
|
|
2491
|
+
groundingSources.push({ uri: annotation.url, title: typeof annotation.title === "string" ? annotation.title : "" });
|
|
2492
|
+
const host = hostOf(annotation.url);
|
|
2493
|
+
if (host && !hostMatchesAnyDomain(host, MUSE_SELF_DOMAINS)) citedDomains.add(host);
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
const messageText = blockTexts.join("");
|
|
2497
|
+
if (messageText.trim()) messageTexts.push(messageText);
|
|
2498
|
+
}
|
|
2499
|
+
const answerText = messageTexts.join("\n\n");
|
|
2500
|
+
let retrievalStatus = "unknown";
|
|
2501
|
+
if (answerText) {
|
|
2502
|
+
if (completedSearch) retrievalStatus = "used";
|
|
2503
|
+
else if (!failedSearch) retrievalStatus = "not-used";
|
|
2504
|
+
}
|
|
2505
|
+
return {
|
|
2506
|
+
provider: "muse",
|
|
2507
|
+
answerText,
|
|
2508
|
+
citedDomains: [...citedDomains],
|
|
2509
|
+
groundingSources,
|
|
2510
|
+
searchQueries: [...searchQueries],
|
|
2511
|
+
retrievedSources: retrievalReported ? retrievedSources : null,
|
|
2512
|
+
retrievalStatus
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
function collectRetrieved(item, action, sources, seen) {
|
|
2516
|
+
if (item.status !== "completed") return;
|
|
2517
|
+
if (action?.type === "open_page") {
|
|
2518
|
+
if (validCitedUrl(action.url) && !seen.has(`page-read ${action.url}`)) {
|
|
2519
|
+
seen.add(`page-read ${action.url}`);
|
|
2520
|
+
sources.push({ uri: action.url, title: "", kind: "page-read", query: null });
|
|
2521
|
+
}
|
|
2522
|
+
return;
|
|
2523
|
+
}
|
|
2524
|
+
if (!Array.isArray(item.results)) return;
|
|
2525
|
+
const query = typeof action?.query === "string" && action.query ? action.query : null;
|
|
2526
|
+
for (const resultValue of item.results) {
|
|
2527
|
+
const result = asRecord(resultValue);
|
|
2528
|
+
if (!result || !validCitedUrl(result.url) || seen.has(`search-result ${result.url}`)) continue;
|
|
2529
|
+
seen.add(`search-result ${result.url}`);
|
|
2530
|
+
sources.push({ uri: result.url, title: typeof result.title === "string" ? result.title : "", kind: "search-result", query });
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
async function generateText5(prompt, config) {
|
|
2534
|
+
const validation = validateConfig5(config);
|
|
2535
|
+
if (!validation.ok) throw new Error(`[provider-muse] ${validation.message}`);
|
|
2536
|
+
try {
|
|
2537
|
+
const rawResponse = await createResponse(config, { model: modelOf(config), input: prompt });
|
|
2538
|
+
if (rawResponse.status !== "completed") throw new Error(statusMessage(rawResponse));
|
|
2539
|
+
const answerText = reparseStoredResult5(rawResponse).answerText;
|
|
2540
|
+
if (!answerText) throw new Error("Meta Model API returned no answer text");
|
|
2541
|
+
return answerText;
|
|
2542
|
+
} catch (err) {
|
|
2543
|
+
throw new Error(`[provider-muse] ${describeError(err)}`);
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
// ../provider-muse/src/list-models.ts
|
|
2548
|
+
import OpenAI5 from "openai";
|
|
2549
|
+
function listModels4(config, signal) {
|
|
2550
|
+
return withRetry(async () => {
|
|
2551
|
+
signal.throwIfAborted();
|
|
2552
|
+
const client = new OpenAI5({
|
|
2553
|
+
apiKey: config.apiKey,
|
|
2554
|
+
baseURL: config.baseUrl || MUSE_BASE_URL,
|
|
2555
|
+
organization: null,
|
|
2556
|
+
project: null,
|
|
2557
|
+
maxRetries: 0,
|
|
2558
|
+
timeout: 2500
|
|
2559
|
+
});
|
|
2560
|
+
const models = [];
|
|
2561
|
+
let seen = 0;
|
|
2562
|
+
for await (const model of client.models.list({ signal })) {
|
|
2563
|
+
signal.throwIfAborted();
|
|
2564
|
+
if (++seen > 1e3) throw new Error("Model catalog exceeded the discovery limit");
|
|
2565
|
+
if (!MUSE_SPARK_MODEL.test(model.id) || /-contributor(?:-|$)/.test(model.id)) continue;
|
|
2566
|
+
models.push({ id: model.id, displayName: model.id, tier: "standard" });
|
|
2567
|
+
}
|
|
2568
|
+
return models;
|
|
2569
|
+
}, {
|
|
2570
|
+
maxRetries: 1,
|
|
2571
|
+
baseDelayMs: 200,
|
|
2572
|
+
isRetryable: (error) => !signal.aborted && isRetryableHttpError(error),
|
|
2573
|
+
computeDelayMs: (_attempt, error, delay) => {
|
|
2574
|
+
const retryDelay = retryAfterDelayMs(error) ?? delay;
|
|
2575
|
+
if (retryDelay >= 2500) throw error;
|
|
2576
|
+
return retryDelay;
|
|
2577
|
+
}
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
|
|
2581
|
+
// ../provider-muse/src/adapter.ts
|
|
2582
|
+
function toMuseConfig(config) {
|
|
2583
|
+
return {
|
|
2584
|
+
apiKey: config.apiKey ?? "",
|
|
2585
|
+
model: config.model,
|
|
2586
|
+
baseUrl: config.baseUrl,
|
|
2587
|
+
quotaPolicy: config.quotaPolicy
|
|
2588
|
+
};
|
|
2589
|
+
}
|
|
2590
|
+
var museAdapter = {
|
|
2591
|
+
name: "muse",
|
|
2592
|
+
displayName: "Muse",
|
|
2593
|
+
mode: "api",
|
|
2594
|
+
supportsLocationContext: true,
|
|
2595
|
+
keyUrl: "https://dev.meta.ai/",
|
|
2596
|
+
modelRegistry: {
|
|
2597
|
+
defaultModel: "muse-spark-1.3",
|
|
2598
|
+
validationPattern: /^muse-spark-[a-z0-9]+(?:[.-][a-z0-9]+)*$/,
|
|
2599
|
+
validationHint: "a Muse Spark text model (e.g. muse-spark-1.3)",
|
|
2600
|
+
knownModels: [
|
|
2601
|
+
{ id: "muse-spark-1.3", displayName: "Muse Spark 1.3", tier: "standard" },
|
|
2602
|
+
{ id: "muse-spark-1.2", displayName: "Muse Spark 1.2", tier: "standard" },
|
|
2603
|
+
{ id: "muse-spark-1.1", displayName: "Muse Spark 1.1", tier: "standard" }
|
|
2604
|
+
]
|
|
2605
|
+
},
|
|
2606
|
+
listModels: listModels4,
|
|
2607
|
+
validateConfig(config) {
|
|
2608
|
+
return validateConfig5(toMuseConfig(config));
|
|
2609
|
+
},
|
|
2610
|
+
healthcheck(config) {
|
|
2611
|
+
return healthcheck5(toMuseConfig(config));
|
|
2612
|
+
},
|
|
2613
|
+
async executeTrackedQuery(input, config) {
|
|
2614
|
+
const raw = await executeTrackedQuery5({ ...input, config: toMuseConfig(config) });
|
|
2615
|
+
return { ...raw, retrievalContract: "native-auto-v1" };
|
|
2616
|
+
},
|
|
2617
|
+
normalizeResult(raw) {
|
|
2618
|
+
return normalizeResult5({
|
|
2619
|
+
provider: "muse",
|
|
2620
|
+
rawResponse: raw.rawResponse,
|
|
2621
|
+
model: raw.model,
|
|
2622
|
+
servedModel: raw.servedModel,
|
|
2623
|
+
groundingSources: raw.groundingSources,
|
|
2624
|
+
searchQueries: raw.searchQueries,
|
|
2625
|
+
retrievedSources: raw.retrievedSources ?? null,
|
|
2626
|
+
retrievalStatus: raw.retrievalStatus
|
|
2627
|
+
});
|
|
2628
|
+
},
|
|
2629
|
+
generateText(prompt, config) {
|
|
2630
|
+
return generateText5(prompt, toMuseConfig(config));
|
|
2631
|
+
}
|
|
2632
|
+
};
|
|
2633
|
+
|
|
2634
|
+
// src/stored-answer-anchors.ts
|
|
2635
|
+
function resolveStoredApiResponse(parsed) {
|
|
2636
|
+
const nested = parsed.apiResponse;
|
|
2637
|
+
if (nested !== null && typeof nested === "object" && !Array.isArray(nested)) {
|
|
2638
|
+
return nested;
|
|
2639
|
+
}
|
|
2640
|
+
if (looksLikeProviderApiResponse(parsed)) {
|
|
2641
|
+
return parsed;
|
|
2642
|
+
}
|
|
2643
|
+
return null;
|
|
2644
|
+
}
|
|
2645
|
+
function looksLikeProviderApiResponse(value) {
|
|
2646
|
+
return Array.isArray(value.output) || Array.isArray(value.content) || Array.isArray(value.candidates) || Array.isArray(value.choices);
|
|
2647
|
+
}
|
|
2648
|
+
function extractStoredAnswerAnchors(provider, rawResponse) {
|
|
2649
|
+
if (!rawResponse) return [];
|
|
2650
|
+
const apiResponse = resolveStoredApiResponse(parseJsonColumn(rawResponse, {}));
|
|
2651
|
+
if (!apiResponse) return [];
|
|
2652
|
+
try {
|
|
2653
|
+
switch (provider) {
|
|
2654
|
+
case ProviderNames.openai:
|
|
2655
|
+
return extractAnchoredSpans(apiResponse);
|
|
2656
|
+
case ProviderNames.claude:
|
|
2657
|
+
return extractAnchoredSpans2(apiResponse);
|
|
2658
|
+
case ProviderNames.gemini:
|
|
2659
|
+
return extractAnchoredSpans3(apiResponse);
|
|
2660
|
+
case ProviderNames.perplexity:
|
|
2661
|
+
return extractAnchoredSpans4(apiResponse);
|
|
2662
|
+
default:
|
|
2663
|
+
return [];
|
|
2664
|
+
}
|
|
2665
|
+
} catch {
|
|
2666
|
+
return [];
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2670
|
+
export {
|
|
2671
|
+
OPENAI_RETRIEVAL_CONTRACT,
|
|
2672
|
+
reparseStoredResult,
|
|
2673
|
+
openaiAdapter,
|
|
2674
|
+
reparseStoredResult2,
|
|
2675
|
+
claudeAdapter,
|
|
2676
|
+
reparseStoredResult3,
|
|
2677
|
+
extractSearchQueriesFromRaw3 as extractSearchQueriesFromRaw,
|
|
2678
|
+
embedQueries,
|
|
2679
|
+
geminiAdapter,
|
|
2680
|
+
reparseStoredResult4,
|
|
2681
|
+
perplexityAdapter,
|
|
2682
|
+
reparseStoredResult5,
|
|
2683
|
+
museAdapter,
|
|
2684
|
+
resolveStoredApiResponse,
|
|
2685
|
+
extractStoredAnswerAnchors
|
|
2686
|
+
};
|