cortico 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 (311) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -0
  3. package/package.json +43 -0
  4. package/src/boot.ts +46 -0
  5. package/src/bot.ts +1342 -0
  6. package/src/config-file.ts +41 -0
  7. package/src/core/README.md +92 -0
  8. package/src/core/billing.ts +26 -0
  9. package/src/core/blobs.ts +106 -0
  10. package/src/core/bus.ts +311 -0
  11. package/src/core/config-schema.ts +201 -0
  12. package/src/core/config.ts +262 -0
  13. package/src/core/core.ts +699 -0
  14. package/src/core/cost.ts +244 -0
  15. package/src/core/event-store.ts +304 -0
  16. package/src/core/fork.ts +113 -0
  17. package/src/core/generation.ts +118 -0
  18. package/src/core/instance-lock.ts +215 -0
  19. package/src/core/ipc-logger.ts +105 -0
  20. package/src/core/language.ts +62 -0
  21. package/src/core/log-context.ts +38 -0
  22. package/src/core/loop.ts +1858 -0
  23. package/src/core/markers.ts +48 -0
  24. package/src/core/prefix.ts +121 -0
  25. package/src/core/run.ts +95 -0
  26. package/src/core/secrets.ts +18 -0
  27. package/src/core/session.ts +56 -0
  28. package/src/core/sessions.ts +261 -0
  29. package/src/core/state.ts +104 -0
  30. package/src/core/template.ts +72 -0
  31. package/src/core/timers.ts +129 -0
  32. package/src/core/tool-log.ts +135 -0
  33. package/src/core/transcript.ts +92 -0
  34. package/src/core/truncate.ts +121 -0
  35. package/src/core/types.ts +1140 -0
  36. package/src/core/usage-log.ts +79 -0
  37. package/src/core/util.ts +386 -0
  38. package/src/deploy-listing.ts +160 -0
  39. package/src/deploy.ts +162 -0
  40. package/src/extensions/README.md +72 -0
  41. package/src/extensions/dry-mount.ts +390 -0
  42. package/src/extensions/manifest.ts +153 -0
  43. package/src/extensions/runtime.ts +42 -0
  44. package/src/extensions.ts +519 -0
  45. package/src/launcher.ts +285 -0
  46. package/src/paths.ts +155 -0
  47. package/src/protocol/open-responses/LICENSE +201 -0
  48. package/src/protocol/open-responses/README.md +14 -0
  49. package/src/protocol/open-responses/context-helpers.ts +27 -0
  50. package/src/protocol/open-responses/context-log.ts +59 -0
  51. package/src/protocol/open-responses/context.ts +89 -0
  52. package/src/protocol/open-responses/generated.ts +115 -0
  53. package/src/protocol/open-responses/index.ts +33 -0
  54. package/src/protocol/open-responses/openapi.json +4230 -0
  55. package/src/protocol/open-responses/stream.ts +146 -0
  56. package/src/protocol/open-responses/tokens.ts +31 -0
  57. package/src/providers/README.md +86 -0
  58. package/src/providers/base.ts +111 -0
  59. package/src/providers/configuration.ts +97 -0
  60. package/src/providers/console/config.ts +21 -0
  61. package/src/providers/console/settings.ts +443 -0
  62. package/src/providers/console/strings.ts +74 -0
  63. package/src/providers/console/types.ts +11 -0
  64. package/src/providers/llamacpp/archive.ts +148 -0
  65. package/src/providers/llamacpp/catalog.ts +247 -0
  66. package/src/providers/llamacpp/config.ts +36 -0
  67. package/src/providers/llamacpp/console/client.ts +6 -0
  68. package/src/providers/llamacpp/console/models-panel.ts +120 -0
  69. package/src/providers/llamacpp/console/runtime-panel.ts +173 -0
  70. package/src/providers/llamacpp/console/server.ts +153 -0
  71. package/src/providers/llamacpp/index.ts +95 -0
  72. package/src/providers/llamacpp/native.ts +51 -0
  73. package/src/providers/llamacpp/options.ts +117 -0
  74. package/src/providers/llamacpp/runtime-store.ts +139 -0
  75. package/src/providers/llamacpp/runtime.ts +214 -0
  76. package/src/providers/llamacpp/server.ts +286 -0
  77. package/src/providers/llamacpp/strings.ts +230 -0
  78. package/src/providers/openai-responses-compat/config.ts +20 -0
  79. package/src/providers/openai-responses-compat/index.ts +89 -0
  80. package/src/providers/openai-responses-compat/native.ts +127 -0
  81. package/src/providers/openai-responses-compat/strings.ts +19 -0
  82. package/src/providers/pricebook.ts +75 -0
  83. package/src/providers/registry.ts +137 -0
  84. package/src/providers/strings.ts +71 -0
  85. package/src/providers/transport/chat.ts +156 -0
  86. package/src/providers/transport/errors.ts +48 -0
  87. package/src/providers/transport/history.ts +68 -0
  88. package/src/providers/transport/native-input.ts +83 -0
  89. package/src/providers/transport/native-types.ts +13 -0
  90. package/src/providers/transport/response-assembly.ts +191 -0
  91. package/src/providers/transport/response-http.ts +196 -0
  92. package/src/providers/transport/response-meters.ts +27 -0
  93. package/src/providers/transport/responses-input.ts +56 -0
  94. package/src/web/README.md +84 -0
  95. package/src/web/client/console-pages/builtins/llm-settings/panel.ts +625 -0
  96. package/src/web/client/console-pages/builtins/llm-settings/pricing-panel.ts +168 -0
  97. package/src/web/client/console-pages/builtins/llm-settings/strings.ts +213 -0
  98. package/src/web/client/console-pages/builtins.ts +10 -0
  99. package/src/web/client/console-pages/context.ts +135 -0
  100. package/src/web/client/console-pages/host.ts +633 -0
  101. package/src/web/client/console-pages/loader.ts +132 -0
  102. package/src/web/client/console-pages/strings.ts +90 -0
  103. package/src/web/client/console-pages/tools/strings.ts +49 -0
  104. package/src/web/client/console-pages/tools/view.ts +215 -0
  105. package/src/web/client/core/api.ts +200 -0
  106. package/src/web/client/core/language.ts +56 -0
  107. package/src/web/client/core/lifecycle.ts +132 -0
  108. package/src/web/client/core/router.ts +199 -0
  109. package/src/web/client/core/stream.ts +157 -0
  110. package/src/web/client/core/websocket.ts +82 -0
  111. package/src/web/client/features/appearance/index.ts +333 -0
  112. package/src/web/client/features/appearance/strings.ts +87 -0
  113. package/src/web/client/features/config/index.ts +11 -0
  114. package/src/web/client/features/config/strings.ts +41 -0
  115. package/src/web/client/features/config/view.ts +428 -0
  116. package/src/web/client/features/core/events.ts +197 -0
  117. package/src/web/client/features/core/index.ts +254 -0
  118. package/src/web/client/features/core/run.ts +56 -0
  119. package/src/web/client/features/core/runlog.ts +214 -0
  120. package/src/web/client/features/core/sessions.ts +53 -0
  121. package/src/web/client/features/core/strings.ts +157 -0
  122. package/src/web/client/features/extensions/index.ts +422 -0
  123. package/src/web/client/features/extensions/strings.ts +164 -0
  124. package/src/web/client/features/feature.ts +93 -0
  125. package/src/web/client/features/live/context.ts +280 -0
  126. package/src/web/client/features/live/fork.ts +156 -0
  127. package/src/web/client/features/live/index.ts +392 -0
  128. package/src/web/client/features/live/onboarding.ts +113 -0
  129. package/src/web/client/features/live/protocol.ts +122 -0
  130. package/src/web/client/features/live/sessions.ts +71 -0
  131. package/src/web/client/features/live/status.ts +68 -0
  132. package/src/web/client/features/live/strings.ts +252 -0
  133. package/src/web/client/features/live/timeline.ts +590 -0
  134. package/src/web/client/features/prompts/editor.ts +292 -0
  135. package/src/web/client/features/prompts/index.ts +346 -0
  136. package/src/web/client/features/prompts/strings.ts +136 -0
  137. package/src/web/client/features/prompts/view.ts +256 -0
  138. package/src/web/client/features/providers/index.ts +100 -0
  139. package/src/web/client/features/providers/strings.ts +23 -0
  140. package/src/web/client/features/settings/general.ts +28 -0
  141. package/src/web/client/features/settings/index.ts +82 -0
  142. package/src/web/client/features/settings/strings.ts +33 -0
  143. package/src/web/client/features/storage/index.ts +1 -0
  144. package/src/web/client/features/storage/strings.ts +45 -0
  145. package/src/web/client/features/storage/view.ts +154 -0
  146. package/src/web/client/features/usage/chart.ts +486 -0
  147. package/src/web/client/features/usage/index.ts +407 -0
  148. package/src/web/client/features/usage/labels.ts +46 -0
  149. package/src/web/client/features/usage/range.ts +36 -0
  150. package/src/web/client/features/usage/state.ts +37 -0
  151. package/src/web/client/features/usage/strings.ts +191 -0
  152. package/src/web/client/features/usage/tooltip.ts +86 -0
  153. package/src/web/client/features/usage/types.ts +96 -0
  154. package/src/web/client/features/worlds/index.ts +424 -0
  155. package/src/web/client/features/worlds/strings.ts +121 -0
  156. package/src/web/client/main.ts +273 -0
  157. package/src/web/client/shell/avatar.ts +233 -0
  158. package/src/web/client/shell/index.ts +549 -0
  159. package/src/web/client/shell/strings.ts +89 -0
  160. package/src/web/client/theme/handoff.ts +43 -0
  161. package/src/web/client/theme/palette.ts +109 -0
  162. package/src/web/client/theme/registry.ts +130 -0
  163. package/src/web/client/theme/storage.ts +72 -0
  164. package/src/web/client/theme/strings.ts +123 -0
  165. package/src/web/client/theme/studio.ts +366 -0
  166. package/src/web/client/ui/actions.ts +109 -0
  167. package/src/web/client/ui/data.ts +185 -0
  168. package/src/web/client/ui/dom.ts +23 -0
  169. package/src/web/client/ui/fields.ts +191 -0
  170. package/src/web/client/ui/format.ts +75 -0
  171. package/src/web/client/ui/icons.ts +183 -0
  172. package/src/web/client/ui/images.ts +91 -0
  173. package/src/web/client/ui/index.ts +89 -0
  174. package/src/web/client/ui/lamp.ts +125 -0
  175. package/src/web/client/ui/log.ts +98 -0
  176. package/src/web/client/ui/overlay.ts +184 -0
  177. package/src/web/client/ui/page.ts +8 -0
  178. package/src/web/client/ui/prompt-input.tsx +311 -0
  179. package/src/web/client/ui/sheet.ts +131 -0
  180. package/src/web/client/ui/strings.ts +71 -0
  181. package/src/web/console-pages.ts +367 -0
  182. package/src/web/files.ts +107 -0
  183. package/src/web/path-picker.ts +296 -0
  184. package/src/web/public/index.html +17 -0
  185. package/src/web/public/styles.css +1715 -0
  186. package/src/web/server.ts +1883 -0
  187. package/src/web/shared/client-panel.ts +603 -0
  188. package/src/web/shared/console-protocol.ts +560 -0
  189. package/src/web/shared/css.d.ts +1 -0
  190. package/src/web/shared/path-picker.ts +23 -0
  191. package/src/web/shared/theme.ts +256 -0
  192. package/src/web/theme-store.ts +37 -0
  193. package/src/world.ts +449 -0
  194. package/src/worlds/bilibili/ENV_PROMPT.md +5 -0
  195. package/src/worlds/bilibili/README.md +176 -0
  196. package/src/worlds/bilibili/audience-admission.ts +995 -0
  197. package/src/worlds/bilibili/client.ts +528 -0
  198. package/src/worlds/bilibili/coalescing-buffer.ts +125 -0
  199. package/src/worlds/bilibili/config.ts +185 -0
  200. package/src/worlds/bilibili/console/client.ts +202 -0
  201. package/src/worlds/bilibili/definition.ts +35 -0
  202. package/src/worlds/bilibili/gift-frame.ts +131 -0
  203. package/src/worlds/bilibili/normalize.ts +452 -0
  204. package/src/worlds/bilibili/overlay/announcement.ts +76 -0
  205. package/src/worlds/bilibili/overlay/assets.ts +82 -0
  206. package/src/worlds/bilibili/overlay/model.ts +494 -0
  207. package/src/worlds/bilibili/overlay/project.ts +202 -0
  208. package/src/worlds/bilibili/overlay/server.ts +286 -0
  209. package/src/worlds/bilibili/overlay/types.ts +217 -0
  210. package/src/worlds/bilibili/overlay/web/app.js +690 -0
  211. package/src/worlds/bilibili/overlay/web/editor.css +297 -0
  212. package/src/worlds/bilibili/overlay/web/editor.html +102 -0
  213. package/src/worlds/bilibili/overlay/web/editor.js +2116 -0
  214. package/src/worlds/bilibili/overlay/web/overlay.html +13 -0
  215. package/src/worlds/bilibili/overlay/web/styles.css +258 -0
  216. package/src/worlds/bilibili/protobuf.ts +123 -0
  217. package/src/worlds/bilibili/wire.ts +94 -0
  218. package/src/worlds/bilibili/world.ts +1389 -0
  219. package/src/worlds/console-fixture/ENV_PROMPT.md +1 -0
  220. package/src/worlds/console-fixture/console/client.ts +72 -0
  221. package/src/worlds/console-fixture/world.ts +73 -0
  222. package/src/worlds/index.ts +15 -0
  223. package/src/worlds/minecraft/ENV_PROMPT.md +32 -0
  224. package/src/worlds/minecraft/ENV_PROMPT_CAMERA.md +2 -0
  225. package/src/worlds/minecraft/LICENSE-mineflayer-pathfinder.txt +21 -0
  226. package/src/worlds/minecraft/README.md +917 -0
  227. package/src/worlds/minecraft/blueprint-plan.ts +915 -0
  228. package/src/worlds/minecraft/blueprint-registry.ts +566 -0
  229. package/src/worlds/minecraft/blueprint-repair.ts +236 -0
  230. package/src/worlds/minecraft/blueprint-resource.ts +272 -0
  231. package/src/worlds/minecraft/blueprint.ts +492 -0
  232. package/src/worlds/minecraft/body-lease.ts +340 -0
  233. package/src/worlds/minecraft/bridge.ts +749 -0
  234. package/src/worlds/minecraft/check.ts +651 -0
  235. package/src/worlds/minecraft/chests.ts +292 -0
  236. package/src/worlds/minecraft/client-launch.ts +272 -0
  237. package/src/worlds/minecraft/client-options.ts +85 -0
  238. package/src/worlds/minecraft/client-skins.ts +164 -0
  239. package/src/worlds/minecraft/client-window.ps1 +91 -0
  240. package/src/worlds/minecraft/client.ts +423 -0
  241. package/src/worlds/minecraft/combat-context.ts +109 -0
  242. package/src/worlds/minecraft/combat.ts +1552 -0
  243. package/src/worlds/minecraft/config.ts +499 -0
  244. package/src/worlds/minecraft/console/access.ts +218 -0
  245. package/src/worlds/minecraft/console/client.ts +244 -0
  246. package/src/worlds/minecraft/console/log.ts +110 -0
  247. package/src/worlds/minecraft/console/mount.ts +420 -0
  248. package/src/worlds/minecraft/console/skin.ts +257 -0
  249. package/src/worlds/minecraft/console/style.css +154 -0
  250. package/src/worlds/minecraft/console/world.ts +449 -0
  251. package/src/worlds/minecraft/deaths.ts +135 -0
  252. package/src/worlds/minecraft/definition.ts +18 -0
  253. package/src/worlds/minecraft/engine-child.ts +274 -0
  254. package/src/worlds/minecraft/engine-ipc.ts +98 -0
  255. package/src/worlds/minecraft/entity-facts.ts +132 -0
  256. package/src/worlds/minecraft/escape.ts +407 -0
  257. package/src/worlds/minecraft/executor.ts +14494 -0
  258. package/src/worlds/minecraft/explored.ts +156 -0
  259. package/src/worlds/minecraft/geometry.ts +205 -0
  260. package/src/worlds/minecraft/goal-plan.ts +647 -0
  261. package/src/worlds/minecraft/item-break.ts +126 -0
  262. package/src/worlds/minecraft/item-facts.ts +146 -0
  263. package/src/worlds/minecraft/item-pick.ts +67 -0
  264. package/src/worlds/minecraft/level-dat.ts +176 -0
  265. package/src/worlds/minecraft/log.ts +132 -0
  266. package/src/worlds/minecraft/mineflayer-fixes.ts +1180 -0
  267. package/src/worlds/minecraft/names.ts +377 -0
  268. package/src/worlds/minecraft/pathfinder-lib.d.ts +13 -0
  269. package/src/worlds/minecraft/pathfinder-perf.ts +796 -0
  270. package/src/worlds/minecraft/piglin.ts +49 -0
  271. package/src/worlds/minecraft/policy.ts +547 -0
  272. package/src/worlds/minecraft/precheck.ts +655 -0
  273. package/src/worlds/minecraft/proxy.ts +445 -0
  274. package/src/worlds/minecraft/ranged.ts +635 -0
  275. package/src/worlds/minecraft/readouts.ts +102 -0
  276. package/src/worlds/minecraft/round.ts +26 -0
  277. package/src/worlds/minecraft/search-observation.ts +92 -0
  278. package/src/worlds/minecraft/server-config.ts +467 -0
  279. package/src/worlds/minecraft/server.ts +658 -0
  280. package/src/worlds/minecraft/show.ts +84 -0
  281. package/src/worlds/minecraft/skills.ts +1763 -0
  282. package/src/worlds/minecraft/terrain.ts +1735 -0
  283. package/src/worlds/minecraft/window.ts +96 -0
  284. package/src/worlds/minecraft/works.ts +179 -0
  285. package/src/worlds/minecraft/world.ts +6438 -0
  286. package/src/worlds/qq/ENV_PROMPT.md +5 -0
  287. package/src/worlds/qq/config.ts +108 -0
  288. package/src/worlds/qq/console/client.ts +126 -0
  289. package/src/worlds/qq/console/events.ts +155 -0
  290. package/src/worlds/qq/console/gate.ts +232 -0
  291. package/src/worlds/qq/console/roster.ts +203 -0
  292. package/src/worlds/qq/console/style.css +65 -0
  293. package/src/worlds/qq/conversation.ts +28 -0
  294. package/src/worlds/qq/definition.ts +62 -0
  295. package/src/worlds/qq/driver.ts +375 -0
  296. package/src/worlds/qq/history-tools.ts +209 -0
  297. package/src/worlds/qq/normalize.ts +323 -0
  298. package/src/worlds/qq/qface-map.ts +282 -0
  299. package/src/worlds/qq/vision-prompt.ts +27 -0
  300. package/src/worlds/qq/vision.ts +642 -0
  301. package/src/worlds/qq/vlm.ts +142 -0
  302. package/src/worlds/qq/world.ts +1503 -0
  303. package/src/worlds/terminal/ENV_PROMPT.md +11 -0
  304. package/src/worlds/terminal/config.ts +9 -0
  305. package/src/worlds/terminal/definition.ts +14 -0
  306. package/src/worlds/terminal/world.ts +700 -0
  307. package/src/worlds/websearch/ENV_PROMPT.md +1 -0
  308. package/src/worlds/websearch/brave-client.ts +261 -0
  309. package/src/worlds/websearch/config.ts +75 -0
  310. package/src/worlds/websearch/definition.ts +20 -0
  311. package/src/worlds/websearch/world.ts +171 -0
