@picassohq/cli 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3062 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +215 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6280 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
  69. package/runtime/packages/picasso-lean-context/timeline.js +418 -0
  70. package/runtime/packages/picasso-librarian/classify.js +146 -0
  71. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  72. package/runtime/packages/picasso-librarian/index.js +878 -0
  73. package/runtime/packages/picasso-librarian/notes.js +159 -0
  74. package/runtime/packages/picasso-librarian/package.json +34 -0
  75. package/runtime/packages/picasso-librarian/state.js +478 -0
  76. package/runtime/packages/picasso-memory/index.js +1184 -0
  77. package/runtime/packages/picasso-memory/package.json +21 -0
  78. package/runtime/packages/picasso-model-router/connections.js +912 -0
  79. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  80. package/runtime/packages/picasso-model-router/index.js +1083 -0
  81. package/runtime/packages/picasso-model-router/package.json +30 -0
  82. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  83. package/runtime/packages/picasso-options/index.js +263 -0
  84. package/runtime/packages/picasso-options/package.json +28 -0
  85. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  86. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  87. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  88. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  89. package/runtime/packages/picasso-sdk-server/aside.js +142 -0
  90. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  91. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  92. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  93. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  94. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  95. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  99. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  100. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  101. package/runtime/packages/picasso-sdk-server/index.js +891 -0
  102. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  103. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  104. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  105. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  106. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  107. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  108. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  109. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  110. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  111. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  112. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  113. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  114. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  115. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  116. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  117. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  118. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  119. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  120. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  122. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  123. package/runtime/packages/picasso-web-search/backends.js +412 -0
  124. package/runtime/packages/picasso-web-search/config.js +121 -0
  125. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  126. package/runtime/packages/picasso-web-search/failure.js +116 -0
  127. package/runtime/packages/picasso-web-search/format.js +42 -0
  128. package/runtime/packages/picasso-web-search/index.js +71 -0
  129. package/runtime/packages/picasso-web-search/package.json +38 -0
  130. package/runtime/packages/picasso-web-search/router.js +156 -0
  131. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  132. package/runtime/packages/picasso-x-reader/command.js +169 -0
  133. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  134. package/runtime/packages/picasso-x-reader/index.js +170 -0
  135. package/runtime/packages/picasso-x-reader/package.json +39 -0
  136. package/runtime/packages/picasso-x-reader/read.js +370 -0
  137. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  138. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  139. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  140. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  141. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  142. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  143. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  144. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  145. package/runtime/plugins/picasso-browser/index.js +424 -0
  146. package/runtime/plugins/picasso-browser/package.json +28 -0
  147. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  148. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  149. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  150. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  151. package/runtime/plugins/picasso-commands/index.js +497 -0
  152. package/runtime/plugins/picasso-commands/package.json +28 -0
  153. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  154. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  155. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  156. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  157. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  158. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  159. package/runtime/plugins/picasso-instructions/index.js +326 -0
  160. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  161. package/runtime/plugins/picasso-instructions/package.json +30 -0
  162. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  163. package/runtime/plugins/picasso-instructions/report.js +161 -0
  164. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  165. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  166. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  167. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  168. package/runtime/plugins/picasso-lean-context/index.js +6280 -0
  169. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  170. package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
  171. package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
  172. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  173. package/runtime/plugins/picasso-librarian/index.js +878 -0
  174. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  175. package/runtime/plugins/picasso-librarian/package.json +34 -0
  176. package/runtime/plugins/picasso-librarian/state.js +478 -0
  177. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  178. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  179. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  180. package/runtime/plugins/picasso-mail/index.js +293 -0
  181. package/runtime/plugins/picasso-mail/package.json +22 -0
  182. package/runtime/plugins/picasso-memory/index.js +1184 -0
  183. package/runtime/plugins/picasso-memory/package.json +21 -0
  184. package/runtime/plugins/picasso-model-router/connections.js +912 -0
  185. package/runtime/plugins/picasso-model-router/index.js +1083 -0
  186. package/runtime/plugins/picasso-model-router/package.json +30 -0
  187. package/runtime/plugins/picasso-options/index.js +263 -0
  188. package/runtime/plugins/picasso-options/package.json +28 -0
  189. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  190. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  191. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  192. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  193. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  194. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  195. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  196. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  197. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  198. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  199. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  200. package/runtime/plugins/picasso-trackers/index.js +895 -0
  201. package/runtime/plugins/picasso-trackers/package.json +28 -0
  202. package/runtime/plugins/picasso-web-search/backends.js +412 -0
  203. package/runtime/plugins/picasso-web-search/config.js +121 -0
  204. package/runtime/plugins/picasso-web-search/failure.js +116 -0
  205. package/runtime/plugins/picasso-web-search/format.js +42 -0
  206. package/runtime/plugins/picasso-web-search/index.js +71 -0
  207. package/runtime/plugins/picasso-web-search/package.json +38 -0
  208. package/runtime/plugins/picasso-web-search/router.js +156 -0
  209. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  210. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  211. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  212. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  213. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  214. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  215. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  216. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  217. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  218. package/runtime/relay/attachment-text.mjs +737 -0
  219. package/runtime/relay/companion/companion.css +126 -0
  220. package/runtime/relay/companion/companion.js +648 -0
  221. package/runtime/relay/companion/icon.svg +5 -0
  222. package/runtime/relay/companion/index.html +25 -0
  223. package/runtime/relay/companion/manifest.json +13 -0
  224. package/runtime/relay/companion/sw.js +41 -0
  225. package/runtime/relay/main.mjs +38580 -0
  226. package/runtime/relay/model-listing.mjs +614 -0
  227. package/runtime/relay/versions-routes.mjs +1400 -0
  228. package/runtime/verify-plugins.mjs +205 -0
  229. package/runtime-lock/package-lock.json +10779 -0
  230. package/runtime-lock/package.json +7 -0
  231. package/scripts/install-runtime.mjs +400 -0
  232. package/README.md +0 -3
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@picasso/trackers",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "dsh cordis plugin: tracker/providers|link|unlink|create|status|list Host Remote endpoints. Links threads to GitHub/GitLab issues (gh/glab argv adapters) and Linear/Jira issues (GraphQL/REST fetch adapters); links persist in a JSON sidecar beside the sessions root.",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "dshTarget": "0.2.2-rc.3",
14
+ "dsh": {
15
+ "bundle": {
16
+ "patch": "./cordis.patch.yml"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "test": "node --import ../../test/setup/hermetic-preload.mjs --test test/*.test.mjs"
21
+ },
22
+ "files": [
23
+ "index.js",
24
+ "cordis.patch.yml",
25
+ "README.md"
26
+ ],
27
+ "license": "UNLICENSED"
28
+ }
@@ -0,0 +1,412 @@
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 Prism (`prism`, `kiro-prism` routes, or an optional fallback): the same Messages server-tool call,
9
+ // answered by Prism itself from its own search pools (no model call)
10
+ //
11
+ // "Native" means the backend whose id the route maps to (NATIVE_ROUTES); any backend can also be a configured
12
+ // fallback. Results carry only structured fields (url, title, snippet, publishedAt); provider prose is never an answer.
13
+ import { safeBaseUrl } from './config.js';
14
+ import { BackendFailure, classifyEngineError, classifyHttp } from './failure.js';
15
+
16
+ export const BACKEND_NAMES = Object.freeze({ deepseek: 'DeepSeek', anthropic: 'Anthropic', openai: 'OpenAI', google: 'Google', prism: 'Prism' });
17
+
18
+ /** Route ids (as the engine names the thread's provider route) that have a native search backend. */
19
+ export const NATIVE_ROUTES = Object.freeze({
20
+ 'deepseek-official': 'deepseek',
21
+ 'deepseek-account': 'deepseek',
22
+ anthropic: 'anthropic',
23
+ openai: 'openai',
24
+ google: 'google',
25
+ // Prism routes: the gateway answers the Messages `web_search_20250305` server tool itself, from its own search pools.
26
+ prism: 'prism',
27
+ 'kiro-prism': 'prism',
28
+ });
29
+
30
+ /** Prism's endpoint when a Prism route's own profile cannot be read (the shipped `prism`/`kiro-prism` baseURL origin). */
31
+ export const DEFAULT_PRISM_URL = 'https://prism.auraone.ai';
32
+
33
+ /** The credential reference each route's key resolves through (the `apiKeyEnv` of dsh/picasso-runtime.cordis.yml). */
34
+ export const KEY_REFS = Object.freeze({ anthropic: 'ANTHROPIC_API_KEY', openai: 'OPENAI_API_KEY', google: 'GOOGLE_API_KEY', deepseek: 'DEEPSEEK_API_KEY' });
35
+
36
+ export const DEFAULT_BASE_URLS = Object.freeze({
37
+ anthropic: 'https://api.anthropic.com',
38
+ openai: 'https://api.openai.com/v1',
39
+ google: 'https://generativelanguage.googleapis.com/v1beta',
40
+ });
41
+
42
+ /** Models used when a backend is a configured fallback (a native search uses the thread's own model). Overridable. */
43
+ 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
+
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
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
53
+ const str = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
54
+ const prompt = (query) => `Perform a web search for the query: ${query}`;
55
+ const REF_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
56
+
57
+ /** The Messages base of a route's OpenAI-style baseURL (`https://host/v1` -> `https://host`); undefined when unsafe. */
58
+ export function messagesBase(baseURL) {
59
+ const safe = safeBaseUrl(baseURL);
60
+ return safe === undefined ? undefined : safe.replace(/\/v1$/u, '');
61
+ }
62
+
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
+ // ---------------------------------------------------------------------------------------------------------------------
88
+ // HTTP
89
+
90
+ /** Up to BODY_PEEK_BYTES of an error body as text; the rest is cancelled unread, so a huge body costs no memory. */
91
+ async function peekBody(response) {
92
+ const reader = response.body?.getReader?.();
93
+ if (reader === undefined) return '';
94
+ const chunks = [];
95
+ let size = 0;
96
+ try {
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
+ }
118
+
119
+ async function postJson(fetchImpl, url, headers, body, signal) {
120
+ const response = await fetchImpl(url, {
121
+ method: 'POST',
122
+ redirect: 'error',
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
+ }
138
+ }
139
+
140
+ // ---------------------------------------------------------------------------------------------------------------------
141
+ // Anthropic Messages server-tool shape (Anthropic, and Prism which answers the same call itself)
142
+
143
+ function messagesError(code) {
144
+ switch (code) {
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
+ }
155
+
156
+ /** Sources of a Messages response: `web_search_tool_result` blocks, snippets from the text blocks' citations. */
157
+ export function parseMessagesSearch(json) {
158
+ const blocks = isRecord(json) && Array.isArray(json.content) ? json.content : [];
159
+ const results = blocks.filter((block) => isRecord(block) && block.type === 'web_search_tool_result');
160
+ if (results.length === 0) throw new BackendFailure('empty');
161
+ const snippets = new Map();
162
+ for (const block of blocks) {
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
+ }
176
+ }
177
+ return { sources: dedupe(found), truncated: false };
178
+ }
179
+
180
+ function messagesBody(model, query) {
181
+ return {
182
+ model,
183
+ max_tokens: MAX_TOKENS,
184
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt(query) }] }],
185
+ tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: MAX_USES }],
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
+ }
219
+ }
220
+ return { sources: dedupe(found), truncated: false };
221
+ }
222
+
223
+ // ---------------------------------------------------------------------------------------------------------------------
224
+ // Gemini grounding
225
+
226
+ export function parseGeminiSearch(json) {
227
+ const candidates = isRecord(json) && Array.isArray(json.candidates) ? json.candidates : [];
228
+ const grounding = candidates.map((candidate) => (isRecord(candidate) ? candidate.groundingMetadata : undefined)).find(isRecord);
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 };
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------------------------------------------------
242
+ // Credentials
243
+
244
+ /** Per-search credential reads through the engine's credential seam; the process environment when it is absent. */
245
+ export function credentialsFrom(ctx, env = process.env) {
246
+ const service = () => ctx?.get?.('credentials');
247
+ return {
248
+ async resolve(ref) {
249
+ try {
250
+ const credentials = service();
251
+ if (credentials !== undefined) return str((await credentials.resolve(ref))?.value);
252
+ return str(env[ref]);
253
+ } catch {
254
+ throw new BackendFailure('credentials');
255
+ }
256
+ },
257
+ async configured(ref) {
258
+ try {
259
+ const credentials = service();
260
+ if (credentials !== undefined) return (await credentials.describe(ref))?.configured === true;
261
+ return str(env[ref]) !== undefined;
262
+ } catch {
263
+ return false;
264
+ }
265
+ },
266
+ };
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------------------------------------------------
270
+ // The backends
271
+
272
+ /**
273
+ * The thread's route profile as the engine holds it (`{ baseURL?, apiKeyEnv? }`), read per search from the llm
274
+ * service's provider directory and the settings namespace that configures the route; undefined when it cannot be read.
275
+ * A home may override a route (the Mac profile points `kiro-prism` at `KIRO_PRISM_API_KEY`), so this, not the shipped
276
+ * catalogue, says which endpoint and key the thread itself uses.
277
+ */
278
+ export function routeProfileFrom(ctx) {
279
+ return async (route) => {
280
+ if (str(route) === undefined) return undefined;
281
+ try {
282
+ const entries = ctx?.get?.('llm')?.listConfigurableProviders?.();
283
+ const entry = Array.isArray(entries) ? entries.find((candidate) => isRecord(candidate) && candidate.provider === route) : undefined;
284
+ if (entry === undefined) return undefined;
285
+ const namespaces = ctx?.get?.('settings')?.describe?.();
286
+ let profile = Array.isArray(namespaces) ? namespaces.find((candidate) => isRecord(candidate) && candidate.ns === entry.settingsNs)?.value : undefined;
287
+ for (const key of Array.isArray(entry.settingsPath) ? entry.settingsPath : []) profile = isRecord(profile) ? profile[key] : undefined;
288
+ const baseURL = (isRecord(profile) ? str(profile.baseURL) : undefined) ?? str(entry.defaultBaseURL);
289
+ const apiKeyEnv = isRecord(profile) ? str(profile.apiKeyEnv) : undefined;
290
+ return { ...(baseURL === undefined ? {} : { baseURL }), ...(apiKeyEnv !== undefined && REF_NAME.test(apiKeyEnv) ? { apiKeyEnv } : {}) };
291
+ } catch {
292
+ return undefined;
293
+ }
294
+ };
295
+ }
296
+
297
+ /**
298
+ * `deps`: `{ creds, fetch, getWeb, routeProfile }`. Every backend answers:
299
+ * `configured(call)` whether a search could be sent (a credential or an engine provider is present); no network
300
+ * `keyRef(call)` the credential reference it needs (for the "no credentials (needs X)" reason), if any
301
+ * `search(request, call)` `call = { signal, route, model, role, config }`
302
+ */
303
+ export function createBackends({ creds, fetch: fetchImpl = globalThis.fetch, getWeb = () => undefined, routeProfile = async () => undefined }) {
304
+ const modelFor = (id, call) => call.config.models[id] ?? (call.role === 'native' && str(call.model) !== undefined ? str(call.model) : DEFAULT_MODELS[id]);
305
+ 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));
307
+ const requireKey = async (id) => {
308
+ const key = await creds.resolve(KEY_REFS[id]);
309
+ if (key === undefined) throw new BackendFailure('credentials', { ref: KEY_REFS[id] });
310
+ return key;
311
+ };
312
+ const keyRefOf = (id) => async () => KEY_REFS[id];
313
+
314
+ // 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.
316
+ const prismTarget = async (call) => {
317
+ if (call.role !== 'native') return { url: call.config.prismUrl, keyRef: call.config.prismKeyRef };
318
+ const profile = await routeProfile(call.route);
319
+ return {
320
+ url: messagesBase(profile?.baseURL) ?? call.config.prismUrl ?? DEFAULT_PRISM_URL,
321
+ keyRef: profile?.apiKeyEnv ?? call.config.prismKeyRef,
322
+ };
323
+ };
324
+
325
+ const engineProvider = () => {
326
+ const registry = getWeb()?.searchProviders;
327
+ if (!(registry instanceof Map)) return undefined;
328
+ return registry.get('deepseek-search-api') ?? registry.get('deepseek-official');
329
+ };
330
+
331
+ return {
332
+ deepseek: {
333
+ id: 'deepseek',
334
+ name: BACKEND_NAMES.deepseek,
335
+ async configured(call) {
336
+ const provider = engineProvider();
337
+ if (provider === undefined) return false;
338
+ try {
339
+ const route = call.role === 'native' ? call.route : 'deepseek-official';
340
+ return provider.available() && (await (provider.ready?.(route) ?? true)) !== false;
341
+ } catch {
342
+ return false;
343
+ }
344
+ },
345
+ async search(request, call) {
346
+ const provider = engineProvider();
347
+ if (provider === undefined) throw new BackendFailure('credentials');
348
+ try {
349
+ return await provider.search({ query: request.query, ...(request.maxResults === undefined ? {} : { maxResults: request.maxResults }) }, call.signal);
350
+ } catch (error) {
351
+ if (call.signal?.aborted === true || error?.code === 'WEB_ABORTED') throw error;
352
+ throw classifyEngineError(error);
353
+ }
354
+ },
355
+ },
356
+ anthropic: {
357
+ id: 'anthropic',
358
+ name: BACKEND_NAMES.anthropic,
359
+ configured: keyed('anthropic'),
360
+ keyRef: keyRefOf('anthropic'),
361
+ async search(request, call) {
362
+ const key = await requireKey('anthropic');
363
+ 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);
364
+ return parseMessagesSearch(json);
365
+ },
366
+ },
367
+ openai: {
368
+ id: 'openai',
369
+ name: BACKEND_NAMES.openai,
370
+ configured: keyed('openai'),
371
+ keyRef: keyRefOf('openai'),
372
+ async search(request, call) {
373
+ const key = await requireKey('openai');
374
+ const body = { model: modelFor('openai', call), input: prompt(request.query), tools: [{ type: 'web_search' }], tool_choice: 'required', store: false };
375
+ return parseOpenAiSearch(await postJson(fetchImpl, `${baseFor('openai', call)}/responses`, { authorization: `Bearer ${key}` }, body, call.signal));
376
+ },
377
+ },
378
+ google: {
379
+ id: 'google',
380
+ name: BACKEND_NAMES.google,
381
+ configured: keyed('google'),
382
+ keyRef: keyRefOf('google'),
383
+ async search(request, call) {
384
+ const key = await requireKey('google');
385
+ const model = encodeURIComponent(modelFor('google', call).replace(/^models\//u, ''));
386
+ const body = { contents: [{ role: 'user', parts: [{ text: prompt(request.query) }] }], tools: [{ google_search: {} }] };
387
+ return parseGeminiSearch(await postJson(fetchImpl, `${baseFor('google', call)}/models/${model}:generateContent`, { 'x-goog-api-key': key }, body, call.signal));
388
+ },
389
+ },
390
+ prism: {
391
+ id: 'prism',
392
+ name: BACKEND_NAMES.prism,
393
+ // As a fallback, optional: active only when both an endpoint and a key are configured (absent is skipped
394
+ // silently). As a Prism route's own search, the route's endpoint and key.
395
+ async configured(call) {
396
+ const { url, keyRef } = await prismTarget(call);
397
+ return url !== undefined && (await creds.configured(keyRef));
398
+ },
399
+ async keyRef(call) {
400
+ return (await prismTarget(call)).keyRef;
401
+ },
402
+ async search(request, call) {
403
+ const { url, keyRef } = await prismTarget(call);
404
+ const key = await creds.resolve(keyRef);
405
+ if (key === undefined || url === undefined) throw new BackendFailure('credentials', { ref: keyRef });
406
+ const headers = { 'x-api-key': key, authorization: `Bearer ${key}`, 'anthropic-version': ANTHROPIC_VERSION };
407
+ const json = await postJson(fetchImpl, `${url}/v1/messages`, headers, messagesBody(modelFor('prism', call), request.query), call.signal);
408
+ return parseMessagesSearch(json);
409
+ },
410
+ },
411
+ };
412
+ }
@@ -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,116 @@
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, ref?: string}} [detail] `ref`: the credential reference a
13
+ * `credentials` failure needs (a name such as `PRISM_API_KEY`, never a value)
14
+ */
15
+ constructor(kind, detail = {}) {
16
+ super(`web search backend failed: ${kind}`);
17
+ this.name = 'BackendFailure';
18
+ this.kind = kind;
19
+ if (detail.status !== undefined) this.status = detail.status;
20
+ if (detail.retryAfterMs !== undefined) this.retryAfterMs = detail.retryAfterMs;
21
+ if (typeof detail.ref === 'string' && REF_NAME.test(detail.ref)) this.ref = detail.ref;
22
+ }
23
+
24
+ get permanent() {
25
+ return PERMANENT_KINDS.has(this.kind);
26
+ }
27
+
28
+ get transient() {
29
+ return TRANSIENT_KINDS.has(this.kind);
30
+ }
31
+
32
+ /** The closed-vocabulary reason shown to the model and the person. */
33
+ get reason() {
34
+ return reasonFor(this.kind, this.status, this.retryAfterMs, this.ref);
35
+ }
36
+ }
37
+
38
+ const REF_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
39
+
40
+ const withStatus = (label, status) => (status === undefined ? label : `${label} (HTTP ${status})`);
41
+
42
+ export function reasonFor(kind, status, retryAfterMs, ref) {
43
+ switch (kind) {
44
+ case 'billing':
45
+ return withStatus('insufficient balance or billing problem', status);
46
+ case 'auth':
47
+ return withStatus('credentials rejected', status);
48
+ case 'forbidden':
49
+ return withStatus('access denied', status);
50
+ case 'rate':
51
+ return `${withStatus('rate limited', status)}${retryAfterMs === undefined ? '' : `, retry after ${Math.ceil(retryAfterMs / 1000)}s`}`;
52
+ case 'server':
53
+ return withStatus('service error', status);
54
+ case 'rejected':
55
+ return withStatus('request rejected', status);
56
+ case 'credentials':
57
+ // The reference names the key to add (`picasso provider set`), never its value.
58
+ return typeof ref === 'string' && REF_NAME.test(ref) ? `no credentials (needs ${ref})` : 'no credentials';
59
+ case 'empty':
60
+ return 'returned no search results block';
61
+ case 'unreadable':
62
+ return 'returned an unreadable response';
63
+ case 'outcome-unknown':
64
+ return 'outcome unknown (the search may have run; not retried)';
65
+ case 'timeout':
66
+ return 'timed out';
67
+ case 'network':
68
+ return 'network error';
69
+ default:
70
+ return 'failed';
71
+ }
72
+ }
73
+
74
+ const BILLING_BODY = /insufficient[ _-]?(?:quota|balance|funds|credit)|credit balance is too low|payment required|billing|exceeded your current quota/iu;
75
+ const AUTH_BODY = /api key not valid|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|authentication/iu;
76
+
77
+ /** Seconds (or an HTTP date) in a Retry-After header, as milliseconds; undefined when absent or unusable. */
78
+ export function retryAfterMs(header, now = Date.now()) {
79
+ if (header === null || header === undefined) return undefined;
80
+ const text = String(header).trim();
81
+ if (text === '') return undefined;
82
+ if (/^\d+(?:\.\d+)?$/u.test(text)) return Math.round(Number(text) * 1000);
83
+ const date = Date.parse(text);
84
+ return Number.isNaN(date) ? undefined : Math.max(0, date - now);
85
+ }
86
+
87
+ /** Classify an HTTP failure from its status and (never surfaced) body text. */
88
+ export function classifyHttp(status, bodyText = '', retryAfterHeader) {
89
+ const body = typeof bodyText === 'string' ? bodyText : '';
90
+ const retry = retryAfterMs(retryAfterHeader);
91
+ const detail = { status, ...(retry === undefined ? {} : { retryAfterMs: retry }) };
92
+ if (status === 402) return new BackendFailure('billing', detail);
93
+ if ([400, 403, 429].includes(status) && BILLING_BODY.test(body)) return new BackendFailure('billing', detail);
94
+ if (status === 401) return new BackendFailure('auth', detail);
95
+ if (status === 400 && AUTH_BODY.test(body)) return new BackendFailure('auth', detail);
96
+ if (status === 403) return new BackendFailure('forbidden', detail);
97
+ if (status === 429) return new BackendFailure('rate', detail);
98
+ if (status >= 500) return new BackendFailure('server', detail);
99
+ return new BackendFailure('rejected', detail);
100
+ }
101
+
102
+ /**
103
+ * Classify an error thrown by an engine-registered provider (a `WebError`: stable `code`, a message that may carry
104
+ * the provider's own text). Only the code and an `HTTP <status>` figure are read from it; the text is dropped.
105
+ */
106
+ export function classifyEngineError(error) {
107
+ if (error instanceof BackendFailure) return error;
108
+ const code = typeof error?.code === 'string' ? error.code : '';
109
+ if (code === 'WEB_PROVIDER_CREDENTIAL_MISSING') return new BackendFailure('credentials');
110
+ const message = typeof error?.message === 'string' ? error.message : '';
111
+ const status = /\bHTTP (\d{3})\b/u.exec(message);
112
+ if (status !== null) return classifyHttp(Number(status[1]), message);
113
+ if (/no web_search_tool_result|no search result/iu.test(message)) return new BackendFailure('empty');
114
+ if (/credential resolution failed|has no (?:API key|credential)/iu.test(message)) return new BackendFailure('credentials');
115
+ return new BackendFailure('network');
116
+ }