@evandu/super-pi-server 0.0.0-stage → 0.1.260

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 (370) hide show
  1. package/README.md +250 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +396 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +450 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,989 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { readModelStore, storeWindowFor } from "./models-store.js";
5
+ import { SUPER_PI_DEFAULT_MAX_TOKENS, SUPER_PI_GUESSED_MAX_TOKENS as GUESSED_MAX_TOKENS } from "./model-context-window.js";
6
+ import { providerProxyFetch, readSharedProviderProxy } from "./provider-proxy.js";
7
+ import { hasStoredCredential, publicProviderNetwork, updateProviderNetwork, ProviderNetworkInputError } from "./provider-network.js";
8
+ import { supportsProviderProxy } from "../shared/provider-network.js";
9
+ import { isThinkingLevel, readThinkingLevelMap } from "../shared/thinking-levels.js";
10
+ import { discoverThinkingLevels } from "./thinking-level-discovery.js";
11
+ const unsupportedProxy = (provider) => !supportsProviderProxy(provider);
12
+ /**
13
+ * The API adapters Pi ships, as the ids a provider may name.
14
+ *
15
+ * Taken from Pi's own `KnownApi` union (`pi-ai/dist/types.d.ts`) rather than invented: the id ends
16
+ * up in `models.json` and Pi looks the adapter up by exactly this string, and an unknown one fails
17
+ * at REQUEST time ("No API provider registered for api: ...") rather than at load time. Offering the
18
+ * list in the form is the difference between a person finding the right value and guessing.
19
+ */
20
+ export const KNOWN_APIS = [
21
+ "openai-completions",
22
+ "anthropic-messages",
23
+ "openai-responses",
24
+ "azure-openai-responses",
25
+ "openai-codex-responses",
26
+ "mistral-conversations",
27
+ "google-generative-ai",
28
+ "google-vertex",
29
+ "bedrock-converse-stream",
30
+ "pi-messages",
31
+ ];
32
+ /** The context window a model gets when the form does not say. Pi's own default. */
33
+ const DEFAULT_CONTEXT_WINDOW = 128000;
34
+ /** The output budget a model gets when the form does not say. Pi's own default. */
35
+ // THE SAME NUMBER AS `SUPER_PI_DEFAULT_MAX_TOKENS`, READ FROM THERE: the placeholder Super Pi
36
+ // stamps is the placeholder the arbitration must recognise later, so they cannot be two literals.
37
+ const DEFAULT_MAX_TOKENS = SUPER_PI_DEFAULT_MAX_TOKENS;
38
+ /**
39
+ * Pi's global configuration directory - where `models.json` and `auth.json` live.
40
+ *
41
+ * `PI_CODING_AGENT_DIR` wins, because that is Pi's own rule (`core/config.js:getAgentDir`) and a
42
+ * person who set it expects Pi to read its config from there. The fallback is Pi's own default,
43
+ * `~/.pi/agent`, with the home directory taken from the environment rather than from `os.homedir()`
44
+ * - on Windows the two disagree often enough to matter.
45
+ */
46
+ export function piAgentDir() {
47
+ const configured = process.env.PI_CODING_AGENT_DIR?.trim();
48
+ if (configured)
49
+ return configured;
50
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
51
+ return home ? join(home, ".pi", "agent") : join(".pi", "agent");
52
+ }
53
+ /** Pi's provider and model definitions. */
54
+ export function piModelsPath(agentDir = piAgentDir()) {
55
+ return join(agentDir, "models.json");
56
+ }
57
+ /** Pi's credential store. */
58
+ export function piAuthPath(agentDir = piAgentDir()) {
59
+ return join(agentDir, "auth.json");
60
+ }
61
+ /**
62
+ * Strips JSONC comments, the way Pi's own parser does.
63
+ *
64
+ * Pi reads `models.json` with comments allowed, so a person may well have written comments in it -
65
+ * and Super Pi has to be able to READ that file to merge into it. A naive strip would corrupt a
66
+ * string that contains `//` (a base URL with a path, an api key with a slash), so this walks the
67
+ * text and tracks whether it is inside a string.
68
+ */
69
+ export function stripJsonComments(text) {
70
+ let out = "";
71
+ let inString = false;
72
+ let inLineComment = false;
73
+ let inBlockComment = false;
74
+ for (let index = 0; index < text.length; index++) {
75
+ const char = text[index];
76
+ const next = text[index + 1];
77
+ if (inLineComment) {
78
+ if (char === "\n") {
79
+ inLineComment = false;
80
+ out += char;
81
+ }
82
+ else
83
+ out += " ";
84
+ continue;
85
+ }
86
+ if (inBlockComment) {
87
+ if (char === "*" && next === "/") {
88
+ inBlockComment = false;
89
+ out += " ";
90
+ index++;
91
+ }
92
+ else
93
+ out += char === "\n" ? "\n" : " ";
94
+ continue;
95
+ }
96
+ if (inString) {
97
+ out += char;
98
+ if (char === "\\" && next !== undefined) {
99
+ out += next;
100
+ index++;
101
+ }
102
+ else if (char === "\"")
103
+ inString = false;
104
+ continue;
105
+ }
106
+ if (char === "\"") {
107
+ inString = true;
108
+ out += char;
109
+ continue;
110
+ }
111
+ if (char === "/" && next === "/") {
112
+ inLineComment = true;
113
+ out += " ";
114
+ index++;
115
+ continue;
116
+ }
117
+ if (char === "/" && next === "*") {
118
+ inBlockComment = true;
119
+ out += " ";
120
+ index++;
121
+ continue;
122
+ }
123
+ out += char;
124
+ }
125
+ return out;
126
+ }
127
+ /** Reads a JSON file, returning undefined when it does not exist. */
128
+ async function readJsonFile(path) {
129
+ let text;
130
+ try {
131
+ text = await readFile(path, "utf8");
132
+ }
133
+ catch (error) {
134
+ if (error.code === "ENOENT")
135
+ return undefined;
136
+ throw error;
137
+ }
138
+ if (!text.trim())
139
+ return undefined;
140
+ try {
141
+ return JSON.parse(stripJsonComments(text));
142
+ }
143
+ catch (error) {
144
+ // A file Super Pi cannot parse is a file Super Pi must NOT overwrite: the person who wrote it
145
+ // put something in there this server does not understand, and replacing it with a parse of
146
+ // nothing would destroy their work.
147
+ throw new Error(`${path} 解析失败,为避免覆盖你的文件已停止写入:${error instanceof Error ? error.message : String(error)}`);
148
+ }
149
+ }
150
+ /** The permissions a file already has, or 0600 when it is new. */
151
+ async function fileMode(path) {
152
+ try {
153
+ const info = await stat(path);
154
+ return info.mode & 0o777;
155
+ }
156
+ catch {
157
+ return 0o600;
158
+ }
159
+ }
160
+ /**
161
+ * Writes a file atomically: a temporary file next to it, then a rename over the target.
162
+ *
163
+ * A rename is atomic on every platform Super Pi runs on, so a reader - Pi, or a person with an
164
+ * editor open - sees either the old file or the new one, never half of each. Writing in place would
165
+ * leave a window in which Pi reads a truncated `models.json` and loses every provider in it.
166
+ */
167
+ async function writeJsonAtomic(path, value) {
168
+ await mkdir(dirname(path), { recursive: true });
169
+ const mode = await fileMode(path);
170
+ const temporary = `${path}.${randomUUID()}.tmp`;
171
+ try {
172
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode });
173
+ await rename(temporary, path);
174
+ }
175
+ catch (error) {
176
+ await writeFile(temporary, "{}", { mode }).catch(() => { });
177
+ throw error;
178
+ }
179
+ }
180
+ /**
181
+ * The fields of a `models.json` provider entry that Pi's schema refuses.
182
+ *
183
+ * PI'S RULE, NOT OURS: `baseUrl`, `name` and `api` are optional, but when they are present they
184
+ * need at least one character. An empty string is not "absent" - it is a value Pi rejects, and Pi
185
+ * rejects the WHOLE FILE when it finds one, which is why one bad entry can empty every picker.
186
+ */
187
+ function invalidModelFields(entry) {
188
+ const fields = [];
189
+ for (const field of ["name", "baseUrl", "api"]) {
190
+ if (entry[field] === "")
191
+ fields.push(field);
192
+ }
193
+ return fields;
194
+ }
195
+ /**
196
+ * The provider entry Super Pi writes into Pi's `models.json`, MERGED into what was already there.
197
+ *
198
+ * NO `apiKey` IS WRITTEN HERE, and that is a decision with a reason behind it: a value in
199
+ * `models.json` goes through Pi's config-value syntax, where `$NAME` means "read this environment
200
+ * variable" and `!command` means "run this and take its output". A key that happens to start with a
201
+ * dollar sign would be silently turned into something else. `auth.json` stores the key verbatim, and
202
+ * it is where Pi's own `/login` puts it, so that is where this goes. A key the PERSON wrote there is
203
+ * left alone, because this function never touches fields it does not own.
204
+ *
205
+ * WHY IT MERGES RATHER THAN REPLACES. Pi's provider schema holds more than this form collects -
206
+ * `cost`, `headers`, `samplingParams`, `thinkingLevelMap`, `modelOverrides`, `oauth`, `authHeader`,
207
+ * an inline `apiKey` - and a settings panel that calls itself a view of Pi's configuration cannot
208
+ * delete the parts of it it has no field for. An earlier version replaced the whole entry, so
209
+ * editing ONE provider silently rewrote every OTHER entry in the file in this app's shape.
210
+ */
211
+ function toPiProvider(provider, existing) {
212
+ const base = existing && typeof existing === "object" ? { ...existing } : {};
213
+ const previousModels = Array.isArray(base.models) ? base.models : [];
214
+ const models = provider.models.map(model => {
215
+ const prior = previousModels.find((entry) => entry?.id === model.id);
216
+ const priorModel = prior && typeof prior === "object" ? prior : {};
217
+ const priorCompat = priorModel.compat && typeof priorModel.compat === "object"
218
+ ? priorModel.compat
219
+ : {};
220
+ const compat = {
221
+ ...priorCompat,
222
+ ...(model.supportsDeveloperRole === undefined ? {} : { supportsDeveloperRole: model.supportsDeveloperRole }),
223
+ ...(model.supportsReasoningEffort === undefined ? {} : { supportsReasoningEffort: model.supportsReasoningEffort }),
224
+ };
225
+ // THE THINKING MAP, IN THREE STATES. A map is written when there is one; `null` REMOVES the one
226
+ // that was there (the levels described an endpoint this model is no longer served by); and
227
+ // ABSENT leaves the saved map alone - a map somebody wrote by hand in Pi's own file is not this
228
+ // form's to delete, and an import that knows nothing about the levels must not throw them away.
229
+ const thinkingLevelMap = model.thinkingLevelMap === null
230
+ ? undefined
231
+ : (model.thinkingLevelMap ?? priorModel.thinkingLevelMap);
232
+ // A MAP MEANS THE MODEL THINKS - UNLESS SOMEBODY SAID OTHERWISE. Pi offers only `off` for a
233
+ // model that does not reason, so levels without `reasoning` would be levels that do nothing;
234
+ // but a model somebody turned off BY HAND stays off, because the map is not a licence to
235
+ // overrule the word that is already there.
236
+ const reasoning = thinkingLevelMap && model.reasoning === undefined
237
+ ? true
238
+ : (model.reasoning ?? false);
239
+ return {
240
+ ...priorModel,
241
+ id: model.id,
242
+ // NEVER AN EMPTY STRING. Pi's schema asks for at least one character, and one empty name
243
+ // invalidates the WHOLE models.json - which takes every custom provider out of every picker
244
+ // with nothing but "must not have fewer than 1 characters" to explain it.
245
+ name: model.name || model.id,
246
+ reasoning,
247
+ input: model.imageInput ? ["text", "image"] : ["text"],
248
+ contextWindow: model.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
249
+ maxTokens: model.maxTokens ?? DEFAULT_MAX_TOKENS,
250
+ ...(Object.keys(compat).length ? { compat } : { compat: undefined }),
251
+ ...(thinkingLevelMap === undefined
252
+ ? (model.thinkingLevelMap === null ? { thinkingLevelMap: undefined } : {})
253
+ : { thinkingLevelMap }),
254
+ };
255
+ });
256
+ return {
257
+ ...base,
258
+ ...(provider.name ? { name: provider.name } : {}),
259
+ // AN EMPTY ADDRESS IS OMITTED, not written as "". Pi's schema refuses a baseUrl shorter than one
260
+ // character, so writing "" for an entry that had none - a built-in override, for instance -
261
+ // would make Pi reject the whole file at its next start.
262
+ ...(provider.baseUrl ? { baseUrl: provider.baseUrl } : {}),
263
+ ...(provider.api ? { api: provider.api } : {}),
264
+ models,
265
+ };
266
+ }
267
+ /**
268
+ * The providers Super Pi manages, and the writes that make Pi know about them.
269
+ *
270
+ * The class owns three files: its own registry, Pi's `models.json` and Pi's `auth.json`. Only the
271
+ * first is a truth source; the other two are rewritten from it.
272
+ */
273
+ export class ProviderRegistry {
274
+ dataDir;
275
+ piDir;
276
+ /**
277
+ * `piDir` is Pi's own configuration directory, and it is a PARAMETER rather than a lookup at
278
+ * write time for one reason: a test that forgets to set `PI_CODING_AGENT_DIR` would then write to
279
+ * the developer's real `~/.pi/agent`. With the directory in hand, a test cannot reach it by
280
+ * accident - it has to be given one.
281
+ */
282
+ constructor(dataDir, piDir = piAgentDir()) {
283
+ this.dataDir = dataDir;
284
+ this.piDir = piDir;
285
+ }
286
+ networkQueue = Promise.resolve();
287
+ async sharedNetworkRecord(known) {
288
+ const saved = await readSharedProviderProxy(this.piDir);
289
+ if (saved)
290
+ return saved;
291
+ // Seed the common address from existing manual settings without rewriting their credentials.
292
+ const [registry, auth] = await Promise.all([this.readRegistry(), readJsonFile(piAuthPath(this.piDir))])
293
+ .catch(() => { throw new Error("无法读取网络设置,请检查 Pi 配置文件的格式和读取权限"); });
294
+ const excludedProviders = known.filter(provider => unsupportedProxy(provider)).map(provider => provider.id);
295
+ const entries = known.filter(provider => !excludedProviders.includes(provider.id)).map(provider => {
296
+ const credential = registry.disabled.find(entry => entry.id === provider.id)?.credential ?? auth?.[provider.id];
297
+ return { id: provider.id, credential: credential };
298
+ }).filter(entry => publicProviderNetwork(entry.credential).mode === "proxy");
299
+ return { env: entries[0]?.credential?.env ?? {}, providers: entries.map(entry => entry.id), excludedProviders };
300
+ }
301
+ async sharedNetwork(known) {
302
+ const record = await this.sharedNetworkRecord(known);
303
+ const visible = publicProviderNetwork({ env: record.env });
304
+ return { httpProxy: visible.httpProxy || visible.httpsProxy, hasAuth: visible.httpProxyHasAuth || visible.httpsProxyHasAuth, providers: record.providers.filter(id => known.some(provider => provider.id === id)) };
305
+ }
306
+ async setSharedNetwork(input, known) {
307
+ const operation = this.networkQueue.catch(() => undefined).then(async () => {
308
+ const value = input;
309
+ if (!value || !Array.isArray(value.providers) || value.providers.length > 1000 || value.providers.some(id => typeof id !== "string" || !known.some(provider => provider.id === id && !unsupportedProxy(provider))))
310
+ throw new ProviderNetworkInputError("请选择支持代理的供应商");
311
+ if (value.httpProxy !== undefined && typeof value.httpProxy !== "string")
312
+ throw new ProviderNetworkInputError("请填写 HTTP / HTTPS 代理地址");
313
+ const current = await this.sharedNetworkRecord(known);
314
+ const address = value.httpProxy ?? current.env.http_proxy ?? current.env.HTTP_PROXY ?? current.env.https_proxy ?? current.env.HTTPS_PROXY ?? current.env.all_proxy ?? current.env.ALL_PROXY ?? "";
315
+ const next = updateProviderNetwork(undefined, !address && !value.providers.length
316
+ ? { mode: "direct" }
317
+ : { mode: "proxy", httpProxy: address, httpsProxy: "", noProxy: "" });
318
+ if (next?.env)
319
+ next.env.ALL_PROXY = next.env.all_proxy = "";
320
+ const record = { env: next?.env ?? {}, providers: [...new Set(value.providers)], excludedProviders: known.filter(unsupportedProxy).map(provider => provider.id) };
321
+ await writeJsonAtomic(join(this.piDir, "shared-provider-proxy.json"), record);
322
+ return this.sharedNetwork(known);
323
+ });
324
+ this.networkQueue = operation;
325
+ return operation;
326
+ }
327
+ async clearNetworkOverride(providerId) {
328
+ const record = await readSharedProviderProxy(this.piDir);
329
+ if (record?.providers.includes(providerId))
330
+ await writeJsonAtomic(join(this.piDir, "shared-provider-proxy.json"), { ...record, providers: record.providers.filter(id => id !== providerId) });
331
+ }
332
+ /** Super Pi's own registry: the providers it manages, with their keys. */
333
+ get registryPath() {
334
+ return join(this.dataDir, "providers.json");
335
+ }
336
+ /** The registry file as one object: the managed providers AND the ones turned off. */
337
+ async readRegistry() {
338
+ const raw = await readJsonFile(this.registryPath);
339
+ if (!raw || typeof raw !== "object")
340
+ return { providers: [], disabled: [] };
341
+ const record = raw;
342
+ const providerList = Array.isArray(record.providers)
343
+ ? record.providers.filter((p) => Boolean(p) && typeof p === "object")
344
+ : [];
345
+ const disabledList = Array.isArray(record.disabled)
346
+ ? record.disabled.filter((p) => Boolean(p) && typeof p === "object" && typeof p.id === "string")
347
+ : [];
348
+ return { providers: providerList, disabled: disabledList };
349
+ }
350
+ /** Writes one half of the registry file without losing the other. */
351
+ async writeRegistry(value) {
352
+ const current = await this.readRegistry();
353
+ await writeJsonAtomic(this.registryPath, {
354
+ providers: value.providers ?? current.providers,
355
+ disabled: value.disabled ?? current.disabled,
356
+ });
357
+ }
358
+ /**
359
+ * Reads all configured providers directly from Pi's models.json and auth.json.
360
+ * Super Pi acts as the direct visual management plane for Pi's model configurations.
361
+ *
362
+ * PROVIDERS THAT ARE TURNED OFF ARE NOT IN HERE. They have been taken out of Pi's files - that is
363
+ * what "off" means - so this list is exactly what Pi would offer, which is what the write path
364
+ * (`set`, `remove`, `applyToPi`) has to reason about. `loadDisabled()` is the other half, for the
365
+ * panel that has to be able to switch them back on.
366
+ */
367
+ async load() {
368
+ const modelsPath = piModelsPath(this.piDir);
369
+ const authPath = piAuthPath(this.piDir);
370
+ const piModels = (await readJsonFile(modelsPath))?.providers ?? {};
371
+ const piAuth = (await readJsonFile(authPath)) ?? {};
372
+ const registry = await this.readRegistry();
373
+ const backupList = registry.providers;
374
+ const backupMap = new Map(backupList.map((p) => [p.id, p]));
375
+ // A provider that is OFF must not come back through the backup: the backup is where our keys
376
+ // live, and a key for a provider the person switched off would silently switch it back on at
377
+ // the next `load()` - before any UI could show the switch.
378
+ const offIds = new Set(registry.disabled.map((entry) => entry.id));
379
+ const providers = [];
380
+ const seen = new Set();
381
+ for (const [pId, pData] of Object.entries(piModels)) {
382
+ if (!pData || typeof pData !== "object" || offIds.has(pId))
383
+ continue;
384
+ seen.add(pId);
385
+ const rec = pData;
386
+ const backup = backupMap.get(pId);
387
+ const baseUrl = typeof rec.baseUrl === "string" ? rec.baseUrl : (backup?.baseUrl ?? "");
388
+ const api = typeof rec.api === "string" ? rec.api : (backup?.api ?? "openai-completions");
389
+ const name = typeof rec.name === "string" ? rec.name : (backup?.name ?? pId);
390
+ const rawModels = Array.isArray(rec.models) ? rec.models : (backup?.models ?? []);
391
+ const models = rawModels.map((m) => {
392
+ // THE THINKING MAP IS READ BACK, or the panel would show a model with no levels while Pi is
393
+ // offering exactly the ones the file says. What is in Pi's own file IS what the model has.
394
+ const thinkingLevelMap = readThinkingLevelMap(m?.thinkingLevelMap);
395
+ return {
396
+ id: typeof m?.id === "string" ? m.id : String(m),
397
+ name: typeof m?.name === "string" ? m.name : m?.id,
398
+ // THE MODEL'S OWN WORD ABOUT THINKING, kept as it was written. A model whose entry says
399
+ // nothing about it stays silent - so the layers below can tell "somebody turned the
400
+ // thinking off" from "nobody ever said" - and the panel fills the gap with false.
401
+ reasoning: typeof m?.reasoning === "boolean" ? m.reasoning : undefined,
402
+ imageInput: Array.isArray(m?.input) ? m.input.includes("image") : false,
403
+ contextWindow: typeof m?.contextWindow === "number" ? m.contextWindow : undefined,
404
+ maxTokens: typeof m?.maxTokens === "number" ? m.maxTokens : undefined,
405
+ // THE TWO COMPATIBILITY SWITCHES ARE READ BACK, or the form would show its own defaults for
406
+ // a setting the file explicitly turned off, and saving the form would silently turn it on.
407
+ ...(typeof m?.compat?.supportsDeveloperRole === "boolean" ? { supportsDeveloperRole: m.compat.supportsDeveloperRole } : {}),
408
+ ...(typeof m?.compat?.supportsReasoningEffort === "boolean" ? { supportsReasoningEffort: m.compat.supportsReasoningEffort } : {}),
409
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
410
+ };
411
+ });
412
+ const apiKey = backup?.apiKey;
413
+ providers.push({
414
+ id: pId,
415
+ name,
416
+ baseUrl,
417
+ api,
418
+ ...(apiKey ? { apiKey } : {}),
419
+ // ANY credential counts, not only a `key`. An OAuth provider keeps `access`/`refresh` in
420
+ // this file, and reporting "no key" for a provider Pi is happily using is a lie the panel
421
+ // would then show next to a working model.
422
+ hasAuthKey: Boolean(hasStoredCredential(piAuth[pId]) || backup?.apiKey),
423
+ // A KEY WRITTEN IN models.json IS A CREDENTIAL TOO, and it is the one Pi's own docs lead
424
+ // with (`"apiKey": "$MY_KEY"`). Without this, such a provider is reported as having no
425
+ // credential - and the panel then says "Pi will not offer it", which is wrong exactly when
426
+ // the environment variable is set and Pi is offering it right now.
427
+ ...(typeof rec.apiKey === "string" && rec.apiKey ? { keyInModelsJson: true } : {}),
428
+ // THE FIELDS PI WILL REFUSE. Pi validates the WHOLE models.json against a schema where an
429
+ // empty string is not a value ("must not have fewer than 1 characters"), and one bad entry
430
+ // invalidates the file - which takes EVERY custom provider out of every picker while this
431
+ // panel, which reads the file leniently, still lists them all. Naming the offending fields
432
+ // is what turns "my provider vanished" into "your file has an empty baseUrl".
433
+ ...(invalidModelFields(rec).length ? { invalidFields: invalidModelFields(rec) } : {}),
434
+ models,
435
+ });
436
+ }
437
+ for (const b of backupList) {
438
+ if (!seen.has(b.id) && !offIds.has(b.id)) {
439
+ providers.push(b);
440
+ }
441
+ }
442
+ return providers;
443
+ }
444
+ /**
445
+ * Pi's OWN providers: the ones that exist because they have a credential in `auth.json` and no
446
+ * entry in `models.json`.
447
+ *
448
+ * WHY THIS IS A SEPARATE READ. A built-in such as `kimi-coding` is defined inside Pi, not in a
449
+ * file - the only thing a person has configured for it is the credential. Those providers are
450
+ * invisible to `load()`, which reads `models.json`, and that is correct for the WRITE path:
451
+ * writing an empty `models.json` entry for a built-in would shadow Pi's own definition with a
452
+ * broken one. But they are exactly what a person wants to switch off ("I stopped paying for this
453
+ * plan"), so the panel has to see them. This returns the ids and the fact of a credential; the
454
+ * models come from Pi's catalogue, which this file layer cannot see.
455
+ */
456
+ async loadCredentialOnly() {
457
+ const modelsPath = piModelsPath(this.piDir);
458
+ const authPath = piAuthPath(this.piDir);
459
+ const piModels = (await readJsonFile(modelsPath))?.providers ?? {};
460
+ const piAuth = (await readJsonFile(authPath)) ?? {};
461
+ const registry = await this.readRegistry();
462
+ const offIds = new Set(registry.disabled.map((entry) => entry.id));
463
+ return Object.keys(piAuth)
464
+ .filter((id) => !piModels[id] && !offIds.has(id))
465
+ .map((id) => ({ id, name: id, baseUrl: "", api: "", hasAuthKey: hasStoredCredential(piAuth[id]), builtin: true, models: [] }));
466
+ }
467
+ /** The providers that are switched off, as the panel needs to see them. */
468
+ async loadDisabled() {
469
+ return (await this.readRegistry()).disabled;
470
+ }
471
+ /**
472
+ * Takes a provider out of Pi's configuration and remembers exactly what was taken out.
473
+ *
474
+ * TWO FILES, and both are needed. `models.json` is where a custom provider's models are defined;
475
+ * `auth.json` is where its credential is. Pi offers a provider's models only when its auth is
476
+ * configured (`ModelRuntime.getAvailable()` filters on exactly that), so removing the credential
477
+ * is what makes a BUILT-IN stop being offered - it has no `models.json` entry to remove - while
478
+ * removing both is what makes a custom one disappear completely.
479
+ *
480
+ * NOTHING IS THROWN AWAY. Both pieces are written into Super Pi's own registry, which is how
481
+ * `enable` can put them back byte for byte. A person switching off a lapsed subscription provider
482
+ * is not asking to forget their endpoint and their models.
483
+ */
484
+ async disable(providerId, models = []) {
485
+ const modelsPath = piModelsPath(this.piDir);
486
+ const authPath = piAuthPath(this.piDir);
487
+ const piModels = (await readJsonFile(modelsPath));
488
+ const piAuth = (await readJsonFile(authPath)) ?? {};
489
+ const currentProviders = { ...(piModels?.providers ?? {}) };
490
+ const modelsEntry = currentProviders[providerId];
491
+ const credential = piAuth[providerId];
492
+ if (!modelsEntry && !credential) {
493
+ throw new Error(`Pi 的配置里没有供应商「${providerId}」,无法停用`);
494
+ }
495
+ // Write Pi's files FIRST, and only then remember the switch. A registry that says "off" while
496
+ // Pi still offers the provider is the one state this must never leave behind: the panel would
497
+ // report a provider as gone while it is still in the picker.
498
+ if (modelsEntry) {
499
+ delete currentProviders[providerId];
500
+ await writeJsonAtomic(modelsPath, { ...(piModels ?? {}), providers: currentProviders });
501
+ }
502
+ if (credential) {
503
+ const nextAuth = { ...piAuth };
504
+ delete nextAuth[providerId];
505
+ await writeJsonAtomic(authPath, nextAuth);
506
+ }
507
+ const registry = await this.readRegistry();
508
+ const record = {
509
+ id: providerId,
510
+ ...(typeof modelsEntry === "object" && modelsEntry && typeof modelsEntry.name === "string"
511
+ ? { name: modelsEntry.name }
512
+ : {}),
513
+ ...(modelsEntry ? { modelsEntry: modelsEntry } : {}),
514
+ ...(credential ? { credential: credential } : {}),
515
+ models,
516
+ };
517
+ try {
518
+ await this.writeRegistry({
519
+ providers: registry.providers.filter((provider) => provider.id !== providerId),
520
+ disabled: [...registry.disabled.filter((entry) => entry.id !== providerId), record],
521
+ });
522
+ }
523
+ catch (error) {
524
+ // The record is what makes the switch reversible, so a failure to write it means the provider
525
+ // has been taken out of Pi's files with nothing left to restore it from. Pi's files are put
526
+ // back before the error is reported - the same rule `set()` follows, for the same reason.
527
+ if (modelsEntry) {
528
+ await writeJsonAtomic(modelsPath, { ...(piModels ?? {}), providers: { ...currentProviders, [providerId]: modelsEntry } }).catch(() => undefined);
529
+ }
530
+ if (credential) {
531
+ await writeJsonAtomic(authPath, { ...piAuth, [providerId]: credential }).catch(() => undefined);
532
+ }
533
+ throw error;
534
+ }
535
+ }
536
+ /**
537
+ * Puts a provider back exactly where `disable` took it from.
538
+ *
539
+ * AN EXISTING ENTRY IS NOT OVERWRITTEN. The person may have re-created the provider (or written a
540
+ * new `models.json` entry for the same id) while it was off; the newer entry is theirs and wins,
541
+ * and only the missing piece is restored. Refusing would be worse: the switch says "back on", and
542
+ * the credential is what makes it usable.
543
+ */
544
+ async enable(providerId) {
545
+ const registry = await this.readRegistry();
546
+ const record = registry.disabled.find((entry) => entry.id === providerId);
547
+ if (!record)
548
+ throw new Error(`供应商「${providerId}」没有被停用`);
549
+ if (record.modelsEntry) {
550
+ const modelsPath = piModelsPath(this.piDir);
551
+ const piModels = (await readJsonFile(modelsPath)) ?? {};
552
+ const providers = { ...(piModels.providers ?? {}) };
553
+ if (!providers[providerId]) {
554
+ providers[providerId] = record.modelsEntry;
555
+ await writeJsonAtomic(modelsPath, { ...piModels, providers });
556
+ }
557
+ }
558
+ if (record.credential) {
559
+ const authPath = piAuthPath(this.piDir);
560
+ const auth = (await readJsonFile(authPath)) ?? {};
561
+ if (!auth[providerId]) {
562
+ await writeJsonAtomic(authPath, { ...auth, [providerId]: record.credential });
563
+ }
564
+ }
565
+ await this.writeRegistry({
566
+ disabled: registry.disabled.filter((entry) => entry.id !== providerId),
567
+ });
568
+ }
569
+ /**
570
+ * Deletes a BUILT-IN provider's credential from Pi's `auth.json`.
571
+ *
572
+ * THE ONLY THING THERE IS TO DELETE. A built-in's models live in Pi itself; what a person has
573
+ * configured for it is the credential, and removing that is what makes Pi stop offering it. This
574
+ * is the PERMANENT version: unlike `disable`, nothing is remembered, so switching it back on means
575
+ * logging in to that provider again (which is what re-subscribing to the plan involves anyway).
576
+ */
577
+ async removeCredential(providerId) {
578
+ const authPath = piAuthPath(this.piDir);
579
+ const auth = (await readJsonFile(authPath));
580
+ if (!auth || !auth[providerId])
581
+ return;
582
+ const nextAuth = { ...auth };
583
+ delete nextAuth[providerId];
584
+ await writeJsonAtomic(authPath, nextAuth);
585
+ }
586
+ /** Forgets a disabled provider without restoring anything: the permanent form of "off". */
587
+ async forgetDisabled(providerId) {
588
+ const registry = await this.readRegistry();
589
+ const next = registry.disabled.filter((entry) => entry.id !== providerId);
590
+ if (next.length === registry.disabled.length)
591
+ throw new Error(`供应商「${providerId}」没有被停用`);
592
+ await this.writeRegistry({ disabled: next });
593
+ }
594
+ /**
595
+ * Removes the empty fields Pi's schema refuses, so the file is accepted again.
596
+ *
597
+ * WHY THIS IS A REPAIR AND NOT A DELETE. An empty `baseUrl` is not a provider with no address -
598
+ * it is a value Pi refuses, and Pi refuses the WHOLE FILE when it sees one. The fix is to drop
599
+ * the empty field (leaving the provider exactly as it was otherwise), NOT to remove the provider:
600
+ * the person wrote it, and an override-only entry - one that only adds models to a built-in - has
601
+ * no address at all, which is legal as long as the field is ABSENT rather than empty.
602
+ *
603
+ * NOTHING ELSE IN THE FILE IS TOUCHED. The entries are read as raw JSON and written back with
604
+ * only the offending fields removed, so a comment-free copy of a hand-written file stays a
605
+ * hand-written file.
606
+ */
607
+ async repairModelsConfig() {
608
+ const modelsPath = piModelsPath(this.piDir);
609
+ const raw = (await readJsonFile(modelsPath));
610
+ if (!raw || !raw.providers || typeof raw.providers !== "object")
611
+ return { fixed: [], changed: false };
612
+ const fixed = [];
613
+ let changed = false;
614
+ const providers = { ...raw.providers };
615
+ for (const [providerId, value] of Object.entries(providers)) {
616
+ if (!value || typeof value !== "object" || Array.isArray(value))
617
+ continue;
618
+ const entry = { ...value };
619
+ let touched = false;
620
+ for (const field of invalidModelFields(entry)) {
621
+ delete entry[field];
622
+ fixed.push(`${providerId}.${field}`);
623
+ touched = true;
624
+ }
625
+ if (Array.isArray(entry.models)) {
626
+ let modelsTouched = false;
627
+ const models = entry.models.map((model) => {
628
+ if (!model || typeof model !== "object" || Array.isArray(model))
629
+ return model;
630
+ const record = { ...model };
631
+ if (record.name === "") {
632
+ delete record.name;
633
+ fixed.push(`${providerId}.models.name`);
634
+ modelsTouched = true;
635
+ }
636
+ return record;
637
+ });
638
+ if (modelsTouched)
639
+ entry.models = models;
640
+ touched = touched || modelsTouched;
641
+ }
642
+ if (touched) {
643
+ providers[providerId] = entry;
644
+ changed = true;
645
+ }
646
+ }
647
+ if (changed)
648
+ await writeJsonAtomic(modelsPath, { ...raw, providers });
649
+ return { fixed, changed };
650
+ }
651
+ /** Writes the registry. The key lives here, so the file is 0600. */
652
+ async save(providers) {
653
+ await this.writeRegistry({ providers });
654
+ }
655
+ /**
656
+ * Directly updates Pi's models.json and auth.json to match the new set of providers.
657
+ * Full visual editor semantics: any provider in models.json is editable and removable.
658
+ */
659
+ async applyToPi(previous, next) {
660
+ const previousIds = new Set(previous.map((provider) => provider.id));
661
+ const nextIds = new Set(next.map((provider) => provider.id));
662
+ const modelsPath = piModelsPath(this.piDir);
663
+ const existing = await readJsonFile(modelsPath) ?? {};
664
+ const existingProviders = existing.providers ?? {};
665
+ const mergedProviders = { ...existingProviders };
666
+ for (const provider of next)
667
+ mergedProviders[provider.id] = toPiProvider(provider, existingProviders[provider.id]);
668
+ for (const id of previousIds)
669
+ if (!nextIds.has(id))
670
+ delete mergedProviders[id];
671
+ await writeJsonAtomic(modelsPath, { ...existing, providers: mergedProviders });
672
+ await this.applyKeysToPi(previous, next);
673
+ }
674
+ /**
675
+ * Writes the keys into Pi's `auth.json`.
676
+ */
677
+ async applyKeysToPi(previous, next) {
678
+ const authPath = piAuthPath(this.piDir);
679
+ const auth = await readJsonFile(authPath) ?? {};
680
+ const nextById = new Map(next.map((provider) => [provider.id, provider]));
681
+ for (const provider of next) {
682
+ if (provider.apiKey) {
683
+ // API-key credentials can carry provider-scoped env (including proxy routing).
684
+ // Preserve these settings when saving a key, but never mix OAuth fields into it.
685
+ const stored = auth[provider.id];
686
+ auth[provider.id] = {
687
+ ...(stored?.type === "api_key" ? stored : {}),
688
+ type: "api_key",
689
+ key: provider.apiKey,
690
+ };
691
+ }
692
+ }
693
+ for (const provider of previous) {
694
+ const updated = nextById.get(provider.id);
695
+ if (updated && updated.apiKey)
696
+ continue;
697
+ if (!updated && !provider.apiKey)
698
+ continue;
699
+ const stored = auth[provider.id];
700
+ if (stored?.type === "api_key" && provider.apiKey && stored.key === provider.apiKey)
701
+ delete auth[provider.id];
702
+ }
703
+ await writeJsonAtomic(authPath, auth);
704
+ }
705
+ }
706
+ /** The provider list as the browser sees it: the key becomes a fact. */
707
+ export function publicProviders(providers) {
708
+ return providers.map(provider => ({
709
+ id: provider.id,
710
+ name: provider.name ?? provider.id,
711
+ baseUrl: provider.baseUrl,
712
+ api: provider.api,
713
+ hasKey: Boolean(provider.apiKey || provider.hasAuthKey),
714
+ ...(provider.keyInModelsJson ? { keyInModelsJson: true } : {}),
715
+ ...(provider.invalidFields?.length ? { invalidFields: [...provider.invalidFields] } : {}),
716
+ ...(provider.builtin ? { builtin: true } : {}),
717
+ ...(provider.disabled ? { disabled: true } : {}),
718
+ models: provider.models.map(model => ({
719
+ id: model.id,
720
+ name: model.name ?? model.id,
721
+ reasoning: model.reasoning ?? false,
722
+ imageInput: model.imageInput ?? false,
723
+ contextWindow: model.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
724
+ maxTokens: model.maxTokens ?? DEFAULT_MAX_TOKENS,
725
+ // THE LEVELS TRAVEL TO THE BROWSER, because the panel shows them and the form sends them back.
726
+ // A model with no map simply has none - the browser must not invent one.
727
+ ...(model.thinkingLevelMap ? { thinkingLevelMap: { ...model.thinkingLevelMap } } : {}),
728
+ })),
729
+ }));
730
+ }
731
+ /**
732
+ * Checks the thinking map a form carried, and returns it in the shape the registry stores.
733
+ *
734
+ * THREE ANSWERS. `undefined` means the form said nothing about the levels, so whatever is saved
735
+ * stays. `null` means the form said "this model has no map", and the saved one goes. A map means
736
+ * "these are the levels", and every one of Pi's seven has to be named - a level that is not a level
737
+ * Pi knows, or a value that is neither a string nor `null`, is refused rather than written into
738
+ * Pi's file, where one bad field takes every provider out of every picker.
739
+ */
740
+ function checkedThinkingLevelMap(raw) {
741
+ if (raw === undefined)
742
+ return undefined;
743
+ if (raw === null)
744
+ return null;
745
+ if (typeof raw !== "object" || Array.isArray(raw))
746
+ throw new Error("思考档位必须是一个对象");
747
+ for (const [key, value] of Object.entries(raw)) {
748
+ if (!isThinkingLevel(key))
749
+ throw new Error(`思考档位「${key}」不是 Pi 的档位`);
750
+ if (value !== null && (typeof value !== "string" || !value.trim())) {
751
+ throw new Error(`思考档位「${key}」的值必须是非空字符串或 null`);
752
+ }
753
+ }
754
+ return readThinkingLevelMap(raw) ?? {};
755
+ }
756
+ /**
757
+ * Checks what the form collected and returns it in the shape the registry stores.
758
+ *
759
+ * EVERY RULE HERE SAYS WHY, because a message a person reads is the only validation they get: the
760
+ * server cannot ask a follow-up question, so a refusal has to name the field and the reason.
761
+ */
762
+ export function validateProvider(input) {
763
+ const raw = (input ?? {});
764
+ const id = typeof raw.id === "string" ? raw.id.trim() : "";
765
+ if (!id)
766
+ throw new Error("供应商 id 不能为空");
767
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(id))
768
+ throw new Error("供应商 id 只能包含字母、数字、点、下划线和连字符,且必须以字母或数字开头");
769
+ const name = typeof raw.name === "string" ? raw.name.trim() : "";
770
+ const baseUrl = typeof raw.baseUrl === "string" ? raw.baseUrl.trim() : "";
771
+ if (!baseUrl)
772
+ throw new Error("API 地址不能为空");
773
+ let parsed;
774
+ try {
775
+ parsed = new URL(baseUrl);
776
+ }
777
+ catch {
778
+ throw new Error(`API 地址不是合法的 URL:${baseUrl}`);
779
+ }
780
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
781
+ throw new Error("API 地址必须是 http:// 或 https://");
782
+ const api = typeof raw.api === "string" ? raw.api.trim() : "";
783
+ if (!api)
784
+ throw new Error("API 类型不能为空");
785
+ if (!KNOWN_APIS.includes(api))
786
+ throw new Error(`API 类型必须是下面之一:${KNOWN_APIS.join("、")}`);
787
+ const apiKey = typeof raw.apiKey === "string" ? raw.apiKey.trim() : "";
788
+ const models = Array.isArray(raw.models) ? raw.models : [];
789
+ if (!models.length)
790
+ throw new Error("至少要添加一个模型");
791
+ const checked = models.map((entry) => {
792
+ const model = (entry ?? {});
793
+ const modelId = typeof model.id === "string" ? model.id.trim() : "";
794
+ if (!modelId)
795
+ throw new Error("模型 id 不能为空");
796
+ if (modelId.length > 200)
797
+ throw new Error("模型 id 太长了");
798
+ const modelName = typeof model.name === "string" ? model.name.trim() : "";
799
+ const contextWindow = typeof model.contextWindow === "number" ? Math.round(model.contextWindow) : undefined;
800
+ if (contextWindow !== undefined && (!Number.isFinite(contextWindow) || contextWindow <= 0))
801
+ throw new Error("上下文窗口必须是一个正数");
802
+ const maxTokens = typeof model.maxTokens === "number" ? Math.round(model.maxTokens) : undefined;
803
+ if (maxTokens !== undefined && (!Number.isFinite(maxTokens) || maxTokens <= 0))
804
+ throw new Error("最大输出 token 必须是一个正数");
805
+ // THE THINKING MAP IS CHECKED RATHER THAN TRUSTED, because it goes straight into Pi's file. A
806
+ // key Pi does not know, or a value that is neither a string nor `null`, is refused here - the
807
+ // same way an empty `baseUrl` is refused, because Pi rejects the WHOLE file over one bad field.
808
+ const thinkingLevelMap = checkedThinkingLevelMap(model.thinkingLevelMap);
809
+ return {
810
+ id: modelId,
811
+ ...(modelName ? { name: modelName } : {}),
812
+ // BOTH WORDS ARE KEPT. A form that says the model does not think says it, and a form that
813
+ // says nothing says nothing - and the difference is the difference between "this model has
814
+ // its thinking switched off" and "nobody ever said".
815
+ ...(typeof model.reasoning === "boolean" ? { reasoning: model.reasoning } : {}),
816
+ ...(model.imageInput === true ? { imageInput: true } : {}),
817
+ ...(contextWindow === undefined ? {} : { contextWindow }),
818
+ ...(maxTokens === undefined ? {} : { maxTokens }),
819
+ ...(model.supportsDeveloperRole === false ? { supportsDeveloperRole: false } : {}),
820
+ ...(model.supportsReasoningEffort === false ? { supportsReasoningEffort: false } : {}),
821
+ ...(thinkingLevelMap === undefined ? {} : { thinkingLevelMap }),
822
+ };
823
+ });
824
+ return {
825
+ id,
826
+ ...(name ? { name } : {}),
827
+ baseUrl,
828
+ api,
829
+ ...(apiKey ? { apiKey } : {}),
830
+ models: checked,
831
+ };
832
+ }
833
+ /**
834
+ * Probes the provider's remote endpoint (OpenAI /models or Ollama /api/tags)
835
+ * and returns the list of available models with inferred metadata.
836
+ */
837
+ export async function fetchRemoteModels(input) {
838
+ const rawBase = (input.baseUrl || "").trim();
839
+ if (!rawBase)
840
+ throw new Error("API 地址不能为空");
841
+ let parsed;
842
+ try {
843
+ parsed = new URL(rawBase);
844
+ }
845
+ catch {
846
+ throw new Error(`API 地址格式不正确:${rawBase}`);
847
+ }
848
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
849
+ throw new Error("API 地址必须以 http:// 或 https:// 开头");
850
+ }
851
+ const cleanBase = rawBase.replace(/\/+$/, "");
852
+ const headers = {
853
+ accept: "application/json",
854
+ };
855
+ if (input.apiKey && input.apiKey.trim()) {
856
+ headers.authorization = `Bearer ${input.apiKey.trim()}`;
857
+ }
858
+ const isOllama = input.api === "ollama" || cleanBase.includes(":11434");
859
+ const candidates = [];
860
+ if (isOllama) {
861
+ candidates.push(`${cleanBase}/api/tags`, `${cleanBase}/v1/models`, `${cleanBase}/models`);
862
+ }
863
+ else if (cleanBase.endsWith("/v1")) {
864
+ candidates.push(`${cleanBase}/models`);
865
+ }
866
+ else {
867
+ candidates.push(`${cleanBase}/v1/models`, `${cleanBase}/models`);
868
+ }
869
+ let lastError = "";
870
+ let lastCause;
871
+ let payload = null;
872
+ // THE URL THAT ANSWERED. A fetch follows redirects, so the endpoint that replied can be a
873
+ // different one from the address in the form - and it is the one that published whatever is
874
+ // being read. Deciding "is this the official endpoint?" from the address that was ASKED would
875
+ // call a redirect's destination the official one.
876
+ let answeredUrl = cleanBase;
877
+ for (const candidate of candidates) {
878
+ try {
879
+ const response = await (providerProxyFetch(input.proxyEnv) ?? fetch)(candidate, {
880
+ headers,
881
+ signal: AbortSignal.timeout(10000),
882
+ });
883
+ if (!response.ok) {
884
+ lastError = `HTTP ${response.status} ${response.statusText}`;
885
+ continue;
886
+ }
887
+ payload = await response.json();
888
+ answeredUrl = response.url || candidate;
889
+ if (payload)
890
+ break;
891
+ }
892
+ catch (error) {
893
+ lastError = error instanceof Error ? error.message : String(error);
894
+ lastCause = error;
895
+ }
896
+ }
897
+ if (!payload) {
898
+ // THE CAUSE, NOT JUST "fetch failed". `fetch` reports every transport-level problem - a refused
899
+ // connection, a reset, an aborted timeout - as the same one-word "fetch failed", so a user staring
900
+ // at 「无法从远程服务获取模型列表 (fetch failed)」 learns nothing and neither does the log. The
901
+ // cause is where the truth is: "The operation was aborted due to timeout" and "connect
902
+ // ECONNREFUSED" are two different problems with two different fixes.
903
+ const cause = lastCause instanceof Error
904
+ ? (lastCause.cause instanceof Error ? lastCause.cause.message : lastCause.cause instanceof Object && lastCause.cause !== null ? String(lastCause.cause.code ?? "") : undefined)
905
+ : undefined;
906
+ throw new Error(`无法从远程服务获取模型列表 (${lastError || "请求超时或无法连接"}${cause ? `:${cause}` : ""})`);
907
+ }
908
+ return parseRemoteModels(payload, { baseUrl: answeredUrl, api: input.api });
909
+ }
910
+ /**
911
+ * THE ANSWER, READ.
912
+ *
913
+ * Split out of `fetchRemoteModels` so that the part worth asserting - what a provider's answer MEANS -
914
+ * can be tested without a network in between. A remote provider answers in three shapes (a bare array,
915
+ * `{data: [...]}` for OpenAI, `{models: [...]}` for Ollama), and each entry names itself with `id`,
916
+ * `name` or `model`; what the panel shows next to it - whether the model reasons, whether it takes
917
+ * images - is inferred from the name, because that is all most providers tell us.
918
+ *
919
+ * `fetchRemoteModels` is the transport; this is the reading. Keeping them apart means the reading can
920
+ * be pinned exactly, and a slow machine can never turn a parsing question into a timeout.
921
+ *
922
+ * THE CONTEXT IS THE ENDPOINT THAT ANSWERED, and it matters for exactly one thing: the thinking
923
+ * levels. A level is only true of the endpoint that published it, so the rules that depend on the
924
+ * address need it - and the rules that do not (a model that declares its own levels) work without
925
+ * it, which is why the context is optional.
926
+ */
927
+ export function parseRemoteModels(payload, context) {
928
+ const rawList = Array.isArray(payload)
929
+ ? payload
930
+ : Array.isArray(payload.data)
931
+ ? payload.data
932
+ : Array.isArray(payload.models)
933
+ ? payload.models
934
+ : [];
935
+ if (rawList.length === 0) {
936
+ throw new Error("远程接口返回的模型列表为空");
937
+ }
938
+ const seen = new Set();
939
+ const discovered = [];
940
+ for (const item of rawList) {
941
+ if (!item || typeof item !== "object")
942
+ continue;
943
+ const rec = item;
944
+ const id = typeof rec.id === "string" ? rec.id.trim() : typeof rec.name === "string" ? rec.name.trim() : typeof rec.model === "string" ? rec.model.trim() : "";
945
+ if (!id || seen.has(id))
946
+ continue;
947
+ seen.add(id);
948
+ const lower = id.toLowerCase();
949
+ // THE THINKING LEVELS ARE READ FIRST, because they are part of the answer about the model.
950
+ const thinkingLevelMap = discoverThinkingLevels(rec, { baseUrl: context?.baseUrl ?? "", api: context?.api });
951
+ // THE PROVIDER'S OWN WORD WINS. A payload that says `reasoning: false` says the model does
952
+ // not think, and neither the model's NAME nor the levels it published may overrule that: a
953
+ // level that is switched off is a level that does nothing, and switching it on behind the
954
+ // provider's back would be writing a fact the provider did not give.
955
+ //
956
+ // When the payload says nothing about it, a published map is a fact about the model - Pi
957
+ // offers ONLY `off` for a model that does not reason, so levels on a "not a reasoning model"
958
+ // would be levels Pi never shows - and the NAME is still a reason for the models nobody
959
+ // described.
960
+ const reasoning = typeof rec.reasoning === "boolean"
961
+ ? rec.reasoning
962
+ : (Boolean(thinkingLevelMap) || /r1|reason|o1|o3|thinking|qwq|deepseek-r1/i.test(lower));
963
+ const imageInput = /vision|vl|4o|gemini|claude-3|flash|pixtral/i.test(lower);
964
+ // THE CATALOGUE IS ASKED BEFORE THE DEFAULT IS GUESSED. A model the provider did not describe
965
+ // used to fall straight to the placeholder 128000/16384, and that stamp was later read back as
966
+ // if a person had chosen it - which is how MiniMax-M3 (a 1,000,000-token model) came to believe
967
+ // it had 128,000. Only a model with NO catalogue entry takes the default.
968
+ const catalogue = storeWindowFor(readModelStore(piAgentDir()), id);
969
+ const contextWindow = typeof rec.context_window === "number"
970
+ ? rec.context_window
971
+ : catalogue?.contextWindow ?? DEFAULT_CONTEXT_WINDOW;
972
+ // THE CATALOGUE OUTRANKS THE REASONING GUESS, AND THE ORDER IS THE WHOLE POINT. A reasoning
973
+ // model used to be stamped with 32768 BEFORE the catalogue was consulted, so a model whose
974
+ // provider publishes a bigger answer limit got a smaller one - the same hole as the window
975
+ // one number over, with the same consequence: the limit Super Pi invented is the limit the
976
+ // session runs on. The guess is what is left when nobody knows better.
977
+ const maxTokens = catalogue?.maxTokens ?? (reasoning ? GUESSED_MAX_TOKENS : DEFAULT_MAX_TOKENS);
978
+ discovered.push({
979
+ id,
980
+ name: id,
981
+ reasoning,
982
+ imageInput,
983
+ contextWindow,
984
+ maxTokens,
985
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
986
+ });
987
+ }
988
+ return discovered.sort((a, b) => a.id.localeCompare(b.id));
989
+ }