@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.
Files changed (230) 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 +3028 -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 +214 -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 +6049 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/timeline.js +417 -0
  69. package/runtime/packages/picasso-librarian/classify.js +146 -0
  70. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  71. package/runtime/packages/picasso-librarian/index.js +878 -0
  72. package/runtime/packages/picasso-librarian/notes.js +159 -0
  73. package/runtime/packages/picasso-librarian/package.json +34 -0
  74. package/runtime/packages/picasso-librarian/state.js +478 -0
  75. package/runtime/packages/picasso-memory/index.js +1184 -0
  76. package/runtime/packages/picasso-memory/package.json +21 -0
  77. package/runtime/packages/picasso-model-router/connections.js +895 -0
  78. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  79. package/runtime/packages/picasso-model-router/index.js +1081 -0
  80. package/runtime/packages/picasso-model-router/package.json +30 -0
  81. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  82. package/runtime/packages/picasso-options/index.js +263 -0
  83. package/runtime/packages/picasso-options/package.json +28 -0
  84. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  85. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  86. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  87. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  88. package/runtime/packages/picasso-sdk-server/aside.js +128 -0
  89. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  90. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  91. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  92. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  93. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  94. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  95. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  99. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  100. package/runtime/packages/picasso-sdk-server/index.js +886 -0
  101. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  102. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  103. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  104. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  105. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  106. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  107. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  108. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  109. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  110. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  111. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  112. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  113. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  114. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  115. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  116. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  117. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  118. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  119. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  120. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  122. package/runtime/packages/picasso-web-search/backends.js +350 -0
  123. package/runtime/packages/picasso-web-search/config.js +121 -0
  124. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  125. package/runtime/packages/picasso-web-search/failure.js +111 -0
  126. package/runtime/packages/picasso-web-search/format.js +35 -0
  127. package/runtime/packages/picasso-web-search/index.js +66 -0
  128. package/runtime/packages/picasso-web-search/package.json +38 -0
  129. package/runtime/packages/picasso-web-search/router.js +155 -0
  130. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  131. package/runtime/packages/picasso-x-reader/command.js +169 -0
  132. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  133. package/runtime/packages/picasso-x-reader/index.js +170 -0
  134. package/runtime/packages/picasso-x-reader/package.json +39 -0
  135. package/runtime/packages/picasso-x-reader/read.js +370 -0
  136. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  137. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  138. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  139. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  140. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  141. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  142. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  143. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  144. package/runtime/plugins/picasso-browser/index.js +424 -0
  145. package/runtime/plugins/picasso-browser/package.json +28 -0
  146. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  147. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  148. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  149. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  150. package/runtime/plugins/picasso-commands/index.js +497 -0
  151. package/runtime/plugins/picasso-commands/package.json +28 -0
  152. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  153. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  154. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  155. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  156. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  157. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  158. package/runtime/plugins/picasso-instructions/index.js +326 -0
  159. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  160. package/runtime/plugins/picasso-instructions/package.json +30 -0
  161. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  162. package/runtime/plugins/picasso-instructions/report.js +161 -0
  163. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  164. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  165. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  166. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  167. package/runtime/plugins/picasso-lean-context/index.js +6049 -0
  168. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  169. package/runtime/plugins/picasso-lean-context/timeline.js +417 -0
  170. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  171. package/runtime/plugins/picasso-librarian/index.js +878 -0
  172. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  173. package/runtime/plugins/picasso-librarian/package.json +34 -0
  174. package/runtime/plugins/picasso-librarian/state.js +478 -0
  175. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  176. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  177. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  178. package/runtime/plugins/picasso-mail/index.js +293 -0
  179. package/runtime/plugins/picasso-mail/package.json +22 -0
  180. package/runtime/plugins/picasso-memory/index.js +1184 -0
  181. package/runtime/plugins/picasso-memory/package.json +21 -0
  182. package/runtime/plugins/picasso-model-router/connections.js +895 -0
  183. package/runtime/plugins/picasso-model-router/index.js +1081 -0
  184. package/runtime/plugins/picasso-model-router/package.json +30 -0
  185. package/runtime/plugins/picasso-options/index.js +263 -0
  186. package/runtime/plugins/picasso-options/package.json +28 -0
  187. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  188. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  189. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  190. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  191. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  192. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  193. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  194. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  195. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  196. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  197. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  198. package/runtime/plugins/picasso-trackers/index.js +895 -0
  199. package/runtime/plugins/picasso-trackers/package.json +28 -0
  200. package/runtime/plugins/picasso-web-search/backends.js +350 -0
  201. package/runtime/plugins/picasso-web-search/config.js +121 -0
  202. package/runtime/plugins/picasso-web-search/failure.js +111 -0
  203. package/runtime/plugins/picasso-web-search/format.js +35 -0
  204. package/runtime/plugins/picasso-web-search/index.js +66 -0
  205. package/runtime/plugins/picasso-web-search/package.json +38 -0
  206. package/runtime/plugins/picasso-web-search/router.js +155 -0
  207. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  208. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  209. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  210. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  211. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  212. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  213. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  214. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  215. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  216. package/runtime/relay/attachment-text.mjs +737 -0
  217. package/runtime/relay/companion/companion.css +126 -0
  218. package/runtime/relay/companion/companion.js +648 -0
  219. package/runtime/relay/companion/icon.svg +5 -0
  220. package/runtime/relay/companion/index.html +25 -0
  221. package/runtime/relay/companion/manifest.json +13 -0
  222. package/runtime/relay/companion/sw.js +41 -0
  223. package/runtime/relay/main.mjs +37252 -0
  224. package/runtime/relay/model-listing.mjs +614 -0
  225. package/runtime/relay/versions-routes.mjs +1198 -0
  226. package/runtime/verify-plugins.mjs +205 -0
  227. package/runtime-lock/package-lock.json +10779 -0
  228. package/runtime-lock/package.json +7 -0
  229. package/scripts/install-runtime.mjs +400 -0
  230. package/README.md +0 -3
