@picassohq/cli 0.0.0-stage → 1.0.1
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/agents/browser_agent.yaml +53 -0
- package/agents/code_reviewer.yaml +49 -0
- package/agents/codebase_investigator.yaml +70 -0
- package/agents/design_auditor.yaml +50 -0
- package/agents/devex_auditor.yaml +50 -0
- package/agents/doc_writer.yaml +54 -0
- package/agents/engineering_architect.yaml +51 -0
- package/agents/generalist.yaml +55 -0
- package/agents/migration_planner.yaml +51 -0
- package/agents/product_reviewer.yaml +48 -0
- package/agents/qa_operator.yaml +52 -0
- package/agents/release_engineer.yaml +50 -0
- package/agents/security_auditor.yaml +62 -0
- package/agents/test_writer.yaml +52 -0
- package/assets/first-light-lockup.png +0 -0
- package/assets/first-light-tagline.png +0 -0
- package/assets/house/README.md +26 -0
- package/assets/house/auraone-banner.png +0 -0
- package/assets/house/auraone-logo.png +0 -0
- package/assets/house/kiro-prism-banner.png +0 -0
- package/assets/house/kiro-prism-logo.png +0 -0
- package/assets/house/picasso-banner.png +0 -0
- package/assets/house/picasso-logo.png +0 -0
- package/assets/wordmark-app.png +0 -0
- package/assets/wordmark-tight.png +0 -0
- package/assets/wordmark.png +0 -0
- package/design/styles.css +1042 -0
- package/dist/build-info.json +37 -0
- package/dist/index.js +3028 -0
- package/goals/cli-hardening.yaml +40 -0
- package/goals/repo-maintenance.yaml +40 -0
- package/package.json +49 -4
- package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
- package/runtime/dsh/picasso-ecosystem.community.json +185 -0
- package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
- package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
- package/runtime/dsh/picasso-isolation.patch.yml +25 -0
- package/runtime/dsh/picasso-providers.patch.yml +373 -0
- package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
- package/runtime/dsh/picasso-sdk.patch.yml +204 -0
- package/runtime/engine-manifest.json +214 -0
- package/runtime/package.json +6 -0
- package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
- package/runtime/packages/picasso-cache-probe/index.js +477 -0
- package/runtime/packages/picasso-cache-probe/package.json +38 -0
- package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-commands/fresh-review.js +573 -0
- package/runtime/packages/picasso-commands/index.js +497 -0
- package/runtime/packages/picasso-commands/package.json +28 -0
- package/runtime/packages/picasso-instructions/conflicts.js +115 -0
- package/runtime/packages/picasso-instructions/formats.js +145 -0
- package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
- package/runtime/packages/picasso-instructions/glob.js +114 -0
- package/runtime/packages/picasso-instructions/globals.js +90 -0
- package/runtime/packages/picasso-instructions/imports.js +123 -0
- package/runtime/packages/picasso-instructions/index.js +326 -0
- package/runtime/packages/picasso-instructions/modes.js +64 -0
- package/runtime/packages/picasso-instructions/package.json +30 -0
- package/runtime/packages/picasso-instructions/parse.js +134 -0
- package/runtime/packages/picasso-instructions/report.js +161 -0
- package/runtime/packages/picasso-instructions/resolve.js +939 -0
- package/runtime/packages/picasso-instructions/scan.js +181 -0
- package/runtime/packages/picasso-instructions/settings.js +150 -0
- package/runtime/packages/picasso-instructions/skills.js +345 -0
- package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
- package/runtime/packages/picasso-lean-context/index.js +6049 -0
- package/runtime/packages/picasso-lean-context/package.json +26 -0
- package/runtime/packages/picasso-lean-context/timeline.js +417 -0
- package/runtime/packages/picasso-librarian/classify.js +146 -0
- package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-librarian/index.js +878 -0
- package/runtime/packages/picasso-librarian/notes.js +159 -0
- package/runtime/packages/picasso-librarian/package.json +34 -0
- package/runtime/packages/picasso-librarian/state.js +478 -0
- package/runtime/packages/picasso-memory/index.js +1184 -0
- package/runtime/packages/picasso-memory/package.json +21 -0
- package/runtime/packages/picasso-model-router/connections.js +895 -0
- package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
- package/runtime/packages/picasso-model-router/index.js +1081 -0
- package/runtime/packages/picasso-model-router/package.json +30 -0
- package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-options/index.js +263 -0
- package/runtime/packages/picasso-options/package.json +28 -0
- package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-progress-reports/index.js +267 -0
- package/runtime/packages/picasso-progress-reports/package.json +30 -0
- package/runtime/packages/picasso-progress-reports/report.js +235 -0
- package/runtime/packages/picasso-sdk-server/aside.js +128 -0
- package/runtime/packages/picasso-sdk-server/connections.js +38 -0
- package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
- package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
- package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
- package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
- package/runtime/packages/picasso-sdk-server/goal.js +131 -0
- package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
- package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
- package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
- package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
- package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
- package/runtime/packages/picasso-sdk-server/index.js +886 -0
- package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
- package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
- package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
- package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
- package/runtime/packages/picasso-sdk-server/package.json +50 -0
- package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
- package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
- package/runtime/packages/picasso-sdk-server/queue.js +322 -0
- package/runtime/packages/picasso-sdk-server/requester.js +43 -0
- package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
- package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
- package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
- package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
- package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
- package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
- package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
- package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
- package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
- package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
- package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
- package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
- package/runtime/packages/picasso-web-search/backends.js +350 -0
- package/runtime/packages/picasso-web-search/config.js +121 -0
- package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
- package/runtime/packages/picasso-web-search/failure.js +111 -0
- package/runtime/packages/picasso-web-search/format.js +35 -0
- package/runtime/packages/picasso-web-search/index.js +66 -0
- package/runtime/packages/picasso-web-search/package.json +38 -0
- package/runtime/packages/picasso-web-search/router.js +155 -0
- package/runtime/packages/picasso-x-reader/circle.js +324 -0
- package/runtime/packages/picasso-x-reader/command.js +169 -0
- package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
- package/runtime/packages/picasso-x-reader/index.js +170 -0
- package/runtime/packages/picasso-x-reader/package.json +39 -0
- package/runtime/packages/picasso-x-reader/read.js +370 -0
- package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
- package/runtime/packages/picasso-x-reader/settings.js +131 -0
- package/runtime/packages/picasso-x-reader/urls.js +154 -0
- package/runtime/packages/picasso-x-reader/xmd.js +512 -0
- package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
- package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
- package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
- package/runtime/plugins/picasso-auto-approve/package.json +28 -0
- package/runtime/plugins/picasso-browser/index.js +424 -0
- package/runtime/plugins/picasso-browser/package.json +28 -0
- package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
- package/runtime/plugins/picasso-checkpoints/index.js +885 -0
- package/runtime/plugins/picasso-checkpoints/package.json +29 -0
- package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
- package/runtime/plugins/picasso-commands/index.js +497 -0
- package/runtime/plugins/picasso-commands/package.json +28 -0
- package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
- package/runtime/plugins/picasso-instructions/formats.js +145 -0
- package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
- package/runtime/plugins/picasso-instructions/glob.js +114 -0
- package/runtime/plugins/picasso-instructions/globals.js +90 -0
- package/runtime/plugins/picasso-instructions/imports.js +123 -0
- package/runtime/plugins/picasso-instructions/index.js +326 -0
- package/runtime/plugins/picasso-instructions/modes.js +64 -0
- package/runtime/plugins/picasso-instructions/package.json +30 -0
- package/runtime/plugins/picasso-instructions/parse.js +134 -0
- package/runtime/plugins/picasso-instructions/report.js +161 -0
- package/runtime/plugins/picasso-instructions/resolve.js +939 -0
- package/runtime/plugins/picasso-instructions/scan.js +181 -0
- package/runtime/plugins/picasso-instructions/settings.js +150 -0
- package/runtime/plugins/picasso-instructions/skills.js +345 -0
- package/runtime/plugins/picasso-lean-context/index.js +6049 -0
- package/runtime/plugins/picasso-lean-context/package.json +26 -0
- package/runtime/plugins/picasso-lean-context/timeline.js +417 -0
- package/runtime/plugins/picasso-librarian/classify.js +146 -0
- package/runtime/plugins/picasso-librarian/index.js +878 -0
- package/runtime/plugins/picasso-librarian/notes.js +159 -0
- package/runtime/plugins/picasso-librarian/package.json +34 -0
- package/runtime/plugins/picasso-librarian/state.js +478 -0
- package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
- package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
- package/runtime/plugins/picasso-mail/inbox.js +207 -0
- package/runtime/plugins/picasso-mail/index.js +293 -0
- package/runtime/plugins/picasso-mail/package.json +22 -0
- package/runtime/plugins/picasso-memory/index.js +1184 -0
- package/runtime/plugins/picasso-memory/package.json +21 -0
- package/runtime/plugins/picasso-model-router/connections.js +895 -0
- package/runtime/plugins/picasso-model-router/index.js +1081 -0
- package/runtime/plugins/picasso-model-router/package.json +30 -0
- package/runtime/plugins/picasso-options/index.js +263 -0
- package/runtime/plugins/picasso-options/package.json +28 -0
- package/runtime/plugins/picasso-progress-reports/index.js +267 -0
- package/runtime/plugins/picasso-progress-reports/package.json +30 -0
- package/runtime/plugins/picasso-progress-reports/report.js +235 -0
- package/runtime/plugins/picasso-provider-models/index.js +436 -0
- package/runtime/plugins/picasso-provider-models/package.json +28 -0
- package/runtime/plugins/picasso-repo-index/index.js +1850 -0
- package/runtime/plugins/picasso-repo-index/package.json +28 -0
- package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
- package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
- package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
- package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
- package/runtime/plugins/picasso-trackers/index.js +895 -0
- package/runtime/plugins/picasso-trackers/package.json +28 -0
- package/runtime/plugins/picasso-web-search/backends.js +350 -0
- package/runtime/plugins/picasso-web-search/config.js +121 -0
- package/runtime/plugins/picasso-web-search/failure.js +111 -0
- package/runtime/plugins/picasso-web-search/format.js +35 -0
- package/runtime/plugins/picasso-web-search/index.js +66 -0
- package/runtime/plugins/picasso-web-search/package.json +38 -0
- package/runtime/plugins/picasso-web-search/router.js +155 -0
- package/runtime/plugins/picasso-x-reader/circle.js +324 -0
- package/runtime/plugins/picasso-x-reader/command.js +169 -0
- package/runtime/plugins/picasso-x-reader/index.js +170 -0
- package/runtime/plugins/picasso-x-reader/package.json +39 -0
- package/runtime/plugins/picasso-x-reader/read.js +370 -0
- package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
- package/runtime/plugins/picasso-x-reader/settings.js +131 -0
- package/runtime/plugins/picasso-x-reader/urls.js +154 -0
- package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
- package/runtime/relay/attachment-text.mjs +737 -0
- package/runtime/relay/companion/companion.css +126 -0
- package/runtime/relay/companion/companion.js +648 -0
- package/runtime/relay/companion/icon.svg +5 -0
- package/runtime/relay/companion/index.html +25 -0
- package/runtime/relay/companion/manifest.json +13 -0
- package/runtime/relay/companion/sw.js +41 -0
- package/runtime/relay/main.mjs +37252 -0
- package/runtime/relay/model-listing.mjs +614 -0
- package/runtime/relay/versions-routes.mjs +1198 -0
- package/runtime/verify-plugins.mjs +205 -0
- package/runtime-lock/package-lock.json +10779 -0
- package/runtime-lock/package.json +7 -0
- package/scripts/install-runtime.mjs +400 -0
- package/README.md +0 -3
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// The search backends: each one turns a query into `{ sources, truncated: false }` or throws a BackendFailure.
|
|
2
|
+
//
|
|
3
|
+
// deepseek the engine's own DeepSeek search providers (`deepseek-search-api`, else `deepseek-official`), reused
|
|
4
|
+
// through the web seam registry so the account sign-in / API key handling stays the engine's
|
|
5
|
+
// anthropic Messages API with the server-side `web_search_20250305` tool
|
|
6
|
+
// openai Responses API with the hosted `web_search` tool
|
|
7
|
+
// google Gemini `generateContent` with `google_search` grounding
|
|
8
|
+
// prism the owner's optional Prism service: the same Messages server-tool call, answered by Prism itself
|
|
9
|
+
//
|
|
10
|
+
// "Native" means the backend whose id the route maps to (NATIVE_ROUTES); any backend can also be a configured
|
|
11
|
+
// fallback. Results carry only structured fields (url, title, snippet, publishedAt); provider prose is never an answer.
|
|
12
|
+
import { BackendFailure, classifyEngineError, classifyHttp } from './failure.js';
|
|
13
|
+
|
|
14
|
+
export const BACKEND_NAMES = Object.freeze({ deepseek: 'DeepSeek', anthropic: 'Anthropic', openai: 'OpenAI', google: 'Google', prism: 'Prism' });
|
|
15
|
+
|
|
16
|
+
/** Route ids (as the engine names the thread's provider route) that have a native search backend. */
|
|
17
|
+
export const NATIVE_ROUTES = Object.freeze({
|
|
18
|
+
'deepseek-official': 'deepseek',
|
|
19
|
+
'deepseek-account': 'deepseek',
|
|
20
|
+
anthropic: 'anthropic',
|
|
21
|
+
openai: 'openai',
|
|
22
|
+
google: 'google',
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/** The credential reference each route's key resolves through (the `apiKeyEnv` of dsh/picasso-runtime.cordis.yml). */
|
|
26
|
+
export const KEY_REFS = Object.freeze({ anthropic: 'ANTHROPIC_API_KEY', openai: 'OPENAI_API_KEY', google: 'GOOGLE_API_KEY', deepseek: 'DEEPSEEK_API_KEY' });
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_BASE_URLS = Object.freeze({
|
|
29
|
+
anthropic: 'https://api.anthropic.com',
|
|
30
|
+
openai: 'https://api.openai.com/v1',
|
|
31
|
+
google: 'https://generativelanguage.googleapis.com/v1beta',
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
/** Models used when a backend is a configured fallback (a native search uses the thread's own model). Overridable. */
|
|
35
|
+
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' });
|
|
36
|
+
|
|
37
|
+
const ANTHROPIC_VERSION = '2023-06-01';
|
|
38
|
+
const USER_AGENT = 'picasso-web-search/0.1';
|
|
39
|
+
const MAX_USES = 2;
|
|
40
|
+
const MAX_TOKENS = 2048;
|
|
41
|
+
const BODY_PEEK_BYTES = 4096;
|
|
42
|
+
const SNIPPET_MAX = 280;
|
|
43
|
+
|
|
44
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
45
|
+
const str = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
|
|
46
|
+
const prompt = (query) => `Perform a web search for the query: ${query}`;
|
|
47
|
+
|
|
48
|
+
/** `{ url, title?, snippet?, publishedAt? }` with absent fields omitted; null when the url is not http(s). */
|
|
49
|
+
function source(url, title, snippet, publishedAt) {
|
|
50
|
+
const link = str(url);
|
|
51
|
+
if (link === undefined || !/^https?:\/\//iu.test(link)) return null;
|
|
52
|
+
const clean = snippet === undefined ? undefined : str(snippet.replace(/\s+/gu, ' '));
|
|
53
|
+
return {
|
|
54
|
+
url: link,
|
|
55
|
+
...(str(title) === undefined ? {} : { title: str(title) }),
|
|
56
|
+
...(clean === undefined ? {} : { snippet: clean.length <= SNIPPET_MAX ? clean : `${clean.slice(0, SNIPPET_MAX - 1)}…` }),
|
|
57
|
+
...(str(publishedAt) === undefined ? {} : { publishedAt: str(publishedAt) }),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function dedupe(list) {
|
|
62
|
+
const seen = new Set();
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const item of list) {
|
|
65
|
+
if (item === null || seen.has(item.url)) continue;
|
|
66
|
+
seen.add(item.url);
|
|
67
|
+
out.push(item);
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
73
|
+
// HTTP
|
|
74
|
+
|
|
75
|
+
/** Up to BODY_PEEK_BYTES of an error body as text; the rest is cancelled unread, so a huge body costs no memory. */
|
|
76
|
+
async function peekBody(response) {
|
|
77
|
+
const reader = response.body?.getReader?.();
|
|
78
|
+
if (reader === undefined) return '';
|
|
79
|
+
const chunks = [];
|
|
80
|
+
let size = 0;
|
|
81
|
+
try {
|
|
82
|
+
while (size < BODY_PEEK_BYTES) {
|
|
83
|
+
const { done, value } = await reader.read();
|
|
84
|
+
if (done) break;
|
|
85
|
+
chunks.push(value);
|
|
86
|
+
size += value.byteLength;
|
|
87
|
+
}
|
|
88
|
+
} catch {
|
|
89
|
+
// An unreadable body classifies by status alone.
|
|
90
|
+
} finally {
|
|
91
|
+
reader.cancel().catch(() => {});
|
|
92
|
+
}
|
|
93
|
+
const bytes = new Uint8Array(Math.min(size, BODY_PEEK_BYTES));
|
|
94
|
+
let offset = 0;
|
|
95
|
+
for (const chunk of chunks) {
|
|
96
|
+
if (offset >= bytes.byteLength) break;
|
|
97
|
+
const part = chunk.subarray(0, bytes.byteLength - offset);
|
|
98
|
+
bytes.set(part, offset);
|
|
99
|
+
offset += part.byteLength;
|
|
100
|
+
}
|
|
101
|
+
return new TextDecoder().decode(bytes);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function postJson(fetchImpl, url, headers, body, signal) {
|
|
105
|
+
const response = await fetchImpl(url, {
|
|
106
|
+
method: 'POST',
|
|
107
|
+
redirect: 'error',
|
|
108
|
+
headers: { 'content-type': 'application/json', accept: 'application/json', 'user-agent': USER_AGENT, ...headers },
|
|
109
|
+
body: JSON.stringify(body),
|
|
110
|
+
...(signal === undefined ? {} : { signal }),
|
|
111
|
+
});
|
|
112
|
+
if (!response.ok) {
|
|
113
|
+
const peek = await peekBody(response);
|
|
114
|
+
// The body is read only to tell a billing refusal from other 4xx; it is dropped, never shown.
|
|
115
|
+
throw classifyHttp(response.status, peek, response.headers?.get?.('retry-after') ?? undefined);
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
return await response.json();
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (signal?.aborted === true) throw error;
|
|
121
|
+
throw new BackendFailure('unreadable');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
126
|
+
// Anthropic Messages server-tool shape (Anthropic, and Prism which answers the same call itself)
|
|
127
|
+
|
|
128
|
+
function messagesError(code) {
|
|
129
|
+
switch (code) {
|
|
130
|
+
case 'too_many_requests':
|
|
131
|
+
return new BackendFailure('rate');
|
|
132
|
+
case 'unavailable':
|
|
133
|
+
return new BackendFailure('server');
|
|
134
|
+
case 'outcome_unknown':
|
|
135
|
+
return new BackendFailure('outcome-unknown');
|
|
136
|
+
default:
|
|
137
|
+
return new BackendFailure('rejected');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Sources of a Messages response: `web_search_tool_result` blocks, snippets from the text blocks' citations. */
|
|
142
|
+
export function parseMessagesSearch(json) {
|
|
143
|
+
const blocks = isRecord(json) && Array.isArray(json.content) ? json.content : [];
|
|
144
|
+
const results = blocks.filter((block) => isRecord(block) && block.type === 'web_search_tool_result');
|
|
145
|
+
if (results.length === 0) throw new BackendFailure('empty');
|
|
146
|
+
const snippets = new Map();
|
|
147
|
+
for (const block of blocks) {
|
|
148
|
+
if (!isRecord(block) || block.type !== 'text' || !Array.isArray(block.citations)) continue;
|
|
149
|
+
for (const cite of block.citations) {
|
|
150
|
+
if (isRecord(cite) && str(cite.url) !== undefined && str(cite.cited_text) !== undefined && !snippets.has(cite.url)) snippets.set(cite.url, cite.cited_text);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const found = [];
|
|
154
|
+
for (const block of results) {
|
|
155
|
+
const content = block.content;
|
|
156
|
+
if (isRecord(content) && content.type === 'web_search_tool_result_error') throw messagesError(content.error_code);
|
|
157
|
+
if (!Array.isArray(content)) continue;
|
|
158
|
+
for (const item of content) {
|
|
159
|
+
if (isRecord(item) && item.type === 'web_search_result') found.push(source(item.url, item.title, snippets.get(item.url), item.page_age));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return { sources: dedupe(found), truncated: false };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function messagesBody(model, query) {
|
|
166
|
+
return {
|
|
167
|
+
model,
|
|
168
|
+
max_tokens: MAX_TOKENS,
|
|
169
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: prompt(query) }] }],
|
|
170
|
+
tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: MAX_USES }],
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
175
|
+
// OpenAI Responses
|
|
176
|
+
|
|
177
|
+
/** The sentence an annotation ends, as plain text: markdown links and bare citations removed. */
|
|
178
|
+
function sentenceBefore(text, index) {
|
|
179
|
+
const head = text.slice(0, Math.max(0, index));
|
|
180
|
+
const start = Math.max(head.lastIndexOf('. '), head.lastIndexOf('\n'), -1) + 1;
|
|
181
|
+
return head
|
|
182
|
+
.slice(start)
|
|
183
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/gu, '$1')
|
|
184
|
+
.replace(/\(\s*\)/gu, '')
|
|
185
|
+
.replace(/^[\s.\-*•]+/u, '')
|
|
186
|
+
.trim();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function parseOpenAiSearch(json) {
|
|
190
|
+
const output = isRecord(json) && Array.isArray(json.output) ? json.output : [];
|
|
191
|
+
if (!output.some((item) => isRecord(item) && item.type === 'web_search_call')) throw new BackendFailure('empty');
|
|
192
|
+
const found = [];
|
|
193
|
+
for (const item of output) {
|
|
194
|
+
if (!isRecord(item) || item.type !== 'message' || !Array.isArray(item.content)) continue;
|
|
195
|
+
for (const part of item.content) {
|
|
196
|
+
if (!isRecord(part) || part.type !== 'output_text' || !Array.isArray(part.annotations)) continue;
|
|
197
|
+
const text = typeof part.text === 'string' ? part.text : '';
|
|
198
|
+
for (const note of part.annotations) {
|
|
199
|
+
if (!isRecord(note) || note.type !== 'url_citation') continue;
|
|
200
|
+
const snippet = Number.isInteger(note.start_index) ? sentenceBefore(text, note.start_index) : '';
|
|
201
|
+
found.push(source(note.url, note.title, snippet === '' ? undefined : snippet));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return { sources: dedupe(found), truncated: false };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
209
|
+
// Gemini grounding
|
|
210
|
+
|
|
211
|
+
export function parseGeminiSearch(json) {
|
|
212
|
+
const candidates = isRecord(json) && Array.isArray(json.candidates) ? json.candidates : [];
|
|
213
|
+
const grounding = candidates.map((candidate) => (isRecord(candidate) ? candidate.groundingMetadata : undefined)).find(isRecord);
|
|
214
|
+
if (grounding === undefined) throw new BackendFailure('empty');
|
|
215
|
+
const chunks = Array.isArray(grounding.groundingChunks) ? grounding.groundingChunks : [];
|
|
216
|
+
const snippets = new Map();
|
|
217
|
+
for (const support of Array.isArray(grounding.groundingSupports) ? grounding.groundingSupports : []) {
|
|
218
|
+
const segment = isRecord(support) && isRecord(support.segment) ? str(support.segment.text) : undefined;
|
|
219
|
+
if (segment === undefined || !Array.isArray(support.groundingChunkIndices)) continue;
|
|
220
|
+
for (const index of support.groundingChunkIndices) if (!snippets.has(index)) snippets.set(index, segment);
|
|
221
|
+
}
|
|
222
|
+
const found = chunks.map((chunk, index) => (isRecord(chunk) && isRecord(chunk.web) ? source(chunk.web.uri, chunk.web.title, snippets.get(index)) : null));
|
|
223
|
+
return { sources: dedupe(found), truncated: false };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
227
|
+
// Credentials
|
|
228
|
+
|
|
229
|
+
/** Per-search credential reads through the engine's credential seam; the process environment when it is absent. */
|
|
230
|
+
export function credentialsFrom(ctx, env = process.env) {
|
|
231
|
+
const service = () => ctx?.get?.('credentials');
|
|
232
|
+
return {
|
|
233
|
+
async resolve(ref) {
|
|
234
|
+
try {
|
|
235
|
+
const credentials = service();
|
|
236
|
+
if (credentials !== undefined) return str((await credentials.resolve(ref))?.value);
|
|
237
|
+
return str(env[ref]);
|
|
238
|
+
} catch {
|
|
239
|
+
throw new BackendFailure('credentials');
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
async configured(ref) {
|
|
243
|
+
try {
|
|
244
|
+
const credentials = service();
|
|
245
|
+
if (credentials !== undefined) return (await credentials.describe(ref))?.configured === true;
|
|
246
|
+
return str(env[ref]) !== undefined;
|
|
247
|
+
} catch {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
255
|
+
// The backends
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* `deps`: `{ creds, fetch, getWeb }`. Every backend answers:
|
|
259
|
+
* `configured(call)` whether a search could be sent (a credential or an engine provider is present); no network
|
|
260
|
+
* `search(request, call)` `call = { signal, route, model, role, config }`
|
|
261
|
+
*/
|
|
262
|
+
export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, getWeb = () => undefined }) {
|
|
263
|
+
const modelFor = (id, call) => call.config.models[id] ?? (call.role === 'native' && str(call.model) !== undefined ? str(call.model) : DEFAULT_MODELS[id]);
|
|
264
|
+
const baseFor = (id, call) => call.config.baseUrls[id] ?? DEFAULT_BASE_URLS[id];
|
|
265
|
+
const keyed = (id) => async (call) => (await creds.configured(KEY_REFS[id])) && Boolean(baseFor(id, call));
|
|
266
|
+
const requireKey = async (id) => {
|
|
267
|
+
const key = await creds.resolve(KEY_REFS[id]);
|
|
268
|
+
if (key === undefined) throw new BackendFailure('credentials');
|
|
269
|
+
return key;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const engineProvider = () => {
|
|
273
|
+
const registry = getWeb()?.searchProviders;
|
|
274
|
+
if (!(registry instanceof Map)) return undefined;
|
|
275
|
+
return registry.get('deepseek-search-api') ?? registry.get('deepseek-official');
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
return {
|
|
279
|
+
deepseek: {
|
|
280
|
+
id: 'deepseek',
|
|
281
|
+
name: BACKEND_NAMES.deepseek,
|
|
282
|
+
async configured(call) {
|
|
283
|
+
const provider = engineProvider();
|
|
284
|
+
if (provider === undefined) return false;
|
|
285
|
+
try {
|
|
286
|
+
const route = call.role === 'native' ? call.route : 'deepseek-official';
|
|
287
|
+
return provider.available() && (await (provider.ready?.(route) ?? true)) !== false;
|
|
288
|
+
} catch {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
async search(request, call) {
|
|
293
|
+
const provider = engineProvider();
|
|
294
|
+
if (provider === undefined) throw new BackendFailure('credentials');
|
|
295
|
+
try {
|
|
296
|
+
return await provider.search({ query: request.query, ...(request.maxResults === undefined ? {} : { maxResults: request.maxResults }) }, call.signal);
|
|
297
|
+
} catch (error) {
|
|
298
|
+
if (call.signal?.aborted === true || error?.code === 'WEB_ABORTED') throw error;
|
|
299
|
+
throw classifyEngineError(error);
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
},
|
|
303
|
+
anthropic: {
|
|
304
|
+
id: 'anthropic',
|
|
305
|
+
name: BACKEND_NAMES.anthropic,
|
|
306
|
+
configured: keyed('anthropic'),
|
|
307
|
+
async search(request, call) {
|
|
308
|
+
const key = await requireKey('anthropic');
|
|
309
|
+
const json = await postJson(fetchImpl, `${baseFor('anthropic', call)}/v1/messages`, { 'x-api-key': key, 'anthropic-version': ANTHROPIC_VERSION }, messagesBody(modelFor('anthropic', call), request.query), call.signal);
|
|
310
|
+
return parseMessagesSearch(json);
|
|
311
|
+
},
|
|
312
|
+
},
|
|
313
|
+
openai: {
|
|
314
|
+
id: 'openai',
|
|
315
|
+
name: BACKEND_NAMES.openai,
|
|
316
|
+
configured: keyed('openai'),
|
|
317
|
+
async search(request, call) {
|
|
318
|
+
const key = await requireKey('openai');
|
|
319
|
+
const body = { model: modelFor('openai', call), input: prompt(request.query), tools: [{ type: 'web_search' }], tool_choice: 'required', store: false };
|
|
320
|
+
return parseOpenAiSearch(await postJson(fetchImpl, `${baseFor('openai', call)}/responses`, { authorization: `Bearer ${key}` }, body, call.signal));
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
google: {
|
|
324
|
+
id: 'google',
|
|
325
|
+
name: BACKEND_NAMES.google,
|
|
326
|
+
configured: keyed('google'),
|
|
327
|
+
async search(request, call) {
|
|
328
|
+
const key = await requireKey('google');
|
|
329
|
+
const model = encodeURIComponent(modelFor('google', call).replace(/^models\//u, ''));
|
|
330
|
+
const body = { contents: [{ role: 'user', parts: [{ text: prompt(request.query) }] }], tools: [{ google_search: {} }] };
|
|
331
|
+
return parseGeminiSearch(await postJson(fetchImpl, `${baseFor('google', call)}/models/${model}:generateContent`, { 'x-goog-api-key': key }, body, call.signal));
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
prism: {
|
|
335
|
+
id: 'prism',
|
|
336
|
+
name: BACKEND_NAMES.prism,
|
|
337
|
+
// Optional: active only when both an endpoint and a key are configured. Absent is skipped silently.
|
|
338
|
+
async configured(call) {
|
|
339
|
+
return call.config.prismUrl !== undefined && (await creds.configured(call.config.prismKeyRef));
|
|
340
|
+
},
|
|
341
|
+
async search(request, call) {
|
|
342
|
+
const key = await creds.resolve(call.config.prismKeyRef);
|
|
343
|
+
if (key === undefined || call.config.prismUrl === undefined) throw new BackendFailure('credentials');
|
|
344
|
+
const headers = { 'x-api-key': key, authorization: `Bearer ${key}`, 'anthropic-version': ANTHROPIC_VERSION };
|
|
345
|
+
const json = await postJson(fetchImpl, `${call.config.prismUrl}/v1/messages`, headers, messagesBody(call.config.models.prism ?? DEFAULT_MODELS.prism, request.query), call.signal);
|
|
346
|
+
return parseMessagesSearch(json);
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
};
|
|
350
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Where the fallback list and the optional endpoints come from. Nothing here is assumed: an empty list is the default,
|
|
2
|
+
// and a backend whose endpoint or key is absent is left out silently (never an error).
|
|
3
|
+
//
|
|
4
|
+
// env (wins) settings.json `settings.webSearch` (read live, mtime cached)
|
|
5
|
+
// PICASSO_WEB_SEARCH_FALLBACKS=prism,... { fallbacks: ['prism', ...] | 'prism,...' }
|
|
6
|
+
// PICASSO_WEB_SEARCH_PRISM_URL=https://… { prismUrl: 'https://…' }
|
|
7
|
+
// PICASSO_WEB_SEARCH_PRISM_KEY_ENV=NAME (credential reference of the Prism key; default PRISM_API_KEY)
|
|
8
|
+
// PICASSO_WEB_SEARCH_<ANTHROPIC|OPENAI|GOOGLE>_BASE_URL / _MODEL endpoint and model when that backend is a fallback
|
|
9
|
+
// PICASSO_WEB_SEARCH_TIMEOUT_MS per-backend time limit (default 20000)
|
|
10
|
+
//
|
|
11
|
+
// Keys are never read here: each backend resolves its key per search through the engine's credential seam.
|
|
12
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
|
|
16
|
+
/** Backends a fallback entry may name, in the vocabulary of the list (`gemini` is an alias of `google`). */
|
|
17
|
+
export const FALLBACK_IDS = Object.freeze(['deepseek', 'anthropic', 'openai', 'google', 'prism']);
|
|
18
|
+
const ALIASES = Object.freeze({ gemini: 'google' });
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_TIMEOUT_MS = 20_000;
|
|
21
|
+
export const DEFAULT_PRISM_KEY_REF = 'PRISM_API_KEY';
|
|
22
|
+
|
|
23
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
24
|
+
|
|
25
|
+
/** `PICASSO_SETTINGS_ROOT ?? <PICASSO_HOME ?? ~/.picasso>/settings`/settings.json (the file every client shares). */
|
|
26
|
+
export function defaultSettingsFile(env = process.env) {
|
|
27
|
+
const root = typeof env.PICASSO_SETTINGS_ROOT === 'string' && env.PICASSO_SETTINGS_ROOT.trim() !== '' ? env.PICASSO_SETTINGS_ROOT : undefined;
|
|
28
|
+
if (root) return join(root, 'settings.json');
|
|
29
|
+
const home = typeof env.PICASSO_HOME === 'string' && env.PICASSO_HOME.trim() !== '' ? env.PICASSO_HOME : join(env.HOME ?? homedir(), '.picasso');
|
|
30
|
+
return join(home, 'settings', 'settings.json');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The ordered, deduplicated fallback ids from a comma/space list or an array; unknown names are dropped. */
|
|
34
|
+
export function parseFallbackList(raw) {
|
|
35
|
+
const items = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(/[\s,]+/u) : [];
|
|
36
|
+
const out = [];
|
|
37
|
+
for (const item of items) {
|
|
38
|
+
if (typeof item !== 'string') continue;
|
|
39
|
+
const key = item.trim().toLowerCase();
|
|
40
|
+
const id = ALIASES[key] ?? key;
|
|
41
|
+
if (FALLBACK_IDS.includes(id) && !out.includes(id)) out.push(id);
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A base URL that is safe to send a key to: https, or http on loopback. No credentials, query or fragment. */
|
|
47
|
+
export function safeBaseUrl(raw) {
|
|
48
|
+
if (typeof raw !== 'string' || raw.trim() === '') return undefined;
|
|
49
|
+
let url;
|
|
50
|
+
try {
|
|
51
|
+
url = new URL(raw.trim());
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
if (url.username !== '' || url.password !== '') return undefined;
|
|
56
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(url.hostname);
|
|
57
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return undefined;
|
|
58
|
+
url.search = '';
|
|
59
|
+
url.hash = '';
|
|
60
|
+
return url.toString().replace(/\/+$/u, '');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const text = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
|
|
64
|
+
|
|
65
|
+
/** The effective configuration from a parsed settings file and the environment (env wins). */
|
|
66
|
+
export function webSearchConfig(file, env = process.env) {
|
|
67
|
+
const settings = isRecord(file) && isRecord(file.settings) ? file.settings : {};
|
|
68
|
+
const stored = isRecord(settings.webSearch) ? settings.webSearch : {};
|
|
69
|
+
const fromEnv = text(env.PICASSO_WEB_SEARCH_FALLBACKS);
|
|
70
|
+
const listed = fromEnv !== undefined ? parseFallbackList(fromEnv) : parseFallbackList(stored.fallbacks);
|
|
71
|
+
const timeout = Number(env.PICASSO_WEB_SEARCH_TIMEOUT_MS);
|
|
72
|
+
const baseUrls = {};
|
|
73
|
+
const models = {};
|
|
74
|
+
for (const id of ['anthropic', 'openai', 'google']) {
|
|
75
|
+
const upper = id.toUpperCase();
|
|
76
|
+
const base = safeBaseUrl(env[`PICASSO_WEB_SEARCH_${upper}_BASE_URL`]);
|
|
77
|
+
if (base !== undefined) baseUrls[id] = base;
|
|
78
|
+
const model = text(env[`PICASSO_WEB_SEARCH_${upper}_MODEL`]);
|
|
79
|
+
if (model !== undefined) models[id] = model;
|
|
80
|
+
}
|
|
81
|
+
const prismUrl = safeBaseUrl(text(env.PICASSO_WEB_SEARCH_PRISM_URL) ?? stored.prismUrl);
|
|
82
|
+
const prismKeyRef = text(env.PICASSO_WEB_SEARCH_PRISM_KEY_ENV);
|
|
83
|
+
// No list anywhere but a Prism endpoint is configured: setting that endpoint is the opt-in, so Prism is tried when the
|
|
84
|
+
// native search fails. Without an endpoint nothing is assumed and the list stays empty.
|
|
85
|
+
const unlisted = fromEnv === undefined && stored.fallbacks === undefined;
|
|
86
|
+
const fallbacks = unlisted && prismUrl !== undefined ? ['prism'] : listed;
|
|
87
|
+
return {
|
|
88
|
+
fallbacks,
|
|
89
|
+
baseUrls,
|
|
90
|
+
models,
|
|
91
|
+
...(prismUrl === undefined ? {} : { prismUrl }),
|
|
92
|
+
prismKeyRef: prismKeyRef !== undefined && /^[A-Za-z_][A-Za-z0-9_]*$/u.test(prismKeyRef) ? prismKeyRef : DEFAULT_PRISM_KEY_REF,
|
|
93
|
+
timeoutMs: Number.isFinite(timeout) && timeout >= 1000 ? Math.min(timeout, 120_000) : DEFAULT_TIMEOUT_MS,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A live reader over the settings file: re-parsed only when its mtime changes; unreadable reads as defaults. */
|
|
98
|
+
export function configReader({ settingsFile, env = process.env } = {}) {
|
|
99
|
+
const file = typeof settingsFile === 'string' && settingsFile !== '' ? settingsFile : defaultSettingsFile(env);
|
|
100
|
+
let mtime;
|
|
101
|
+
let cached = webSearchConfig(undefined, env);
|
|
102
|
+
return () => {
|
|
103
|
+
let stat;
|
|
104
|
+
try {
|
|
105
|
+
stat = statSync(file);
|
|
106
|
+
} catch {
|
|
107
|
+
mtime = undefined;
|
|
108
|
+
cached = webSearchConfig(undefined, env);
|
|
109
|
+
return cached;
|
|
110
|
+
}
|
|
111
|
+
if (stat.mtimeMs !== mtime) {
|
|
112
|
+
mtime = stat.mtimeMs;
|
|
113
|
+
try {
|
|
114
|
+
cached = webSearchConfig(JSON.parse(readFileSync(file, 'utf8')), env);
|
|
115
|
+
} catch {
|
|
116
|
+
cached = webSearchConfig(undefined, env);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return cached;
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Picasso web search routing — one bundle patch layer row (loader insert).
|
|
2
|
+
# The row only registers the `picasso-web-search` provider with the web seam; the seam's `searchProvider` pin
|
|
3
|
+
# (`dsh/picasso-ecosystem.cordis.patch.yml` on the CLI, `PICASSO_WEB_SEARCH_ROWS` in the Mac relay) selects it.
|
|
4
|
+
# Fallbacks are configured with PICASSO_WEB_SEARCH_FALLBACKS or `settings.webSearch` (see README.md).
|
|
5
|
+
- insert:
|
|
6
|
+
- id: picasso-web-search
|
|
7
|
+
name: '@picasso/web-search'
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// How a backend failure is classified: one closed vocabulary of reasons, whatever the provider said. The reason text
|
|
2
|
+
// is what the model and the person read, so it never carries a response body, a URL, a key or a request id.
|
|
3
|
+
|
|
4
|
+
/** Kinds that are billing or authorisation problems: the backend is not tried again for the rest of the session. */
|
|
5
|
+
export const PERMANENT_KINDS = Object.freeze(new Set(['billing', 'auth', 'forbidden']));
|
|
6
|
+
/** Kinds that get one bounded retry (honouring Retry-After). */
|
|
7
|
+
export const TRANSIENT_KINDS = Object.freeze(new Set(['rate', 'server']));
|
|
8
|
+
|
|
9
|
+
export class BackendFailure extends Error {
|
|
10
|
+
/**
|
|
11
|
+
* @param {string} kind billing | auth | forbidden | rate | server | rejected | credentials | empty | unreadable | network | outcome-unknown | timeout
|
|
12
|
+
* @param {{status?: number, retryAfterMs?: number}} [detail]
|
|
13
|
+
*/
|
|
14
|
+
constructor(kind, detail = {}) {
|
|
15
|
+
super(`web search backend failed: ${kind}`);
|
|
16
|
+
this.name = 'BackendFailure';
|
|
17
|
+
this.kind = kind;
|
|
18
|
+
if (detail.status !== undefined) this.status = detail.status;
|
|
19
|
+
if (detail.retryAfterMs !== undefined) this.retryAfterMs = detail.retryAfterMs;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
get permanent() {
|
|
23
|
+
return PERMANENT_KINDS.has(this.kind);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
get transient() {
|
|
27
|
+
return TRANSIENT_KINDS.has(this.kind);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The closed-vocabulary reason shown to the model and the person. */
|
|
31
|
+
get reason() {
|
|
32
|
+
return reasonFor(this.kind, this.status, this.retryAfterMs);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const withStatus = (label, status) => (status === undefined ? label : `${label} (HTTP ${status})`);
|
|
37
|
+
|
|
38
|
+
export function reasonFor(kind, status, retryAfterMs) {
|
|
39
|
+
switch (kind) {
|
|
40
|
+
case 'billing':
|
|
41
|
+
return withStatus('insufficient balance or billing problem', status);
|
|
42
|
+
case 'auth':
|
|
43
|
+
return withStatus('credentials rejected', status);
|
|
44
|
+
case 'forbidden':
|
|
45
|
+
return withStatus('access denied', status);
|
|
46
|
+
case 'rate':
|
|
47
|
+
return `${withStatus('rate limited', status)}${retryAfterMs === undefined ? '' : `, retry after ${Math.ceil(retryAfterMs / 1000)}s`}`;
|
|
48
|
+
case 'server':
|
|
49
|
+
return withStatus('service error', status);
|
|
50
|
+
case 'rejected':
|
|
51
|
+
return withStatus('request rejected', status);
|
|
52
|
+
case 'credentials':
|
|
53
|
+
return 'no credentials';
|
|
54
|
+
case 'empty':
|
|
55
|
+
return 'returned no search results block';
|
|
56
|
+
case 'unreadable':
|
|
57
|
+
return 'returned an unreadable response';
|
|
58
|
+
case 'outcome-unknown':
|
|
59
|
+
return 'outcome unknown (the search may have run; not retried)';
|
|
60
|
+
case 'timeout':
|
|
61
|
+
return 'timed out';
|
|
62
|
+
case 'network':
|
|
63
|
+
return 'network error';
|
|
64
|
+
default:
|
|
65
|
+
return 'failed';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const BILLING_BODY = /insufficient[ _-]?(?:quota|balance|funds|credit)|credit balance is too low|payment required|billing|exceeded your current quota/iu;
|
|
70
|
+
const AUTH_BODY = /api key not valid|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|authentication/iu;
|
|
71
|
+
|
|
72
|
+
/** Seconds (or an HTTP date) in a Retry-After header, as milliseconds; undefined when absent or unusable. */
|
|
73
|
+
export function retryAfterMs(header, now = Date.now()) {
|
|
74
|
+
if (header === null || header === undefined) return undefined;
|
|
75
|
+
const text = String(header).trim();
|
|
76
|
+
if (text === '') return undefined;
|
|
77
|
+
if (/^\d+(?:\.\d+)?$/u.test(text)) return Math.round(Number(text) * 1000);
|
|
78
|
+
const date = Date.parse(text);
|
|
79
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - now);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Classify an HTTP failure from its status and (never surfaced) body text. */
|
|
83
|
+
export function classifyHttp(status, bodyText = '', retryAfterHeader) {
|
|
84
|
+
const body = typeof bodyText === 'string' ? bodyText : '';
|
|
85
|
+
const retry = retryAfterMs(retryAfterHeader);
|
|
86
|
+
const detail = { status, ...(retry === undefined ? {} : { retryAfterMs: retry }) };
|
|
87
|
+
if (status === 402) return new BackendFailure('billing', detail);
|
|
88
|
+
if ([400, 403, 429].includes(status) && BILLING_BODY.test(body)) return new BackendFailure('billing', detail);
|
|
89
|
+
if (status === 401) return new BackendFailure('auth', detail);
|
|
90
|
+
if (status === 400 && AUTH_BODY.test(body)) return new BackendFailure('auth', detail);
|
|
91
|
+
if (status === 403) return new BackendFailure('forbidden', detail);
|
|
92
|
+
if (status === 429) return new BackendFailure('rate', detail);
|
|
93
|
+
if (status >= 500) return new BackendFailure('server', detail);
|
|
94
|
+
return new BackendFailure('rejected', detail);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Classify an error thrown by an engine-registered provider (a `WebError`: stable `code`, a message that may carry
|
|
99
|
+
* the provider's own text). Only the code and an `HTTP <status>` figure are read from it; the text is dropped.
|
|
100
|
+
*/
|
|
101
|
+
export function classifyEngineError(error) {
|
|
102
|
+
if (error instanceof BackendFailure) return error;
|
|
103
|
+
const code = typeof error?.code === 'string' ? error.code : '';
|
|
104
|
+
if (code === 'WEB_PROVIDER_CREDENTIAL_MISSING') return new BackendFailure('credentials');
|
|
105
|
+
const message = typeof error?.message === 'string' ? error.message : '';
|
|
106
|
+
const status = /\bHTTP (\d{3})\b/u.exec(message);
|
|
107
|
+
if (status !== null) return classifyHttp(Number(status[1]), message);
|
|
108
|
+
if (/no web_search_tool_result|no search result/iu.test(message)) return new BackendFailure('empty');
|
|
109
|
+
if (/credential resolution failed|has no (?:API key|credential)/iu.test(message)) return new BackendFailure('credentials');
|
|
110
|
+
return new BackendFailure('network');
|
|
111
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The text contract the surfaces read. The plugin writes these two shapes into the tool result; the Mac and the
|
|
2
|
+
// TUI parse them back (`packages/shared/src/search-backend.ts` and its Swift twin) from the shared fixture
|
|
3
|
+
// `packages/shared/test/fixtures/search-backend/cases.json`, so a change here is a change there.
|
|
4
|
+
//
|
|
5
|
+
// fallback answered -> the result's `content` starts with one line: Search backend: <Name> (fallback)
|
|
6
|
+
// nothing answered -> the tool error is
|
|
7
|
+
// Web search is unavailable right now.
|
|
8
|
+
// Backends tried:
|
|
9
|
+
// - <Name>: <reason>
|
|
10
|
+
// ...
|
|
11
|
+
// <instruction to the model>
|
|
12
|
+
//
|
|
13
|
+
// Names come from a closed table and reasons from a closed vocabulary (failure.js): no provider response body, URL,
|
|
14
|
+
// key or request id ever reaches this text.
|
|
15
|
+
|
|
16
|
+
export const BACKEND_MARKER_PREFIX = 'Search backend: ';
|
|
17
|
+
export const BACKEND_MARKER_SUFFIX = ' (fallback)';
|
|
18
|
+
export const UNAVAILABLE_HEADLINE = 'Web search is unavailable right now.';
|
|
19
|
+
export const BACKENDS_TRIED_LABEL = 'Backends tried:';
|
|
20
|
+
export const UNAVAILABLE_INSTRUCTION =
|
|
21
|
+
'Tell the user that web search is unavailable right now and why. Do not substitute scraping search engines (DuckDuckGo, Bing, Google) from the shell or by fetching search result pages, and do not make up results.';
|
|
22
|
+
|
|
23
|
+
/** The one line a fallback backend's answer starts with. */
|
|
24
|
+
export function formatBackendMarker(name) {
|
|
25
|
+
return `${BACKEND_MARKER_PREFIX}${name}${BACKEND_MARKER_SUFFIX}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** `attempts`: `[{ name, reason }]` in the order tried. An empty list says no backend is configured for this route. */
|
|
29
|
+
export function formatUnavailable(attempts) {
|
|
30
|
+
const lines =
|
|
31
|
+
attempts.length === 0
|
|
32
|
+
? ['- none: this model route has no native web search and no fallback is configured']
|
|
33
|
+
: attempts.map((attempt) => `- ${attempt.name}: ${attempt.reason}`);
|
|
34
|
+
return [UNAVAILABLE_HEADLINE, BACKENDS_TRIED_LABEL, ...lines, UNAVAILABLE_INSTRUCTION].join('\n');
|
|
35
|
+
}
|