pop-agent 0.0.0-stage → 0.1.0

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 (375) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +620 -2
  3. package/README.zh.md +622 -0
  4. package/dist/server/approval/read-only.js +107 -0
  5. package/dist/server/approval/rules.js +73 -0
  6. package/dist/server/approval/scope.js +164 -0
  7. package/dist/server/approval/unattended.js +25 -0
  8. package/dist/server/asr/bridge.js +244 -0
  9. package/dist/server/asr/install.js +188 -0
  10. package/dist/server/asr/paths.js +101 -0
  11. package/dist/server/asr/routes.js +62 -0
  12. package/dist/server/brand.js +2 -0
  13. package/dist/server/cli-config.js +65 -0
  14. package/dist/server/cli-info.js +169 -0
  15. package/dist/server/cli.js +602 -0
  16. package/dist/server/computer/apps.js +152 -0
  17. package/dist/server/computer/cli.js +322 -0
  18. package/dist/server/computer/framing.js +36 -0
  19. package/dist/server/computer/helper-client.js +268 -0
  20. package/dist/server/computer/paths.js +114 -0
  21. package/dist/server/computer/routes.js +118 -0
  22. package/dist/server/computer/settings.js +169 -0
  23. package/dist/server/computer/skill.js +131 -0
  24. package/dist/server/computer/status.js +134 -0
  25. package/dist/server/cron/agent-run.js +121 -0
  26. package/dist/server/cron/index.js +539 -0
  27. package/dist/server/cron/tool.js +155 -0
  28. package/dist/server/engine/builtin.js +180 -0
  29. package/dist/server/engine/catalog-probe.js +34 -0
  30. package/dist/server/engine/catalog.js +8 -0
  31. package/dist/server/engine/claude-map.js +297 -0
  32. package/dist/server/engine/claude-sessions.js +581 -0
  33. package/dist/server/engine/claude-transport.js +75 -0
  34. package/dist/server/engine/claude.js +414 -0
  35. package/dist/server/engine/cli-version.js +119 -0
  36. package/dist/server/engine/codex-approvals.js +45 -0
  37. package/dist/server/engine/codex-map.js +298 -0
  38. package/dist/server/engine/codex-sessions.js +159 -0
  39. package/dist/server/engine/codex-subagents.js +349 -0
  40. package/dist/server/engine/codex-transport.js +49 -0
  41. package/dist/server/engine/codex.js +530 -0
  42. package/dist/server/engine/dsh-history.js +195 -0
  43. package/dist/server/engine/dsh-log.js +256 -0
  44. package/dist/server/engine/dsh-map.js +223 -0
  45. package/dist/server/engine/dsh-prompt-patch.js +48 -0
  46. package/dist/server/engine/dsh-sessions.js +206 -0
  47. package/dist/server/engine/dsh-transport.js +37 -0
  48. package/dist/server/engine/dsh.js +329 -0
  49. package/dist/server/engine/engine-install.js +182 -0
  50. package/dist/server/engine/engine-routes.js +54 -0
  51. package/dist/server/engine/engine-specs.js +65 -0
  52. package/dist/server/engine/engine-versions.js +41 -0
  53. package/dist/server/engine/export-html-tree-patch.js +89 -0
  54. package/dist/server/engine/fake.js +263 -0
  55. package/dist/server/engine/jsonrpc-stdio.js +275 -0
  56. package/dist/server/engine/model-registry-reload.js +115 -0
  57. package/dist/server/engine/narrate-guidance.js +25 -0
  58. package/dist/server/engine/opencode-map.js +500 -0
  59. package/dist/server/engine/opencode-projects.js +61 -0
  60. package/dist/server/engine/opencode-sessions.js +201 -0
  61. package/dist/server/engine/opencode-transport.js +48 -0
  62. package/dist/server/engine/opencode.js +434 -0
  63. package/dist/server/engine/pi-appearance-tool.js +101 -0
  64. package/dist/server/engine/pi-canvas-tool.js +181 -0
  65. package/dist/server/engine/pi-cron-tool.js +196 -0
  66. package/dist/server/engine/pi-events.js +153 -0
  67. package/dist/server/engine/pi-plugins.js +312 -0
  68. package/dist/server/engine/pi-rename.js +14 -0
  69. package/dist/server/engine/pi-retry.js +124 -0
  70. package/dist/server/engine/pi-sdk.js +1272 -0
  71. package/dist/server/engine/pi-session-model.js +23 -0
  72. package/dist/server/engine/pi-stop.js +28 -0
  73. package/dist/server/engine/pi-subagent-tool.js +188 -0
  74. package/dist/server/engine/pi-subagents.js +445 -0
  75. package/dist/server/engine/pi-thinking.js +34 -0
  76. package/dist/server/engine/pi-transcript.js +247 -0
  77. package/dist/server/engine/pi-turn-outcome.js +25 -0
  78. package/dist/server/engine/pi-version.js +11 -0
  79. package/dist/server/engine/port.js +1 -0
  80. package/dist/server/engine/registry.js +61 -0
  81. package/dist/server/engine/resource-signature.js +55 -0
  82. package/dist/server/engine/scratch.js +13 -0
  83. package/dist/server/engine/subagent-guidance.js +22 -0
  84. package/dist/server/engine/suggestion-guidance.js +24 -0
  85. package/dist/server/engine/switchable.js +22 -0
  86. package/dist/server/engine/wiring.js +225 -0
  87. package/dist/server/files/content-search.js +187 -0
  88. package/dist/server/files/dir-routes.js +104 -0
  89. package/dist/server/files/file-search.js +64 -0
  90. package/dist/server/files/file-service.js +286 -0
  91. package/dist/server/files/files-routes.js +278 -0
  92. package/dist/server/files/git-info.js +428 -0
  93. package/dist/server/files/path-resolve.js +176 -0
  94. package/dist/server/files/pick-path-routes.js +162 -0
  95. package/dist/server/http/auth-routes.js +454 -0
  96. package/dist/server/http/auth.js +306 -0
  97. package/dist/server/http/aux-routes.js +98 -0
  98. package/dist/server/http/client-log-routes.js +49 -0
  99. package/dist/server/http/compress.js +102 -0
  100. package/dist/server/http/file-headers.js +75 -0
  101. package/dist/server/http/health-and-static.js +46 -0
  102. package/dist/server/http/live-routes.js +116 -0
  103. package/dist/server/http/login-activity.js +76 -0
  104. package/dist/server/http/login-guard.js +185 -0
  105. package/dist/server/http/login-page.js +347 -0
  106. package/dist/server/http/password-store.js +88 -0
  107. package/dist/server/http/voice-settings-routes.js +30 -0
  108. package/dist/server/http/ws-routes.js +141 -0
  109. package/dist/server/index.js +1085 -0
  110. package/dist/server/markers/actions.js +281 -0
  111. package/dist/server/mcp/codex-mcp-store.js +190 -0
  112. package/dist/server/mcp/json-mcp-store.js +276 -0
  113. package/dist/server/mcp/mcp-auth.js +194 -0
  114. package/dist/server/mcp/mcp-command.js +137 -0
  115. package/dist/server/mcp/mcp-engine-shared.js +112 -0
  116. package/dist/server/mcp/mcp-import.js +289 -0
  117. package/dist/server/mcp/mcp-market-sources.js +192 -0
  118. package/dist/server/mcp/mcp-market-types.js +5 -0
  119. package/dist/server/mcp/mcp-market.js +174 -0
  120. package/dist/server/mcp/mcp-probe.js +170 -0
  121. package/dist/server/mcp/mcp-routes.js +71 -0
  122. package/dist/server/mcp/mcp-store.js +286 -0
  123. package/dist/server/mcp/none-mcp-store.js +27 -0
  124. package/dist/server/mcp/pi-mcp-config.js +308 -0
  125. package/dist/server/pi-gate.js +106 -0
  126. package/dist/server/plugins/engine-plugin-stores.js +265 -0
  127. package/dist/server/plugins/plugin-routes.js +22 -0
  128. package/dist/server/protocol-parse.js +533 -0
  129. package/dist/server/protocol-settings.js +1 -0
  130. package/dist/server/protocol.js +8 -0
  131. package/dist/server/providers/catalog-store.js +89 -0
  132. package/dist/server/providers/catalog-writes.js +199 -0
  133. package/dist/server/providers/catalog.js +77 -0
  134. package/dist/server/providers/codex-models.js +96 -0
  135. package/dist/server/providers/codex-test.js +124 -0
  136. package/dist/server/providers/enabled-models.js +110 -0
  137. package/dist/server/providers/import-models.js +69 -0
  138. package/dist/server/providers/import-routes.js +266 -0
  139. package/dist/server/providers/model-kind.js +35 -0
  140. package/dist/server/providers/model-test.js +113 -0
  141. package/dist/server/providers/one-shot.js +218 -0
  142. package/dist/server/providers/probe-routes.js +26 -0
  143. package/dist/server/providers/probe.js +84 -0
  144. package/dist/server/providers/provider-handlers.js +240 -0
  145. package/dist/server/providers/provider-pool.js +63 -0
  146. package/dist/server/providers/provider-store.js +502 -0
  147. package/dist/server/providers/request-headers.js +7 -0
  148. package/dist/server/providers/subscription-routes.js +183 -0
  149. package/dist/server/providers/validate.js +249 -0
  150. package/dist/server/push/push-routes.js +171 -0
  151. package/dist/server/push/push.js +239 -0
  152. package/dist/server/push/vapid-config.js +179 -0
  153. package/dist/server/session/appearance.js +79 -0
  154. package/dist/server/session/approval-bridge.js +119 -0
  155. package/dist/server/session/attachment-resolve.js +21 -0
  156. package/dist/server/session/canvas-artifacts.js +108 -0
  157. package/dist/server/session/canvas-store.js +137 -0
  158. package/dist/server/session/canvas-suggest.js +70 -0
  159. package/dist/server/session/canvas.js +323 -0
  160. package/dist/server/session/client-view.js +82 -0
  161. package/dist/server/session/close-ephemeral.js +23 -0
  162. package/dist/server/session/conversation-create.js +87 -0
  163. package/dist/server/session/cron-prompt-routes.js +25 -0
  164. package/dist/server/session/cron-prompt.js +59 -0
  165. package/dist/server/session/delete-session.js +125 -0
  166. package/dist/server/session/engine-switch.js +118 -0
  167. package/dist/server/session/fork-session.js +38 -0
  168. package/dist/server/session/lock.js +82 -0
  169. package/dist/server/session/model-controller.js +149 -0
  170. package/dist/server/session/move-session.js +40 -0
  171. package/dist/server/session/notices.js +33 -0
  172. package/dist/server/session/one-shot.js +95 -0
  173. package/dist/server/session/persist-ephemeral.js +48 -0
  174. package/dist/server/session/pi-opener.js +163 -0
  175. package/dist/server/session/pi-refresh.js +51 -0
  176. package/dist/server/session/pi-sessions-provider.js +41 -0
  177. package/dist/server/session/pi-sessions.js +431 -0
  178. package/dist/server/session/refresh-actions.js +58 -0
  179. package/dist/server/session/rename-session.js +23 -0
  180. package/dist/server/session/runtime-services.js +37 -0
  181. package/dist/server/session/runtime-types.js +1 -0
  182. package/dist/server/session/runtime.js +844 -0
  183. package/dist/server/session/session-stats.js +91 -0
  184. package/dist/server/session/settings.js +526 -0
  185. package/dist/server/session/snapshot-for.js +9 -0
  186. package/dist/server/session/stats-refresher.js +55 -0
  187. package/dist/server/session/subagents.js +119 -0
  188. package/dist/server/session/suggest-title.js +33 -0
  189. package/dist/server/session/switch-conversation.js +111 -0
  190. package/dist/server/session/template-prompt-routes.js +26 -0
  191. package/dist/server/session/template-prompt.js +110 -0
  192. package/dist/server/session/throttle.js +14 -0
  193. package/dist/server/session/title-prompt.js +128 -0
  194. package/dist/server/session/turn-events.js +198 -0
  195. package/dist/server/session/turn-finish.js +97 -0
  196. package/dist/server/session/turn-markers.js +31 -0
  197. package/dist/server/session/turn-queue.js +264 -0
  198. package/dist/server/session/turn-send.js +138 -0
  199. package/dist/server/session/turn-watchdog.js +77 -0
  200. package/dist/server/session/voice-settings.js +39 -0
  201. package/dist/server/sessions/session-routes.js +97 -0
  202. package/dist/server/skills/skill-install.js +184 -0
  203. package/dist/server/skills/skill-routes.js +134 -0
  204. package/dist/server/skills/skill-store.js +163 -0
  205. package/dist/server/skills/skillhub.js +213 -0
  206. package/dist/server/skills/zip.js +121 -0
  207. package/dist/server/snapshot/fan-out.js +12 -0
  208. package/dist/server/snapshot/messages.js +117 -0
  209. package/dist/server/snapshot/sender.js +53 -0
  210. package/dist/server/snapshot/state.js +274 -0
  211. package/dist/server/subagents/profile-store.js +305 -0
  212. package/dist/server/terminal/terminal-routes.js +223 -0
  213. package/dist/server/terminal/terminal-session.js +197 -0
  214. package/dist/server/tts/edge-worker-source.js +48 -0
  215. package/dist/server/tts/edge.js +143 -0
  216. package/dist/server/tts/local-voices.js +35 -0
  217. package/dist/server/tts/local.js +192 -0
  218. package/dist/server/tts/routes.js +56 -0
  219. package/dist/server/tts/service.js +97 -0
  220. package/dist/server/tts/types.js +7 -0
  221. package/dist/server/tts/voices.js +21 -0
  222. package/dist/server/update-check.js +147 -0
  223. package/dist/server/update-prompt.js +131 -0
  224. package/dist/server/uploads/upload-routes.js +67 -0
  225. package/dist/server/uploads/upload-store.js +113 -0
  226. package/dist/server/util/atomic-write.js +18 -0
  227. package/dist/server/util/data-dir.js +36 -0
  228. package/dist/server/util/desktop.js +216 -0
  229. package/dist/server/util/env.js +202 -0
  230. package/dist/server/util/file-mode.js +57 -0
  231. package/dist/server/util/ids.js +28 -0
  232. package/dist/server/util/json-file.js +38 -0
  233. package/dist/server/util/log-file.js +67 -0
  234. package/dist/server/util/log.js +52 -0
  235. package/dist/server/util/origin.js +117 -0
  236. package/dist/server/util/paths.js +187 -0
  237. package/dist/server/util/pricing-index.js +117 -0
  238. package/dist/server/util/pricing.js +214 -0
  239. package/dist/server/util/prune-pty.js +72 -0
  240. package/dist/server/util/spawn-cli.js +147 -0
  241. package/dist/server/util/startup.js +34 -0
  242. package/dist/server/util/upstream-version.js +177 -0
  243. package/dist/server/util/usage.js +19 -0
  244. package/dist/server/util/version.js +59 -0
  245. package/dist/server/web-proxy/picker-script.js +495 -0
  246. package/dist/server/web-proxy/proxy-routes.js +205 -0
  247. package/dist/server/web-proxy/proxy-url.js +76 -0
  248. package/dist/server/web-proxy/rewrite.js +98 -0
  249. package/dist/server/web-proxy/wrapper.js +92 -0
  250. package/dist/server/ws/handle-message.js +182 -0
  251. package/dist/server/ws/reply-frame.js +5 -0
  252. package/helper/asr/Info.plist +24 -0
  253. package/helper/asr/build.sh +59 -0
  254. package/helper/asr/main.swift +279 -0
  255. package/helper/asr/release/ASRBridge.zip +0 -0
  256. package/package.json +120 -5
  257. package/web/dist/apple-touch-icon-precomposed.png +0 -0
  258. package/web/dist/apple-touch-icon.png +0 -0
  259. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_abnfDiagram-WEYOIA3C-Cxf7yoVn.js +1 -0
  260. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_architectureDiagram-ZHVYKT53-BtmjGlGq.js +1 -0
  261. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_c4Diagram-XDPPPE54-CMVGVtIk.js +1 -0
  262. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_cynefinDiagram-WF24UDRP-7i0BPrM8.js +1 -0
  263. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_diagram-CBK3MWTC-G70wUrpC.js +1 -0
  264. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_diagram-ODIL2UCW-DG5xxpj4.js +1 -0
  265. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_diagram-PFBEJUXE-TVSrX2lz.js +1 -0
  266. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_diagram-TYUNFSNR-B5kj_W4w.js +1 -0
  267. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_ebnfDiagram-V4P3TTPT-CYDlMnIy.js +1 -0
  268. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_ishikawaDiagram-HPEHV2GE-Bwle1LQ4.js +1 -0
  269. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_mindmap-definition-6OY57UG3-Dp_r4po3.js +1 -0
  270. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_pegDiagram-ECIUJNBX-D0XH8M0y.js +1 -0
  271. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_railroadDiagram-Y72NRBL7-BYBIBrHp.js +1 -0
  272. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_swimlanes-B3ENRKFQ-Bj4-4hK8.js +1 -0
  273. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_swimlanesDiagram-AYQRV4AK-Cr0JbDyV.js +1 -0
  274. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_usecaseDiagram-WPOLBNNX-BN92OiEn.js +1 -0
  275. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_vennDiagram-Q3Y3IDCW--PhbzdU_.js +1 -0
  276. package/web/dist/assets/_pop-agent-mermaid-pruned_chunk_wardleyDiagram-IVAIDKWA-nObiqZ0S.js +1 -0
  277. package/web/dist/assets/_pop-agent-mermaid-pruned_katex_katex-Zojedrce.js +1 -0
  278. package/web/dist/assets/approval.en-BFhMPNWP.mp3 +0 -0
  279. package/web/dist/assets/approval.zh-DWqP6Pcu.mp3 +0 -0
  280. package/web/dist/assets/arc-Dn7mfTUL.js +1 -0
  281. package/web/dist/assets/architecture-WOLXFQ4H-DwHKr8GA.js +1 -0
  282. package/web/dist/assets/array-BifhSqXX.js +1 -0
  283. package/web/dist/assets/blockDiagram-RJAE7QA3-CA2AOM6-.js +140 -0
  284. package/web/dist/assets/channel-PVcvMEH-.js +1 -0
  285. package/web/dist/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  286. package/web/dist/assets/chunk-55XCU76K-DlITu1ZH.js +1 -0
  287. package/web/dist/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  288. package/web/dist/assets/chunk-7S6XSTFO-DzX1XF3_.js +2 -0
  289. package/web/dist/assets/chunk-AQDTSKZB-BdEDejS-.js +72 -0
  290. package/web/dist/assets/chunk-DSNLSHJZ-Chj2PD0m.js +129 -0
  291. package/web/dist/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  292. package/web/dist/assets/chunk-HNE4Q36P-V3jylrEv.js +1 -0
  293. package/web/dist/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  294. package/web/dist/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  295. package/web/dist/assets/chunk-NGNAAXSQ-DuHRe0y2.js +136 -0
  296. package/web/dist/assets/chunk-VQ5W62QI-BiWZxVe5.js +1 -0
  297. package/web/dist/assets/chunk-WQQL4CDK-BtyaHLI7.js +10 -0
  298. package/web/dist/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  299. package/web/dist/assets/chunk-ZAUX2LTX-DS3wpSTy.js +62 -0
  300. package/web/dist/assets/chunk-ZCHMQSOR-at82jgqF.js +2 -0
  301. package/web/dist/assets/classDiagram-v2-4MYWR3UA-CTgR1e3M.js +217 -0
  302. package/web/dist/assets/cose-bilkent-JH36ORCC-DW-hnOsq.js +1 -0
  303. package/web/dist/assets/cynefin-EF2NZ3EQ-Pg-c-yVE.js +1 -0
  304. package/web/dist/assets/dagre-NK4GIZVX-B0Ivt5Pn.js +4 -0
  305. package/web/dist/assets/diagram-I5XIIV2D-jE6SNlbX.js +24 -0
  306. package/web/dist/assets/diagram-RJA3I4VV-DQJNgW0u.js +41 -0
  307. package/web/dist/assets/done.en-s1tZOg6A.mp3 +0 -0
  308. package/web/dist/assets/done.zh-Dq-Os4NS.mp3 +0 -0
  309. package/web/dist/assets/elk-QONTBCTQ-KOJVoDyP.js +27 -0
  310. package/web/dist/assets/erDiagram-KYQIGQAA-DNUqfe2J.js +99 -0
  311. package/web/dist/assets/error.en-BGPHdZVi.mp3 +0 -0
  312. package/web/dist/assets/error.zh-DdFp64-u.mp3 +0 -0
  313. package/web/dist/assets/eventmodeling-K75KTNOO-DnxXCUaf.js +1 -0
  314. package/web/dist/assets/flowDiagram-IUGLLWBU-CRLc8ozS.js +213 -0
  315. package/web/dist/assets/ganttDiagram-R7GPNTJY-DDLhSPGT.js +292 -0
  316. package/web/dist/assets/gitGraph-VSP46ZUC-BjfoZeXP.js +1 -0
  317. package/web/dist/assets/gitGraphDiagram-PDYL7XHY-6uZGw3lU.js +106 -0
  318. package/web/dist/assets/graphlib-DS17s2tU.js +1 -0
  319. package/web/dist/assets/highlight-DMv0JmTA.js +5 -0
  320. package/web/dist/assets/i18n-en-H5OrSHR5.js +1 -0
  321. package/web/dist/assets/index-CQ1VhLwx.js +79 -0
  322. package/web/dist/assets/index-DB6jJFLf.css +1 -0
  323. package/web/dist/assets/info-OHQRW6UA-BMDHcIvy.js +1 -0
  324. package/web/dist/assets/infoDiagram-MVDRKAX5-C2d1Uwhn.js +2 -0
  325. package/web/dist/assets/init-C-OQMol4.js +1 -0
  326. package/web/dist/assets/journeyDiagram-BOSHW7O7-BAE_nPCd.js +139 -0
  327. package/web/dist/assets/kanban-definition-FNSA4HC5-C2Z3ejvx.js +89 -0
  328. package/web/dist/assets/line-DHlXL-f4.js +1 -0
  329. package/web/dist/assets/linear-B363vzIx.js +1 -0
  330. package/web/dist/assets/markdown-Bcx45PNe.js +31 -0
  331. package/web/dist/assets/math-Dh0H2mym.js +1 -0
  332. package/web/dist/assets/mermaid-parser.core-CxD9DMnU.js +7 -0
  333. package/web/dist/assets/mermaid.core-CdVzG6_M.js +44 -0
  334. package/web/dist/assets/ordinal-BDEzSJ7C.js +1 -0
  335. package/web/dist/assets/packet-JDAUHWVQ-Cx23kBS5.js +1 -0
  336. package/web/dist/assets/path-fybaL0A-.js +1 -0
  337. package/web/dist/assets/pie-XZMESJXO-BDdtcaza.js +1 -0
  338. package/web/dist/assets/pieDiagram-GNMPY74T-DRqt_o8d.js +39 -0
  339. package/web/dist/assets/quadrantDiagram-D57K4MC3-Cq3-_E3T.js +7 -0
  340. package/web/dist/assets/radar-ABXABTNO-yJ_gp7Uq.js +1 -0
  341. package/web/dist/assets/railroad-I3PHUGI6-BFVVDyfL.js +1 -0
  342. package/web/dist/assets/railroad-abnf-LNEFI6M7-BhhpD6rl.js +1 -0
  343. package/web/dist/assets/railroad-ebnf-DWYD2UWJ-os_iV6TA.js +1 -0
  344. package/web/dist/assets/railroad-peg-JR7BVNR7-kex9mDBE.js +1 -0
  345. package/web/dist/assets/react-TO3cgmuO.js +9 -0
  346. package/web/dist/assets/requirementDiagram-EQYSW5RA-BnDM54-F.js +84 -0
  347. package/web/dist/assets/rolldown-runtime-COiEfhsA.js +1 -0
  348. package/web/dist/assets/sankeyDiagram-SY24JHO5-CMQmL2Tu.js +40 -0
  349. package/web/dist/assets/sequenceDiagram-BLEHNHQU-Dqhxl46T.js +169 -0
  350. package/web/dist/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  351. package/web/dist/assets/src-BWF7jMDv.js +1 -0
  352. package/web/dist/assets/stateDiagram-v2-A6IESKWZ-D1u1qdD7.js +291 -0
  353. package/web/dist/assets/steer.en-1RIP4K_0.mp3 +0 -0
  354. package/web/dist/assets/steer.zh-BCINYQs7.mp3 +0 -0
  355. package/web/dist/assets/stopped.en-CFPMi6oy.mp3 +0 -0
  356. package/web/dist/assets/stopped.zh-D2CUs-KZ.mp3 +0 -0
  357. package/web/dist/assets/timeline-definition-JXYKGLGB-DEjsSeWV.js +120 -0
  358. package/web/dist/assets/treeView-D4JQ5SDB-BXYISxgj.js +1 -0
  359. package/web/dist/assets/treemap-SAJKECNS-B6BJK2c0.js +1 -0
  360. package/web/dist/assets/wardley-7MLQ67FV-DsjBYeKs.js +1 -0
  361. package/web/dist/assets/xterm-BrP-ENHg.css +1 -0
  362. package/web/dist/assets/xterm-C3-Bm0Yw.js +16 -0
  363. package/web/dist/assets/xychartDiagram-4URNHDU4-CBbRqTE2.js +7 -0
  364. package/web/dist/favicon-32.png +0 -0
  365. package/web/dist/favicon.ico +0 -0
  366. package/web/dist/favicon.svg +25 -0
  367. package/web/dist/icons/apple-touch-icon-180.png +0 -0
  368. package/web/dist/icons/icon-1024.png +0 -0
  369. package/web/dist/icons/icon-192.png +0 -0
  370. package/web/dist/icons/icon-512.png +0 -0
  371. package/web/dist/icons/icon-maskable-512.png +0 -0
  372. package/web/dist/index.html +62 -0
  373. package/web/dist/manifest.webmanifest +17 -0
  374. package/web/dist/maskable.svg +25 -0
  375. package/web/dist/sw.js +40 -0
