@picassohq/cli 1.0.3 → 1.0.4
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/build-info.json +1 -1
- package/dist/index.js +1591 -1251
- package/package.json +1 -1
- package/runtime/engine-manifest.json +22 -11
- package/runtime/packages/picasso-compaction/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-compaction/index.js +623 -0
- package/runtime/packages/picasso-compaction/package.json +27 -0
- package/runtime/packages/picasso-lean-context/argument-repair.js +422 -0
- package/runtime/packages/picasso-lean-context/index.js +23 -2
- package/runtime/packages/picasso-model-router/connections.js +49 -3
- package/runtime/packages/picasso-model-router/index.js +32 -1
- package/runtime/packages/picasso-model-router/package.json +3 -1
- package/runtime/packages/picasso-model-router/thinking-default.js +212 -0
- package/runtime/packages/picasso-web-search/backends.js +245 -195
- package/runtime/packages/picasso-web-search/config.js +75 -27
- package/runtime/packages/picasso-web-search/cordis.patch.yml +2 -1
- package/runtime/packages/picasso-web-search/failure.js +7 -1
- package/runtime/packages/picasso-web-search/index.js +7 -5
- package/runtime/packages/picasso-web-search/package.json +6 -0
- package/runtime/packages/picasso-web-search/requests.js +339 -0
- package/runtime/packages/picasso-web-search/router.js +17 -12
- package/runtime/plugins/picasso-compaction/index.js +623 -0
- package/runtime/plugins/picasso-compaction/package.json +27 -0
- package/runtime/plugins/picasso-lean-context/argument-repair.js +422 -0
- package/runtime/plugins/picasso-lean-context/index.js +23 -2
- package/runtime/plugins/picasso-model-router/connections.js +49 -3
- package/runtime/plugins/picasso-model-router/index.js +32 -1
- package/runtime/plugins/picasso-model-router/package.json +3 -1
- package/runtime/plugins/picasso-model-router/thinking-default.js +212 -0
- package/runtime/plugins/picasso-provider-models/index.js +236 -4
- package/runtime/plugins/picasso-web-search/backends.js +245 -195
- package/runtime/plugins/picasso-web-search/config.js +75 -27
- package/runtime/plugins/picasso-web-search/failure.js +7 -1
- package/runtime/plugins/picasso-web-search/index.js +7 -5
- package/runtime/plugins/picasso-web-search/package.json +6 -0
- package/runtime/plugins/picasso-web-search/requests.js +339 -0
- package/runtime/plugins/picasso-web-search/router.js +17 -12
- package/runtime/relay/main.mjs +2776 -1494
- package/runtime/relay/model-listing.mjs +337 -26
- package/runtime/relay/versions-routes.mjs +65 -3
|
@@ -4,16 +4,44 @@
|
|
|
4
4
|
// through the web seam registry so the account sign-in / API key handling stays the engine's
|
|
5
5
|
// anthropic Messages API with the server-side `web_search_20250305` tool
|
|
6
6
|
// openai Responses API with the hosted `web_search` tool
|
|
7
|
-
// google Gemini `generateContent` with `google_search` grounding
|
|
7
|
+
// google Gemini `generateContent` with `google_search` grounding (its redirect links resolved to the pages)
|
|
8
8
|
// prism Prism (`prism`, `kiro-prism` routes, or an optional fallback): the same Messages server-tool call,
|
|
9
9
|
// answered by Prism itself from its own search pools (no model call)
|
|
10
|
+
// picasso Picasso's managed search (`POST /v1/managed/search` with the signed-in account): the managed route's own
|
|
11
|
+
// search, and the last automatic fallback of every route while the person is signed in. The request goes
|
|
12
|
+
// through the capability the managed transport plugin publishes in the same engine process
|
|
13
|
+
// (MANAGED_SEARCH_SYMBOL), so the account token never reaches this plugin.
|
|
10
14
|
//
|
|
11
|
-
// "Native" means the backend whose id the route maps to (NATIVE_ROUTES); any backend can also be a
|
|
12
|
-
//
|
|
15
|
+
// "Native" means the backend whose id the route maps to (NATIVE_ROUTES); any backend can also be a fallback (listed, or
|
|
16
|
+
// automatic when no list is set). Results carry only structured fields (url, title, snippet, publishedAt); provider prose is never an answer.
|
|
17
|
+
// The request and response shapes live in requests.js, which the Picasso API's managed search shares.
|
|
13
18
|
import { safeBaseUrl } from './config.js';
|
|
14
19
|
import { BackendFailure, classifyEngineError, classifyHttp } from './failure.js';
|
|
20
|
+
import {
|
|
21
|
+
dedupeSources,
|
|
22
|
+
geminiSearchRequest,
|
|
23
|
+
messagesSearchRequest,
|
|
24
|
+
minimaxSearchRequest,
|
|
25
|
+
normalizeSource,
|
|
26
|
+
openAiSearchBody,
|
|
27
|
+
parseOpenAiSearch,
|
|
28
|
+
postJson,
|
|
29
|
+
prismHeaders,
|
|
30
|
+
} from './requests.js';
|
|
15
31
|
|
|
16
|
-
export
|
|
32
|
+
export {
|
|
33
|
+
GROUNDING_RESOLVE_MAX,
|
|
34
|
+
GROUNDING_RESOLVE_TIMEOUT_MS,
|
|
35
|
+
MINIMAX_SEARCH_PATH,
|
|
36
|
+
isGroundingRedirect,
|
|
37
|
+
parseGeminiSearch,
|
|
38
|
+
parseMessagesSearch,
|
|
39
|
+
parseMiniMaxSearch,
|
|
40
|
+
parseOpenAiSearch,
|
|
41
|
+
resolveGroundingRedirects,
|
|
42
|
+
} from './requests.js';
|
|
43
|
+
|
|
44
|
+
export const BACKEND_NAMES = Object.freeze({ deepseek: 'DeepSeek', anthropic: 'Anthropic', openai: 'OpenAI', google: 'Google', prism: 'Prism', minimax: 'MiniMax', picasso: 'Picasso' });
|
|
17
45
|
|
|
18
46
|
/** Route ids (as the engine names the thread's provider route) that have a native search backend. */
|
|
19
47
|
export const NATIVE_ROUTES = Object.freeze({
|
|
@@ -25,8 +53,50 @@ export const NATIVE_ROUTES = Object.freeze({
|
|
|
25
53
|
// Prism routes: the gateway answers the Messages `web_search_20250305` server tool itself, from its own search pools.
|
|
26
54
|
prism: 'prism',
|
|
27
55
|
'kiro-prism': 'prism',
|
|
56
|
+
// MiniMax routes (the official ones and any route the person named minimax-*, e.g. a local key-rotation proxy): the
|
|
57
|
+
// coding-plan search at the route's own origin.
|
|
58
|
+
minimax: 'minimax',
|
|
59
|
+
'minimax-cn': 'minimax',
|
|
60
|
+
// Picasso's managed route (the engine route the managed transport registers; `picasso provider use picasso-free` on
|
|
61
|
+
// the CLI, the managed models on the Mac): Picasso's own search with the signed-in account.
|
|
62
|
+
'picasso-managed': 'picasso',
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
/** The native backend of a route: NATIVE_ROUTES, plus every `minimax-*` route a person added. */
|
|
66
|
+
export function nativeBackendFor(route) {
|
|
67
|
+
if (typeof route !== 'string') return undefined;
|
|
68
|
+
if (Object.hasOwn(NATIVE_ROUTES, route)) return NATIVE_ROUTES[route];
|
|
69
|
+
return /^minimax[-_]/iu.test(route) ? 'minimax' : undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** MiniMax's coding-plan search: the default origin and the route's shipped key reference. */
|
|
73
|
+
export const DEFAULT_MINIMAX_URL = 'https://api.minimax.io';
|
|
74
|
+
const MINIMAX_KEY_REFS = Object.freeze({ minimax: 'MINIMAX_API_KEY', 'minimax-cn': 'MINIMAX_CN_API_KEY' });
|
|
75
|
+
|
|
76
|
+
/** The Prism routes a fallback search may borrow, in order, and each one's shipped key reference. */
|
|
77
|
+
export const PRISM_ROUTES = Object.freeze(['kiro-prism', 'prism']);
|
|
78
|
+
export const PRISM_ROUTE_KEY_REFS = Object.freeze({ 'kiro-prism': 'PRISM_API_KEY', prism: 'PRISM_API_KEY' });
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The provider routes whose key each fallback borrows. A fallback whose routes are all disconnected (`disconnected` in
|
|
82
|
+
* the shared model-connections.json) is never tried: Picasso does not use a disconnected route's key, even though it
|
|
83
|
+
* still resolves (often from the shell environment other tools need). Picasso's managed search has no route here.
|
|
84
|
+
*/
|
|
85
|
+
export const FALLBACK_ROUTES = Object.freeze({
|
|
86
|
+
deepseek: Object.freeze(['deepseek-official']),
|
|
87
|
+
anthropic: Object.freeze(['anthropic']),
|
|
88
|
+
openai: Object.freeze(['openai']),
|
|
89
|
+
google: Object.freeze(['google']),
|
|
90
|
+
prism: PRISM_ROUTES,
|
|
28
91
|
});
|
|
29
92
|
|
|
93
|
+
/** Whether a fallback may not be used because every route it borrows from is disconnected. */
|
|
94
|
+
export function fallbackDisconnected(id, disconnected) {
|
|
95
|
+
const routes = FALLBACK_ROUTES[id];
|
|
96
|
+
if (routes === undefined || !Array.isArray(disconnected) || disconnected.length === 0) return false;
|
|
97
|
+
return routes.every((route) => disconnected.includes(route));
|
|
98
|
+
}
|
|
99
|
+
|
|
30
100
|
/** Prism's endpoint when a Prism route's own profile cannot be read (the shipped `prism`/`kiro-prism` baseURL origin). */
|
|
31
101
|
export const DEFAULT_PRISM_URL = 'https://prism.auraone.ai';
|
|
32
102
|
|
|
@@ -39,19 +109,11 @@ export const DEFAULT_BASE_URLS = Object.freeze({
|
|
|
39
109
|
google: 'https://generativelanguage.googleapis.com/v1beta',
|
|
40
110
|
});
|
|
41
111
|
|
|
42
|
-
/** Models used when a backend is a
|
|
112
|
+
/** Models used when a backend is a fallback (a native search uses the thread's own model). Overridable. */
|
|
43
113
|
export const DEFAULT_MODELS = Object.freeze({ anthropic: 'claude-haiku-4-5', openai: 'gpt-5-mini', google: 'gemini-2.5-flash', prism: 'claude-sonnet-5.5' });
|
|
44
114
|
|
|
45
|
-
const ANTHROPIC_VERSION = '2023-06-01';
|
|
46
|
-
const USER_AGENT = 'picasso-web-search/0.1';
|
|
47
|
-
const MAX_USES = 2;
|
|
48
|
-
const MAX_TOKENS = 2048;
|
|
49
|
-
const BODY_PEEK_BYTES = 4096;
|
|
50
|
-
const SNIPPET_MAX = 280;
|
|
51
|
-
|
|
52
115
|
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
53
116
|
const str = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
|
|
54
|
-
const prompt = (query) => `Perform a web search for the query: ${query}`;
|
|
55
117
|
const REF_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
56
118
|
|
|
57
119
|
/** The Messages base of a route's OpenAI-style baseURL (`https://host/v1` -> `https://host`); undefined when unsafe. */
|
|
@@ -60,182 +122,59 @@ export function messagesBase(baseURL) {
|
|
|
60
122
|
return safe === undefined ? undefined : safe.replace(/\/v1$/u, '');
|
|
61
123
|
}
|
|
62
124
|
|
|
63
|
-
/** `{ url, title?, snippet?, publishedAt? }` with absent fields omitted; null when the url is not http(s). */
|
|
64
|
-
function source(url, title, snippet, publishedAt) {
|
|
65
|
-
const link = str(url);
|
|
66
|
-
if (link === undefined || !/^https?:\/\//iu.test(link)) return null;
|
|
67
|
-
const clean = snippet === undefined ? undefined : str(snippet.replace(/\s+/gu, ' '));
|
|
68
|
-
return {
|
|
69
|
-
url: link,
|
|
70
|
-
...(str(title) === undefined ? {} : { title: str(title) }),
|
|
71
|
-
...(clean === undefined ? {} : { snippet: clean.length <= SNIPPET_MAX ? clean : `${clean.slice(0, SNIPPET_MAX - 1)}…` }),
|
|
72
|
-
...(str(publishedAt) === undefined ? {} : { publishedAt: str(publishedAt) }),
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function dedupe(list) {
|
|
77
|
-
const seen = new Set();
|
|
78
|
-
const out = [];
|
|
79
|
-
for (const item of list) {
|
|
80
|
-
if (item === null || seen.has(item.url)) continue;
|
|
81
|
-
seen.add(item.url);
|
|
82
|
-
out.push(item);
|
|
83
|
-
}
|
|
84
|
-
return out;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
125
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
88
|
-
//
|
|
126
|
+
// Picasso's managed search
|
|
89
127
|
|
|
90
|
-
/**
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
while (size < BODY_PEEK_BYTES) {
|
|
98
|
-
const { done, value } = await reader.read();
|
|
99
|
-
if (done) break;
|
|
100
|
-
chunks.push(value);
|
|
101
|
-
size += value.byteLength;
|
|
102
|
-
}
|
|
103
|
-
} catch {
|
|
104
|
-
// An unreadable body classifies by status alone.
|
|
105
|
-
} finally {
|
|
106
|
-
reader.cancel().catch(() => {});
|
|
107
|
-
}
|
|
108
|
-
const bytes = new Uint8Array(Math.min(size, BODY_PEEK_BYTES));
|
|
109
|
-
let offset = 0;
|
|
110
|
-
for (const chunk of chunks) {
|
|
111
|
-
if (offset >= bytes.byteLength) break;
|
|
112
|
-
const part = chunk.subarray(0, bytes.byteLength - offset);
|
|
113
|
-
bytes.set(part, offset);
|
|
114
|
-
offset += part.byteLength;
|
|
115
|
-
}
|
|
116
|
-
return new TextDecoder().decode(bytes);
|
|
117
|
-
}
|
|
128
|
+
/**
|
|
129
|
+
* Where the managed transport plugin (packages/core/src/dsh/managed-transport.ts) publishes the managed-search
|
|
130
|
+
* capability in the engine process: `{ version: 1, available(signal?): Promise<boolean>, search({ query, maxResults? },
|
|
131
|
+
* signal?): Promise<Response> }`. `search` answers with the API's (or the Mac relay's proxy's) raw `Response` to
|
|
132
|
+
* `POST /v1/managed/search`; `available` asks the same path with GET. The account token stays inside that plugin.
|
|
133
|
+
*/
|
|
134
|
+
export const MANAGED_SEARCH_SYMBOL = Symbol.for('picasso.managed-search');
|
|
118
135
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
headers: { 'content-type': 'application/json', accept: 'application/json', 'user-agent': USER_AGENT, ...headers },
|
|
124
|
-
body: JSON.stringify(body),
|
|
125
|
-
...(signal === undefined ? {} : { signal }),
|
|
126
|
-
});
|
|
127
|
-
if (!response.ok) {
|
|
128
|
-
const peek = await peekBody(response);
|
|
129
|
-
// The body is read only to tell a billing refusal from other 4xx; it is dropped, never shown.
|
|
130
|
-
throw classifyHttp(response.status, peek, response.headers?.get?.('retry-after') ?? undefined);
|
|
131
|
-
}
|
|
132
|
-
try {
|
|
133
|
-
return await response.json();
|
|
134
|
-
} catch (error) {
|
|
135
|
-
if (signal?.aborted === true) throw error;
|
|
136
|
-
throw new BackendFailure('unreadable');
|
|
137
|
-
}
|
|
136
|
+
/** The published capability, or undefined (signed out at launch, managed lane off, or not in an engine). */
|
|
137
|
+
export function managedSearchCapability() {
|
|
138
|
+
const capability = globalThis[MANAGED_SEARCH_SYMBOL];
|
|
139
|
+
return isRecord(capability) && capability.version === 1 && typeof capability.available === 'function' && typeof capability.search === 'function' ? capability : undefined;
|
|
138
140
|
}
|
|
139
141
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
+
/** How long a yes / no from `available()` is reused before asking again. */
|
|
143
|
+
export const MANAGED_AVAILABLE_TTL_MS = Object.freeze({ yes: 60_000, no: 15_000 });
|
|
142
144
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
case 'too_many_requests':
|
|
146
|
-
return new BackendFailure('rate');
|
|
147
|
-
case 'unavailable':
|
|
148
|
-
return new BackendFailure('server');
|
|
149
|
-
case 'outcome_unknown':
|
|
150
|
-
return new BackendFailure('outcome-unknown');
|
|
151
|
-
default:
|
|
152
|
-
return new BackendFailure('rejected');
|
|
153
|
-
}
|
|
154
|
-
}
|
|
145
|
+
/** The upstream kinds a managed search may report (`502 {error:"managed_search_failed", reason}`) that read as such. */
|
|
146
|
+
const MANAGED_PASS_THROUGH_KINDS = new Set(['timeout', 'rate', 'empty', 'outcome-unknown', 'network', 'unreadable']);
|
|
155
147
|
|
|
156
|
-
/**
|
|
157
|
-
export function
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
if (!isRecord(block) || block.type !== 'text' || !Array.isArray(block.citations)) continue;
|
|
164
|
-
for (const cite of block.citations) {
|
|
165
|
-
if (isRecord(cite) && str(cite.url) !== undefined && str(cite.cited_text) !== undefined && !snippets.has(cite.url)) snippets.set(cite.url, cite.cited_text);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
const found = [];
|
|
169
|
-
for (const block of results) {
|
|
170
|
-
const content = block.content;
|
|
171
|
-
if (isRecord(content) && content.type === 'web_search_tool_result_error') throw messagesError(content.error_code);
|
|
172
|
-
if (!Array.isArray(content)) continue;
|
|
173
|
-
for (const item of content) {
|
|
174
|
-
if (isRecord(item) && item.type === 'web_search_result') found.push(source(item.url, item.title, snippets.get(item.url), item.page_age));
|
|
175
|
-
}
|
|
148
|
+
/** A managed search answer as a BackendFailure (closed vocabulary; the server's own text is never shown). */
|
|
149
|
+
export async function managedSearchFailure(response) {
|
|
150
|
+
let body;
|
|
151
|
+
try {
|
|
152
|
+
body = await response.json();
|
|
153
|
+
} catch {
|
|
154
|
+
body = undefined;
|
|
176
155
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
return
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// ---------------------------------------------------------------------------------------------------------------------
|
|
190
|
-
// OpenAI Responses
|
|
191
|
-
|
|
192
|
-
/** The sentence an annotation ends, as plain text: markdown links and bare citations removed. */
|
|
193
|
-
function sentenceBefore(text, index) {
|
|
194
|
-
const head = text.slice(0, Math.max(0, index));
|
|
195
|
-
const start = Math.max(head.lastIndexOf('. '), head.lastIndexOf('\n'), -1) + 1;
|
|
196
|
-
return head
|
|
197
|
-
.slice(start)
|
|
198
|
-
.replace(/\[([^\]]*)\]\([^)]*\)/gu, '$1')
|
|
199
|
-
.replace(/\(\s*\)/gu, '')
|
|
200
|
-
.replace(/^[\s.\-*•]+/u, '')
|
|
201
|
-
.trim();
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
export function parseOpenAiSearch(json) {
|
|
205
|
-
const output = isRecord(json) && Array.isArray(json.output) ? json.output : [];
|
|
206
|
-
if (!output.some((item) => isRecord(item) && item.type === 'web_search_call')) throw new BackendFailure('empty');
|
|
207
|
-
const found = [];
|
|
208
|
-
for (const item of output) {
|
|
209
|
-
if (!isRecord(item) || item.type !== 'message' || !Array.isArray(item.content)) continue;
|
|
210
|
-
for (const part of item.content) {
|
|
211
|
-
if (!isRecord(part) || part.type !== 'output_text' || !Array.isArray(part.annotations)) continue;
|
|
212
|
-
const text = typeof part.text === 'string' ? part.text : '';
|
|
213
|
-
for (const note of part.annotations) {
|
|
214
|
-
if (!isRecord(note) || note.type !== 'url_citation') continue;
|
|
215
|
-
const snippet = Number.isInteger(note.start_index) ? sentenceBefore(text, note.start_index) : '';
|
|
216
|
-
found.push(source(note.url, note.title, snippet === '' ? undefined : snippet));
|
|
217
|
-
}
|
|
218
|
-
}
|
|
156
|
+
const code = isRecord(body) && typeof body.error === 'string' ? body.error : undefined;
|
|
157
|
+
const retry = response.headers?.get?.('retry-after') ?? undefined;
|
|
158
|
+
const { status } = response;
|
|
159
|
+
if (status === 401) return new BackendFailure('signed-out');
|
|
160
|
+
if (code === 'managed_daily_limit_reached') return new BackendFailure('quota');
|
|
161
|
+
if (status === 429) return classifyHttp(429, '', retry);
|
|
162
|
+
if (status === 403) return new BackendFailure('forbidden', { status });
|
|
163
|
+
if (status === 502 && code === 'managed_search_failed') {
|
|
164
|
+
const reason = isRecord(body) && typeof body.reason === 'string' ? body.reason : undefined;
|
|
165
|
+
if (reason !== undefined && MANAGED_PASS_THROUGH_KINDS.has(reason)) return new BackendFailure(reason);
|
|
166
|
+
return new BackendFailure('server', { status });
|
|
219
167
|
}
|
|
220
|
-
return
|
|
168
|
+
if (status >= 500) return new BackendFailure('server', { status });
|
|
169
|
+
return new BackendFailure('rejected', { status });
|
|
221
170
|
}
|
|
222
171
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
if (grounding === undefined) throw new BackendFailure('empty');
|
|
230
|
-
const chunks = Array.isArray(grounding.groundingChunks) ? grounding.groundingChunks : [];
|
|
231
|
-
const snippets = new Map();
|
|
232
|
-
for (const support of Array.isArray(grounding.groundingSupports) ? grounding.groundingSupports : []) {
|
|
233
|
-
const segment = isRecord(support) && isRecord(support.segment) ? str(support.segment.text) : undefined;
|
|
234
|
-
if (segment === undefined || !Array.isArray(support.groundingChunkIndices)) continue;
|
|
235
|
-
for (const index of support.groundingChunkIndices) if (!snippets.has(index)) snippets.set(index, segment);
|
|
236
|
-
}
|
|
237
|
-
const found = chunks.map((chunk, index) => (isRecord(chunk) && isRecord(chunk.web) ? source(chunk.web.uri, chunk.web.title, snippets.get(index)) : null));
|
|
238
|
-
return { sources: dedupe(found), truncated: false };
|
|
172
|
+
/** `{ sources: [...] }` from the managed search, each source re-normalized, at most `maxResults`. */
|
|
173
|
+
export function parseManagedSearch(json, maxResults) {
|
|
174
|
+
if (!isRecord(json) || !Array.isArray(json.sources)) throw new BackendFailure('unreadable');
|
|
175
|
+
const sources = dedupeSources(json.sources.map((item) => (isRecord(item) ? normalizeSource(item.url, item.title, item.snippet, item.publishedAt) : null)));
|
|
176
|
+
const limit = Number.isInteger(maxResults) && maxResults > 0 ? maxResults : sources.length;
|
|
177
|
+
return { sources: sources.slice(0, limit), truncated: false };
|
|
239
178
|
}
|
|
240
179
|
|
|
241
180
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
@@ -263,6 +202,16 @@ export function credentialsFrom(ctx, env = process.env) {
|
|
|
263
202
|
return false;
|
|
264
203
|
}
|
|
265
204
|
},
|
|
205
|
+
/** Whether the key comes only from the process environment (the engine's credential layer says so). */
|
|
206
|
+
async fromEnvironment(ref) {
|
|
207
|
+
try {
|
|
208
|
+
const credentials = service();
|
|
209
|
+
if (credentials !== undefined) return /^(?:env|environment|process)/iu.test(String((await credentials.describe(ref))?.source ?? ''));
|
|
210
|
+
return str(env[ref]) !== undefined;
|
|
211
|
+
} catch {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
},
|
|
266
215
|
};
|
|
267
216
|
}
|
|
268
217
|
|
|
@@ -295,15 +244,40 @@ export function routeProfileFrom(ctx) {
|
|
|
295
244
|
}
|
|
296
245
|
|
|
297
246
|
/**
|
|
298
|
-
* `deps`: `{ creds, fetch, getWeb, routeProfile }`. Every backend answers:
|
|
247
|
+
* `deps`: `{ creds, fetch, getWeb, routeProfile, managedSearch?, now? }`. Every backend answers:
|
|
299
248
|
* `configured(call)` whether a search could be sent (a credential or an engine provider is present); no network
|
|
300
249
|
* `keyRef(call)` the credential reference it needs (for the "no credentials (needs X)" reason), if any
|
|
250
|
+
* `unconfigured(call)` the failure a native search that cannot be sent reports instead (optional)
|
|
301
251
|
* `search(request, call)` `call = { signal, route, model, role, config }`
|
|
302
252
|
*/
|
|
303
|
-
export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, getWeb = () => undefined, routeProfile = async () => undefined }) {
|
|
253
|
+
export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, getWeb = () => undefined, routeProfile = async () => undefined, managedSearch = managedSearchCapability, now = Date.now }) {
|
|
254
|
+
// The managed capability's yes/no, reused for MANAGED_AVAILABLE_TTL_MS (one loopback or API GET per minute at most).
|
|
255
|
+
let availability;
|
|
256
|
+
const managedAvailable = async () => {
|
|
257
|
+
const capability = managedSearch();
|
|
258
|
+
if (capability === undefined) return false;
|
|
259
|
+
if (availability !== undefined && availability.capability === capability && availability.until > now()) return availability.value;
|
|
260
|
+
let value = false;
|
|
261
|
+
try {
|
|
262
|
+
value = (await capability.available()) === true;
|
|
263
|
+
} catch {
|
|
264
|
+
value = false;
|
|
265
|
+
}
|
|
266
|
+
availability = { capability, value, until: now() + (value ? MANAGED_AVAILABLE_TTL_MS.yes : MANAGED_AVAILABLE_TTL_MS.no) };
|
|
267
|
+
return value;
|
|
268
|
+
};
|
|
269
|
+
// A fallback never borrows a key found only in the environment for a route the person has not connected
|
|
270
|
+
// (`connected` in the shared model-connections.json; owner 2026-11-17: such a key never connects a provider by itself).
|
|
271
|
+
const heldEnvKey = async (id, ref, call) => {
|
|
272
|
+
if (call.role === 'native' || ref === undefined || typeof creds.fromEnvironment !== 'function') return false;
|
|
273
|
+
const routes = FALLBACK_ROUTES[id] ?? [];
|
|
274
|
+
const connected = Array.isArray(call.config.connected) ? call.config.connected : [];
|
|
275
|
+
if (routes.length === 0 || routes.some((route) => connected.includes(route))) return false;
|
|
276
|
+
return (await creds.fromEnvironment(ref)) === true;
|
|
277
|
+
};
|
|
304
278
|
const modelFor = (id, call) => call.config.models[id] ?? (call.role === 'native' && str(call.model) !== undefined ? str(call.model) : DEFAULT_MODELS[id]);
|
|
305
279
|
const baseFor = (id, call) => call.config.baseUrls[id] ?? DEFAULT_BASE_URLS[id];
|
|
306
|
-
const keyed = (id) => async (call) => (await creds.configured(KEY_REFS[id])) && Boolean(baseFor(id, call));
|
|
280
|
+
const keyed = (id) => async (call) => (await creds.configured(KEY_REFS[id])) && !(await heldEnvKey(id, KEY_REFS[id], call)) && Boolean(baseFor(id, call));
|
|
307
281
|
const requireKey = async (id) => {
|
|
308
282
|
const key = await creds.resolve(KEY_REFS[id]);
|
|
309
283
|
if (key === undefined) throw new BackendFailure('credentials', { ref: KEY_REFS[id] });
|
|
@@ -312,9 +286,24 @@ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, get
|
|
|
312
286
|
const keyRefOf = (id) => async () => KEY_REFS[id];
|
|
313
287
|
|
|
314
288
|
// Prism as the thread's own route: the route's endpoint and key reference (its profile), else the configured Prism
|
|
315
|
-
// endpoint and key, else the shipped endpoint. As a fallback: only the configured endpoint and key.
|
|
289
|
+
// endpoint and key, else the shipped endpoint. As a fallback in a written list: only the configured endpoint and key.
|
|
290
|
+
// As an automatic fallback (no list): the configured endpoint, else a connected Prism route's own endpoint and key.
|
|
316
291
|
const prismTarget = async (call) => {
|
|
317
|
-
if (call.role !== 'native')
|
|
292
|
+
if (call.role !== 'native') {
|
|
293
|
+
if (call.config.prismUrl !== undefined || call.config.auto !== true) return { url: call.config.prismUrl, keyRef: call.config.prismKeyRef };
|
|
294
|
+
// No list and no endpoint configured: a connected Prism route (its own endpoint and key) serves the search. A
|
|
295
|
+
// disconnected Prism route lends nothing, and while one is disconnected the shipped key reference is not tried
|
|
296
|
+
// either (it is that route's key).
|
|
297
|
+
const disconnected = Array.isArray(call.config.disconnected) ? call.config.disconnected : [];
|
|
298
|
+
for (const route of PRISM_ROUTES) {
|
|
299
|
+
if (disconnected.includes(route)) continue;
|
|
300
|
+
const profile = await routeProfile(route);
|
|
301
|
+
const keyRef = profile?.apiKeyEnv ?? PRISM_ROUTE_KEY_REFS[route];
|
|
302
|
+
if (await creds.configured(keyRef)) return { url: messagesBase(profile?.baseURL) ?? DEFAULT_PRISM_URL, keyRef };
|
|
303
|
+
}
|
|
304
|
+
if (PRISM_ROUTES.some((route) => disconnected.includes(route))) return { url: undefined, keyRef: undefined };
|
|
305
|
+
return { url: DEFAULT_PRISM_URL, keyRef: call.config.prismKeyRef };
|
|
306
|
+
}
|
|
318
307
|
const profile = await routeProfile(call.route);
|
|
319
308
|
return {
|
|
320
309
|
url: messagesBase(profile?.baseURL) ?? call.config.prismUrl ?? DEFAULT_PRISM_URL,
|
|
@@ -322,6 +311,17 @@ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, get
|
|
|
322
311
|
};
|
|
323
312
|
};
|
|
324
313
|
|
|
314
|
+
// MiniMax as the thread's own route: the origin of the route's endpoint (a key-rotation proxy on loopback included)
|
|
315
|
+
// and its key reference; the official endpoint and MINIMAX_API_KEY when the profile cannot be read.
|
|
316
|
+
const minimaxTarget = async (call) => {
|
|
317
|
+
const profile = await routeProfile(call.route);
|
|
318
|
+
const base = safeBaseUrl(profile?.baseURL);
|
|
319
|
+
return {
|
|
320
|
+
url: base === undefined ? DEFAULT_MINIMAX_URL : new URL(base).origin,
|
|
321
|
+
keyRef: profile?.apiKeyEnv ?? MINIMAX_KEY_REFS[call.route] ?? 'MINIMAX_API_KEY',
|
|
322
|
+
};
|
|
323
|
+
};
|
|
324
|
+
|
|
325
325
|
const engineProvider = () => {
|
|
326
326
|
const registry = getWeb()?.searchProviders;
|
|
327
327
|
if (!(registry instanceof Map)) return undefined;
|
|
@@ -337,6 +337,7 @@ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, get
|
|
|
337
337
|
if (provider === undefined) return false;
|
|
338
338
|
try {
|
|
339
339
|
const route = call.role === 'native' ? call.route : 'deepseek-official';
|
|
340
|
+
if (await heldEnvKey('deepseek', KEY_REFS.deepseek, call)) return false;
|
|
340
341
|
return provider.available() && (await (provider.ready?.(route) ?? true)) !== false;
|
|
341
342
|
} catch {
|
|
342
343
|
return false;
|
|
@@ -360,8 +361,8 @@ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, get
|
|
|
360
361
|
keyRef: keyRefOf('anthropic'),
|
|
361
362
|
async search(request, call) {
|
|
362
363
|
const key = await requireKey('anthropic');
|
|
363
|
-
const
|
|
364
|
-
return
|
|
364
|
+
const { result } = await messagesSearchRequest({ fetch: fetchImpl, base: baseFor('anthropic', call), headers: { 'x-api-key': key }, model: modelFor('anthropic', call), query: request.query, signal: call.signal });
|
|
365
|
+
return result;
|
|
365
366
|
},
|
|
366
367
|
},
|
|
367
368
|
openai: {
|
|
@@ -371,7 +372,7 @@ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, get
|
|
|
371
372
|
keyRef: keyRefOf('openai'),
|
|
372
373
|
async search(request, call) {
|
|
373
374
|
const key = await requireKey('openai');
|
|
374
|
-
const body =
|
|
375
|
+
const body = openAiSearchBody(modelFor('openai', call), request.query);
|
|
375
376
|
return parseOpenAiSearch(await postJson(fetchImpl, `${baseFor('openai', call)}/responses`, { authorization: `Bearer ${key}` }, body, call.signal));
|
|
376
377
|
},
|
|
377
378
|
},
|
|
@@ -382,19 +383,37 @@ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, get
|
|
|
382
383
|
keyRef: keyRefOf('google'),
|
|
383
384
|
async search(request, call) {
|
|
384
385
|
const key = await requireKey('google');
|
|
385
|
-
const
|
|
386
|
-
|
|
387
|
-
|
|
386
|
+
const { result } = await geminiSearchRequest({ fetch: fetchImpl, base: baseFor('google', call), key, model: modelFor('google', call), query: request.query, signal: call.signal });
|
|
387
|
+
return result;
|
|
388
|
+
},
|
|
389
|
+
},
|
|
390
|
+
minimax: {
|
|
391
|
+
id: 'minimax',
|
|
392
|
+
name: BACKEND_NAMES.minimax,
|
|
393
|
+
async configured(call) {
|
|
394
|
+
if (call.role !== 'native') return false;
|
|
395
|
+
const { url, keyRef } = await minimaxTarget(call);
|
|
396
|
+
return url !== undefined && (await creds.configured(keyRef));
|
|
397
|
+
},
|
|
398
|
+
async keyRef(call) {
|
|
399
|
+
return (await minimaxTarget(call)).keyRef;
|
|
400
|
+
},
|
|
401
|
+
async search(request, call) {
|
|
402
|
+
const { url, keyRef } = await minimaxTarget(call);
|
|
403
|
+
const key = await creds.resolve(keyRef);
|
|
404
|
+
if (key === undefined || url === undefined) throw new BackendFailure('credentials', { ref: keyRef });
|
|
405
|
+
const { result } = await minimaxSearchRequest({ fetch: fetchImpl, origin: url, key, query: request.query, signal: call.signal });
|
|
406
|
+
return result;
|
|
388
407
|
},
|
|
389
408
|
},
|
|
390
409
|
prism: {
|
|
391
410
|
id: 'prism',
|
|
392
411
|
name: BACKEND_NAMES.prism,
|
|
393
|
-
// As a fallback, optional: active only when both an endpoint and a key are
|
|
394
|
-
//
|
|
412
|
+
// As a fallback, optional: active only when both an endpoint and a key are present (absent is skipped silently);
|
|
413
|
+
// see prismTarget. As a Prism route's own search, the route's endpoint and key.
|
|
395
414
|
async configured(call) {
|
|
396
415
|
const { url, keyRef } = await prismTarget(call);
|
|
397
|
-
return url !== undefined && (await creds.configured(keyRef));
|
|
416
|
+
return url !== undefined && keyRef !== undefined && (await creds.configured(keyRef)) && !(await heldEnvKey('prism', keyRef, call));
|
|
398
417
|
},
|
|
399
418
|
async keyRef(call) {
|
|
400
419
|
return (await prismTarget(call)).keyRef;
|
|
@@ -403,9 +422,40 @@ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, get
|
|
|
403
422
|
const { url, keyRef } = await prismTarget(call);
|
|
404
423
|
const key = await creds.resolve(keyRef);
|
|
405
424
|
if (key === undefined || url === undefined) throw new BackendFailure('credentials', { ref: keyRef });
|
|
406
|
-
const
|
|
407
|
-
|
|
408
|
-
|
|
425
|
+
const { result } = await messagesSearchRequest({ fetch: fetchImpl, base: url, headers: prismHeaders(key), model: modelFor('prism', call), query: request.query, signal: call.signal });
|
|
426
|
+
return result;
|
|
427
|
+
},
|
|
428
|
+
},
|
|
429
|
+
picasso: {
|
|
430
|
+
id: 'picasso',
|
|
431
|
+
name: BACKEND_NAMES.picasso,
|
|
432
|
+
// Active while the managed transport has published its capability (signed in, managed lane on) and the API (or
|
|
433
|
+
// the Mac relay's proxy) says the account can search. Absent, it is left out silently as a fallback.
|
|
434
|
+
async configured() {
|
|
435
|
+
return managedAvailable();
|
|
436
|
+
},
|
|
437
|
+
unconfigured() {
|
|
438
|
+
return new BackendFailure('signed-out');
|
|
439
|
+
},
|
|
440
|
+
async search(request, call) {
|
|
441
|
+
const capability = managedSearch();
|
|
442
|
+
if (capability === undefined) throw new BackendFailure('signed-out');
|
|
443
|
+
const body = { query: request.query, ...(Number.isInteger(request.maxResults) ? { maxResults: request.maxResults } : {}) };
|
|
444
|
+
const response = await capability.search(body, call.signal);
|
|
445
|
+
if (!response.ok) {
|
|
446
|
+
const failure = await managedSearchFailure(response);
|
|
447
|
+
// A refusal of the account itself also tells the next `configured` to ask again.
|
|
448
|
+
if (failure.kind === 'signed-out' || failure.kind === 'forbidden') availability = undefined;
|
|
449
|
+
throw failure;
|
|
450
|
+
}
|
|
451
|
+
let json;
|
|
452
|
+
try {
|
|
453
|
+
json = await response.json();
|
|
454
|
+
} catch (error) {
|
|
455
|
+
if (call.signal?.aborted === true) throw error;
|
|
456
|
+
throw new BackendFailure('unreadable');
|
|
457
|
+
}
|
|
458
|
+
return parseManagedSearch(json, body.maxResults);
|
|
409
459
|
},
|
|
410
460
|
},
|
|
411
461
|
};
|