@@ -0,0 +1,895 @@
1
+ // @picasso/model-router — ordered model connections with automatic fallback.
2
+ //
3
+ // A "connection" is one configured provider route the engine can reach (an API key, a gateway, a coding plan, a
4
+ // subscription, or Picasso's free managed route). The user orders them; when a request fails because of quota, a
5
+ // 429, out-of-credit/billing, an expired or refused key (401/403) or a provider outage, the next turn or step moves
6
+ // to the next connection in that order that serves the same model (or an equivalent configured one).
7
+ //
8
+ // Shared by both surfaces:
9
+ // - the order and the policy live in `<PICASSO_SETTINGS_ROOT ?? <PICASSO_HOME ?? ~/.picasso>/settings>/model-connections.json`
10
+ // (`{version: 1, policy, order, equivalents?}`); the Mac writes it through `modelRouter/setConnections`, the CLI
11
+ // (`picasso models connections`, TUI `/connections`) writes the same file directly;
12
+ // - the switch reuses the engine's own model-route switch (the same non-persisting `selectForNextRequest` seam the
13
+ // router uses on the Mac, `session/model/set`'s selection on the CLI): a provider switch is a model/route change,
14
+ // so the tools → system → Tier-1 prefix is untouched;
15
+ // - the run gets a quiet note through a session plugin record (`plugin:picasso/connection`, inner type
16
+ // `connection/switch`), which both transcripts render as one line;
17
+ // - "Ask" uses the engine's user-questions waterfall, which both surfaces already answer with one click.
18
+ //
19
+ // Error classification reads the engine's real failure shape (`LlmFailure {code, status?, message,
20
+ // providerRetryAfterMs?}`, normalized at the final adapter boundary — dsh-llm `QUOTA` / `ACCOUNT_QUOTA` / `AUTH` /
21
+ // `INVALID_CREDENTIAL` / `MISSING_CREDENTIAL` / `RATE_LIMIT` / `SERVER` / `TIMEOUT` / `TRANSPORT` / `HTTP_<n>` /
22
+ // `PI_AI_ERROR`), never provider message parsing alone.
23
+
24
+ import { createHash } from 'node:crypto';
25
+ import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
26
+ import { userInfo } from 'node:os';
27
+ import { dirname, join } from 'node:path';
28
+
29
+ export const CONNECTIONS_FILENAME = 'model-connections.json';
30
+ export const POLICIES = Object.freeze(['ask', 'ask-managed', 'auto']);
31
+ export const DEFAULT_POLICY = 'ask';
32
+ /** How long a failed connection rests before a probe (or the next request) may move the session back. */
33
+ export const DEFAULT_COOLDOWN_MS = 60_000;
34
+ /** The longest a provider `Retry-After` may stretch that rest. */
35
+ export const MAX_COOLDOWN_MS = 15 * 60_000;
36
+ export const PROBE_TIMEOUT_MS = 10_000;
37
+ /** The most connection switches one failing step may make before the failure is left to the engine. */
38
+ export const MAX_SWITCHES_PER_STEP = 2;
39
+ /** Test/dev override of the rest (`PICASSO_CONNECTION_COOLDOWN_MS`), e.g. a short e2e recovery. */
40
+ export const ENV_COOLDOWN_MS = 'PICASSO_CONNECTION_COOLDOWN_MS';
41
+ /**
42
+ * A rate limit with nowhere to switch: wait this long, then try the step again. Provider limits are per-minute windows
43
+ * ("retry in about a minute"); the engine's own retries are spent in ~15 s, so a turn on a busy shared org used to end.
44
+ */
45
+ export const DEFAULT_RATE_LIMIT_WAIT_MS = 60_000;
46
+ /** The most rate-limit waits one failing step makes before the failure ends the turn. */
47
+ export const MAX_RATE_LIMIT_WAITS_PER_STEP = 3;
48
+ /** A provider's own wait hint shorter than this still waits this long (the engine already spent its quick retries). */
49
+ export const MIN_RATE_LIMIT_WAIT_MS = 10_000;
50
+ /**
51
+ * The longest a turn sits out one rate limit. A provider asking for more (a daily window, "try again in 2 h") is
52
+ * surfaced to the person instead of holding the turn silently.
53
+ */
54
+ export const MAX_RATE_LIMIT_WAIT_MS = 5 * 60_000;
55
+ /** Sessions whose wait counters are kept (a subagent is a session of its own); the oldest are dropped past this. */
56
+ const MAX_TRACKED_SESSIONS = 256;
57
+ /** Test/dev override of the wait (`PICASSO_RATE_LIMIT_WAIT_MS`). */
58
+ export const ENV_RATE_LIMIT_WAIT_MS = 'PICASSO_RATE_LIMIT_WAIT_MS';
59
+
60
+ export function rateLimitWaitMs(env = process.env) {
61
+ const value = Number(env[ENV_RATE_LIMIT_WAIT_MS]);
62
+ return env[ENV_RATE_LIMIT_WAIT_MS] !== undefined && Number.isFinite(value) && value >= 0 ? value : DEFAULT_RATE_LIMIT_WAIT_MS;
63
+ }
64
+
65
+ /**
66
+ * How long one rate limit is waited out: the provider's hint (floored at {@link MIN_RATE_LIMIT_WAIT_MS}), else
67
+ * {@link rateLimitWaitMs}. Undefined when the hint is past {@link MAX_RATE_LIMIT_WAIT_MS}: do not wait, surface it.
68
+ * An explicit `PICASSO_RATE_LIMIT_WAIT_MS` (tests, e2e) is the floor too, so a short override stays short.
69
+ */
70
+ export function rateLimitPlanMs(retryAfterMs, env = process.env) {
71
+ const fallback = rateLimitWaitMs(env);
72
+ if (retryAfterMs === undefined) return fallback;
73
+ if (retryAfterMs > MAX_RATE_LIMIT_WAIT_MS) return undefined;
74
+ const floor = env[ENV_RATE_LIMIT_WAIT_MS] !== undefined ? Math.min(MIN_RATE_LIMIT_WAIT_MS, fallback) : MIN_RATE_LIMIT_WAIT_MS;
75
+ return Math.max(floor, retryAfterMs);
76
+ }
77
+
78
+ const UNIT_MS = { ms: 1, millisecond: 1, milliseconds: 1, s: 1000, sec: 1000, secs: 1000, second: 1000, seconds: 1000, m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000, h: 3_600_000, hr: 3_600_000, hrs: 3_600_000, hour: 3_600_000, hours: 3_600_000 };
79
+ const DURATION_TOKEN = /(\d+(?:\.\d+)?)\s*(ms|milliseconds?|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)(?![a-z])/giu;
80
+
81
+ /** `"6m0s"`, `"1.5s"`, `"2 minutes 30 seconds"`, `"20ms"` → ms; undefined when it is not a duration. */
82
+ function durationMs(text) {
83
+ let total = 0;
84
+ let any = false;
85
+ for (const [, amount, unit] of text.matchAll(DURATION_TOKEN)) {
86
+ total += Number(amount) * UNIT_MS[unit.toLowerCase()];
87
+ any = true;
88
+ }
89
+ return any && Number.isFinite(total) ? Math.round(total) : undefined;
90
+ }
91
+
92
+ /** A `Retry-After`-style value: bare seconds, a duration, or an HTTP date. */
93
+ function waitValueMs(value, now = Date.now()) {
94
+ if (typeof value === 'number') return Number.isFinite(value) && value > 0 ? Math.round(value * 1000) : undefined;
95
+ if (typeof value !== 'string' || value.trim() === '') return undefined;
96
+ const text = value.trim();
97
+ if (/^\d+(?:\.\d+)?$/u.test(text)) return Number(text) > 0 ? Math.round(Number(text) * 1000) : undefined;
98
+ const duration = /^(?:\d+(?:\.\d+)?\s*[a-z]+\s*)+$/iu.test(text) ? durationMs(text) : undefined;
99
+ if (duration !== undefined) return duration > 0 ? duration : undefined;
100
+ const date = Date.parse(text);
101
+ return Number.isFinite(date) && date > now ? date - now : undefined;
102
+ }
103
+
104
+ function headerValue(headers, name) {
105
+ if (headers === undefined || headers === null) return undefined;
106
+ if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
107
+ if (!isRecord(headers)) return undefined;
108
+ const key = Object.keys(headers).find((entry) => entry.toLowerCase() === name);
109
+ return key === undefined ? undefined : headers[key];
110
+ }
111
+
112
+ /**
113
+ * The wait a provider asked for, in ms: the engine's `providerRetryAfterMs`, else `Retry-After`, the OpenAI
114
+ * `x-ratelimit-reset-*` pair (the later one), Gemini `RetryInfo.retryDelay`, or the wording of the message
115
+ * ("Please try again in 1.5s", "retry-after: 17", `"retryDelay":"34s"`). The adapters keep the status and message
116
+ * only, so the message is the usual carrier. Undefined: no usable hint.
117
+ */
118
+ export function retryHintMs(record, now = Date.now()) {
119
+ if (!isRecord(record)) return undefined;
120
+ if (Number.isFinite(record.providerRetryAfterMs) && record.providerRetryAfterMs > 0) return record.providerRetryAfterMs;
121
+ const headers = record.headers ?? record.responseHeaders;
122
+ const direct = waitValueMs(headerValue(headers, 'retry-after-ms') !== undefined ? Number(headerValue(headers, 'retry-after-ms')) / 1000 : undefined, now)
123
+ ?? waitValueMs(headerValue(headers, 'retry-after'), now)
124
+ ?? waitValueMs(record.retryAfterMs !== undefined ? Number(record.retryAfterMs) / 1000 : undefined, now)
125
+ ?? waitValueMs(record.retryAfter, now);
126
+ if (direct !== undefined) return direct;
127
+ const resets = ['x-ratelimit-reset-requests', 'x-ratelimit-reset-tokens']
128
+ .map((name) => waitValueMs(headerValue(headers, name), now))
129
+ .filter((value) => value !== undefined);
130
+ if (resets.length > 0) return Math.max(...resets);
131
+ for (const detail of [...(Array.isArray(record.details) ? record.details : []), ...(isRecord(record.error) && Array.isArray(record.error.details) ? record.error.details : [])]) {
132
+ if (!isRecord(detail) || typeof detail.retryDelay !== 'string') continue;
133
+ const delay = waitValueMs(detail.retryDelay, now);
134
+ if (delay !== undefined) return delay;
135
+ }
136
+ const message = typeof record.message === 'string' ? record.message : '';
137
+ const quoted = /[\\"']*retry[-_ ]?delay[\\"']*\s*[:=]\s*[\\"']*((?:\d+(?:\.\d+)?\s*[a-z]+\s*)+)/iu.exec(message)?.[1];
138
+ const after = /retry[-_ ]?after[\\"']*\s*[:=]?\s*[\\"']*(\d+(?:\.\d+)?)(?!\d)\s*(ms|milliseconds?|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)?(?![a-z])/iu.exec(message);
139
+ const again = /\b(?:try|retry)\s+(?:again\s+)?in\s+((?:\d+(?:\.\d+)?\s*(?:ms|milliseconds?|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)(?![a-z])\s*(?:and\s+)?)+)/iu.exec(message)?.[1];
140
+ if (quoted !== undefined) return waitValueMs(quoted);
141
+ if (after !== null) return waitValueMs(after[2] === undefined ? after[1] : `${after[1]}${after[2]}`);
142
+ if (again !== undefined) return durationMs(again);
143
+ return undefined;
144
+ }
145
+
146
+ /** Resolves true after `ms`, false as soon as `signal` aborts. */
147
+ function abortableSleep(ms, signal) {
148
+ if (signal?.aborted) return Promise.resolve(false);
149
+ return new Promise((resolve) => {
150
+ const done = (value) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); resolve(value); };
151
+ const onAbort = () => done(false);
152
+ const timer = setTimeout(() => done(true), ms);
153
+ signal?.addEventListener('abort', onAbort, { once: true });
154
+ });
155
+ }
156
+
157
+ export function cooldownMs(env = process.env) {
158
+ const value = Number(env[ENV_COOLDOWN_MS]);
159
+ return env[ENV_COOLDOWN_MS] !== undefined && Number.isFinite(value) && value > 0 ? value : DEFAULT_COOLDOWN_MS;
160
+ }
161
+ /** User-question id of the one-click "switch?" prompt. */
162
+ export const ASK_QUESTION_ID = 'picasso-connection-switch';
163
+ export const RECORD_TYPE = 'plugin:picasso/connection';
164
+ export const SWITCH_EVENT = 'connection/switch';
165
+
166
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
167
+ const nonEmpty = (value) => typeof value === 'string' && value.length > 0;
168
+
169
+ // ── Labels and kinds ─────────────────────────────────────────────────────────────────────────────────
170
+
171
+ const LABELS = {
172
+ anthropic: 'Anthropic',
173
+ openai: 'OpenAI',
174
+ 'azure-foundry': 'Azure Foundry',
175
+ 'azure-openai': 'Azure OpenAI',
176
+ google: 'Google',
177
+ 'google-vertex': 'Vertex AI',
178
+ 'amazon-bedrock': 'Amazon Bedrock',
179
+ 'deepseek-official': 'DeepSeek',
180
+ deepseek: 'DeepSeek',
181
+ openrouter: 'OpenRouter',
182
+ 'kiro-prism': 'Prism',
183
+ prism: 'Prism',
184
+ xai: 'xAI',
185
+ moonshotai: 'Moonshot',
186
+ kimi: 'Kimi',
187
+ 'kimi-coding': 'Kimi Coding Plan',
188
+ qwen: 'Qwen',
189
+ zai: 'Z.ai',
190
+ 'zai-coding': 'Z.ai Coding Plan',
191
+ zhipu: 'Zhipu',
192
+ minimax: 'MiniMax',
193
+ xiaomi: 'Xiaomi',
194
+ groq: 'Groq',
195
+ cerebras: 'Cerebras',
196
+ fireworks: 'Fireworks',
197
+ together: 'Together',
198
+ mistral: 'Mistral',
199
+ nvidia: 'NVIDIA',
200
+ huggingface: 'Hugging Face',
201
+ 'github-copilot': 'GitHub Copilot',
202
+ 'openai-codex': 'ChatGPT subscription',
203
+ 'anthropic-subscription': 'Claude subscription',
204
+ 'picasso-managed': 'Picasso free',
205
+ 'picasso-free': 'Picasso free',
206
+ ollama: 'Ollama',
207
+ vllm: 'vLLM',
208
+ lmstudio: 'LM Studio',
209
+ };
210
+
211
+ const GATEWAYS = new Set(['openrouter', 'kiro-prism', 'prism', 'together', 'fireworks', 'huggingface', 'nvidia', 'vercel-ai-gateway', 'tokenrouter', 'requesty', 'litellm']);
212
+ const SUBSCRIPTIONS = new Set(['github-copilot', 'openai-codex', 'anthropic-subscription', 'google-gemini-cli', 'google-antigravity']);
213
+ const LOCAL = new Set(['ollama', 'vllm', 'lmstudio', 'llamacpp']);
214
+
215
+ /** Is this route Picasso's free managed route? */
216
+ export function isManagedRoute(id) {
217
+ return id === 'picasso-managed' || id === 'picasso-free';
218
+ }
219
+
220
+ /** The connection kind the UIs group/badge by. */
221
+ export function connectionKind(id) {
222
+ if (isManagedRoute(id)) return 'managed';
223
+ if (SUBSCRIPTIONS.has(id) || /-(?:subscription|oauth)$/u.test(id)) return 'subscription';
224
+ if (/coding(?:-plan)?$/u.test(id) || /-coding-/u.test(id)) return 'coding-plan';
225
+ if (GATEWAYS.has(id)) return 'gateway';
226
+ if (LOCAL.has(id)) return 'local';
227
+ return 'api-key';
228
+ }
229
+
230
+ /** A human label for a route id (no engine names). */
231
+ export function connectionLabel(id, name) {
232
+ if (nonEmpty(LABELS[id])) return LABELS[id];
233
+ if (nonEmpty(name) && name !== id) return name;
234
+ return String(id).split(/[-_]/u).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ');
235
+ }
236
+
237
+ // ── Same endpoint, same key ──────────────────────────────────────────────────────────────────────────
238
+
239
+ /** `https://Host/v1/` and `https://host/v1` are one endpoint. */
240
+ export function normalizeEndpoint(url) {
241
+ if (!nonEmpty(url)) return undefined;
242
+ try {
243
+ const parsed = new URL(url.trim());
244
+ return `${parsed.protocol}//${parsed.host.toLowerCase()}${parsed.pathname.replace(/\/+$/u, '')}`;
245
+ } catch {
246
+ return url.trim().replace(/\/+$/u, '').toLowerCase();
247
+ }
248
+ }
249
+
250
+ /**
251
+ * The fingerprint two routes share when they reach the same endpoint with the same key, else undefined (a route
252
+ * with no declared endpoint is never merged). The key is compared by a SHA-256 of its value when it can be resolved
253
+ * (`resolveKey(ref)`), otherwise by the credential reference name; the key itself never leaves this function.
254
+ *
255
+ * @param {{baseURL?: string, apiKey?: string, apiKeyEnv?: string}|undefined} profile - one llm-pi-ai route.
256
+ * @param {(ref: string) => string|undefined} [resolveKey]
257
+ */
258
+ export function routeIdentity(profile, resolveKey = () => undefined) {
259
+ if (!isRecord(profile)) return undefined;
260
+ const endpoint = normalizeEndpoint(profile.baseURL);
261
+ if (endpoint === undefined) return undefined;
262
+ let key;
263
+ if (nonEmpty(profile.apiKey)) key = `key:${createHash('sha256').update(profile.apiKey).digest('hex')}`;
264
+ else if (nonEmpty(profile.apiKeyEnv)) {
265
+ const value = resolveKey(profile.apiKeyEnv);
266
+ key = nonEmpty(value) ? `key:${createHash('sha256').update(value).digest('hex')}` : `ref:${profile.apiKeyEnv}`;
267
+ }
268
+ return key === undefined ? undefined : `${endpoint} ${key}`;
269
+ }
270
+
271
+ // ── Error classification ─────────────────────────────────────────────────────────────────────────────
272
+
273
+ const QUOTA_WORDING = /\binsufficient[\s_-]+(?:quota|balance|credits?|funds)\b|\b(?:quota|usage[\s_-]+limit)[\s_-]+(?:exceeded|exhausted|reached)\b|\bexceed(?:ed|s)?[\s_-]+(?:(?:your|the)[\s_-]+)?(?:current[\s_-]+)?quota\b|\b(?:balance|credits?)[\s_-]+(?:exhausted|depleted)\b|\bout[\s_-]+of[\s_-]+(?:credits?|budget)\b/i;
274
+ const STRONG_BILLING_WORDING = /\bpayment[\s_-]+required\b|\bcredit[\s_-]+balance\b|\bspend(?:ing)?[\s_-]+limit\b/i;
275
+ /** "billing" alone also turns up in a rate-limit answer that links the billing page, so on its own it is weak. */
276
+ const BILLING_WORDING = /\bbilling\b/i;
277
+ const RATE_LIMIT_WORDING = /rate[\s_-]?limit|\b(?:try|retry)\s+(?:again\s+)?in\b/i;
278
+ /** Quota wording that is a spent allowance or a daily window, whatever wait it names. */
279
+ const SPENT_QUOTA_WORDING = /\bper[\s_-]?day\b|\bdaily\b|\binsufficient\b|\bbalance\b|\bcredits?\b/i;
280
+ /** A quota answer naming a wait this short is a rate window (Gemini's free tier names one per minute). */
281
+ const SHORT_QUOTA_WINDOW_MS = 2 * 60_000;
282
+ const OUTAGE_CODES = new Set(['SERVER', 'TIMEOUT', 'TRANSPORT', 'EMPTY_RESPONSE']);
283
+ const AUTH_CODES = new Set(['AUTH', 'INVALID_CREDENTIAL', 'MISSING_CREDENTIAL']);
284
+
285
+ /**
286
+ * Classify one engine `LlmFailure` (or an `llm/retry` event's `failure`/`error`).
287
+ *
288
+ * @returns {{kind: 'quota'|'billing'|'rate-limit'|'auth'|'outage'|'other', fallback: boolean, transient: boolean,
289
+ * reason: string, retryAfterMs?: number}}
290
+ * `fallback` — the failure moves the session to the next connection; `transient` — the engine's own retry
291
+ * policy gets the first go (429 / 5xx / timeouts), the switch happens once it gives up.
292
+ */
293
+ export function classifyFailure(failure) {
294
+ const record = isRecord(failure) ? failure : { message: String(failure ?? '') };
295
+ const code = typeof record.code === 'string' ? record.code.toUpperCase() : '';
296
+ const status = Number.isInteger(record.status) ? record.status : Number.isInteger(Number(/^HTTP_(\d{3})$/u.exec(code)?.[1])) ? Number(/^HTTP_(\d{3})$/u.exec(code)[1]) : undefined;
297
+ const message = typeof record.message === 'string' ? record.message : '';
298
+ const retryAfterMs = retryHintMs(record);
299
+ const out = (kind, fallback, transient, reason) => ({ kind, fallback, transient, reason, ...(retryAfterMs === undefined ? {} : { retryAfterMs }) });
300
+
301
+ if (code === 'ABORTED' || code === 'CONTEXT_WINDOW_EXCEEDED' || code === 'IMAGE_OFFLOAD_REQUIRED') {
302
+ return out('other', false, false, 'request error');
303
+ }
304
+ // Spent quota and credit are judged before the request-error exit: an out-of-credit answer is a 400, which the
305
+ // adapter files as INVALID_REQUEST, and it must still move the run to the next connection (never be waited out).
306
+ if (code === 'QUOTA' || code === 'ACCOUNT_QUOTA' || QUOTA_WORDING.test(message)) {
307
+ const windowed = code !== 'ACCOUNT_QUOTA' && status !== 402 && retryAfterMs !== undefined && retryAfterMs <= SHORT_QUOTA_WINDOW_MS && !SPENT_QUOTA_WORDING.test(message);
308
+ return windowed ? out('rate-limit', true, true, 'is rate limited') : out('quota', true, false, 'hit its limit');
309
+ }
310
+ const linksBilling = (status === 429 || code === 'RATE_LIMIT') &&RATE_LIMIT_WORDING.test(message) && !STRONG_BILLING_WORDING.test(message);
311
+ if (status === 402 || STRONG_BILLING_WORDING.test(message) || (BILLING_WORDING.test(message) && !linksBilling)) return out('billing', true, false, 'is out of credit');
312
+ if (code === 'INVALID_REQUEST') return out('other', false, false, 'request error');
313
+ if (AUTH_CODES.has(code) || status === 401 || status === 403) {
314
+ return out('auth', true, false, code === 'MISSING_CREDENTIAL' ? 'is missing' : 'expired or was refused');
315
+ }
316
+ if (code === 'RATE_LIMIT' || status === 429 || /\b429\b|rate[\s_-]?limit/i.test(message)) return out('rate-limit', true, true, 'is rate limited');
317
+ if (OUTAGE_CODES.has(code) || (status !== undefined && status >= 500) || /\b(?:overloaded(?:_error)?|service unavailable|bad gateway)\b/i.test(message)) {
318
+ return out('outage', true, true, 'is unavailable');
319
+ }
320
+ if (code === 'PI_AI_ERROR' && /\b(?:401|403)\b/u.test(message)) return out('auth', true, false, 'expired or was refused');
321
+ return out('other', false, false, 'request error');
322
+ }
323
+
324
+ /** The note's reason clause: "Anthropic key hit its limit", "OpenRouter is unavailable". */
325
+ export function reasonPhrase(label, classified) {
326
+ const keyed = classified.kind === 'quota' || classified.kind === 'auth' || classified.kind === 'billing';
327
+ const subject = keyed && !/\b(?:key|plan|subscription)$/iu.test(label) ? `${label} key` : label;
328
+ return `${subject} ${classified.reason}`;
329
+ }
330
+
331
+ /** A short human reason for a probe failure ("Rate limited (429)"). */
332
+ export function probeReason(classified, failure) {
333
+ const status = Number.isInteger(failure?.status) ? ` (${failure.status})` : '';
334
+ switch (classified.kind) {
335
+ case 'quota': return `Hit its usage limit${status}`;
336
+ case 'billing': return `Out of credit${status}`;
337
+ case 'auth': return failure?.code === 'MISSING_CREDENTIAL' ? 'No key configured' : `Key expired or not allowed${status}`;
338
+ case 'rate-limit': return `Rate limited${status}`;
339
+ case 'outage': return `Provider unavailable${status}`;
340
+ default: return (typeof failure?.message === 'string' && failure.message ? failure.message.slice(0, 160) : 'Request failed') + status;
341
+ }
342
+ }
343
+
344
+ // ── Model equivalence ───────────────────────────────────────────────────────────────────────────────
345
+
346
+ /** `anthropic/claude-sonnet-5.5`, `Claude-Sonnet-5.5` and `claude-sonnet-5.5` share one key. */
347
+ export function modelKey(model) {
348
+ const text = String(model ?? '').trim().toLowerCase();
349
+ const tail = text.includes('/') ? text.slice(text.lastIndexOf('/') + 1) : text;
350
+ return tail.replace(/[._\s]+/gu, '-');
351
+ }
352
+
353
+ /** Whether `candidate` serves `model` (same id, same key, or a configured equivalence group). */
354
+ export function sameModel(model, candidate, equivalents = []) {
355
+ if (model === candidate) return true;
356
+ const a = modelKey(model);
357
+ const b = modelKey(candidate);
358
+ if (a === b) return true;
359
+ return equivalents.some((group) => group.some((entry) => modelKey(entry) === a) && group.some((entry) => modelKey(entry) === b));
360
+ }
361
+
362
+ // ── Settings file ────────────────────────────────────────────────────────────────────────────────────
363
+
364
+ function accountHome() {
365
+ try {
366
+ return userInfo().homedir;
367
+ } catch {
368
+ return process.env.HOME ?? '';
369
+ }
370
+ }
371
+
372
+ /** `<PICASSO_SETTINGS_ROOT ?? <PICASSO_HOME ?? ~/.picasso>/settings>/model-connections.json`. */
373
+ export function connectionsFile(env = process.env) {
374
+ const root = nonEmpty(env.PICASSO_SETTINGS_ROOT?.trim()) ? env.PICASSO_SETTINGS_ROOT : undefined;
375
+ if (root !== undefined) return join(root, CONNECTIONS_FILENAME);
376
+ const home = nonEmpty(env.PICASSO_HOME?.trim()) ? env.PICASSO_HOME : join(accountHome(), '.picasso');
377
+ return join(home, 'settings', CONNECTIONS_FILENAME);
378
+ }
379
+
380
+ /** Normalize a stored document: unknown policy → default, order de-duplicated, equivalence groups ≥ 2 ids. */
381
+ export function normalizeSettings(raw) {
382
+ const value = isRecord(raw) ? raw : {};
383
+ const policy = POLICIES.includes(value.policy) ? value.policy : DEFAULT_POLICY;
384
+ const order = [];
385
+ for (const id of Array.isArray(value.order) ? value.order : []) if (nonEmpty(id) && !order.includes(id)) order.push(id);
386
+ const equivalents = (Array.isArray(value.equivalents) ? value.equivalents : [])
387
+ .map((group) => (Array.isArray(group) ? group.filter(nonEmpty) : []))
388
+ .filter((group) => group.length >= 2);
389
+ // Per-model reasoning levels, shared with the CLI (`apps/cli/src/model-effort.ts`): the default level chosen for a
390
+ // model (`"<route>/<model>": "<level>"`) and the models that cannot run with thinking off. Kept through every save.
391
+ const efforts = {};
392
+ if (isRecord(value.efforts)) {
393
+ for (const [ref, level] of Object.entries(value.efforts)) {
394
+ if (nonEmpty(ref) && ref.includes('/') && nonEmpty(level) && /^[a-z][a-z0-9-]{0,15}$/u.test(level)) efforts[ref] = level;
395
+ }
396
+ }
397
+ const alwaysThinks = [];
398
+ for (const ref of Array.isArray(value.alwaysThinks) ? value.alwaysThinks : []) {
399
+ if (nonEmpty(ref) && ref.includes('/') && !alwaysThinks.includes(ref)) alwaysThinks.push(ref);
400
+ }
401
+ // The default level for every model (`picasso models default-effort --all <level>`, the Mac's Default thinking).
402
+ const defaultEffort =
403
+ nonEmpty(value.defaultEffort) &&
404
+ /^[a-z][a-z0-9-]{0,15}$/u.test(value.defaultEffort) &&
405
+ !/^(?:off|none|disabled|minimal-off)$/u.test(value.defaultEffort)
406
+ ? value.defaultEffort
407
+ : undefined;
408
+ // What a model pick applies to, remembered for the next pick (CLI `/model` picker, the Mac's model menus):
409
+ // `default` (absent) = this chat and every new session/thread; `session` = this chat only.
410
+ const modelPickScope = value.modelPickScope === 'session' ? 'session' : undefined;
411
+ return {
412
+ version: 1,
413
+ policy,
414
+ order,
415
+ ...(equivalents.length === 0 ? {} : { equivalents }),
416
+ ...(Object.keys(efforts).length === 0 ? {} : { efforts }),
417
+ ...(alwaysThinks.length === 0 ? {} : { alwaysThinks }),
418
+ ...(defaultEffort === undefined ? {} : { defaultEffort }),
419
+ ...(modelPickScope === undefined ? {} : { modelPickScope }),
420
+ };
421
+ }
422
+
423
+ /**
424
+ * A live reader: re-parsed only when the file changes; a missing or unreadable file reads as defaults. The change stamp is
425
+ * inode + size + mtime: `writeSettings` replaces the file by rename (a new inode), so two saves inside one mtime tick
426
+ * (coarse on some filesystems) are still seen — keyed on mtime alone, the second save read back as the first.
427
+ */
428
+ export function settingsReader(file = connectionsFile()) {
429
+ let cache = { stamp: undefined, value: normalizeSettings(undefined) };
430
+ return () => {
431
+ let stamp;
432
+ try {
433
+ const stat = statSync(file);
434
+ stamp = `${stat.ino}:${stat.size}:${stat.mtimeMs}`;
435
+ } catch {
436
+ stamp = 'missing';
437
+ }
438
+ if (stamp !== cache.stamp) {
439
+ let value = normalizeSettings(undefined);
440
+ if (stamp !== 'missing') {
441
+ try {
442
+ value = normalizeSettings(JSON.parse(readFileSync(file, 'utf8')));
443
+ } catch {
444
+ // unreadable → defaults
445
+ }
446
+ }
447
+ cache = { stamp, value };
448
+ }
449
+ return cache.value;
450
+ };
451
+ }
452
+
453
+ /** Write the settings atomically (temp file + rename, 0600). Returns the normalized document. */
454
+ export function writeSettings(next, file = connectionsFile()) {
455
+ const value = normalizeSettings(next);
456
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
457
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
458
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
459
+ renameSync(temp, file);
460
+ return value;
461
+ }
462
+
463
+ /** Ordered ids: the stored order first (only ids that exist), then every other id in its given order. */
464
+ export function orderIds(ids, order) {
465
+ const known = new Set(ids);
466
+ const head = order.filter((id) => known.has(id));
467
+ return [...head, ...ids.filter((id) => !head.includes(id))];
468
+ }
469
+
470
+ /** Move one id within an order (`up` / `down` / `top` / `bottom` / a 1-based position). */
471
+ export function moveId(order, id, where) {
472
+ const list = order.filter((entry) => entry !== id);
473
+ const index = order.indexOf(id);
474
+ if (index < 0) return [...order];
475
+ let target;
476
+ if (where === 'up') target = Math.max(0, index - 1);
477
+ else if (where === 'down') target = Math.min(list.length, index + 1);
478
+ else if (where === 'top') target = 0;
479
+ else if (where === 'bottom') target = list.length;
480
+ else if (Number.isInteger(where)) target = Math.min(list.length, Math.max(0, where - 1));
481
+ else throw new RangeError(`unknown move "${where}" (up, down, top, bottom or a position)`);
482
+ list.splice(target, 0, id);
483
+ return list;
484
+ }
485
+
486
+ // ── Fallback controller ─────────────────────────────────────────────────────────────────────────────
487
+
488
+ /**
489
+ * The fallback state machine. Every engine seam is injected so tests drive it with fakes:
490
+ *
491
+ * @param {object} deps
492
+ * @param {() => {policy, order, equivalents?}} deps.settings - live settings.
493
+ * @param {() => Promise<{id: string, name?: string}[]>} deps.providers - the engine's provider routes.
494
+ * @param {(id: string) => Promise<string[]>} deps.models - model ids a route serves (empty = not configured).
495
+ * @param {(id: string) => Promise<string|undefined>|string|undefined} [deps.identity] - endpoint + key fingerprint of
496
+ * a route; routes with the same fingerprint are one connection.
497
+ * @param {(agent, selection, options?: {immediate?: boolean}) => Promise<object|undefined>} deps.install - install
498
+ * `{provider, model, reasoningEffort?}` for the agent's next request (non-persisting); `immediate` also applies it
499
+ * to the step being retried. Resolves to the installed selection.
500
+ * @param {(agent) => {provider, model, reasoningEffort?}|undefined} deps.current - the agent's current route.
501
+ * @param {(connection, model) => Promise<{ok: boolean, failure?: object}>} [deps.probe] - a tiny probe request.
502
+ * @param {(agent, question, signal) => Promise<string|undefined>} [deps.ask] - one-click question; resolves to the
503
+ * picked option label, undefined when no answerer is available.
504
+ * @param {(agent, event) => void} [deps.note] - append the quiet run note.
505
+ * @param {() => number} [deps.now]
506
+ * @param {(line: string) => void} [deps.log]
507
+ */
508
+ export class ConnectionFallback {
509
+ constructor(deps) {
510
+ this.deps = deps;
511
+ this.now = deps.now ?? (() => Date.now());
512
+ this.log = deps.log ?? (() => undefined);
513
+ /** connection id → {kind, reason, since, until} for connections that failed. */
514
+ this.degraded = new Map();
515
+ /** session id → {home: {id, model, reasoningEffort?}, active: {id, model}} while running on a fallback. */
516
+ this.sessions = new Map();
517
+ /** session id → epoch ms of the last recovery probe (throttle). */
518
+ this.lastProbe = new Map();
519
+ /** session id → {key: 'turn:step', count} switches made for one failing step. */
520
+ this.stepSwitches = new Map();
521
+ /** Rate-limit waits per session for its current step: `{key: "<turn>:<step>", count}`. */
522
+ this.rateWaits = new Map();
523
+ }
524
+
525
+ /**
526
+ * The ordered connections: configured provider routes (those serving ≥ 1 model) in the user's order. Routes that
527
+ * reach the same endpoint with the same key (`deps.identity`) are one connection: falling back from one to the
528
+ * other could never help. The merged row keeps the first route in the user's order as its id, lists the others in
529
+ * `aliases`, serves the union of their models and has one label.
530
+ */
531
+ async list() {
532
+ const settings = this.deps.settings();
533
+ const providers = await this.deps.providers();
534
+ const rows = [];
535
+ for (const provider of providers) {
536
+ if (!nonEmpty(provider?.id)) continue;
537
+ let models = [];
538
+ try {
539
+ models = await this.deps.models(provider.id);
540
+ } catch {
541
+ models = [];
542
+ }
543
+ if (models.length === 0) continue;
544
+ let identity;
545
+ try {
546
+ identity = typeof this.deps.identity === 'function' ? await this.deps.identity(provider.id) : undefined;
547
+ } catch {
548
+ identity = undefined;
549
+ }
550
+ rows.push({ id: provider.id, label: connectionLabel(provider.id, provider.name), kind: connectionKind(provider.id), models, identity });
551
+ }
552
+ // Managed last unless the user placed it.
553
+ const ids = [...rows.filter((row) => row.kind !== 'managed'), ...rows.filter((row) => row.kind === 'managed')].map((row) => row.id);
554
+ const ordered = orderIds(ids, settings.order).map((id) => rows.find((entry) => entry.id === id));
555
+ /** member route id → model id → member route serving it, per merged connection id. */
556
+ this.routes = new Map();
557
+ const merged = [];
558
+ for (const row of ordered) {
559
+ const group = nonEmpty(row.identity) ? merged.find((entry) => entry.identity === row.identity) : undefined;
560
+ if (group === undefined) {
561
+ merged.push({ ...row, aliases: [] });
562
+ this.routes.set(row.id, new Map(row.models.map((model) => [model, row.id])));
563
+ continue;
564
+ }
565
+ group.aliases.push(row.id);
566
+ const served = this.routes.get(group.id);
567
+ for (const model of row.models) {
568
+ if (served.has(model)) continue;
569
+ served.set(model, row.id);
570
+ group.models = [...group.models, model];
571
+ }
572
+ }
573
+ return merged.map(({ identity: _identity, aliases, ...row }) => {
574
+ const down = this.downFor(row.id, aliases);
575
+ return {
576
+ ...row,
577
+ ...(aliases.length === 0 ? {} : { aliases }),
578
+ status: down === undefined ? 'ok' : 'degraded',
579
+ ...(down === undefined ? {} : { reason: down.reason, since: down.since }),
580
+ };
581
+ });
582
+ }
583
+
584
+ /** The rest recorded for a connection or any route merged into it (the one that ends last). */
585
+ downFor(id, aliases = []) {
586
+ let found;
587
+ for (const member of [id, ...aliases]) {
588
+ const down = this.degraded.get(member);
589
+ if (down !== undefined && (found === undefined || down.until > found.until)) found = down;
590
+ }
591
+ return found;
592
+ }
593
+
594
+ /** The view `modelRouter/connections` answers. */
595
+ async view() {
596
+ return { policy: this.deps.settings().policy, connections: await this.list() };
597
+ }
598
+
599
+ /**
600
+ * The next connection (in order) that serves `model` or an equivalent, skipping `fromId` and resting ones.
601
+ * @returns {Promise<{connection, model}|undefined>}
602
+ */
603
+ async nextFor(fromId, model) {
604
+ const { equivalents = [] } = this.deps.settings();
605
+ const now = this.now();
606
+ for (const connection of await this.list()) {
607
+ // A route merged into the failing one is the same endpoint and key: never a fallback.
608
+ if (connection.id === fromId || connection.aliases?.includes(fromId)) continue;
609
+ const down = this.downFor(connection.id, connection.aliases);
610
+ if (down !== undefined && down.until > now) continue;
611
+ const served = connection.models.find((id) => id === model) ?? connection.models.find((id) => sameModel(model, id, equivalents));
612
+ if (served === undefined) continue;
613
+ // The member route that lists the model carries the request (same endpoint and key as the connection's id).
614
+ const route = this.routes?.get(connection.id)?.get(served) ?? connection.id;
615
+ return { connection: route === connection.id ? connection : { ...connection, id: route }, model: served };
616
+ }
617
+ return undefined;
618
+ }
619
+
620
+ markDegraded(id, classified, label) {
621
+ const now = this.now();
622
+ const rest = Math.min(MAX_COOLDOWN_MS, Math.max(cooldownMs(), classified.retryAfterMs ?? 0));
623
+ this.degraded.set(id, { kind: classified.kind, reason: reasonPhrase(label, classified), since: now, until: now + rest });
624
+ }
625
+
626
+ /**
627
+ * `agent/request-error` waterfall. Owns recovery only for a top-level agent whose failure classifies as a
628
+ * fallback, when a next connection exists and the policy (or the user) allows the switch; otherwise delegates.
629
+ */
630
+ async onRequestError(payload, next) {
631
+ const agent = payload?.agent;
632
+ const classified = classifyFailure(payload?.failure);
633
+ if (!classified.fallback || agent === undefined) return next();
634
+ const stepKey = `${payload?.turn ?? '?'}:${payload?.step ?? '?'}`;
635
+ if (isChildAgent(agent)) {
636
+ // A subagent never switches connections, but it waits out a rate limit like its parent does.
637
+ const downstream = await next();
638
+ if (downstream !== undefined && downstream !== null) return downstream;
639
+ return (await this.waitOutRateLimit(agent, payload, classified, stepKey)) ? { kind: 'retry' } : undefined;
640
+ }
641
+ // Loop guard: one step never switches more than MAX_SWITCHES_PER_STEP times (a route that keeps failing after
642
+ // a switch is left to the engine instead of bouncing between connections).
643
+ const sessionId = sessionIdOf(agent);
644
+ const seen = this.stepSwitches.get(sessionId);
645
+ const count = seen?.key === stepKey ? seen.count : 0;
646
+ if (count >= MAX_SWITCHES_PER_STEP) {
647
+ const downstream = await next();
648
+ if (downstream !== undefined && downstream !== null) return downstream;
649
+ return (await this.waitOutRateLimit(agent, payload, classified, stepKey)) ? { kind: 'retry' } : downstream;
650
+ }
651
+ if (classified.transient) {
652
+ // The engine's own retry policy (llm-retry) gets the first go at a 429 / 5xx; switch once it gives up.
653
+ const downstream = await next();
654
+ if (downstream !== undefined && downstream !== null) return downstream;
655
+ }
656
+ if (payload?.signal?.aborted) return undefined;
657
+ try {
658
+ const switched = await this.fallback(agent, payload, classified);
659
+ if (switched) {
660
+ this.stepSwitches.set(sessionId, { key: stepKey, count: count + 1 });
661
+ return { kind: 'retry' };
662
+ }
663
+ } catch (error) {
664
+ this.log(`model connections: fallback skipped (${error instanceof Error ? error.message : String(error)}).`);
665
+ }
666
+ if (await this.waitOutRateLimit(agent, payload, classified, stepKey)) return { kind: 'retry' };
667
+ return classified.transient ? undefined : next();
668
+ }
669
+
670
+ /**
671
+ * A rate limit the engine's retries could not outlast and no other connection could take: note it, wait out the
672
+ * provider's window (its `Retry-After`, else {@link rateLimitWaitMs}) and retry the step, at most
673
+ * {@link MAX_RATE_LIMIT_WAITS_PER_STEP} times per step. Stopping the turn ends the wait at once.
674
+ */
675
+ async waitOutRateLimit(agent, payload, classified, stepKey) {
676
+ if (classified.kind !== 'rate-limit' || payload?.signal?.aborted) return false;
677
+ const sessionId = sessionIdOf(agent);
678
+ const seen = this.rateWaits.get(sessionId);
679
+ const count = seen?.key === stepKey ? seen.count : 0;
680
+ if (count >= MAX_RATE_LIMIT_WAITS_PER_STEP) return false;
681
+ // A provider asking for longer than a turn should sit still (a daily window): no wait, the failure is shown.
682
+ const ms = rateLimitPlanMs(classified.retryAfterMs);
683
+ if (ms === undefined) return false;
684
+ // Counters are per session (a subagent is one too); keep the newest ones so a long engine run stays bounded.
685
+ this.rateWaits.delete(sessionId);
686
+ this.rateWaits.set(sessionId, { key: stepKey, count: count + 1 });
687
+ while (this.rateWaits.size > MAX_TRACKED_SESSIONS) this.rateWaits.delete(this.rateWaits.keys().next().value);
688
+ const current = this.deps.current?.(agent) ?? {};
689
+ const fromId = nonEmpty(payload?.provider) ? payload.provider : current.provider;
690
+ const label = nonEmpty(fromId) ? connectionLabel(fromId) : 'The provider';
691
+ const seconds = Math.max(1, Math.round(ms / 1000));
692
+ this.deps.note?.(agent, {
693
+ type: SWITCH_EVENT,
694
+ direction: 'wait',
695
+ from: { id: fromId ?? '', label, ...(nonEmpty(current.model) ? { model: current.model } : {}) },
696
+ reason: classified.kind,
697
+ waitMs: ms,
698
+ attempt: count + 1,
699
+ note: `${label} is rate limited · trying again in ${seconds} s (${count + 1} of ${MAX_RATE_LIMIT_WAITS_PER_STEP})`,
700
+ });
701
+ const sleep = this.deps.sleep ?? abortableSleep;
702
+ const waited = await sleep(ms, payload?.signal);
703
+ return waited !== false && !payload?.signal?.aborted;
704
+ }
705
+
706
+ async fallback(agent, payload, classified) {
707
+ const current = this.deps.current(agent) ?? {};
708
+ const fromId = nonEmpty(payload?.provider) ? payload.provider : current.provider;
709
+ const model = current.model;
710
+ if (!nonEmpty(fromId) || !nonEmpty(model)) return false;
711
+ const fromLabel = connectionLabel(fromId);
712
+ this.markDegraded(fromId, classified, fromLabel);
713
+ const target = await this.nextFor(fromId, model);
714
+ if (target === undefined) return false;
715
+ const { policy } = this.deps.settings();
716
+ const needsAsk = policy === 'ask' || (policy === 'ask-managed' && target.connection.kind === 'managed');
717
+ const why = reasonPhrase(fromLabel, classified);
718
+ if (needsAsk) {
719
+ if (typeof this.deps.ask !== 'function') return false;
720
+ const yes = `Switch to ${target.connection.label}`;
721
+ const picked = await this.deps.ask(agent, {
722
+ id: ASK_QUESTION_ID,
723
+ header: 'Connection',
724
+ question: `${why}. Continue on ${target.connection.label}?`,
725
+ detail: `${target.connection.label} serves ${target.model}. Picasso moves back to ${fromLabel} once it recovers.`,
726
+ options: [{ label: yes, description: `Use ${target.connection.label} for this run` }, { label: 'Not now', description: 'Stop here' }],
727
+ }, payload?.signal);
728
+ if (picked !== yes) return false;
729
+ }
730
+ const sessionId = sessionIdOf(agent);
731
+ const known = this.sessions.get(sessionId);
732
+ const home = known?.home ?? { id: fromId, model, ...(nonEmpty(current.reasoningEffort) ? { reasoningEffort: current.reasoningEffort } : {}) };
733
+ const selection = { provider: target.connection.id, model: target.model, ...(nonEmpty(current.reasoningEffort) ? { reasoningEffort: current.reasoningEffort } : {}) };
734
+ // `immediate`: the failed step is retried right away, so the switch must reach that retry's request too.
735
+ const installed = await this.deps.install(agent, selection, { immediate: true });
736
+ if (installed === undefined) return false;
737
+ this.sessions.set(sessionId, { home, active: { id: target.connection.id, model: installed.model ?? target.model } });
738
+ this.lastProbe.set(sessionId, this.now());
739
+ this.deps.note?.(agent, {
740
+ type: SWITCH_EVENT,
741
+ direction: 'fallback',
742
+ from: { id: fromId, label: fromLabel, model },
743
+ to: { id: target.connection.id, label: target.connection.label, model: installed.model ?? target.model },
744
+ reason: classified.kind,
745
+ note: `Switched to ${target.connection.label} · ${why}`,
746
+ });
747
+ return true;
748
+ }
749
+
750
+ /**
751
+ * `agent/pre-step`: while a session runs on a fallback, once the home connection's rest is over, probe it (or,
752
+ * with no probe seam, just try it on this request) and move back when it answers.
753
+ */
754
+ async maybeRestore(agent) {
755
+ const sessionId = sessionIdOf(agent);
756
+ const state = this.sessions.get(sessionId);
757
+ if (state === undefined || isChildAgent(agent)) return false;
758
+ const now = this.now();
759
+ const down = this.degraded.get(state.home.id);
760
+ if (down !== undefined && down.until > now) return false;
761
+ const last = this.lastProbe.get(sessionId) ?? 0;
762
+ if (down !== undefined && now - last < cooldownMs()) return false;
763
+ this.lastProbe.set(sessionId, now);
764
+ const homeLabel = connectionLabel(state.home.id);
765
+ if (typeof this.deps.probe === 'function') {
766
+ let result;
767
+ try {
768
+ result = await this.deps.probe({ id: state.home.id, label: homeLabel }, state.home.model);
769
+ } catch (error) {
770
+ result = { ok: false, failure: { code: 'TRANSPORT', message: error instanceof Error ? error.message : String(error) } };
771
+ }
772
+ if (!result?.ok) {
773
+ const classified = classifyFailure(result?.failure);
774
+ this.markDegraded(state.home.id, classified.fallback ? classified : { ...classified, kind: 'outage', reason: 'is unavailable' }, homeLabel);
775
+ return false;
776
+ }
777
+ }
778
+ // `immediate`: the step being prepared (its route is already fixed) runs on the recovered connection too.
779
+ const installed = await this.deps.install(agent, {
780
+ provider: state.home.id,
781
+ model: state.home.model,
782
+ ...(nonEmpty(state.home.reasoningEffort) ? { reasoningEffort: state.home.reasoningEffort } : {}),
783
+ }, { immediate: true });
784
+ if (installed === undefined) return false;
785
+ this.degraded.delete(state.home.id);
786
+ this.sessions.delete(sessionId);
787
+ this.deps.note?.(agent, {
788
+ type: SWITCH_EVENT,
789
+ direction: 'restore',
790
+ from: { id: state.active.id, label: connectionLabel(state.active.id), model: state.active.model },
791
+ to: { id: state.home.id, label: homeLabel, model: installed.model ?? state.home.model },
792
+ reason: 'recovered',
793
+ note: `Back on ${homeLabel}`,
794
+ });
795
+ return true;
796
+ }
797
+
798
+ /** A connection answered (probe or a successful request): clear its rest. */
799
+ recovered(id) {
800
+ this.degraded.delete(id);
801
+ }
802
+
803
+ /** A user's own model pick ends the session's fallback bookkeeping (they chose the route). */
804
+ forget(sessionId) {
805
+ this.sessions.delete(sessionId);
806
+ this.lastProbe.delete(sessionId);
807
+ this.stepSwitches.delete(sessionId);
808
+ this.rateWaits.delete(sessionId);
809
+ }
810
+
811
+ /** `modelRouter/checkAccess {id, model?}` — one tiny probe request. */
812
+ async checkAccess(params) {
813
+ const id = params?.id;
814
+ if (!nonEmpty(id)) throw new TypeError('checkAccess needs a connection id');
815
+ const started = this.now();
816
+ let model = nonEmpty(params?.model) ? params.model : undefined;
817
+ if (model === undefined) {
818
+ const models = await this.deps.models(id).catch(() => []);
819
+ model = models[0];
820
+ }
821
+ if (model === undefined) return { id, ok: false, reason: 'No models configured for this connection', code: 'NO_MODELS', latencyMs: 0 };
822
+ if (typeof this.deps.probe !== 'function') return { id, model, ok: false, reason: 'Probing is unavailable here', code: 'NO_PROBE', latencyMs: 0 };
823
+ let result;
824
+ try {
825
+ result = await this.deps.probe({ id, label: connectionLabel(id) }, model);
826
+ } catch (error) {
827
+ result = { ok: false, failure: { code: 'TRANSPORT', message: error instanceof Error ? error.message : String(error) } };
828
+ }
829
+ const latencyMs = Math.max(0, this.now() - started);
830
+ if (result?.ok) {
831
+ this.recovered(id);
832
+ return { id, model, ok: true, latencyMs };
833
+ }
834
+ const failure = result?.failure ?? {};
835
+ const classified = classifyFailure(failure);
836
+ if (classified.fallback) this.markDegraded(id, classified, connectionLabel(id));
837
+ return {
838
+ id,
839
+ model,
840
+ ok: false,
841
+ reason: probeReason(classified, failure),
842
+ kind: classified.kind,
843
+ ...(nonEmpty(failure.code) ? { code: failure.code } : {}),
844
+ ...(Number.isInteger(failure.status) ? { status: failure.status } : {}),
845
+ latencyMs,
846
+ };
847
+ }
848
+ }
849
+
850
+ export function sessionIdOf(agent) {
851
+ return agent?.session?.header?.id ?? agent?.session?.id ?? agent?.id;
852
+ }
853
+
854
+ export function isChildAgent(agent) {
855
+ const header = agent?.session?.header;
856
+ if (!isRecord(header)) return false;
857
+ return header.origin === 'subagent' || (Number.isSafeInteger(header.delegationDepth) && header.delegationDepth > 0);
858
+ }
859
+
860
+ /**
861
+ * A probe over the engine's LLM registry: one `stream` call, one-word prompt, `maxTokens: 1`, bounded by
862
+ * {@link PROBE_TIMEOUT_MS}. Resolves `{ok: true}` on any non-error finish, else `{ok: false, failure}`.
863
+ */
864
+ export function llmProbe(llm, { timeoutMs = PROBE_TIMEOUT_MS } = {}) {
865
+ return async (connection, model) => {
866
+ const registry = typeof llm === 'function' ? llm() : llm;
867
+ if (registry === undefined || registry === null || typeof registry.stream !== 'function') {
868
+ return { ok: false, failure: { code: 'NO_ADAPTER', message: 'model access is unavailable' } };
869
+ }
870
+ const controller = new AbortController();
871
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
872
+ try {
873
+ for await (const chunk of registry.stream({
874
+ provider: connection.id,
875
+ model,
876
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'ping' }] }],
877
+ maxTokens: 1,
878
+ signal: controller.signal,
879
+ })) {
880
+ if (chunk?.type !== 'finish') continue;
881
+ const reason = chunk.reason;
882
+ if (reason?.kind === 'error' || reason?.kind === 'aborted') {
883
+ const failure = reason.failure ?? { code: 'SERVER', message: 'request failed' };
884
+ return { ok: false, failure: controller.signal.aborted && reason.kind === 'aborted' ? { code: 'TIMEOUT', message: 'probe timed out' } : failure };
885
+ }
886
+ return { ok: true };
887
+ }
888
+ return { ok: true };
889
+ } catch (error) {
890
+ return { ok: false, failure: { code: isRecord(error) && nonEmpty(error.code) ? error.code : 'TRANSPORT', message: error instanceof Error ? error.message : String(error), ...(isRecord(error) && Number.isInteger(error.status) ? { status: error.status } : {}) } };
891
+ } finally {
892
+ clearTimeout(timer);
893
+ }
894
+ };
895
+ }