evolcore 0.0.1 → 0.0.3
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.
- package/CHANGELOG.md +64 -0
- package/LICENSE +21 -0
- package/MIGRATION-0.5.0.md +378 -0
- package/README.md +318 -14
- package/ROLE_ACCESS_CONTROL.md +174 -0
- package/assets/.env.template +4 -0
- package/bin/ec-safe-output.js +161 -0
- package/bin/ec.js +29 -0
- package/dist/agents/baseagent.js +163 -0
- package/dist/agents/claude-runner.js +2565 -0
- package/dist/agents/codex-app-server-client.js +448 -0
- package/dist/agents/codex-runner.js +2682 -0
- package/dist/agents/gemini-runner.js +666 -0
- package/dist/agents/runner-types.js +75 -0
- package/dist/aun/aid/agentmd.js +216 -0
- package/dist/aun/aid/client.js +132 -0
- package/dist/aun/aid/control-aid.js +91 -0
- package/dist/aun/aid/identity.js +518 -0
- package/dist/aun/aid/index.js +4 -0
- package/dist/aun/aid/store.js +74 -0
- package/dist/aun/aid/types.js +1 -0
- package/dist/aun/aid/validation.js +21 -0
- package/dist/aun/group-identity.js +10 -0
- package/dist/aun/msg/group-index.js +6 -0
- package/dist/aun/msg/group.js +1231 -0
- package/dist/aun/msg/history.js +123 -0
- package/dist/aun/msg/index.js +5 -0
- package/dist/aun/msg/p2p.js +393 -0
- package/dist/aun/msg/payload-type.js +27 -0
- package/dist/aun/msg/upload.js +137 -0
- package/dist/aun/outbox.js +168 -0
- package/dist/aun/rpc/caller.js +42 -0
- package/dist/aun/rpc/connection.js +25 -0
- package/dist/aun/rpc/index.js +2 -0
- package/dist/aun/service-proxy.js +225 -0
- package/dist/aun/storage/download.js +29 -0
- package/dist/aun/storage/index.js +3 -0
- package/dist/aun/storage/manage.js +10 -0
- package/dist/aun/storage/upload.js +68 -0
- package/dist/channels/aun.js +4164 -0
- package/dist/channels/contact-bind-code.js +134 -0
- package/dist/channels/daemon.js +422 -0
- package/dist/channels/dingtalk.js +1479 -0
- package/dist/channels/feishu.js +1865 -0
- package/dist/channels/qqbot.js +409 -0
- package/dist/channels/wechat.js +817 -0
- package/dist/channels/wecom-card.js +101 -0
- package/dist/channels/wecom-onboarding.js +82 -0
- package/dist/channels/wecom-state.js +191 -0
- package/dist/channels/wecom.js +1157 -0
- package/dist/cli/agent-command.js +642 -0
- package/dist/cli/agent.js +1059 -0
- package/dist/cli/aun-commands.js +2003 -0
- package/dist/cli/bench.js +1228 -0
- package/dist/cli/cli-argv.js +66 -0
- package/dist/cli/code-stats.js +329 -0
- package/dist/cli/command-log.js +82 -0
- package/dist/cli/config-selector.js +69 -0
- package/dist/cli/config.js +261 -0
- package/dist/cli/contact.js +71 -0
- package/dist/cli/ctl-command.js +62 -0
- package/dist/cli/daemon-commands.js +2750 -0
- package/dist/cli/fs-command.js +1447 -0
- package/dist/cli/handoff-command.js +302 -0
- package/dist/cli/help.js +35 -0
- package/dist/cli/index.js +374 -0
- package/dist/cli/init-channel.js +1372 -0
- package/dist/cli/init.js +590 -0
- package/dist/cli/link-rules.js +240 -0
- package/dist/cli/model.js +591 -0
- package/dist/cli/net-check.js +723 -0
- package/dist/cli/queue-command.js +150 -0
- package/dist/cli/raw-key-input.js +25 -0
- package/dist/cli/response.js +344 -0
- package/dist/cli/restart-monitor.js +480 -0
- package/dist/cli/stats.js +609 -0
- package/dist/cli/task-context.js +80 -0
- package/dist/cli/trigger-command.js +545 -0
- package/dist/cli/version.js +93 -0
- package/dist/cli/watch-logs.js +33 -0
- package/dist/cli/watch-msg.js +673 -0
- package/dist/config/boot-log.js +266 -0
- package/dist/config/builtin-role-templates.js +42 -0
- package/dist/config/builtin-roles.js +91 -0
- package/dist/config/config-batch-get.js +11 -0
- package/dist/config/config-field-policy.js +261 -0
- package/dist/config/config-manager.js +1120 -0
- package/dist/config/config-operation-service.js +384 -0
- package/dist/config/contact-alias.js +68 -0
- package/dist/config/contact-book-store.js +454 -0
- package/dist/config/contact-book-v2-startup.js +35 -0
- package/dist/config/contact-book.js +224 -0
- package/dist/config/contact-operation-service.js +110 -0
- package/dist/config/gateway-config.js +858 -0
- package/dist/config/lifecycle.js +17 -0
- package/dist/config/mention-mode.js +27 -0
- package/dist/config/merge.js +161 -0
- package/dist/config/owner-policy.js +4 -0
- package/dist/config/peer-role-resolver.js +218 -0
- package/dist/config/resolved-config-op.js +483 -0
- package/dist/config/role-config-v4-startup.js +32 -0
- package/dist/config/role-config-v5-startup.js +27 -0
- package/dist/config/role-ranks.js +18 -0
- package/dist/config/role-schema.js +105 -0
- package/dist/config/role-service.js +156 -0
- package/dist/config/role-store.js +215 -0
- package/dist/config/roles.js +64 -0
- package/dist/config/schema-registry.js +154 -0
- package/dist/config/snapshot.js +598 -0
- package/dist/config-store.js +501 -0
- package/dist/core/auth/agent-delegation.js +111 -0
- package/dist/core/auth/auth-gateway.js +166 -0
- package/dist/core/auth/authenticated-actor.js +6 -0
- package/dist/core/auth/authorization-audit.js +119 -0
- package/dist/core/auth/operation-authorizer.js +720 -0
- package/dist/core/auth/operation-catalog.js +731 -0
- package/dist/core/baseagent-loader.js +54 -0
- package/dist/core/bootstrap-service.js +175 -0
- package/dist/core/capability/capability-manager.js +316 -0
- package/dist/core/capability/providers/claude-capability-provider.js +176 -0
- package/dist/core/capability/providers/codex-capability-provider.js +148 -0
- package/dist/core/capability/providers/gemini-capability-provider.js +10 -0
- package/dist/core/capability/types.js +27 -0
- package/dist/core/causation/audit.js +103 -0
- package/dist/core/causation/aun-association.js +111 -0
- package/dist/core/causation/context.js +93 -0
- package/dist/core/causation/index.js +4 -0
- package/dist/core/causation/types.js +2 -0
- package/dist/core/channel-loader.js +277 -0
- package/dist/core/command/agent-control.js +616 -0
- package/dist/core/command/cli-intent-parser.js +225 -0
- package/dist/core/command/command-handler.js +1733 -0
- package/dist/core/command/connect-menu.js +374 -0
- package/dist/core/command/menu-handler.js +3452 -0
- package/dist/core/command/menu-protocol.js +247 -0
- package/dist/core/command/role-menu.js +1623 -0
- package/dist/core/command/slash-gate.js +148 -0
- package/dist/core/command/slash-handler.js +3066 -0
- package/dist/core/daemon-file-cache.js +222 -0
- package/dist/core/event-bus.js +32 -0
- package/dist/core/event-catalog.js +810 -0
- package/dist/core/evolagent-registry.js +545 -0
- package/dist/core/evolagent.js +342 -0
- package/dist/core/handoff/dispatcher.js +229 -0
- package/dist/core/handoff/mutex.js +46 -0
- package/dist/core/handoff/runtime.js +324 -0
- package/dist/core/handoff/store.js +537 -0
- package/dist/core/handoff/types.js +12 -0
- package/dist/core/inference/text-inference.js +173 -0
- package/dist/core/interaction-registration.js +10 -0
- package/dist/core/interaction-router.js +278 -0
- package/dist/core/message/create-status.js +67 -0
- package/dist/core/message/im-renderer.js +659 -0
- package/dist/core/message/items-formatter.js +76 -0
- package/dist/core/message/logical-queue-bridge.js +123 -0
- package/dist/core/message/message-bridge.js +874 -0
- package/dist/core/message/message-cache.js +56 -0
- package/dist/core/message/message-log.js +339 -0
- package/dist/core/message/message-processor.js +4 -0
- package/dist/core/message/message-queue.js +1446 -0
- package/dist/core/message/message-utils.js +76 -0
- package/dist/core/message/peer-mode.js +105 -0
- package/dist/core/message/pending-hints.js +232 -0
- package/dist/core/message/response-depth.js +33 -0
- package/dist/core/message/response-engine.js +4020 -0
- package/dist/core/message/response-snapshot.js +83 -0
- package/dist/core/message/send-receipt.js +24 -0
- package/dist/core/message/stream-debouncer.js +139 -0
- package/dist/core/message/stream-idle-monitor.js +124 -0
- package/dist/core/model/config-scope.js +162 -0
- package/dist/core/model/field-scope.js +78 -0
- package/dist/core/model/model-catalog.js +227 -0
- package/dist/core/model/model-diagnostics.js +182 -0
- package/dist/core/model/model-permission.js +90 -0
- package/dist/core/permission/approval-gateway.js +1017 -0
- package/dist/core/permission/ec-command-parser.js +347 -0
- package/dist/core/permission/execution-sandbox.js +16 -0
- package/dist/core/permission/index.js +6 -0
- package/dist/core/permission/mode.js +24 -0
- package/dist/core/permission/sandbox-runtime.js +265 -0
- package/dist/core/permission/tool-policy.js +1019 -0
- package/dist/core/permission/unix-socket-policy.js +99 -0
- package/dist/core/protected-paths.js +332 -0
- package/dist/core/relation/peer-identity.js +222 -0
- package/dist/core/relation/peer-key.js +1 -0
- package/dist/core/role/runtime-policy.js +141 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +218 -0
- package/dist/core/session/adapters/codex-session-file-adapter.js +333 -0
- package/dist/core/session/adapters/gemini-session-file-adapter.js +181 -0
- package/dist/core/session/session-file-adapter.js +7 -0
- package/dist/core/session/session-file-health.js +45 -0
- package/dist/core/session/session-fs-store.js +273 -0
- package/dist/core/session/session-key.js +24 -0
- package/dist/core/session/session-manager.js +1643 -0
- package/dist/core/session/session-mapper.js +100 -0
- package/dist/core/session/session-renew.js +314 -0
- package/dist/core/session/session-title.js +128 -0
- package/dist/core/session/session-turn-coordinator.js +205 -0
- package/dist/core/session/session-turns.js +67 -0
- package/dist/core/system-channels.js +29 -0
- package/dist/eck/baseagent-caps.js +18 -0
- package/dist/eck/detect.js +47 -0
- package/dist/eck/group-rules-sync.js +345 -0
- package/dist/eck/init.js +77 -0
- package/dist/eck/kit-renderer.js +359 -0
- package/dist/eck/manifest-engine.js +446 -0
- package/dist/eck/message-renderer.js +199 -0
- package/dist/eck/rules-loader.js +28 -0
- package/dist/index.js +2926 -4
- package/dist/ipc.js +777 -0
- package/dist/paths.js +262 -0
- package/dist/product.js +18 -0
- package/dist/response-system/context-builder.js +71 -0
- package/dist/response-system/coordinator.js +117 -0
- package/dist/response-system/decision-executor.js +86 -0
- package/dist/response-system/engines/v1/index.js +21 -0
- package/dist/response-system/engines/v1/interactive-flow.js +27 -0
- package/dist/response-system/engines/v1/proactive-flow.js +137 -0
- package/dist/response-system/engines/v1/types.js +1 -0
- package/dist/response-system/extensions.js +41 -0
- package/dist/response-system/index.js +6 -0
- package/dist/response-system/modes/index.js +7 -0
- package/dist/response-system/modes/single-session/index.js +72 -0
- package/dist/response-system/queues/fifo-queue.js +44 -0
- package/dist/response-system/queues/index.js +6 -0
- package/dist/response-system/queues/lifo-queue.js +42 -0
- package/dist/response-system/queues/priority-queue.js +63 -0
- package/dist/response-system/registry.js +97 -0
- package/dist/response-system/resolver.js +37 -0
- package/dist/response-system/selector.js +23 -0
- package/dist/response-system/types.js +7 -0
- package/dist/stats/billing.js +163 -0
- package/dist/stats/budget.js +93 -0
- package/dist/stats/db.js +403 -0
- package/dist/stats/eck-vars.js +89 -0
- package/dist/stats/index.js +11 -0
- package/dist/stats/normalizer.js +80 -0
- package/dist/stats/price-resolver.js +138 -0
- package/dist/stats/query.js +763 -0
- package/dist/stats/role-budget.js +168 -0
- package/dist/stats/writer.js +151 -0
- package/dist/trigger/anomaly-store.js +258 -0
- package/dist/trigger/audit.js +152 -0
- package/dist/trigger/event-source.js +119 -0
- package/dist/trigger/feedback.js +685 -0
- package/dist/trigger/history.js +290 -0
- package/dist/trigger/manager.js +294 -0
- package/dist/trigger/parser.js +595 -0
- package/dist/trigger/patch.js +155 -0
- package/dist/trigger/scheduler.js +1602 -0
- package/dist/trigger/script-executor.js +155 -0
- package/dist/trigger/state.js +145 -0
- package/dist/trigger/types.js +1 -0
- package/dist/trigger/validation.js +634 -0
- package/dist/types.js +12 -0
- package/dist/utils/aid-bind.js +313 -0
- package/dist/utils/atomic-write.js +95 -0
- package/dist/utils/avatar-upload.js +123 -0
- package/dist/utils/cross-platform.js +297 -0
- package/dist/utils/ecweb-utils.js +73 -0
- package/dist/utils/error-dict.json +153 -0
- package/dist/utils/error-utils.js +349 -0
- package/dist/utils/instance-registry.js +444 -0
- package/dist/utils/locale.js +21 -0
- package/dist/utils/log-writer.js +270 -0
- package/dist/utils/logger.js +89 -0
- package/dist/utils/markdown-to-plain-text.js +20 -0
- package/dist/utils/media-cache.js +274 -0
- package/dist/utils/model-prices.jsonl +20 -0
- package/dist/utils/npm-ops.js +210 -0
- package/dist/utils/process-introspect.js +133 -0
- package/dist/utils/process-tree-stats.js +271 -0
- package/dist/utils/project-path.js +74 -0
- package/dist/utils/restart-safety.js +31 -0
- package/dist/utils/stats.js +410 -0
- package/dist/utils/system-memory.js +62 -0
- package/dist/utils/tool-summary.js +284 -0
- package/dist/utils/welcome.js +268 -0
- package/kits/docs/GUIDE.md +20 -0
- package/kits/docs/INDEX.md +66 -0
- package/kits/docs/aun/CHEATSHEET.md +19 -0
- package/kits/docs/aun/SYNC_PROTOCOL.md +15 -0
- package/kits/docs/channels/aun.md +65 -0
- package/kits/docs/channels/feishu.md +56 -0
- package/kits/docs/context-assembly.md +366 -0
- package/kits/docs/eck_templates/GUIDE.template.md +22 -0
- package/kits/docs/eck_templates/INDEX.template.md +28 -0
- package/kits/docs/eck_templates/path-registry.template.md +33 -0
- package/kits/docs/eck_templates/runtime.template.md +19 -0
- package/kits/docs/evolcore/INDEX.md +68 -0
- package/kits/docs/evolcore/agent.md +77 -0
- package/kits/docs/evolcore/aid.md +52 -0
- package/kits/docs/evolcore/config.md +149 -0
- package/kits/docs/evolcore/contact.md +57 -0
- package/kits/docs/evolcore/ctl.md +46 -0
- package/kits/docs/evolcore/event.md +216 -0
- package/kits/docs/evolcore/fs-architecture.md +1215 -0
- package/kits/docs/evolcore/fs.md +110 -0
- package/kits/docs/evolcore/group-fs.md +17 -0
- package/kits/docs/evolcore/group-rules.md +226 -0
- package/kits/docs/evolcore/group.md +150 -0
- package/kits/docs/evolcore/model.md +50 -0
- package/kits/docs/evolcore/msg.md +136 -0
- package/kits/docs/evolcore/response.md +75 -0
- package/kits/docs/evolcore/rpc.md +37 -0
- package/kits/docs/evolcore/self-summary.md +29 -0
- package/kits/docs/evolcore/stats.md +83 -0
- package/kits/docs/evolcore/storage.md +50 -0
- package/kits/docs/evolcore/trigger.md +539 -0
- package/kits/docs/identity/AID_PROFILE_SPEC.md +26 -0
- package/kits/docs/identity/PATH_OPS.md +16 -0
- package/kits/docs/identity/ROLE_DETAIL.md +23 -0
- package/kits/docs/identity/identity-tools.md +26 -0
- package/kits/docs/path-registry.md +43 -0
- package/kits/docs/prompt-loading-architecture.md +266 -0
- package/kits/docs/venues/aun-group.md +45 -0
- package/kits/docs/venues/aun-private.md +10 -0
- package/kits/docs/venues/client-desktop.md +10 -0
- package/kits/docs/venues/client-mobile.md +10 -0
- package/kits/docs/venues/feishu-group.md +13 -0
- package/kits/docs/venues/feishu-private.md +9 -0
- package/kits/docs/venues/group.md +25 -0
- package/kits/docs/venues/private.md +10 -0
- package/kits/eck_manifest.auxiliary.json +43 -0
- package/kits/eck_manifest.json +203 -0
- package/kits/eck_message_manifest.json +63 -0
- package/kits/migrations/README-role-config-v4.md +32 -0
- package/kits/migrations/migrate-contact-book-v2.mjs +747 -0
- package/kits/migrations/migrate-role-config-v4.mjs +623 -0
- package/kits/migrations/migrate-role-config-v5.mjs +346 -0
- package/kits/migrations/rename-config-file.mjs +99 -0
- package/kits/rules/01-overview.md +142 -0
- package/kits/rules/02-navigation.md +76 -0
- package/kits/rules/03-identity.md +34 -0
- package/kits/rules/04-relation.md +59 -0
- package/kits/rules/05-venue.md +44 -0
- package/kits/rules/06-channel.md +59 -0
- package/kits/schemas/_meta.json +32 -0
- package/kits/schemas/agent-config.schema.1.json +177 -0
- package/kits/schemas/agent-config.schema.2.json +239 -0
- package/kits/schemas/agent-config.schema.3.json +119 -0
- package/kits/schemas/agent-config.schema.4.json +208 -0
- package/kits/schemas/agent-config.schema.5.json +326 -0
- package/kits/schemas/agent-config.schema.6.json +322 -0
- package/kits/schemas/contact-book.schema.1.json +36 -0
- package/kits/schemas/contact-book.schema.2.json +43 -0
- package/kits/schemas/daemon.schema.1.json +90 -0
- package/kits/schemas/defaults.schema.1.json +81 -0
- package/kits/schemas/menu-exec-schema-commands.md +208 -0
- package/kits/schemas/migrations/README.md +28 -0
- package/kits/schemas/relation-config.schema.1.json +158 -0
- package/kits/schemas/relation-config.schema.2.json +73 -0
- package/kits/schemas/relation-config.schema.3.json +50 -0
- package/kits/schemas/relation-config.schema.4.json +47 -0
- package/kits/schemas/relation-config.schema.5.json +47 -0
- package/kits/schemas/role-config.schema.1.json +201 -0
- package/kits/schemas/role-registry.schema.1.json +35 -0
- package/kits/schemas/single-session.schema.1.json +31 -0
- package/kits/templates/bootstrap-welcome.md +15 -0
- package/kits/templates/message-fragments/handoff-request-to-target.md +13 -0
- package/kits/templates/message-fragments/handoff-response-to-origin.md +10 -0
- package/kits/templates/message-fragments/inject-default.md +2 -0
- package/kits/templates/message-fragments/item.md +2 -0
- package/kits/templates/roles/admin.json +9 -0
- package/kits/templates/roles/member.json +41 -0
- package/kits/templates/roles/owner.json +9 -0
- package/kits/templates/roles/visitor.json +40 -0
- package/kits/templates/system-fragments/baseagent.md +14 -0
- package/kits/templates/system-fragments/bootstrap.md +16 -0
- package/kits/templates/system-fragments/channel.md +48 -0
- package/kits/templates/system-fragments/commands.md +28 -0
- package/kits/templates/system-fragments/identity.md +11 -0
- package/kits/templates/system-fragments/relation.md +19 -0
- package/kits/templates/system-fragments/session.md +53 -0
- package/kits/templates/system-fragments/venue.md +31 -0
- package/package.json +50 -15
- package/dist/index.d.ts +0 -7
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ec stats — Token 用量统计 CLI 命令。
|
|
3
|
+
*/
|
|
4
|
+
import { resolveRoot } from '../paths.js';
|
|
5
|
+
import { wantsHelp } from './help.js';
|
|
6
|
+
import { queryAggregated, querySessionTurns, queryContextBreakdown, queryTopPeers, queryTopModels, queryMessageAggregated, queryPeerList, querySummary, queryPeerDaily, queryTaskModelCalls, querySessionModelCalls } from '../stats/query.js';
|
|
7
|
+
import { getBudgetStatus } from '../stats/budget.js';
|
|
8
|
+
const HELP = `ec stats — Token 用量与费用统计
|
|
9
|
+
|
|
10
|
+
Usage: ec stats [options]
|
|
11
|
+
|
|
12
|
+
时间范围:
|
|
13
|
+
(无参数) 今日概览
|
|
14
|
+
--today 同上
|
|
15
|
+
--hour 最近 24 小时,按小时分组
|
|
16
|
+
--week 本周
|
|
17
|
+
--month 本月
|
|
18
|
+
--from <date> --to <date> 任意区间(YYYY-MM-DD)
|
|
19
|
+
|
|
20
|
+
维度过滤(可组合):
|
|
21
|
+
--agent <aid> 指定 agent
|
|
22
|
+
--peer <X> 对端(裸 AID 自动前缀 aun#,或 channel#id 格式)
|
|
23
|
+
--model <model-id> 指定模型
|
|
24
|
+
--session <id> 指定会话
|
|
25
|
+
|
|
26
|
+
聚合粒度:
|
|
27
|
+
--by hour|day|week|month|model|peer|agent
|
|
28
|
+
|
|
29
|
+
快捷视图:
|
|
30
|
+
--session <id> 单个会话明细
|
|
31
|
+
--session <id> --last 会话最后一轮用量 + 累计(等价 status.completed)
|
|
32
|
+
--context <id> 会话 context breakdown 细目
|
|
33
|
+
--budget 预算状态
|
|
34
|
+
--top-peers [--limit N] 对端排行
|
|
35
|
+
--top-models [--limit N] 模型排行
|
|
36
|
+
--traffic 消息收发条数与字节数
|
|
37
|
+
--sql "<query>" 直接执行只读 SQL
|
|
38
|
+
--rebuild 全量重建日聚合表 usage_daily(运维兜底/排查)
|
|
39
|
+
--peers [--limit N] 私聊对端列表(带累计 token/calls/活跃日)
|
|
40
|
+
--groups [--limit N] 群聊列表(同上)
|
|
41
|
+
--summary 指定时间范围总消耗汇总(token/USD/CNY)
|
|
42
|
+
--peer-detail <id> 指定对端 AID 或 peer_key,按天返回消耗明细
|
|
43
|
+
--task-calls <taskId> 一个 task 的逐次大模型调用明细
|
|
44
|
+
--session-calls <id> 一个会话的逐次大模型调用明细
|
|
45
|
+
|
|
46
|
+
输出格式:
|
|
47
|
+
--format json JSON 输出
|
|
48
|
+
--help, -h 显示此帮助
|
|
49
|
+
|
|
50
|
+
示例:
|
|
51
|
+
ec stats
|
|
52
|
+
ec stats --month --agent bot.agentid.pub
|
|
53
|
+
ec stats --peer alice.aid.pub
|
|
54
|
+
ec stats --session abc123 --format json`;
|
|
55
|
+
const RESET = '\x1b[0m';
|
|
56
|
+
const BOLD = '\x1b[1m';
|
|
57
|
+
const DIM = '\x1b[2m';
|
|
58
|
+
const GREEN = '\x1b[32m';
|
|
59
|
+
const BLUE = '\x1b[34m';
|
|
60
|
+
const CYAN = '\x1b[36m';
|
|
61
|
+
const YELLOW = '\x1b[33m';
|
|
62
|
+
const RED = '\x1b[31m';
|
|
63
|
+
function fail(formatJson, code, message) {
|
|
64
|
+
if (formatJson) {
|
|
65
|
+
console.log(JSON.stringify({ ok: false, code, error: message }, null, 2));
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
console.error(`❌ ${message} (${code})`);
|
|
69
|
+
}
|
|
70
|
+
process.exit(1);
|
|
71
|
+
}
|
|
72
|
+
function pad(s, n) { return s.padEnd(n); }
|
|
73
|
+
function padR(s, n) { return s.padStart(n); }
|
|
74
|
+
function fmtTokens(n) {
|
|
75
|
+
if (n >= 1_000_000)
|
|
76
|
+
return (n / 1_000_000).toFixed(1) + 'M';
|
|
77
|
+
if (n >= 1_000)
|
|
78
|
+
return (n / 1_000).toFixed(1) + 'k';
|
|
79
|
+
return String(n);
|
|
80
|
+
}
|
|
81
|
+
function fmtBytes(n) {
|
|
82
|
+
if (n >= 1_073_741_824)
|
|
83
|
+
return (n / 1_073_741_824).toFixed(1) + 'GB';
|
|
84
|
+
if (n >= 1_048_576)
|
|
85
|
+
return (n / 1_048_576).toFixed(1) + 'MB';
|
|
86
|
+
if (n >= 1_024)
|
|
87
|
+
return (n / 1_024).toFixed(1) + 'KB';
|
|
88
|
+
return n + 'B';
|
|
89
|
+
}
|
|
90
|
+
function printTable(headers, rows) {
|
|
91
|
+
const widths = headers.map((h, i) => Math.max(h.length, ...rows.map(r => (r[i] || '').length)));
|
|
92
|
+
const sep = widths.map(w => '─'.repeat(w + 2)).join('┼');
|
|
93
|
+
console.log(headers.map((h, i) => ` ${pad(h, widths[i])} `).join('│'));
|
|
94
|
+
console.log(sep);
|
|
95
|
+
for (const row of rows) {
|
|
96
|
+
console.log(row.map((c, i) => ` ${pad(c || '', widths[i])} `).join('│'));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function parseDateArg(s) {
|
|
100
|
+
const d = new Date(s + 'T00:00:00Z');
|
|
101
|
+
if (isNaN(d.getTime()))
|
|
102
|
+
throw new Error(`Invalid date: ${s}`);
|
|
103
|
+
return d.getTime();
|
|
104
|
+
}
|
|
105
|
+
export async function handleStats(args) {
|
|
106
|
+
// Help
|
|
107
|
+
if (wantsHelp(args)) {
|
|
108
|
+
console.log(HELP);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const home = resolveRoot();
|
|
112
|
+
const flags = {};
|
|
113
|
+
const positional = [];
|
|
114
|
+
// Parse args
|
|
115
|
+
for (let i = 0; i < args.length; i++) {
|
|
116
|
+
const a = args[i];
|
|
117
|
+
if (a.startsWith('--')) {
|
|
118
|
+
const key = a.slice(2);
|
|
119
|
+
const next = args[i + 1];
|
|
120
|
+
if (next && !next.startsWith('--')) {
|
|
121
|
+
flags[key] = next;
|
|
122
|
+
i++;
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
flags[key] = true;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
positional.push(a);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const isJson = flags.format === 'json';
|
|
133
|
+
// 全量重建日聚合表(运维兜底/排查),不依赖时间范围。
|
|
134
|
+
if (flags.rebuild) {
|
|
135
|
+
const { rebuildDailyRollup, getDb } = await import('../stats/db.js');
|
|
136
|
+
const { resolvePrices } = await import('../stats/price-resolver.js');
|
|
137
|
+
const startedAt = Date.now();
|
|
138
|
+
// 步骤1:回填 usage_events 的 cost 字段(只处理 cost_official_usd IS NULL 的行)
|
|
139
|
+
console.log(`${CYAN}正在回填历史事件的费用数据...${RESET}`);
|
|
140
|
+
const db = getDb(home);
|
|
141
|
+
if (!db)
|
|
142
|
+
fail(isJson, 'REBUILD_FAILED', 'usage_events 回填失败(DB 不可用)');
|
|
143
|
+
const allEvents = db.prepare(`SELECT * FROM usage_events WHERE cost_official_usd IS NULL`).all();
|
|
144
|
+
let updated = 0;
|
|
145
|
+
const batchSize = 1000;
|
|
146
|
+
for (let i = 0; i < allEvents.length; i += batchSize) {
|
|
147
|
+
db.exec('BEGIN');
|
|
148
|
+
const batch = allEvents.slice(i, i + batchSize);
|
|
149
|
+
for (const event of batch) {
|
|
150
|
+
const prices = resolvePrices(home, event); // 不传 gatewayPricing,全走本地 JSONL
|
|
151
|
+
db.prepare(`
|
|
152
|
+
UPDATE usage_events
|
|
153
|
+
SET cost_official_usd = ?, cost_official_cny = ?,
|
|
154
|
+
cost_gateway_usd = ?, cost_gateway_cny = ?
|
|
155
|
+
WHERE id = ?
|
|
156
|
+
`).run(prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null, event.id);
|
|
157
|
+
updated++;
|
|
158
|
+
}
|
|
159
|
+
db.exec('COMMIT');
|
|
160
|
+
if (!isJson && (i + batch.length) % 5000 === 0) {
|
|
161
|
+
console.log(` 已处理 ${i + batch.length}/${allEvents.length} 条事件...`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
console.log(`${GREEN}✓ 回填完成:${updated} 条事件${RESET}`);
|
|
165
|
+
// 步骤2:重建 usage_daily(会自动聚合 cost 字段)
|
|
166
|
+
console.log(`${CYAN}正在重建日聚合表...${RESET}`);
|
|
167
|
+
const n = rebuildDailyRollup(home);
|
|
168
|
+
const ms = Date.now() - startedAt;
|
|
169
|
+
if (n < 0)
|
|
170
|
+
fail(isJson, 'REBUILD_FAILED', 'usage_daily 重建失败(DB 不可用或 SQL 错误)');
|
|
171
|
+
if (isJson) {
|
|
172
|
+
console.log(JSON.stringify({ ok: true, events_backfilled: updated, daily_rows: n, duration_ms: ms }, null, 2));
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
console.log(`${GREEN}✓ usage_daily 重建完成:${n} 行,总耗时 ${ms}ms${RESET}`);
|
|
176
|
+
}
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
// Determine time range
|
|
180
|
+
let from_ts;
|
|
181
|
+
let to_ts;
|
|
182
|
+
let granularity = 'day';
|
|
183
|
+
const now = new Date();
|
|
184
|
+
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
|
185
|
+
if (flags.from && typeof flags.from === 'string') {
|
|
186
|
+
from_ts = parseDateArg(flags.from);
|
|
187
|
+
if (flags.to && typeof flags.to === 'string')
|
|
188
|
+
to_ts = parseDateArg(flags.to);
|
|
189
|
+
}
|
|
190
|
+
else if (flags.hour) {
|
|
191
|
+
from_ts = Date.now() - 24 * 60 * 60 * 1000;
|
|
192
|
+
granularity = 'hour';
|
|
193
|
+
}
|
|
194
|
+
else if (flags.week) {
|
|
195
|
+
const dayOfWeek = now.getDay();
|
|
196
|
+
from_ts = todayStart - dayOfWeek * 86400000;
|
|
197
|
+
granularity = 'day';
|
|
198
|
+
}
|
|
199
|
+
else if (flags.month) {
|
|
200
|
+
from_ts = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
|
|
201
|
+
granularity = 'day';
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
// default: today
|
|
205
|
+
from_ts = todayStart;
|
|
206
|
+
granularity = 'hour';
|
|
207
|
+
}
|
|
208
|
+
// Granularity override
|
|
209
|
+
if (flags.by && typeof flags.by === 'string') {
|
|
210
|
+
if (['hour', 'day', 'week', 'month', 'model', 'peer', 'agent'].includes(flags.by)) {
|
|
211
|
+
granularity = flags.by;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Filter
|
|
215
|
+
const filter = { from_ts, to_ts };
|
|
216
|
+
if (flags.agent && typeof flags.agent === 'string')
|
|
217
|
+
filter.agent_aid = flags.agent;
|
|
218
|
+
if (flags.peer && typeof flags.peer === 'string') {
|
|
219
|
+
// AUN 简写:不含 # 时默认 aun 渠道
|
|
220
|
+
filter.peer_key = flags.peer.includes('#') ? flags.peer : `aun#${encodeURIComponent(flags.peer)}`;
|
|
221
|
+
}
|
|
222
|
+
if (flags.model && typeof flags.model === 'string')
|
|
223
|
+
filter.model = flags.model;
|
|
224
|
+
if (flags.session && typeof flags.session === 'string')
|
|
225
|
+
filter.session_id = flags.session;
|
|
226
|
+
// ── 结构化查询:私聊/群聊列表、总消耗汇总、对端按天明细 ──────────────────
|
|
227
|
+
if (flags.peers || flags.groups) {
|
|
228
|
+
const peerType = flags.peers ? 'private' : 'group';
|
|
229
|
+
const limit = typeof flags.limit === 'string' ? parseInt(flags.limit) || 50 : 50;
|
|
230
|
+
const rows = queryPeerList(home, { peer_type: peerType, from_ts, to_ts, agent_aid: filter.agent_aid, limit });
|
|
231
|
+
if (isJson) {
|
|
232
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
console.log(`\n${BOLD}📊 ${peerType === 'private' ? '私聊' : '群聊'}列表${RESET}\n`);
|
|
236
|
+
if (!rows.length) {
|
|
237
|
+
console.log(' (无数据)');
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const headers = ['#', 'Peer ID', 'Tokens', 'Calls', 'Sessions', 'First', 'Last'];
|
|
241
|
+
const tableRows = rows.map((r, i) => [
|
|
242
|
+
String(i + 1), r.peer_id, fmtTokens(r.total_tokens), String(r.calls),
|
|
243
|
+
String(r.session_count), r.first_day, r.last_day,
|
|
244
|
+
]);
|
|
245
|
+
printTable(headers, tableRows);
|
|
246
|
+
console.log();
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (flags.summary) {
|
|
250
|
+
const result = querySummary(home, { from_ts, to_ts, agent_aid: filter.agent_aid, peer_key: filter.peer_key });
|
|
251
|
+
if (isJson) {
|
|
252
|
+
console.log(JSON.stringify(result, null, 2));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
console.log(`\n${BOLD}📊 用量汇总${RESET}\n`);
|
|
256
|
+
console.log(` Input: ${fmtTokens(result.input_tokens)}`);
|
|
257
|
+
console.log(` Output: ${fmtTokens(result.output_tokens)}`);
|
|
258
|
+
console.log(` Cache read: ${fmtTokens(result.cache_read_tokens)}`);
|
|
259
|
+
console.log(` Cache write: ${fmtTokens(result.cache_creation_tokens)}`);
|
|
260
|
+
console.log(` Total tokens: ${fmtTokens(result.total_tokens)}`);
|
|
261
|
+
console.log(` Calls: ${result.calls}`);
|
|
262
|
+
const totalIn = result.input_tokens + result.cache_read_tokens;
|
|
263
|
+
const cacheHitRate = totalIn > 0 ? (result.cache_read_tokens / totalIn * 100).toFixed(1) : '0.0';
|
|
264
|
+
console.log(` Cache hit: ${cacheHitRate}%`);
|
|
265
|
+
console.log();
|
|
266
|
+
console.log(`${BOLD}Cost:${RESET}`);
|
|
267
|
+
if (result.cost_official_usd > 0 || result.cost_official_cny > 0) {
|
|
268
|
+
console.log(` Official: ${GREEN}$${result.cost_official_usd.toFixed(4)}${RESET} ¥${result.cost_official_cny.toFixed(4)}`);
|
|
269
|
+
}
|
|
270
|
+
if (result.cost_gateway_usd > 0 || result.cost_gateway_cny > 0) {
|
|
271
|
+
console.log(` Gateway: ${GREEN}$${result.cost_gateway_usd.toFixed(4)}${RESET} ¥${result.cost_gateway_cny.toFixed(4)}`);
|
|
272
|
+
}
|
|
273
|
+
console.log();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (flags['peer-detail'] && typeof flags['peer-detail'] === 'string') {
|
|
277
|
+
const input = flags['peer-detail'];
|
|
278
|
+
// 含 # 视为完整 peer_key(精确匹配),否则视为裸 peer_id(LIKE 匹配)
|
|
279
|
+
const peerOpts = input.includes('#')
|
|
280
|
+
? { peer_key: input, from_ts, to_ts, agent_aid: filter.agent_aid }
|
|
281
|
+
: { peer_id: input, from_ts, to_ts, agent_aid: filter.agent_aid };
|
|
282
|
+
const rows = queryPeerDaily(home, peerOpts);
|
|
283
|
+
if (isJson) {
|
|
284
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (!rows.length) {
|
|
288
|
+
console.log('No data for the specified peer and range.');
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
console.log(`\n${BOLD}📊 对端明细 — ${input}${RESET}\n`);
|
|
292
|
+
const headers = ['Day', 'Input', 'Output', 'Cache', 'Calls', 'HitRate', 'USD', 'CNY'];
|
|
293
|
+
const tableRows = rows.map(r => [
|
|
294
|
+
r.period, fmtTokens(r.input_tokens), fmtTokens(r.output_tokens),
|
|
295
|
+
fmtTokens(r.cache_read_tokens), String(r.call_count),
|
|
296
|
+
(r.cache_hit_rate * 100).toFixed(0) + '%',
|
|
297
|
+
r.usd > 0 ? '$' + r.usd.toFixed(4) : '—',
|
|
298
|
+
r.cny > 0 ? '¥' + r.cny.toFixed(4) : '—',
|
|
299
|
+
]);
|
|
300
|
+
printTable(headers, tableRows);
|
|
301
|
+
console.log();
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
// 逐次大模型调用明细
|
|
305
|
+
if ((flags['task-calls'] && typeof flags['task-calls'] === 'string') ||
|
|
306
|
+
(flags['session-calls'] && typeof flags['session-calls'] === 'string')) {
|
|
307
|
+
const byTask = typeof flags['task-calls'] === 'string';
|
|
308
|
+
const key = (byTask ? flags['task-calls'] : flags['session-calls']);
|
|
309
|
+
const rows = byTask ? queryTaskModelCalls(home, key) : querySessionModelCalls(home, key);
|
|
310
|
+
if (isJson) {
|
|
311
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (!rows.length) {
|
|
315
|
+
console.log('No model calls found.');
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
console.log(`\n${BOLD}📊 大模型调用明细 — ${key}${RESET}\n`);
|
|
319
|
+
const headers = ['#', 'Model', 'Input', 'Output', 'CacheR', 'CacheW', 'Task', 'Deg'];
|
|
320
|
+
const tableRows = rows.map(r => [
|
|
321
|
+
String(r.call_index),
|
|
322
|
+
r.model.split('-').slice(0, 3).join('-'),
|
|
323
|
+
fmtTokens(r.input_tokens), fmtTokens(r.output_tokens),
|
|
324
|
+
fmtTokens(r.cache_read_tokens), fmtTokens(r.cache_creation_tokens),
|
|
325
|
+
r.task_id, r.degraded ? 'Y' : '',
|
|
326
|
+
]);
|
|
327
|
+
printTable(headers, tableRows);
|
|
328
|
+
console.log();
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
// Special views
|
|
332
|
+
if (flags.sql && typeof flags.sql === 'string') {
|
|
333
|
+
// 直接执行 SQL(只读,仅 SELECT)
|
|
334
|
+
const sql = flags.sql.trim();
|
|
335
|
+
if (!/^\s*select/i.test(sql)) {
|
|
336
|
+
console.error('Only SELECT queries are allowed.');
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
const { openReadonlyDb, getDbPath } = await import('../stats/db.js');
|
|
340
|
+
const db = openReadonlyDb(getDbPath(home));
|
|
341
|
+
if (!db) {
|
|
342
|
+
console.error('Stats DB not available.');
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
const rows = db.prepare(sql).all();
|
|
347
|
+
if (isJson) {
|
|
348
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
349
|
+
}
|
|
350
|
+
else if (rows.length === 0) {
|
|
351
|
+
console.log('(empty result)');
|
|
352
|
+
}
|
|
353
|
+
else {
|
|
354
|
+
const keys = Object.keys(rows[0]);
|
|
355
|
+
printTable(keys, rows.map(r => keys.map(k => String(r[k] ?? ''))));
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
catch (e) {
|
|
359
|
+
console.error(`SQL error: ${e.message || e}`);
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
db.close();
|
|
363
|
+
}
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
if (flags.budget) {
|
|
367
|
+
const status = getBudgetStatus(home, filter.agent_aid, filter.peer_key);
|
|
368
|
+
if (isJson) {
|
|
369
|
+
console.log(JSON.stringify(status, null, 2));
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
console.log(`\n${BOLD}📊 Budget Status${RESET}\n`);
|
|
373
|
+
console.log(` Daily limit: ${status.daily_limit_usd >= 0 ? '$' + status.daily_limit_usd.toFixed(2) : 'unlimited'}`);
|
|
374
|
+
console.log(` Daily used: ${GREEN}$${status.daily_used_usd.toFixed(4)}${RESET}`);
|
|
375
|
+
console.log(` Daily remaining: ${status.daily_remaining_usd >= 0 ? '$' + status.daily_remaining_usd.toFixed(2) : 'unlimited'}`);
|
|
376
|
+
console.log(` Monthly limit: ${status.monthly_limit_usd >= 0 ? '$' + status.monthly_limit_usd.toFixed(2) : 'unlimited'}`);
|
|
377
|
+
console.log(` Monthly used: ${GREEN}$${status.monthly_used_usd.toFixed(4)}${RESET}`);
|
|
378
|
+
console.log(` Monthly remaining: ${status.monthly_remaining_usd >= 0 ? '$' + status.monthly_remaining_usd.toFixed(2) : 'unlimited'}`);
|
|
379
|
+
console.log(` Usage: ${status.pct_used > 80 ? RED : status.pct_used > 60 ? YELLOW : GREEN}${status.pct_used.toFixed(1)}%${RESET}`);
|
|
380
|
+
console.log(` Hard blocked: ${status.hard_blocked ? RED + 'YES' + RESET : 'no'}`);
|
|
381
|
+
console.log(` Soft warn: ${status.soft_warn ? YELLOW + 'yes' + RESET : 'no'}`);
|
|
382
|
+
console.log(` Auto warn: ${status.auto_warn ? YELLOW + 'yes' + RESET : 'no'}`);
|
|
383
|
+
console.log();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (flags.context && typeof flags.context === 'string') {
|
|
387
|
+
const rows = queryContextBreakdown(home, flags.context);
|
|
388
|
+
if (isJson) {
|
|
389
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (!rows.length) {
|
|
393
|
+
console.log('No context breakdown data for this session.');
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
console.log(`\n${BOLD}📊 Context Breakdown — session ${flags.context}${RESET}\n`);
|
|
397
|
+
const headers = ['Turn', 'System', 'Tools', 'MCP', 'Agents', 'Memory', 'Skills', 'Messages', 'Free', 'Total', 'Max'];
|
|
398
|
+
const tableRows = rows.map(r => [
|
|
399
|
+
String(r.turn_count),
|
|
400
|
+
fmtTokens(r.system_prompt ?? 0), fmtTokens(r.system_tools ?? 0),
|
|
401
|
+
fmtTokens(r.mcp_tools ?? 0), fmtTokens(r.custom_agents ?? 0),
|
|
402
|
+
fmtTokens(r.memory_files ?? 0), fmtTokens(r.skills ?? 0),
|
|
403
|
+
fmtTokens(r.messages ?? 0), fmtTokens(r.free_space ?? 0),
|
|
404
|
+
fmtTokens(r.total_estimated ?? 0), fmtTokens(r.max_tokens ?? 0),
|
|
405
|
+
]);
|
|
406
|
+
printTable(headers, tableRows);
|
|
407
|
+
console.log();
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (flags['top-peers']) {
|
|
411
|
+
const limit = typeof flags.limit === 'string' ? parseInt(flags.limit) || 10 : 10;
|
|
412
|
+
const rows = queryTopPeers(home, filter, limit);
|
|
413
|
+
if (isJson) {
|
|
414
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
console.log(`\n${BOLD}📊 Top Peers${RESET}\n`);
|
|
418
|
+
const headers = ['#', 'Peer', 'Tokens', 'Calls'];
|
|
419
|
+
const tableRows = rows.map((r, i) => [
|
|
420
|
+
String(i + 1), r.peer_key, fmtTokens(r.total_tokens), String(r.call_count),
|
|
421
|
+
]);
|
|
422
|
+
printTable(headers, tableRows);
|
|
423
|
+
console.log();
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (flags['top-models']) {
|
|
427
|
+
const limit = typeof flags.limit === 'string' ? parseInt(flags.limit) || 10 : 10;
|
|
428
|
+
const rows = queryTopModels(home, filter, limit);
|
|
429
|
+
if (isJson) {
|
|
430
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
console.log(`\n${BOLD}📊 Top Models${RESET}\n`);
|
|
434
|
+
const headers = ['#', 'Model', 'Tokens', 'Calls'];
|
|
435
|
+
const tableRows = rows.map((r, i) => [
|
|
436
|
+
String(i + 1), r.model, fmtTokens(r.total_tokens), String(r.call_count),
|
|
437
|
+
]);
|
|
438
|
+
printTable(headers, tableRows);
|
|
439
|
+
console.log();
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (flags.traffic) {
|
|
443
|
+
const rows = queryMessageAggregated(home, granularity, filter);
|
|
444
|
+
if (isJson) {
|
|
445
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
if (!rows.length) {
|
|
449
|
+
console.log('No traffic data for the selected range.');
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
const periodLabel = flags.hour ? 'Last 24h' : flags.week ? 'This Week' : flags.month ? 'This Month' : 'Today';
|
|
453
|
+
console.log(`\n${BOLD}📊 ${periodLabel} — Network Traffic${RESET}\n`);
|
|
454
|
+
const headers = ['Period', 'Msg In', 'Msg Out', 'Bytes In', 'Bytes Out'];
|
|
455
|
+
const tableRows = rows.map(r => [
|
|
456
|
+
r.period,
|
|
457
|
+
String(r.msg_in), String(r.msg_out),
|
|
458
|
+
fmtBytes(r.bytes_in), fmtBytes(r.bytes_out),
|
|
459
|
+
]);
|
|
460
|
+
printTable(headers, tableRows);
|
|
461
|
+
const totIn = rows.reduce((s, r) => s + r.msg_in, 0);
|
|
462
|
+
const totOut = rows.reduce((s, r) => s + r.msg_out, 0);
|
|
463
|
+
const totBIn = rows.reduce((s, r) => s + r.bytes_in, 0);
|
|
464
|
+
const totBOut = rows.reduce((s, r) => s + r.bytes_out, 0);
|
|
465
|
+
console.log(`\n ${DIM}Total: in=${totIn} out=${totOut} bytes_in=${fmtBytes(totBIn)} bytes_out=${fmtBytes(totBOut)}${RESET}\n`);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (flags.session && typeof flags.session === 'string') {
|
|
469
|
+
const rows = querySessionTurns(home, flags.session);
|
|
470
|
+
// --last: 返回最后一轮用量 + 会话累计(与 status.completed metadata 等价)
|
|
471
|
+
if (flags.last) {
|
|
472
|
+
if (!rows.length) {
|
|
473
|
+
if (isJson) {
|
|
474
|
+
console.log(JSON.stringify({ ok: false, error: 'No usage data for this session' }, null, 2));
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
console.log('No usage data for this session.');
|
|
478
|
+
}
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
const last = rows[rows.length - 1];
|
|
482
|
+
const totIn = rows.reduce((s, r) => s + r.input_tokens, 0);
|
|
483
|
+
const totOut = rows.reduce((s, r) => s + r.output_tokens, 0);
|
|
484
|
+
const totCacheRead = rows.reduce((s, r) => s + r.cache_read_tokens, 0);
|
|
485
|
+
const totCacheCreation = rows.reduce((s, r) => s + r.cache_creation_tokens, 0);
|
|
486
|
+
const totUsd = rows.reduce((s, r) => s + r.usd, 0);
|
|
487
|
+
const totCny = rows.reduce((s, r) => s + r.cny, 0);
|
|
488
|
+
const totOfficialUsd = rows.reduce((s, r) => s + r.cost_official_usd, 0);
|
|
489
|
+
const totOfficialCny = rows.reduce((s, r) => s + r.cost_official_cny, 0);
|
|
490
|
+
const totGatewayUsd = rows.reduce((s, r) => s + r.cost_gateway_usd, 0);
|
|
491
|
+
const totGatewayCny = rows.reduce((s, r) => s + r.cost_gateway_cny, 0);
|
|
492
|
+
const totCacheAll = totIn + totCacheRead;
|
|
493
|
+
const sessionCacheHitRate = totCacheAll > 0 ? totCacheRead / totCacheAll : 0;
|
|
494
|
+
// model_spec
|
|
495
|
+
const { resolveModelSpec } = await import('../stats/billing.js');
|
|
496
|
+
const spec = resolveModelSpec(home, last.model);
|
|
497
|
+
const result = {
|
|
498
|
+
turn: {
|
|
499
|
+
input_tokens: last.input_tokens,
|
|
500
|
+
output_tokens: last.output_tokens,
|
|
501
|
+
cache_read_tokens: last.cache_read_tokens,
|
|
502
|
+
cache_creation_tokens: last.cache_creation_tokens,
|
|
503
|
+
model: last.model,
|
|
504
|
+
cost_usd: last.usd,
|
|
505
|
+
cost_cny: last.cny,
|
|
506
|
+
// 原价 + 网关实际价
|
|
507
|
+
cost: {
|
|
508
|
+
official: { usd: last.cost_official_usd, cny: last.cost_official_cny },
|
|
509
|
+
gateway: { usd: last.cost_gateway_usd, cny: last.cost_gateway_cny },
|
|
510
|
+
},
|
|
511
|
+
cache_hit_rate: last.cache_read_tokens / ((last.input_tokens + last.cache_read_tokens) || 1),
|
|
512
|
+
context_window_pct: last.context_window_pct ?? 0,
|
|
513
|
+
duration_ms: last.duration_ms ?? 0,
|
|
514
|
+
},
|
|
515
|
+
session_total: {
|
|
516
|
+
input_tokens: totIn,
|
|
517
|
+
output_tokens: totOut,
|
|
518
|
+
cache_read_tokens: totCacheRead,
|
|
519
|
+
cache_creation_tokens: totCacheCreation,
|
|
520
|
+
cost_usd: totUsd,
|
|
521
|
+
cost_cny: totCny,
|
|
522
|
+
cost: {
|
|
523
|
+
official: { usd: totOfficialUsd, cny: totOfficialCny },
|
|
524
|
+
gateway: { usd: totGatewayUsd, cny: totGatewayCny },
|
|
525
|
+
},
|
|
526
|
+
call_count: rows.length,
|
|
527
|
+
cache_hit_rate: sessionCacheHitRate,
|
|
528
|
+
},
|
|
529
|
+
model_spec: {
|
|
530
|
+
context_window: spec.context_window,
|
|
531
|
+
max_input_tokens: spec.max_input_tokens,
|
|
532
|
+
max_output_tokens: spec.max_output_tokens,
|
|
533
|
+
},
|
|
534
|
+
};
|
|
535
|
+
if (isJson) {
|
|
536
|
+
console.log(JSON.stringify(result, null, 2));
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
console.log(`\n${BOLD}📊 Session Last Turn — ${flags.session}${RESET}\n`);
|
|
540
|
+
console.log(` Model: ${CYAN}${result.turn.model}${RESET}`);
|
|
541
|
+
console.log(` Input: ${fmtTokens(result.turn.input_tokens)}`);
|
|
542
|
+
console.log(` Output: ${fmtTokens(result.turn.output_tokens)}`);
|
|
543
|
+
console.log(` Cache read: ${fmtTokens(result.turn.cache_read_tokens)}`);
|
|
544
|
+
console.log(` Cache hit: ${(result.turn.cache_hit_rate * 100).toFixed(1)}%`);
|
|
545
|
+
console.log(` Context: ${result.turn.context_window_pct}%`);
|
|
546
|
+
console.log(` Cost: ${result.turn.cost_usd > 0 ? GREEN + '$' + result.turn.cost_usd.toFixed(4) + RESET : ''}${result.turn.cost_cny > 0 ? GREEN + ' ¥' + result.turn.cost_cny.toFixed(4) + RESET : ''}`);
|
|
547
|
+
console.log(` Duration: ${result.turn.duration_ms}ms`);
|
|
548
|
+
console.log(`\n ${DIM}Session total: input=${fmtTokens(result.session_total.input_tokens)} output=${fmtTokens(result.session_total.output_tokens)} USD=$${totUsd.toFixed(4)} CNY=¥${totCny.toFixed(4)} calls=${result.session_total.call_count}${RESET}\n`);
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
if (isJson) {
|
|
552
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
if (!rows.length) {
|
|
556
|
+
console.log('No usage data for this session.');
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
console.log(`\n${BOLD}📊 Session ${flags.session}${RESET}\n`);
|
|
560
|
+
const headers = ['Time', 'Model', 'Input', 'Output', 'Cache', 'Ctx%', 'USD', 'CNY'];
|
|
561
|
+
const tableRows = rows.map(r => {
|
|
562
|
+
const t = new Date(r.ts).toLocaleTimeString();
|
|
563
|
+
return [
|
|
564
|
+
t, r.model.split('-').slice(0, 2).join('-'),
|
|
565
|
+
fmtTokens(r.input_tokens), fmtTokens(r.output_tokens),
|
|
566
|
+
fmtTokens(r.cache_read_tokens),
|
|
567
|
+
r.context_window_pct != null ? r.context_window_pct.toFixed(0) + '%' : '—',
|
|
568
|
+
r.usd > 0 ? '$' + r.usd.toFixed(4) : '—',
|
|
569
|
+
r.cny > 0 ? '¥' + r.cny.toFixed(4) : '—',
|
|
570
|
+
];
|
|
571
|
+
});
|
|
572
|
+
printTable(headers, tableRows);
|
|
573
|
+
// Totals
|
|
574
|
+
const totIn = rows.reduce((s, r) => s + r.input_tokens, 0);
|
|
575
|
+
const totOut = rows.reduce((s, r) => s + r.output_tokens, 0);
|
|
576
|
+
const totUsd = rows.reduce((s, r) => s + r.usd, 0);
|
|
577
|
+
const totCny = rows.reduce((s, r) => s + r.cny, 0);
|
|
578
|
+
console.log(`\n ${DIM}Total: input=${fmtTokens(totIn)} output=${fmtTokens(totOut)} USD=$${totUsd.toFixed(4)} CNY=¥${totCny.toFixed(4)} turns=${rows.length}${RESET}\n`);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
// Default: aggregated view
|
|
582
|
+
const rows = queryAggregated(home, granularity, filter);
|
|
583
|
+
if (isJson) {
|
|
584
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
if (!rows.length) {
|
|
588
|
+
console.log('No usage data for the selected range.');
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
const periodLabel = flags.hour ? 'Last 24h' : flags.week ? 'This Week' : flags.month ? 'This Month' : 'Today';
|
|
592
|
+
console.log(`\n${BOLD}📊 ${periodLabel} — Token Usage${RESET}\n`);
|
|
593
|
+
const headers = ['Period', 'Input', 'Output', 'Cache↑', 'CacheHit', 'Calls', 'HitRate'];
|
|
594
|
+
const tableRows = rows.map(r => [
|
|
595
|
+
r.period,
|
|
596
|
+
fmtTokens(r.input_tokens), fmtTokens(r.output_tokens),
|
|
597
|
+
fmtTokens(r.cache_creation_tokens), fmtTokens(r.cache_read_tokens),
|
|
598
|
+
String(r.call_count),
|
|
599
|
+
(r.cache_hit_rate * 100).toFixed(0) + '%',
|
|
600
|
+
]);
|
|
601
|
+
printTable(headers, tableRows);
|
|
602
|
+
// Summary
|
|
603
|
+
const totIn = rows.reduce((s, r) => s + r.input_tokens, 0);
|
|
604
|
+
const totOut = rows.reduce((s, r) => s + r.output_tokens, 0);
|
|
605
|
+
const totCalls = rows.reduce((s, r) => s + r.call_count, 0);
|
|
606
|
+
const totCacheRead = rows.reduce((s, r) => s + r.cache_read_tokens, 0);
|
|
607
|
+
const overallHit = (totIn + totCacheRead) > 0 ? (totCacheRead / (totIn + totCacheRead) * 100).toFixed(1) : '0';
|
|
608
|
+
console.log(`\n ${DIM}Total: input=${fmtTokens(totIn)} output=${fmtTokens(totOut)} calls=${totCalls} cache_hit_rate=${overallHit}%${RESET}\n`);
|
|
609
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { normalizeCausation } from '../core/causation/context.js';
|
|
2
|
+
export const TASK_RUNTIME_CONTEXT_ENV = 'EVOLCORE_TASK_RUNTIME_CONTEXT';
|
|
3
|
+
function isPlainObject(value) {
|
|
4
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
function optionalString(value) {
|
|
7
|
+
return typeof value === 'string' ? value : undefined;
|
|
8
|
+
}
|
|
9
|
+
function normalizeTaskRuntimeContext(value) {
|
|
10
|
+
const handoffIds = Array.isArray(value.handoffIds)
|
|
11
|
+
? value.handoffIds.filter((id) => typeof id === 'string')
|
|
12
|
+
: undefined;
|
|
13
|
+
return {
|
|
14
|
+
taskId: optionalString(value.taskId),
|
|
15
|
+
sessionId: optionalString(value.sessionId),
|
|
16
|
+
messageId: optionalString(value.messageId),
|
|
17
|
+
channel: optionalString(value.channel),
|
|
18
|
+
channelId: optionalString(value.channelId),
|
|
19
|
+
chatType: optionalString(value.chatType),
|
|
20
|
+
selfAid: optionalString(value.selfAid),
|
|
21
|
+
peerId: optionalString(value.peerId),
|
|
22
|
+
peerName: optionalString(value.peerName),
|
|
23
|
+
peerType: optionalString(value.peerType),
|
|
24
|
+
peerRole: optionalString(value.peerRole),
|
|
25
|
+
threadId: optionalString(value.threadId),
|
|
26
|
+
handoffIds: handoffIds?.length ? handoffIds : undefined,
|
|
27
|
+
causation: normalizeCausation(value.causation),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export function runtimeRefMessageIdForMsgSend(args) {
|
|
31
|
+
const runtime = args.runtime;
|
|
32
|
+
if (!runtime)
|
|
33
|
+
return undefined;
|
|
34
|
+
if (runtime.channel !== 'aun' || runtime.chatType !== 'private')
|
|
35
|
+
return undefined;
|
|
36
|
+
if (!runtime.selfAid || runtime.selfAid !== args.from)
|
|
37
|
+
return undefined;
|
|
38
|
+
return runtime.messageId || undefined;
|
|
39
|
+
}
|
|
40
|
+
export function parseTaskRuntimeContext(raw) {
|
|
41
|
+
if (!raw)
|
|
42
|
+
return undefined;
|
|
43
|
+
try {
|
|
44
|
+
const parsed = JSON.parse(raw);
|
|
45
|
+
return isPlainObject(parsed) ? normalizeTaskRuntimeContext(parsed) : undefined;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export function readTaskRuntimeContextFromEnv(env = process.env) {
|
|
52
|
+
return parseTaskRuntimeContext(env[TASK_RUNTIME_CONTEXT_ENV]);
|
|
53
|
+
}
|
|
54
|
+
export async function readTaskRuntimeContextFromDaemon(sessionId, timeoutMs = 500) {
|
|
55
|
+
if (!sessionId)
|
|
56
|
+
return undefined;
|
|
57
|
+
try {
|
|
58
|
+
const [{ resolvePaths }, { ipcQuery }] = await Promise.all([
|
|
59
|
+
import('../paths.js'),
|
|
60
|
+
import('../ipc.js'),
|
|
61
|
+
]);
|
|
62
|
+
const response = await ipcQuery(resolvePaths().socket, { type: 'task-runtime-context', sessionId }, timeoutMs);
|
|
63
|
+
return response?.ok && response.context ? response.context : undefined;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export async function readBestTaskRuntimeContext(env = process.env) {
|
|
70
|
+
const envContext = readTaskRuntimeContextFromEnv(env);
|
|
71
|
+
const sessionId = env.EVOLCORE_SESSION_ID || envContext?.sessionId;
|
|
72
|
+
return (await readTaskRuntimeContextFromDaemon(sessionId)) ?? envContext;
|
|
73
|
+
}
|
|
74
|
+
export function buildTaskRuntimeEnv(ctx) {
|
|
75
|
+
const clean = normalizeTaskRuntimeContext(ctx);
|
|
76
|
+
return {
|
|
77
|
+
EVOLCORE_SESSION_ID: ctx.sessionId ?? '',
|
|
78
|
+
[TASK_RUNTIME_CONTEXT_ENV]: JSON.stringify(clean),
|
|
79
|
+
};
|
|
80
|
+
}
|