@@ -0,0 +1,407 @@
1
+ /**
2
+ * 用量与成本页读取跨重启保留的调用流水,按时段与范围统计 token、成本和请求次数,按各角色实际模型计价。
3
+ * 状态属于本次 mount;定时器使用 lifecycle.interval,监听绑定 signal,tooltip 挂在本页 root。领域图表由 chart.ts 提供。
4
+ */
5
+
6
+ import type { ConsoleUi, Disposable } from '../../../shared/client-panel.ts';
7
+ import { get } from '../../core/api.ts';
8
+ import { consoleFormat } from '../../ui/format.ts';
9
+ import { pageIntro } from '../../ui/page.ts';
10
+ import { getThemeStudio } from '../../theme/studio.ts';
11
+ import type { FeatureContext, FrameworkFeature } from '../feature.ts';
12
+ import { bucketLabel, renderChart } from './chart.ts';
13
+ import { U_TYPES, themeColorResolver } from './labels.ts';
14
+ import { localDate, usageQuery, usageRange } from './range.ts';
15
+ import { createUsageState } from './state.ts';
16
+ import { S } from './strings.ts';
17
+ import { createUsageTip } from './tooltip.ts';
18
+ import type { UsageAccum, UsageAggregate, UsageBucketOption, UsageGroupStat, UsageMetric } from './types.ts';
19
+
20
+ /** 自动刷新的周期。 */
21
+ const LIVE_MS = 15_000;
22
+ /** 窗口尺寸变化后延迟重画图表,合并连续 resize 事件。 */
23
+ const RESIZE_DEBOUNCE_MS = 80;
24
+
25
+ const BUCKETS: ReadonlyArray<{ value: UsageBucketOption; label: string }> = [
26
+ { value: 'auto', label: S.bucketAuto },
27
+ { value: 'minute', label: S.bucketMinute },
28
+ { value: 'hour', label: S.bucketHour },
29
+ { value: 'day', label: S.bucketDay },
30
+ { value: 'week', label: S.bucketWeek },
31
+ { value: 'month', label: S.bucketMonth },
32
+ ];
33
+
34
+ const PRESETS: ReadonlyArray<{ value: string; label: string }> = [
35
+ { value: '1', label: S.presetToday },
36
+ { value: '3', label: S.preset3 },
37
+ { value: '7', label: S.preset7 },
38
+ { value: '30', label: S.preset30 },
39
+ { value: '90', label: S.preset90 },
40
+ { value: '0', label: S.presetCustom },
41
+ ];
42
+
43
+ const METRICS: ReadonlyArray<{ value: UsageMetric; label: string }> = [
44
+ { value: 'cost', label: S.metricCost },
45
+ { value: 'tokens', label: 'token' },
46
+ ];
47
+
48
+ function errText(err: unknown): string {
49
+ return err instanceof Error ? err.message : String(err);
50
+ }
51
+
52
+ /** abort 不是失败,是"这一页已经不在了"。 */
53
+ function isAbort(err: unknown): boolean {
54
+ return (err as { name?: unknown } | null)?.name === 'AbortError';
55
+ }
56
+
57
+ /** 一行工具条(`.usagebar`)。与 `ui.rowbar()` 的差别只在版式,这一页有自己的一套。 */
58
+ function usagebar(ui: ConsoleUi): HTMLDivElement {
59
+ return ui.h('div', 'usagebar');
60
+ }
61
+
62
+ export function mountUsage(ctx: FeatureContext): void {
63
+ const { ui, root, lifecycle } = ctx;
64
+ const doc = root.ownerDocument;
65
+ const win = doc.defaultView;
66
+ const state = createUsageState();
67
+ const color = themeColorResolver(doc);
68
+ const tip = lifecycle.own(createUsageTip(doc, root));
69
+ const intro = pageIntro(ui, S.pageTitle);
70
+
71
+ // ---- 工具条 ---------------------------------------------------------------
72
+ const bar1 = usagebar(ui);
73
+ const presets = ui.segmented(PRESETS, {
74
+ value: String(state.days),
75
+ onSelect: (v) => {
76
+ state.days = Number(v);
77
+ customRange.classList.toggle('hidden', state.days !== 0);
78
+ if (state.days === 0) {
79
+ if (!state.from) state.from = localDate(6);
80
+ if (!state.to) state.to = localDate(0);
81
+ fromInput.value = state.from;
82
+ toInput.value = state.to;
83
+ }
84
+ void load();
85
+ },
86
+ });
87
+ const fromInput = ui.input({
88
+ type: 'date',
89
+ onChange: (v) => { state.from = v; if (state.days === 0) void load(); },
90
+ });
91
+ const toInput = ui.input({
92
+ type: 'date',
93
+ onChange: (v) => { state.to = v; if (state.days === 0) void load(); },
94
+ });
95
+ const customRange = ui.h('span', 'urange hidden');
96
+ customRange.append(fromInput, ui.h('span', null, ' — '), toInput);
97
+ const liveBox = ui.checkbox(S.liveRefresh, {
98
+ title: S.liveRefreshTitle(LIVE_MS / 1000),
99
+ onChange: (on) => setLive(on),
100
+ });
101
+ const refreshBtn = ui.button(S.refresh, { size: 'sm', onClick: () => void load() });
102
+ bar1.append(presets.el, customRange, ui.h('span', 'grow'), liveBox.el, refreshBtn);
103
+
104
+ const bar2 = usagebar(ui);
105
+ const bucketSeg = ui.segmented(BUCKETS, {
106
+ size: 'sm',
107
+ value: state.bucket,
108
+ onSelect: (v) => { state.bucket = v as UsageBucketOption; void load(); },
109
+ });
110
+ const bkHint = ui.h('span', 'ubkhint');
111
+ const rangeHint = ui.h('span', 'urangehint');
112
+ bar2.append(ui.h('span', 'ulabel', S.granularity), bucketSeg.el, bkHint, ui.h('span', 'grow'), rangeHint);
113
+ let basis = 'marginal';
114
+ let currency = '';
115
+ const currencySelect = ui.select({ options: [{value:'',label:S.autoCurrency}], onChange: value => { currency = value; void load(); } });
116
+ const basisSelect = ui.select({ options: [{value:'marginal',label:S.basisMarginal},{value:'equivalent',label:S.basisEquivalent}], onChange: value => { basis = value; void load(); } });
117
+ bar2.append(ui.h('span', 'ulabel', S.ledger), basisSelect, currencySelect);
118
+ const billingHint = ui.h('p', 'muted');
119
+ const controls = ui.h('div', 'usagecontrols');
120
+ controls.append(bar1, bar2, billingHint);
121
+
122
+ // ---- 概览读数 -------------------------------------------------------------
123
+ const cards = ui.statgrid();
124
+ cards.classList.add('usagecards');
125
+
126
+ // ---- 成本构成 -------------------------------------------------------------
127
+ const compSheet = ui.sheet({ title: S.compTitle });
128
+ const compBox = ui.h('div');
129
+ compBox.id = 'u-comp';
130
+ compSheet.body.appendChild(compBox);
131
+
132
+ // ---- 主图 -----------------------------------------------------------------
133
+ const mainSheet = ui.sheet({
134
+ title: S.mainTitle,
135
+ en: 'time series',
136
+ desc: S.mainDesc,
137
+ });
138
+ const mainCtrls = ui.rowbar();
139
+ const metricSeg = ui.segmented(METRICS, {
140
+ size: 'sm',
141
+ value: state.metric,
142
+ onSelect: (v) => { state.metric = v as UsageMetric; renderMain(); },
143
+ });
144
+ mainCtrls.append(metricSeg.el, ui.h('span', 'ulabel', S.split));
145
+ for (const [dim, label] of [['type', S.dimType], ['role', S.dimRole], ['model', S.dimModel]] as const) {
146
+ mainCtrls.appendChild(ui.checkbox(label, {
147
+ onChange: (on) => { state.splitDims[dim] = on; renderMain(); },
148
+ }).el);
149
+ }
150
+ mainCtrls.appendChild(ui.h('span', 'grow'));
151
+ mainCtrls.appendChild(ui.checkbox(S.sortByShare, {
152
+ title: S.sortByShareTitle,
153
+ onChange: (on) => { state.sortByShare = on; renderMain(); },
154
+ }).el);
155
+ const mainLegend = ui.h('div', 'chart-legend');
156
+ const mainBox = ui.h('div');
157
+ mainBox.id = 'usagechart';
158
+ mainSheet.body.append(mainCtrls, mainLegend, mainBox);
159
+
160
+ // ---- 调用图 ---------------------------------------------------------------
161
+ const callSheet = ui.sheet({ title: S.callTitle, en: 'requests' });
162
+ const callCtrls = ui.rowbar();
163
+ callCtrls.appendChild(ui.h('span', 'ulabel', S.split));
164
+ for (const [dim, label] of [['role', S.dimRole], ['model', S.dimModel]] as const) {
165
+ callCtrls.appendChild(ui.checkbox(label, {
166
+ onChange: (on) => { state.callDims[dim] = on; renderCalls(); },
167
+ }).el);
168
+ }
169
+ callCtrls.appendChild(ui.h('span', 'grow'));
170
+ callCtrls.appendChild(ui.checkbox(S.sortByShare, {
171
+ title: S.sortByShareTitle,
172
+ onChange: (on) => { state.callSortByShare = on; renderCalls(); },
173
+ }).el);
174
+ const callLegend = ui.h('div', 'chart-legend');
175
+ const callBox = ui.h('div');
176
+ callBox.id = 'usagecalls';
177
+ callSheet.body.append(callCtrls, callLegend, callBox);
178
+
179
+ // ---- 两张分组表 -----------------------------------------------------------
180
+ const GROUP_HEAD = [S.headCalls, S.headInput, S.headOutput, S.headCache, S.headCost, S.headAvg];
181
+ const roleSheet = ui.sheet({ title: S.byRole, en: 'by role' });
182
+ const roleTable = ui.table({ head: [S.dimRole, ...GROUP_HEAD] });
183
+ roleSheet.body.appendChild(roleTable.el);
184
+ const modelSheet = ui.sheet({ title: S.byModel, en: 'by model' });
185
+ const modelTable = ui.table({ head: [S.dimModel, ...GROUP_HEAD] });
186
+ modelSheet.body.appendChild(modelTable.el);
187
+ const tables = ui.h('div', 'usagetables');
188
+ tables.append(roleSheet.el, modelSheet.el);
189
+
190
+ root.append(intro, controls, cards, compSheet.el, mainSheet.el, callSheet.el, tables);
191
+
192
+ // ---- 渲染 -----------------------------------------------------------------
193
+
194
+ function renderMain(): void {
195
+ if (!state.data) return;
196
+ renderChart(
197
+ { doc, ui, box: mainBox, legend: mainLegend, tip, color },
198
+ state.data,
199
+ { metric: state.metric, dims: state.splitDims, allowType: true, sort: state.sortByShare },
200
+ );
201
+ }
202
+
203
+ function renderCalls(): void {
204
+ if (!state.data) return;
205
+ renderChart(
206
+ { doc, ui, box: callBox, legend: callLegend, tip, color },
207
+ state.data,
208
+ { metric: 'calls', dims: state.callDims, allowType: false, sort: state.callSortByShare },
209
+ );
210
+ }
211
+
212
+ function renderCards(d: UsageAggregate): void {
213
+ const cur = d.currency || 'USD';
214
+ const t: Partial<UsageGroupStat> = d.totals || {};
215
+ const series = d.series || [];
216
+ const calls = t.calls || 0;
217
+ // 空范围整排清零的读数读起来像坏了;一句话说清"没数据"和"数据坏了"的分别。
218
+ if (calls === 0) {
219
+ cards.replaceChildren(ui.placeholder(S.noCalls));
220
+ return;
221
+ }
222
+ const totTok = (t.promptTokens || 0) + (t.completionTokens || 0);
223
+ const successful = d.successful ?? t;
224
+ const avgCost = successful.calls ? (successful.cost || 0) / successful.calls : 0;
225
+ const avgTok = calls ? totTok / calls : 0;
226
+ const rShare = (t.completionTokens || 0) > 0
227
+ ? (t.reasoningTokens || 0) / (t.completionTokens || 1)
228
+ : null;
229
+ let peak: (typeof series)[number] | null = null;
230
+ for (const p of series) if (!peak || (p.cost || 0) > (peak.cost || 0)) peak = p;
231
+
232
+ cards.replaceChildren();
233
+ const items: Parameters<typeof ui.stat>[0][] = [
234
+ { k: S.cardKnownCost, v: (t.pricedCalls || 0) === 0 && !t.cost && (t.unpricedCalls || 0) > 0 ? S.unknown : consoleFormat.money(t.cost, cur), accent: true },
235
+ { k: S.cardCalls, v: calls.toLocaleString() },
236
+ { k: S.cardAvgCost, v: consoleFormat.money(avgCost, cur), unit: S.approxTok(consoleFormat.count(Math.round(avgTok))) },
237
+ { k: S.cardInput, v: consoleFormat.count(t.promptTokens || 0), unit: S.hitRate(consoleFormat.percent(t.cacheHitRate)) },
238
+ { k: S.cardOutput, v: consoleFormat.count(t.completionTokens || 0), unit: S.reasoningShare(consoleFormat.percent(rShare)) },
239
+ { k: S.cardCacheRate, v: consoleFormat.percent(t.cacheHitRate) },
240
+ { k: S.cardCoverage, v: `${t.pricedCalls || 0} / ${calls}`, unit: S.unpriced(t.unpricedCalls || 0) },
241
+ { k: S.cardPeak, v: peak ? consoleFormat.money(peak.cost, cur) : '—', unit: peak ? bucketLabel(peak.bucket, d.bucket || 'day') : '' },
242
+ ];
243
+ // 失败消耗是总消耗的子集。
244
+ const f: Partial<UsageAccum> = d.failed || {};
245
+ if ((f.calls || 0) > 0) {
246
+ items.push({
247
+ k: S.cardFailed, v: S.failedCalls((f.calls || 0).toLocaleString()),
248
+ unit: S.burned(consoleFormat.count((f.promptTokens || 0) + (f.completionTokens || 0))),
249
+ });
250
+ }
251
+ for (const item of items) cards.appendChild(ui.stat(item));
252
+ }
253
+
254
+ function renderComposition(d: UsageAggregate): void {
255
+ compBox.replaceChildren();
256
+ const cur = d.currency || 'USD';
257
+ const t: Partial<UsageGroupStat> = d.totals || {};
258
+ const total = t.cost || 0;
259
+ if (!(total > 0)) {
260
+ compBox.appendChild(ui.placeholder(S.noCostData));
261
+ return;
262
+ }
263
+ const parts = [
264
+ { label: S.partCacheHit, val: t.costCacheHit || 0, color: color(U_TYPES[0]!.color) },
265
+ { label: S.partCacheMiss, val: t.costCacheMiss || 0, color: color(U_TYPES[1]!.color) },
266
+ { label: S.partOutput, val: t.costOutput || 0, color: color(U_TYPES[2]!.color) },
267
+ ];
268
+ if (t.costOther) parts.push({ label: S.partOther, val: t.costOther, color: color('chart-4') });
269
+ const bar = ui.h('div', 'compbar');
270
+ for (const p of parts) {
271
+ const seg = ui.h('div', 'compseg');
272
+ seg.style.width = (p.val / total) * 100 + '%';
273
+ seg.style.background = p.color;
274
+ seg.title = `${p.label} ${consoleFormat.money(p.val, cur)}`;
275
+ bar.appendChild(seg);
276
+ }
277
+ const leg = ui.h('div', 'compleg');
278
+ for (const p of parts) {
279
+ const it = ui.h('div', 'compitem');
280
+ const sw = ui.h('span', 'compsw');
281
+ sw.style.background = p.color;
282
+ it.append(
283
+ sw,
284
+ ui.h('span', null, p.label),
285
+ ui.h('span', 'compamt', consoleFormat.money(p.val, cur)),
286
+ ui.h('span', 'comppct', `(${consoleFormat.percent(p.val / total)})`),
287
+ );
288
+ leg.appendChild(it);
289
+ }
290
+ compBox.append(bar, leg);
291
+ }
292
+
293
+ /**
294
+ * 首列印的是**声明方给的名字**,给不出就印 id 原文。角色 id 由Persona定义、
295
+ * 模型名由供应商定义,控制台两边都不认识,也就不为任何一边备一张翻译表。
296
+ */
297
+ function renderGroup(
298
+ table: ReturnType<ConsoleUi['table']>,
299
+ groups: readonly UsageGroupStat[],
300
+ cur: string,
301
+ ): void {
302
+ table.clear(groups.length ? undefined : S.noData);
303
+ if (!groups.length) return;
304
+ for (const g of groups) {
305
+ const avg = g.calls ? (g.cost || 0) / g.calls : 0;
306
+ table.addRow([
307
+ g.label || g.key,
308
+ { text: g.calls || 0, cls: 'mono' },
309
+ { text: consoleFormat.count(g.promptTokens), cls: 'mono' },
310
+ { text: consoleFormat.count(g.completionTokens), cls: 'mono' },
311
+ { text: consoleFormat.percent(g.cacheHitRate), cls: 'mono' },
312
+ { text: consoleFormat.money(g.cost, cur), cls: 'mono' },
313
+ { text: consoleFormat.money(avg, cur), cls: 'mono' },
314
+ ]);
315
+ }
316
+ }
317
+
318
+ function renderHints(d: UsageAggregate): void {
319
+ const unit = d.bucket || 'day';
320
+ bkHint.textContent = state.bucket === 'auto'
321
+ ? S.autoBucket(BUCKETS.find((b) => b.value === unit)?.label ?? unit)
322
+ : '';
323
+ rangeHint.textContent = S.rangeHint(d.from || '—', d.to || '—', (d.series || []).length);
324
+ }
325
+
326
+ function renderAll(d: UsageAggregate): void {
327
+ const currencies = [...new Set((d.balances ?? []).filter(balance => balance.basis === basis).map(balance => balance.currency))];
328
+ currencySelect.replaceChildren(...['', ...currencies].map(value => {
329
+ const option = doc.createElement('option');
330
+ option.value = value;
331
+ option.textContent = value || S.autoCurrency;
332
+ return option;
333
+ }));
334
+ currencySelect.value = currency;
335
+ billingHint.textContent = S.billingHint +
336
+ (d.totals?.unknownUsageCalls ? S.unknownUsage(d.totals.unknownUsageCalls) : '');
337
+ if (d.ledger?.error) billingHint.textContent += S.ledgerError(d.ledger.pending, d.ledger.error);
338
+ renderCards(d);
339
+ renderComposition(d);
340
+ renderMain();
341
+ renderCalls();
342
+ renderGroup(roleTable, d.byRole || [], d.currency || 'USD');
343
+ renderGroup(modelTable, d.byModel || [], d.currency || 'USD');
344
+ renderHints(d);
345
+ }
346
+
347
+ // ---- 取数 -----------------------------------------------------------------
348
+
349
+ async function load(): Promise<void> {
350
+ const range = usageRange(state.days, { from: state.from, to: state.to });
351
+ try {
352
+ const d = await get<UsageAggregate>(
353
+ `/api/usage?${usageQuery(state.bucket, range)}&basis=${basis}&currency=${encodeURIComponent(currency)}`,
354
+ { signal: ctx.signal },
355
+ );
356
+ if (ctx.signal.aborted) return;
357
+ state.data = d;
358
+ renderAll(d);
359
+ } catch (err) {
360
+ if (isAbort(err) || ctx.signal.aborted) return;
361
+ cards.replaceChildren(ui.placeholder(S.loadFailed(errText(err))));
362
+ }
363
+ }
364
+
365
+ // ---- 自动刷新 -------------------------------------------------------------
366
+
367
+ let liveTimer: Disposable | null = null;
368
+ function setLive(on: boolean): void {
369
+ liveTimer?.dispose();
370
+ liveTimer = on ? lifecycle.interval(() => void load(), LIVE_MS) : null;
371
+ }
372
+
373
+ // ---- 重画触发:主题换色 / 改窗宽 -------------------------------------------
374
+ // 两者都只重画,不重取:数据没变,变的是画布与配色。
375
+
376
+ /** 配色变了。图上的颜色是从 CSS 变量现读的,所以只能整张重画。 */
377
+ function repaint(): void {
378
+ tip.hide();
379
+ if (!state.data) return;
380
+ renderMain();
381
+ renderCalls();
382
+ renderComposition(state.data);
383
+ }
384
+
385
+ lifecycle.own(getThemeStudio({ doc }).onChange(() => repaint()));
386
+
387
+ if (win) {
388
+ let pending: Disposable | null = null;
389
+ win.addEventListener('resize', () => {
390
+ if (!state.data) return;
391
+ pending?.dispose();
392
+ pending = lifecycle.timeout(() => { renderMain(); renderCalls(); }, RESIZE_DEBOUNCE_MS);
393
+ }, { signal: ctx.signal });
394
+ }
395
+
396
+ cards.appendChild(ui.placeholder(S.loading));
397
+ void load();
398
+ }
399
+
400
+ export const usageFeature: FrameworkFeature = {
401
+ route: 'usage',
402
+ label: S.navLabel,
403
+ icon: 'chart',
404
+ navGroup: S.navGroup,
405
+ needsAny: ['usage'],
406
+ mount: mountUsage,
407
+ };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 用量页的配色与主题读取。角色 id 是人格定义的不透明字符串;标签由 UsageGroupStat.label 提供,缺席时显示 id。
3
+ * 按键的字典序分配调色板位置,使颜色不随成本排序变化。命中、未命中与输出为框架 UsageAccum 字段,使用固定记账口径。
4
+ */
5
+
6
+ import { readThemeColor } from '../../theme/palette.ts';
7
+ import { S } from './strings.ts';
8
+ import type { ColorResolver, UsageTypeKey } from './types.ts';
9
+
10
+ /** 通用系列色,按位次取。 */
11
+ export const U_PALETTE = [
12
+ 'chart-1', 'chart-2', 'chart-3', 'chart-4',
13
+ 'chart-5', 'chart-6', 'chart-7', 'chart-8',
14
+ ] as const;
15
+
16
+ export interface UsageTypeSpec {
17
+ key: UsageTypeKey;
18
+ label: string;
19
+ color: string;
20
+ }
21
+
22
+ /** 自下而上堆叠:缓存命中 → 未缓存输入 → 输出。 */
23
+ export const U_TYPES: readonly UsageTypeSpec[] = [
24
+ { key: 'cacheHit', label: S.typeCacheHit, color: 'chart-hit' },
25
+ { key: 'cacheMiss', label: S.typeCacheMiss, color: 'chart-miss' },
26
+ { key: 'output', label: S.typeOutput, color: 'chart-output' },
27
+ { key: 'other', label: S.typeOther, color: 'chart-4' },
28
+ ];
29
+
30
+ const HEX6 = /^#[0-9a-f]{6}$/i;
31
+
32
+ /** 最后一道兜底。见下面 `themeColor` 的注释。 */
33
+ const FALLBACK_INK = '#8a8a8a';
34
+
35
+ /**
36
+ * 通过 readThemeColor 读取主题颜色,并验证为 hex。compositeColors/hexToHsl 需要 hex,而主题变量或 --ink-dim 可为空或采用 rgb 格式,因此此处补充格式回落。
37
+ */
38
+ export function themeColor(doc: Document, key: string): string {
39
+ const hit = readThemeColor(doc, key);
40
+ return HEX6.test(hit) ? hit : FALLBACK_INK;
41
+ }
42
+
43
+ /** 绑好 `doc` 的解析器,交给图表那一层用。 */
44
+ export function themeColorResolver(doc: Document): ColorResolver {
45
+ return (token) => themeColor(doc, token);
46
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 时间范围:预设天数 ↔ 具体 `from` / `to`。
3
+ *
4
+ * 一律走**本地时区**的年月日:服务端的桶前缀也是本地时区串(`src/core/cost.ts`),
5
+ * 拿 `toISOString().slice(0,10)` 会在 UTC+8 的凌晨八小时里整整差一天。
6
+ */
7
+
8
+ /** `offsetDays` 天前的本地日期(`YYYY-MM-DD`)。0 = 今天。 */
9
+ export function localDate(offsetDays: number, now: number = Date.now()): string {
10
+ const d = new Date(now - offsetDays * 86400000);
11
+ const p = (n: number): string => String(n).padStart(2, '0');
12
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
13
+ }
14
+
15
+ export interface UsageRange {
16
+ from: string | null;
17
+ to: string | null;
18
+ }
19
+
20
+ /**
21
+ * `days === 0` 是"自定义"档:此时取两个日期框里的值(空串 = 不限)。
22
+ * 其余档位是"近 N 天",含今天,所以起点是 `N-1` 天前。
23
+ */
24
+ export function usageRange(days: number, custom: UsageRange, now: number = Date.now()): UsageRange {
25
+ if (days === 0) return { from: custom.from || null, to: custom.to || null };
26
+ return { from: localDate(days - 1, now), to: localDate(0, now) };
27
+ }
28
+
29
+ /** `/api/usage` 的查询串。空的 from/to 不出现在 URL 里。 */
30
+ export function usageQuery(bucket: string, range: UsageRange): string {
31
+ const q = new URLSearchParams();
32
+ q.set('bucket', bucket);
33
+ if (range.from) q.set('from', range.from);
34
+ if (range.to) q.set('to', range.to);
35
+ return q.toString();
36
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 用量页状态由每次 mount 的工厂创建,保存在该次挂载闭包,卸载后释放,避免继承其他 bot、范围或数据的选择。
3
+ */
4
+
5
+ import type { UsageAggregate, UsageBucketOption, UsageDimFlags, UsageMetric } from './types.ts';
6
+
7
+ export interface UsageState {
8
+ /** 预设天数;0 = 自定义范围(此时读 `from` / `to`)。 */
9
+ days: number;
10
+ from: string;
11
+ to: string;
12
+ bucket: UsageBucketOption;
13
+ metric: UsageMetric;
14
+ /** 主图的拆分维度(含"类型")。 */
15
+ splitDims: UsageDimFlags;
16
+ /** 调用图的拆分维度(没有"类型")。 */
17
+ callDims: UsageDimFlags;
18
+ sortByShare: boolean;
19
+ callSortByShare: boolean;
20
+ /** 最近一次取回的数据。重绘(换指标、换拆分、主题换色、窗口改宽)不重取。 */
21
+ data: UsageAggregate | null;
22
+ }
23
+
24
+ export function createUsageState(): UsageState {
25
+ return {
26
+ days: 7,
27
+ from: '',
28
+ to: '',
29
+ bucket: 'auto',
30
+ metric: 'cost',
31
+ splitDims: { type: false, role: false, model: false },
32
+ callDims: { role: false, model: false },
33
+ sortByShare: false,
34
+ callSortByShare: false,
35
+ data: null,
36
+ };
37
+ }