@@ -0,0 +1,117 @@
1
+ /**
2
+ * 握手校验(ADR-0006 §握手)—— 本 ADR 的核心条目。
3
+ *
4
+ * 为什么必须有:WebSocket **不受同源策略保护**。你浏览器里打开的任意网页都能向
5
+ * `ws://127.0.0.1:<port>` 发起升级请求;若服务端不校验 Origin,那个网页就能驱动
6
+ * 你这台机器上的 shell。所以「只绑 loopback」并不够,握手是第一道也是唯一一道门。
7
+ *
8
+ * 规则:
9
+ * - 无 Origin(非浏览器客户端:测试脚本 / CLI / 健康检查)→ 放行;
10
+ * - 有 Origin → 主机名在允许列表(loopback 或 `POP_AGENT_ALLOWED_HOSTS` 里配的域名)+ 端口匹配;
11
+ * - Host 头:如果带了,必须是 loopback 且端口在白名单里(防 DNS rebinding 一类)。
12
+ *
13
+ * 全是纯函数。
14
+ */
15
+ const LOOPBACK_HOSTNAMES = ["127.0.0.1", "localhost", "::1", "[::1]"];
16
+ function allowedPorts(policy) {
17
+ return [policy.port, ...(policy.devPorts ?? [])];
18
+ }
19
+ export function isLoopbackHostname(hostname) {
20
+ const normalized = hostname.toLowerCase();
21
+ return LOOPBACK_HOSTNAMES.includes(normalized) || normalized === "::1";
22
+ }
23
+ /** 主机名在白名单里(loopback 或用户显式配置的域名/局域网 IP) */
24
+ function isAllowedHostname(hostname, policy) {
25
+ if (isLoopbackHostname(hostname))
26
+ return true;
27
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
28
+ return (policy.extraHosts ?? []).some((item) => item.toLowerCase() === normalized);
29
+ }
30
+ function portMatches(port, policy) {
31
+ // 缺端口时按默认端口推断:http→80 / https→443,都不可能命中,视为不匹配
32
+ if (!port)
33
+ return false;
34
+ return allowedPorts(policy).includes(Number.parseInt(port, 10));
35
+ }
36
+ /** 校验 `Origin` 请求头 */
37
+ export function isAllowedOrigin(origin, policy) {
38
+ if (!origin)
39
+ return true; // 非浏览器客户端
40
+ let url;
41
+ try {
42
+ url = new URL(origin);
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ if (url.protocol !== "http:" && url.protocol !== "https:")
48
+ return false;
49
+ if (!isAllowedHostname(url.hostname, policy))
50
+ return false;
51
+ // 配置了域名(反向代理场景)时端口可能是 80/443,那两种按名字放行
52
+ if (isLoopbackHostname(url.hostname) === false && (url.port === "" || url.port === "80" || url.port === "443")) {
53
+ return true;
54
+ }
55
+ return portMatches(url.port, policy);
56
+ }
57
+ /** 把 `Host` 头切成「主机名 + 端口」(IPv6 带方括号) */
58
+ function splitHost(host) {
59
+ const trimmed = host.trim();
60
+ if (trimmed.startsWith("[")) {
61
+ const end = trimmed.indexOf("]");
62
+ if (end < 0)
63
+ return { name: trimmed.toLowerCase(), port: "" };
64
+ const rest = trimmed.slice(end + 1);
65
+ return { name: trimmed.slice(0, end + 1).toLowerCase(), port: rest.startsWith(":") ? rest.slice(1) : "" };
66
+ }
67
+ const index = trimmed.lastIndexOf(":");
68
+ if (index < 0)
69
+ return { name: trimmed.toLowerCase(), port: "" };
70
+ return { name: trimmed.slice(0, index).toLowerCase(), port: trimmed.slice(index + 1) };
71
+ }
72
+ function normalizePort(port, protocol) {
73
+ if (port !== "")
74
+ return port;
75
+ return protocol === "https:" ? "443" : "80";
76
+ }
77
+ /**
78
+ * `Host` 头是不是「本机回环」(`127.0.0.1:9090` / `localhost:9090` / `[::1]:9090`)。
79
+ *
80
+ * 为什么鉴权要用它:只看 TCP 对端地址是不够的 —— **同机反代 / 隧道**
81
+ * (nginx、cloudflared、tailscale serve、frp…)打过来的连接,对端永远是 127.0.0.1。
82
+ * 于是「从公网域名访问」和「在电脑前点开」在网络层长得一模一样。
83
+ * 判据必须是「这个请求**是发往谁的**」(Host),而不只是「是谁连过来的」。
84
+ *
85
+ * 没有 Host 头(HTTP/1.0、老客户端)→ 认为无法判断,按回环处理:
86
+ * 浏览器与任何反代都会带 Host,不带的一定是本机脚本。
87
+ */
88
+ export function isLoopbackHostHeader(host) {
89
+ if (!host)
90
+ return true;
91
+ const { name } = splitHost(host);
92
+ const bare = name.replace(/^\[|\]$/g, "");
93
+ // 127.0.0.0/8 整段都是回环(与 auth.ts 的 isLoopback 同一口径),不只是 127.0.0.1
94
+ return isLoopbackHostname(bare) || bare.startsWith("127.");
95
+ }
96
+ /**
97
+ * `Origin` 和 `Host` 是不是同一个源。
98
+ *
99
+ * HTTP 面的门禁靠它:**同源请求永远放行**(不管你用什么域名/域名解析进来 —— 页面是从这儿加载的,
100
+ * 它的 POST 当然该能用),跨源的才去比白名单。跨站请求这两个头一定不一致
101
+ * (Host 由 URL 决定,Origin 由页面自己的源决定,浏览器两边都不给脚本改)。
102
+ */
103
+ export function isSameOrigin(origin, host) {
104
+ if (!origin || !host)
105
+ return false;
106
+ let url;
107
+ try {
108
+ url = new URL(origin);
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ const target = splitHost(host);
114
+ const originName = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
115
+ const targetName = target.name.replace(/^\[|\]$/g, "");
116
+ return (originName === targetName && normalizePort(url.port, url.protocol) === normalizePort(target.port, url.protocol));
117
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * 路径解析与约束(纯函数)。
3
+ *
4
+ * 两个场景用它:
5
+ * 1. `web/dist` 在哪 —— 源码运行与编译运行的层数不同(M1 踩过);
6
+ * 2. 路径是否落在工作区内 —— ADR-0006:`realpath` 之后必须在根内(防 `..` 与 symlink 逃逸)。
7
+ *
8
+ * 刻意把 `realpath` 作为参数注入:不依赖真实文件系统,调用方传 `fs.realpathSync`。
9
+ */
10
+ import { join, relative, resolve, sep } from "node:path";
11
+ /**
12
+ * 把路径统一成 `/` 分隔,**只用于「标识符」(相对路径 key / URL 参数 / 前端展示)**,
13
+ * 不要拿它去读写文件 —— 真实文件操作一律走 `join`/`resolve`。
14
+ *
15
+ * 为什么必须有这一层:git 输出的 pathspec、前端拼的相对路径、历史会话里存的全是 `/`;
16
+ * 而 Windows 上的 `join()` 产出的是 `\`。不统一的话同一份文件在文件树、git 状态、
17
+ * 搜索结果里会变成三个不同的 key(界面上就是「M/A 标记集体消失」)。
18
+ */
19
+ export function toPosixPath(path) {
20
+ return path.split(sep).join("/");
21
+ }
22
+ /**
23
+ * Windows 保留设备名:`NUL`、`CON`、`COM1`…
24
+ * 它们会被当成设备而不是文件(甚至带扩展名也一样,`nul.txt` 同样是设备)。
25
+ */
26
+ const WINDOWS_RESERVED = new Set([
27
+ "con",
28
+ "prn",
29
+ "aux",
30
+ "nul",
31
+ ...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),
32
+ ...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`),
33
+ ]);
34
+ /** 控制字符(0x00-0x1f)在 Windows 文件名里一律非法;用码点判断避开控制字符正则 */
35
+ function hasControlChars(value) {
36
+ for (let index = 0; index < value.length; index += 1)
37
+ if (value.charCodeAt(index) < 32)
38
+ return true;
39
+ return false;
40
+ }
41
+ /**
42
+ * 纯函数:路径在 Windows 上是否「注定打不开」(POSIX 上永远返回 null)。
43
+ *
44
+ * 为什么要在入口就拒:Windows 上这些情况不是「报个错」而是「静默干奇怪的事」——
45
+ * `join(root, "NUL")` 会命中设备名(读到空内容、看上去成功);`foo.txt:bar` 会打开
46
+ * NTFS 备用数据流;超长路径在 Node 没加 `\\?\` 前缀时直接 `ENOENT`,
47
+ * 而递归搜索里的 `catch` 会把整棵子树静默丢掉。
48
+ */
49
+ export function checkWindowsPath(value, platform = process.platform, maxLength = 250) {
50
+ if (platform !== "win32" || value === "")
51
+ return null;
52
+ if (value.length > maxLength)
53
+ return `路径太长(Windows 上限约 260 字符):${value.slice(0, 48)}…`;
54
+ // 盘符里的冒号是合法的:先剥掉再逐段检查
55
+ const withoutDrive = value.replace(/^[A-Za-z]:/, "");
56
+ for (const segment of withoutDrive.split(/[\\/]+/)) {
57
+ if (segment === "")
58
+ continue;
59
+ if (/[<>:"|?*]/.test(segment) || hasControlChars(segment))
60
+ return `路径里有 Windows 不允许的字符:${segment}`;
61
+ if (/[. ]$/.test(segment))
62
+ return `Windows 不允许文件名以空格或点结尾:${segment}`;
63
+ const stem = (segment.split(".")[0] ?? "").trim().toLowerCase();
64
+ if (WINDOWS_RESERVED.has(stem))
65
+ return `「${segment}」是 Windows 的保留设备名,不能当文件路径`;
66
+ }
67
+ return null;
68
+ }
69
+ /**
70
+ * 归一化「项目 / 工作区」路径(用户报的 bug:新建项目后侧栏里同一个项目出现两次)。
71
+ *
72
+ * 事故链:macOS 的原生目录选择框(`POSIX path of chosen`)回的是 `/a/b/`(**带尾斜杠**),
73
+ * 这个字符串被当成会话的 workspace 存起来;而 pi 的 `SessionManager` 建会话时会先
74
+ * `resolvePath(cwd)`(= `path.resolve`),写进会话 header 的是 `/a/b`。
75
+ * 于是同一个项目在侧栏里有了两个 key(`/a/b/` 与 `/a/b`):扫盘那份一个组、
76
+ * 内存里这条会话又一个组,**两条都叫 piv、里面是同一条会话**(还都显示「运行中」)。
77
+ *
78
+ * 所以 workspace 一律在这里归一化成 pi 会写进 header 的那个形状 —— `resolve()` 正好做三件事:
79
+ * 去掉尾斜杠 / 折叠重复分隔符 / 消掉 `.` 与 `..`。跟 pi 保持同一个算法,两边才对得上。
80
+ * 认不出(空串、非绝对路径)就原样返回:不猜、也不把脏数据改写成别的路径。
81
+ */
82
+ export function normalizeWorkspacePath(value) {
83
+ const trimmed = value.trim();
84
+ if (trimmed === "")
85
+ return "";
86
+ // 只归一化绝对路径:相对路径 / 提示词当 cwd 的脏数据没有「正确形状」可言
87
+ if (!trimmed.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(trimmed) && !trimmed.startsWith("\\\\"))
88
+ return trimmed;
89
+ return resolve(trimmed);
90
+ }
91
+ /**
92
+ * 用户「手输 / 粘贴」进来的目录路径 → 能拿去 `realpath` 的形状(纯函数,不碰文件系统)。
93
+ *
94
+ * Windows 上有三种「看着对、其实不是绝对路径」的输入,以前都会**静默**变成「跳转没反应」
95
+ * (服务端只认 `isAbsolute`,不认就直接回落成当前工作区,用户以为按钮坏了):
96
+ * 1. 资源管理器「复制文件地址」给的是带引号的 `"C:\Users\me\Desktop"`;
97
+ * 2. 只写了盘符的 `C:` / `c:` —— `isAbsolute("C:") === false`;
98
+ * 3. 从别处粘来的 `%USERPROFILE%` 这类环境变量(Windows 用户很爱这么写)。
99
+ * 只做「去引号 / 补根分隔符 / 展开 `%VAR%`」,认不出来就原样返回:不猜。
100
+ */
101
+ export function normalizePathInput(value, env = process.env) {
102
+ let text = value.trim();
103
+ // 整串被一对引号包着才剥(Windows 路径里本来就不允许引号)
104
+ for (const quote of ['"', "'"]) {
105
+ if (text.length >= 2 && text.startsWith(quote) && text.endsWith(quote)) {
106
+ text = text.slice(1, -1).trim();
107
+ }
108
+ }
109
+ // `%USERPROFILE%\x` → 真实路径(只展开存在的变量,展开不了就留着原样)
110
+ if (text.includes("%")) {
111
+ text = text.replace(/%([^%\\/]+)%/g, (whole, name) => env[name] ?? env[name.toUpperCase()] ?? whole);
112
+ }
113
+ // 只有盘符:`C:` 不是绝对路径,补上根分隔符才是
114
+ if (/^[A-Za-z]:$/.test(text))
115
+ return `${text}\\`;
116
+ return text;
117
+ }
118
+ export function pickExisting(candidates, exists) {
119
+ for (const candidate of candidates)
120
+ if (exists(candidate))
121
+ return candidate;
122
+ return null;
123
+ }
124
+ /** web/dist 的候选路径:先是「源码运行」,再是「编译后运行」 */
125
+ export function webDistCandidates(serverDir) {
126
+ return [join(serverDir, "..", "web", "dist"), join(serverDir, "..", "..", "web", "dist")];
127
+ }
128
+ /**
129
+ * `candidate` 是否在 `root` 之内。
130
+ *
131
+ * 用「相对路径不以 `..` 开头」判断,而不是字符串 `startsWith`:
132
+ * `/root2` 不是 `/root` 的子路径,但 `startsWith("/root")` 会误判为真。
133
+ * 传入的路径应当是**已经 realpath 过**的(调用方负责),否则 symlink 能逃出去。
134
+ */
135
+ export function isPathInside(root, candidate) {
136
+ const relativePath = relative(resolve(root), resolve(candidate));
137
+ if (relativePath === "")
138
+ return true; // 就是根本身
139
+ return !isEscapePath(relativePath);
140
+ }
141
+ /**
142
+ * `relative()` 的结果是不是「向上逃逸」。
143
+ *
144
+ * 为什么要单独一个函数:`startsWith("..")` 会把名字以两个点开头的**合法**条目
145
+ * (`..foo`、`...cache`)也当成逃逸 —— 那种文件在文件树里看得见、点开却报越界。
146
+ * 逃逸只有两种写法:正好是 `..`,或者 `..` 后面跟一个分隔符。
147
+ */
148
+ export function isEscapePath(relativePath) {
149
+ if (relativePath === "..")
150
+ return true;
151
+ if (relativePath.startsWith(`..${sep}`))
152
+ return true;
153
+ // 不同盘符 / UNC 下 relative() 会直接返回绝对路径
154
+ return isAbsoluteLike(relativePath);
155
+ }
156
+ function isAbsoluteLike(path) {
157
+ return path.startsWith(sep) || /^[A-Za-z]:[\\/]/.test(path);
158
+ }
159
+ /**
160
+ * 解析到真实路径并确认在工作区内(ADR-0006)。
161
+ * `realpath` 失败(路径不存在)时按「不在根内」处理 —— 宁可拒绝,不要放行。
162
+ */
163
+ export function resolveInsideRoot(root, candidate, realpath) {
164
+ // Windows 的非法字符 / 保留名 / 超长路径在这里统一挡掉(POSIX 上是空操作)。
165
+ // 放在这一层是因为它是文件、终端、上传的公共入口 —— 一处把关比每个调用方各写一遂靠谱。
166
+ const windowsProblem = checkWindowsPath(candidate);
167
+ if (windowsProblem !== null)
168
+ return { ok: false, reason: windowsProblem };
169
+ let realRoot;
170
+ try {
171
+ realRoot = realpath(root);
172
+ }
173
+ catch {
174
+ return { ok: false, reason: `工作区根无法解析:${root}` };
175
+ }
176
+ let realCandidate;
177
+ try {
178
+ realCandidate = realpath(candidate);
179
+ }
180
+ catch {
181
+ return { ok: false, reason: `路径不存在或无法解析:${candidate}` };
182
+ }
183
+ if (!isPathInside(realRoot, realCandidate)) {
184
+ return { ok: false, reason: `路径越界(不在工作区内):${candidate}` };
185
+ }
186
+ return { ok: true, path: realCandidate };
187
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * 分时价格的**运行时索引**(`provider/model` → 时段表 + 全天价)。
3
+ *
4
+ * 为什么要有这一层:算钱的时候手里只有「模型名 + token 数 + 时刻」,
5
+ * 而那可能是每一轮里的每一次模型调用 —— 不能每次都去读 JSON。
6
+ * 所以在两处刷新一次、之后只查内存:
7
+ * - 服务启动时(`server/index.ts`);
8
+ * - 模型表热重载时(`engine/model-registry-reload.ts` 本来就要读这两份配置)。
9
+ *
10
+ * 查不到 = 这个模型没配时段 → 调用方继续用引擎给的 cost(既有行为完全不变)。
11
+ * 配置写坏了(手改 JSON 写坏)→ 那一项当作没配,不抛、不把整张表带崩。
12
+ */
13
+ import { readFile } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+ import { costOfUsage, normalizePrice, priceAt, validateSchedule, } from "./pricing.js";
16
+ export const MODELS_FILE = "models.json";
17
+ export const MODELS_STORE_FILE = "models-store.json";
18
+ let byRef = new Map();
19
+ let byModel = new Map();
20
+ function toEntry(model) {
21
+ const parsed = validateSchedule(model.costSchedule, "分时价格");
22
+ const schedule = parsed.ok ? parsed.value : null;
23
+ const base = normalizePrice(model.cost);
24
+ if (!schedule && !base)
25
+ return null;
26
+ return { base, schedule };
27
+ }
28
+ /** 纯函数:把若干 provider 的模型摊成索引(同 provider/model 后者覆盖前者,与「自定义优先」一致) */
29
+ function buildPriceIndex(sources) {
30
+ const refs = new Map();
31
+ for (const source of sources) {
32
+ for (const model of source.models) {
33
+ if (typeof model?.id !== "string" || model.id === "")
34
+ continue;
35
+ const entry = toEntry(model);
36
+ const ref = `${source.provider}/${model.id}`;
37
+ if (entry)
38
+ refs.set(ref, entry);
39
+ else
40
+ refs.delete(ref);
41
+ }
42
+ }
43
+ // 裸模型名(只有一份时才认):有的引擎只报 `modelId` 不带 provider
44
+ const bare = new Map();
45
+ for (const [ref, entry] of refs) {
46
+ const id = ref.slice(ref.indexOf("/") + 1);
47
+ if (!bare.has(id))
48
+ bare.set(id, entry);
49
+ else if (bare.get(id) !== entry)
50
+ bare.set(id, null); // 重名 → 有歧义,不猜
51
+ }
52
+ return { byRef: refs, byModel: bare };
53
+ }
54
+ /** 用一批配置替换索引(热重载 / 启动都用它) */
55
+ export function setPriceIndex(sources) {
56
+ const built = buildPriceIndex(sources);
57
+ byRef = built.byRef;
58
+ byModel = built.byModel;
59
+ }
60
+ async function readJson(path) {
61
+ try {
62
+ const parsed = JSON.parse(await readFile(path, "utf8"));
63
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
64
+ }
65
+ catch {
66
+ return {}; // 不存在 / 坏文件都按空表处理(可重建,见 ADR-0005)
67
+ }
68
+ }
69
+ /** 从 pi 的两份配置重建索引(自定义那份额外优先,和 provider 列表的顺序一致) */
70
+ export async function refreshPriceIndex(agentDir) {
71
+ const [catalog, store] = await Promise.all([
72
+ readJson(join(agentDir, MODELS_FILE)),
73
+ readJson(join(agentDir, MODELS_STORE_FILE)),
74
+ ]);
75
+ const sources = [];
76
+ const collect = (raw) => {
77
+ if (typeof raw !== "object" || raw === null)
78
+ return;
79
+ for (const [provider, entry] of Object.entries(raw)) {
80
+ if (typeof entry !== "object" || entry === null)
81
+ continue;
82
+ const models = entry.models;
83
+ if (!Array.isArray(models))
84
+ continue;
85
+ sources.push({ provider, models: models });
86
+ }
87
+ };
88
+ collect(catalog.providers);
89
+ collect(store);
90
+ setPriceIndex(sources);
91
+ }
92
+ /** `provider/model` → 价格项;裸模型名也能查(无歧义时) */
93
+ function priceEntryFor(modelRef) {
94
+ if (typeof modelRef !== "string" || modelRef === "")
95
+ return null;
96
+ const exact = byRef.get(modelRef);
97
+ if (exact)
98
+ return exact;
99
+ // 引擎报的 provider 前缀和我们配置的不一致时,退回裸模型名(有重名就查不到,宁可不改账)
100
+ const slash = modelRef.lastIndexOf("/");
101
+ return byModel.get(slash >= 0 ? modelRef.slice(slash + 1) : modelRef) ?? null;
102
+ }
103
+ /**
104
+ * 这一刻这次调用该记多少钱(美元)。
105
+ *
106
+ * 返回 `undefined` = 这个模型没配分时价格 → 调用方保留引擎算出来的 cost。
107
+ * 配了时段之后**不再用**引擎的 cost:厂商的分时价引擎根本不知道,混着算只会更错。
108
+ */
109
+ export function scheduledCost(modelRef, usage, atMs) {
110
+ const entry = priceEntryFor(modelRef);
111
+ if (!entry || !entry.schedule)
112
+ return undefined;
113
+ const price = priceAt(entry.schedule, entry.base, atMs);
114
+ if (!price)
115
+ return undefined;
116
+ return costOfUsage(usage, price);
117
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * 分时价格(模型计费的扩展,ADR-0026 D 期)。
3
+ *
4
+ * 为什么需要:有的厂商按时段定价(高峰期 / 低峰期),一天里切成好几段,
5
+ * 同一百万 tokens 的钱在不同时段不一样。pi 的模型表只认「一个模型一套价」,
6
+ * 它算出来的 cost 在这些厂商身上必然是错的 —— 所以这里多存一张「时段 → 价格」表,
7
+ * 由**我们自己**按调用发生的时刻挑价格(引擎给的 cost 只在没配时段时兜底)。
8
+ *
9
+ * 约定(都写进界面提示里,别让用户猜):
10
+ * - `start` 必填,`end` 可空:空 = 一直用到**下一段**开始(最后一段跨零点回到最早那段);
11
+ * - `start > end` 表示跨零点(22:00–02:00);
12
+ * - 段内的价格字段可以留空:留空 = 沿用模型的「全天价格」(配置里那份 cost);
13
+ * - 时间按**本机时区**解释(界面显示什么就是什么,不做 UTC 换算);
14
+ * - 没配时段 = 全天一个价(既有行为完全不变)。
15
+ *
16
+ * 这一层是纯函数:不读文件、不看时钟(时间一律由调用方传 `atMs`),结果完全确定。
17
+ */
18
+ const PRICE_FIELDS = ["input", "output", "cacheRead", "cacheWrite"];
19
+ const MAX_PRICE_SEGMENTS = 32;
20
+ const MINUTES_PER_DAY = 1440;
21
+ /** 纯函数:`HH:MM`(也认 `H:MM` / `HH:MM:SS`,秒直接丢掉)→ 当天第几分钟;不合法返回 null */
22
+ function parseClock(raw) {
23
+ if (typeof raw !== "string")
24
+ return null;
25
+ // 秒可有可无:浏览器 / 系统给的 time 值不统一(有的会带秒),
26
+ // 在这儿报「必须是 HH:MM」只会让用户莫名其妙
27
+ const match = /^(\d{1,2}):(\d{2})(?::\d{2}(?:\.\d+)?)?$/.exec(raw.trim());
28
+ if (!match)
29
+ return null;
30
+ const hours = Number(match[1]);
31
+ const minutes = Number(match[2]);
32
+ if (!Number.isFinite(hours) || !Number.isFinite(minutes))
33
+ return null;
34
+ if (hours > 23 || minutes > 59)
35
+ return null;
36
+ return hours * 60 + minutes;
37
+ }
38
+ /** 纯函数:分钟 → `HH:MM`(界面/日志用) */
39
+ function formatClock(minutes) {
40
+ const normalized = ((Math.round(minutes) % MINUTES_PER_DAY) + MINUTES_PER_DAY) % MINUTES_PER_DAY;
41
+ const hours = Math.floor(normalized / 60);
42
+ return `${String(hours).padStart(2, "0")}:${String(normalized % 60).padStart(2, "0")}`;
43
+ }
44
+ /** 纯函数:某一时刻是当天第几分钟(本机时区) */
45
+ function minutesOfDay(atMs) {
46
+ const date = new Date(atMs);
47
+ return date.getHours() * 60 + date.getMinutes();
48
+ }
49
+ /**
50
+ * 纯函数:把时段表展开成 `[start, end)` 窗口。
51
+ *
52
+ * 没填 end 的段落到下一段开始;**最后一段**落到最早那段的开始(跨零点回去),
53
+ * 这样「只填几个低峰窗口的起点」也能表达完整的 24 小时。
54
+ */
55
+ function windowsOf(schedule) {
56
+ const parsed = [];
57
+ for (const segment of schedule) {
58
+ const start = parseClock(segment.start);
59
+ if (start === null)
60
+ continue;
61
+ parsed.push({ segment, start });
62
+ }
63
+ parsed.sort((left, right) => left.start - right.start);
64
+ return parsed.map((item, index) => {
65
+ const explicit = parseClock(item.segment.end);
66
+ if (item.segment.end !== undefined && item.segment.end !== "" && explicit !== null) {
67
+ // 结束早于/等于开始 = 跨零点(22:00–02:00)
68
+ return { ...item, end: explicit > item.start ? explicit : explicit + MINUTES_PER_DAY };
69
+ }
70
+ const next = index + 1 < parsed.length
71
+ ? parsed[index + 1].start
72
+ : parsed[0].start + MINUTES_PER_DAY;
73
+ return { ...item, end: next > item.start ? next : next + MINUTES_PER_DAY };
74
+ });
75
+ }
76
+ /**
77
+ * 纯函数:`atMs` 这一刻生效的那一段。
78
+ *
79
+ * 没配时段 / 这一刻没有任何段覆盖 → null(调用方用全天价)。
80
+ * 段与段重叠时**起点更晚的那段优先**(更具体的配置赢)。
81
+ */
82
+ function activeSegment(schedule, atMs) {
83
+ if (!schedule || schedule.length === 0)
84
+ return null;
85
+ const minutes = minutesOfDay(atMs);
86
+ let best = null;
87
+ let bestOrder = Number.NEGATIVE_INFINITY;
88
+ for (const window of windowsOf(schedule)) {
89
+ // 跨零点的窗口(end > 1440)要把「明天的这份分钟数」也算一遍
90
+ const covered = (minutes >= window.start && minutes < window.end) ||
91
+ (minutes + MINUTES_PER_DAY >= window.start && minutes + MINUTES_PER_DAY < window.end);
92
+ if (!covered)
93
+ continue;
94
+ const order = window.start <= minutes ? window.start : window.start - MINUTES_PER_DAY;
95
+ if (order > bestOrder) {
96
+ bestOrder = order;
97
+ best = window;
98
+ }
99
+ }
100
+ return best ? best.segment : null;
101
+ }
102
+ /** 纯函数:把 cost 字段收敛成价格(驼峰 / 下划线都认;一个数都没有 → null) */
103
+ export function normalizePrice(raw) {
104
+ if (typeof raw !== "object" || raw === null)
105
+ return null;
106
+ const record = raw;
107
+ const number = (field) => {
108
+ const snake = field.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`);
109
+ const value = record[field] ?? record[snake];
110
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
111
+ };
112
+ const input = number("input");
113
+ const output = number("output");
114
+ const cacheRead = number("cacheRead");
115
+ const cacheWrite = number("cacheWrite");
116
+ if (input === null && output === null && cacheRead === null && cacheWrite === null)
117
+ return null;
118
+ return { input: input ?? 0, output: output ?? 0, cacheRead: cacheRead ?? 0, cacheWrite: cacheWrite ?? 0 };
119
+ }
120
+ /**
121
+ * 纯函数:`atMs` 这一刻该用的价格。
122
+ *
123
+ * 段内没填的字段 → 全天价(`base`);全天价也没有 → 0(这一项不收费,和 pi 的口径一致)。
124
+ * 段表和全天价都拿不到 → null(调用方保留引擎给的 cost)。
125
+ */
126
+ export function priceAt(schedule, base, atMs) {
127
+ const segment = activeSegment(schedule, atMs);
128
+ if (!segment && !base)
129
+ return null;
130
+ const pick = (field) => {
131
+ const value = segment?.[field];
132
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
133
+ return value;
134
+ return base?.[field] ?? 0;
135
+ };
136
+ return { input: pick("input"), output: pick("output"), cacheRead: pick("cacheRead"), cacheWrite: pick("cacheWrite") };
137
+ }
138
+ /** 纯函数:一次调用(或一轮合计)花多少钱(美元)。价格是「每百万 tokens」 */
139
+ export function costOfUsage(usage, price) {
140
+ const tokens = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
141
+ const total = tokens(usage.input) * price.input +
142
+ tokens(usage.output) * price.output +
143
+ tokens(usage.cacheRead) * price.cacheRead +
144
+ tokens(usage.cacheWrite) * price.cacheWrite;
145
+ return total / 1_000_000;
146
+ }
147
+ /**
148
+ * 纯函数:把配置里的原始值校验 + 收敛成时段表。
149
+ *
150
+ * 一次收集**全部**问题(前端的表单是手填的,挤牙膏式试错太烦)。
151
+ * 空数组 / 没填 = null(= 全天一个价)。
152
+ */
153
+ export function validateSchedule(raw, label = "分时价格") {
154
+ if (raw === undefined || raw === null)
155
+ return { ok: true, value: null };
156
+ if (!Array.isArray(raw))
157
+ return { ok: false, errors: [`${label}必须是数组`] };
158
+ if (raw.length === 0)
159
+ return { ok: true, value: null };
160
+ if (raw.length > MAX_PRICE_SEGMENTS)
161
+ return { ok: false, errors: [`${label}最多 ${MAX_PRICE_SEGMENTS} 段`] };
162
+ const errors = [];
163
+ const seen = new Set();
164
+ const segments = [];
165
+ raw.forEach((item, index) => {
166
+ const position = index + 1;
167
+ if (typeof item !== "object" || item === null) {
168
+ errors.push(`第 ${position} 段不是对象`);
169
+ return;
170
+ }
171
+ const record = item;
172
+ const start = parseClock(record.start);
173
+ if (start === null) {
174
+ errors.push(`第 ${position} 段起始时间必须是 HH:MM`);
175
+ return;
176
+ }
177
+ if (seen.has(start))
178
+ errors.push(`${formatClock(start)} 这个起始时间填了两次`);
179
+ seen.add(start);
180
+ const segment = { start: formatClock(start) };
181
+ const rawEnd = record.end;
182
+ if (rawEnd !== undefined && rawEnd !== null && rawEnd !== "") {
183
+ const end = parseClock(rawEnd);
184
+ if (end === null)
185
+ errors.push(`第 ${position} 段结束时间必须是 HH:MM(留空 = 到下一段开始)`);
186
+ else if (end === start)
187
+ errors.push(`第 ${position} 段结束时间和起始时间相同`);
188
+ else
189
+ segment.end = formatClock(end);
190
+ }
191
+ for (const field of PRICE_FIELDS) {
192
+ const value = record[field];
193
+ if (value === undefined || value === null || value === "")
194
+ continue;
195
+ const number = typeof value === "number" ? value : Number(String(value).trim());
196
+ if (!Number.isFinite(number) || number < 0) {
197
+ errors.push(`第 ${position} 段${PRICE_LABELS[field]}必须是非负数(留空 = 沿用全天价)`);
198
+ continue;
199
+ }
200
+ segment[field] = number;
201
+ }
202
+ segments.push(segment);
203
+ });
204
+ if (errors.length > 0)
205
+ return { ok: false, errors };
206
+ segments.sort((left, right) => (parseClock(left.start) ?? 0) - (parseClock(right.start) ?? 0));
207
+ return { ok: true, value: segments.length > 0 ? segments : null };
208
+ }
209
+ const PRICE_LABELS = {
210
+ input: "输入价格",
211
+ output: "输出价格",
212
+ cacheRead: "缓存读价格",
213
+ cacheWrite: "缓存写价格",
214
+ };